text
stringlengths
14
6.51M
{ 참고 글 : http://blog.hjf.pe.kr/336 } unit CachedUpdateForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.VCLUI.Wait, Vcl.ExtCtrls, Vcl.DBCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.UI, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls; type TForm2 = class(TForm) DBGrid1: TDBGrid; DBNavigator1: TDBNavigator; DBGrid2: TDBGrid; btnViewCache: TButton; btnApplyUpdates: TButton; btnCancelUpdates: TButton; Label1: TLabel; btnOldValue: TButton; btnLastUndo: TButton; btnRevertRecord: TButton; btnSavePoint: TButton; btnBackSPoint: TButton; procedure btnCancelUpdatesClick(Sender: TObject); procedure btnApplyUpdatesClick(Sender: TObject); procedure btnViewCacheClick(Sender: TObject); procedure btnOldValueClick(Sender: TObject); procedure btnLastUndoClick(Sender: TObject); procedure btnRevertRecordClick(Sender: TObject); procedure btnSavePointClick(Sender: TObject); procedure btnBackSPointClick(Sender: TObject); private { Private declarations } FSavePoint: Integer; public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} uses CachedUpdateModule; procedure TForm2.btnCancelUpdatesClick(Sender: TObject); begin DM.FDQuery1.CancelUpdates; DM.FDQuery1.Refresh; end; procedure TForm2.btnLastUndoClick(Sender: TObject); begin DM.FDQuery1.UndoLastChange(True); end; procedure TForm2.btnOldValueClick(Sender: TObject); begin ShowMessage(format('이전 값: %s -> 새로운 값: %s', [ DM.FDQuery1.FieldByName('FIELD1').OldValue, DM.FDQuery1.FieldByName('FIELD1').Value ])); end; procedure TForm2.btnRevertRecordClick(Sender: TObject); begin DM.FDQuery1.RevertRecord; end; procedure TForm2.btnSavePointClick(Sender: TObject); begin FSavePoint := DM.FDQuery1.SavePoint; end; procedure TForm2.btnViewCacheClick(Sender: TObject); begin if DM.FDQuery1.Active then begin DM.FDMemTable1.CloneCursor(DM.FDQuery1, True); DM.FDMemTable1.FilterChanges := [rtModified, rtInserted, rtDeleted]; end; end; procedure TForm2.btnApplyUpdatesClick(Sender: TObject); var iErr: Integer; begin DM.FDConnection1.StartTransaction; // ApplyUpdates는 오류를 발생하지 않음 iErr := DM.FDQuery1.ApplyUpdates(-1); if iErr = 0 then begin DM.FDQuery1.CommitUpdates; // 변경로그 지우기 DM.FDConnection1.Commit; end else DM.FDConnection1.Rollback; DM.FDQuery1.Refresh; end; procedure TForm2.btnBackSPointClick(Sender: TObject); begin if FSavePoint > 0 then DM.FDQuery1.SavePoint := FSavePoint; end; end.
unit Unit27; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type TForm27 = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form27: TForm27; implementation {$R *.dfm} uses Unit28; type TClasseTerceiroHack = class(TClasseTerceiros) public end; TClasseTerceiroHelper = class helper for TClasseTerceiros public function f3: integer; end; procedure TForm27.FormCreate(Sender: TObject); var ct: TObject; f: Double; i: integer; begin { ct := TClasseTerceiroHack.Create; if ct is TClasseTerceiros then begin caption := (ct as TClasseTerceiroHack).f3.ToString; end; } try try i := 0; caption := 'semerro'; if i = 0 then raise Exception.Create('I nao pode ser zero'); f := 10 / i; caption := f.ToString; finally caption := 'xxxxx'; end; except on e: Exception do begin // logar em arquivo // DebugLog(e.message); caption := e.message; raise; end; end; end; { TClasseTerceiroHack } function TClasseTerceiroHelper.f3: integer; begin result := 3; end; end.
//Exercicio 77: Modifique o problema anterior de modo que caso o usuário digite um número negativo o algoritmo peça //novamente a quantidade de números e repita este procedimento até que o usuário forneça um número positivo. { Solução em Portugol Algoritmo Exercicio 77; Var vet: vetor[1..10000] de real; maior: Real; N,i,quantidade_maior: inteiro; Inicio exiba("Programa que lê N números, diz qual o maior deles e quantas vezes foi digitado."); exiba("Digite a quantidade de números que serão lidos: "); leia(N); enquanto(N <= 0)faça exiba("Digite um número positivo."); leia(N): fimenquanto; quantidade_maior <- 0; para i <- 1 até N faça exiba("Digite o ",i,"º número:"); leia(vet[i]); se(i = 1) então Inicio maior <- vet[i]; quantidade_maior <- 1; Fim senão se(vet[i] = maior) então quantidade_maior <- quantidade_maior + 1 senão se(vet[i] > maior) então Inicio maior <- vet[i]; quantidade_maior <- 1; Fim; fimse; fimse; fimse; fimpara; exiba("O maior número é: ",maior," e aparece ",quantidade_maior," vezes."); Fim. } // Solução em Pascal Program Exercicio77; uses crt; var vet: array[1..10000] of real; maior: Real; N,i,quantidade_maior: integer; begin clrscr; writeln('Programa que lê N números, diz qual o maior deles e quantas vezes foi digitado.'); WriteLn('Digite a quantidade de números que serão lidos: '); readln(N); while(N <= 0)do Begin writeln('Digite um número positivo.'); readln(N); End; quantidade_maior := 0; for i := 1 to N do Begin WriteLn('Digite o ',i,'º número:'); Readln(vet[i]); if(i = 1) then Begin maior := vet[i]; quantidade_maior := 1; End else if(vet[i] = maior) then quantidade_maior := quantidade_maior + 1 else if(vet[i] > maior) then Begin maior := vet[i]; quantidade_maior := 1; End; End; WriteLn('O maior número é: ',maior:0:2,' e aparece ',quantidade_maior,' vezes.'); repeat until keypressed; end.
{ *************************************************************************** Copyright (c) 2016-2022 Kike Pérez Unit : Quick.Threads Description : Thread safe collections Author : Kike Pérez Version : 1.5 Created : 09/03/2018 Modified : 14/06/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** 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 Quick.Threads; {$i QuickLib.inc} interface uses Classes, Types, SysUtils, DateUtils, Quick.Commons, //Quick.Chrono, Quick.Value, Quick.FaultControl, {$IFNDEF FPC} System.RTLConsts, System.Generics.Collections, System.SyncObjs; {$ELSE} RtlConsts, Generics.Collections, syncobjs; {$ENDIF} type TThreadedQueueCS<T> = class private FQueue: array of T; FQueueSize, FQueueOffset: Integer; FQueueLock: TCriticalSection; {$IFDEF FPC} FQueueCondVar : TEventObject; {$ELSE} FQueueCondVar: TConditionVariableCS; {$ENDIF} FShutDown: Boolean; FPushTimeout, FPopTimeout: Cardinal; FTotalItemsPushed, FTotalItemsPopped: Cardinal; public constructor Create(AQueueDepth: Integer = 16; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE); destructor Destroy; override; procedure Grow(ADelta: Integer); function PushItem(const AItem: T): TWaitResult; overload; function PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; overload; function PopItem: T; overload; function PopItem(var AQueueSize: Integer): T; overload; function PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; overload; function PopItem(var AItem: T): TWaitResult; overload; procedure DoShutDown; procedure Clear; property QueueSize: Integer read FQueueSize; property ShutDown: Boolean read FShutDown; property TotalItemsPushed: Cardinal read FTotalItemsPushed; property TotalItemsPopped: Cardinal read FTotalItemsPopped; end; TThreadedQueueList<T> = class private fQueue : TQueue<T>; fQueueSize : Integer; fQueueLock : TCriticalSection; {$IFDEF FPC} FQueueCondVar : TSimpleEvent; {$ELSE} FQueueCondVar: TConditionVariableCS; {$ENDIF} fShutDown : Boolean; fPushTimeout : Cardinal; fPopTimeout : Cardinal; fTotalItemsPushed : Cardinal; fTotalItemsPopped : Cardinal; public constructor Create(AQueueDepth: Integer = 10; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE); destructor Destroy; override; procedure Grow(ADelta: Integer); function PushItem(const AItem: T): TWaitResult; overload; function PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; overload; function PopItem: T; overload; function PopItem(var AQueueSize: Integer): T; overload; function PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; overload; function PopItem(var AItem: T): TWaitResult; overload; procedure DoShutDown; property QueueSize: Integer read FQueueSize; property ShutDown: Boolean read FShutDown; property TotalItemsPushed: Cardinal read FTotalItemsPushed; property TotalItemsPopped: Cardinal read FTotalItemsPopped; end; {$IFNDEF FPC} TThreadObjectList<T: class> = class(TList<T>) private fList: TObjectList<T>; fLock: TObject; fDuplicates: TDuplicates; function GetItem(aIndex : Integer) : T; procedure SetItem(aIndex : Integer; aValue : T); public constructor Create(OwnedObjects : Boolean); destructor Destroy; override; property Items[Index : Integer] : T read GetItem write SetItem ; default; procedure Add(const Item: T); procedure Clear; function LockList: TObjectList<T>; procedure Remove(const Item: T); inline; procedure RemoveItem(const Item: T; Direction: TDirection); procedure UnlockList; inline; property Duplicates: TDuplicates read fDuplicates write fDuplicates; end; {$ENDIF} {$IFNDEF FPC} TAnonExceptionProc = reference to procedure(aException : Exception); TAnonProc = TProc; {$ELSE} TProc = procedure of object; TAnonExceptionProc = procedure(aException : Exception) of object; {$ENDIF} TThreadWorkStatus = (wsRunning, wsDone, wsException); TSimpleThread = class(TThread) private fExecuteProc : TProc; {$IFNDEF FPC} fTimeoutFlag : TLightweightEvent; {$ELSE} fTimeoutFlag : TSimpleEvent; {$ENDIF} public constructor Create(aProc: TProc; aCreateSuspended, aFreeOnTerminate : Boolean); destructor Destroy; override; procedure Execute; override; function WaitFor(const aTimeout : Cardinal) : TWaitResult; overload; end; TAdvThread = class(TThread) private fExecuteProc : TProc; fExceptionProc : TAnonExceptionProc; fTerminateProc : TProc; fExecuteWithSync : Boolean; fTerminateWithSync : Boolean; procedure DoExecute; procedure CallToTerminate; protected procedure DoTerminate; override; public constructor Create(aProc : TProc; aSynchronize : Boolean); procedure OnException(aProc : TAnonExceptionProc); procedure OnTerminate(aProc : TProc; aSynchronize : Boolean); procedure Execute; override; end; IAnonymousThread = interface procedure Start; function OnException(aProc : TAnonExceptionProc) : IAnonymousThread; function OnTerminate(aProc : TProc) : IAnonymousThread; function OnTerminate_Sync(aProc : TProc) : IAnonymousThread; end; TAnonymousThread = class(TInterfacedObject,IAnonymousThread) private fThread : TAdvThread; constructor Create(aProc : TProc; aSynchronize : Boolean); public class function Execute(aProc : TProc) : IAnonymousThread; overload; class function Execute_Sync(aProc : TProc) : IAnonymousThread; overload; procedure Start; function OnException(aProc : TAnonExceptionProc) : IAnonymousThread; function OnTerminate(aProc : TProc) : IAnonymousThread; overload; function OnTerminate_Sync(aProc : TProc) : IAnonymousThread; overload; end; TParamValue = class private fName : string; fValue : TFlexValue; fOwned : Boolean; public constructor Create; overload; constructor Create(const aName : string; aValue : TFlexValue; aOwnedValue : Boolean); overload; constructor Create(const aName: string; aValue: TVarRec; aOwnedValue: Boolean); overload; destructor Destroy; override; property Name : string read fName write fName; property Value : TFlexValue read fValue write fValue; property Owned : Boolean read fOwned write fOwned; end; TParamList = TObjectList<TParamValue>; TWorkTaskStatus = (wtsPending, wtsAssigned, wtsRunning, wtsDone, wtsException); TScheduleMode = (smRunOnce, smRepeatMode); TTimeMeasure = (tmDays, tmHours, tmMinutes, tmSeconds, tmMilliseconds); ETaskAddError = class(Exception); ETaskInitializationError = class(Exception); ETaskExecutionError = class(Exception); ETaskParamError = class(Exception); ETaskSchedulerError = class(Exception); ITask = interface ['{0182FD36-5A7C-4C00-BBF8-7CFB1E3F9BB1}'] function GetParam(aIndex : Integer) : TFlexValue; overload; function GetParam(const aName : string) : TFlexValue; overload; function GetParam2(aIndex : Integer) : PFlexValue; procedure SetParam(aIndex : Integer; Value : TFlexValue); overload; procedure SetParam(const aName : string; Value : TFlexValue); overload; function TaskStatus : TWorkTaskStatus; function GetNumWorker : Integer; procedure SetNumWorker(Value : Integer); function GetIdTask : Int64; procedure SetIdTask(Value : Int64); function GetResult : TFlexValue; procedure SetResult(aValue : TFlexValue); procedure DoExecute; procedure DoException(aException : Exception); procedure DoTerminate; procedure Enable; procedure Disable; {$IFNDEF FPC} property Param[index : Integer] : TFlexValue read GetParam write SetParam; default; property Param[const Name : string] : TFlexValue read GetParam write SetParam; default; {$ELSE} property Param[index : Integer] : TFlexValue read GetParam write SetParam; property ParamByName[const Name : string] : TFlexValue read GetParam write SetParam; default; {$ENDIF} property NumWorker : Integer read GetNumWorker write SetNumWorker; property Result : TFlexValue read GetResult write SetResult; property IdTask : Int64 read GetIdTask; function Done : Boolean; function Failed : Boolean; function NumRetries : Integer; function MaxRetries : Integer; function LastException : Exception; function CircuitBreaked : Boolean; function IsEnabled : Boolean; end; {$IFNDEF FPC} TTaskProc = reference to procedure(task : ITask); TTaskExceptionProc = reference to procedure(task : ITask; aException : Exception); TTaskRetryProc = reference to procedure(task : ITask; aException : Exception; var aStopRetries : Boolean); {$ELSE} TTaskProc = procedure(task : ITask) of object; TTaskExceptionProc = procedure(task : ITask; aException : Exception) of object; TTaskRetryProc = procedure(task : ITask; aException : Exception; var aStopRetries : Boolean) of object; {$ENDIF} IWorkTask = interface(ITask) function OnInitialize(aTaskProc : TTaskProc) : IWorkTask; function OnException(aTaskProc : TTaskExceptionProc) : IWorkTask; function OnException_Sync(aTaskProc : TTaskExceptionProc) : IWorkTask; function OnRetry(aTaskProc : TTaskRetryProc) : IWorkTask; function OnTerminated(aTaskProc : TTaskProc) : IWorkTask; function OnTerminated_Sync(aTaskProc : TTaskProc) : IWorkTask; function Retry(aMaxRetries : Integer) : IWorkTask; function RetryForever : IWorkTask; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload; function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IWorkTask; overload; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload; function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IWorkTask; overload; function SetParameter(const aName : string; aValue : TFlexValue) : IWorkTask; overload; procedure Run; end; IScheduledTask = interface(ITask) ['{AE551638-ECDE-4F64-89BF-F07BFCB9C9F7}'] function OnInitialize(aTaskProc : TTaskProc) : IScheduledTask; function OnException(aTaskProc : TTaskExceptionProc) : IScheduledTask; function OnException_Sync(aTaskProc : TTaskExceptionProc) : IScheduledTask; function OnRetry(aTaskProc : TTaskRetryProc) : IScheduledTask; function OnTerminated(aTaskProc : TTaskProc) : IScheduledTask; function OnTerminated_Sync(aTaskProc : TTaskProc) : IScheduledTask; function OnExpired(aTaskProc : TTaskProc) : IScheduledTask; function OnExpired_Sync(aTaskProc : TTaskProc) : IScheduledTask; function Retry(aMaxRetries : Integer) : IScheduledTask; function RetryForever : IScheduledTask; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload; function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IScheduledTask; overload; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload; function CheckSchedule : Boolean; procedure DoExpire; function GetTaskName : string; function StartAt(aStartDate : TDateTime) : IScheduledTask; function StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask; function StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask; function StartOnDayChange : IScheduledTask; function StartNow : IScheduledTask; function StartInMinutes(aMinutes : Word) : IScheduledTask; function StartInSeconds(aSeconds : Word) : IScheduledTask; procedure RunOnce; procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure); overload; procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); overload; procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); overload; procedure RepeatEveryDay; procedure RepeatEveryWeek; function IsFinished : Boolean; procedure Cancel; property Name : string read GetTaskName; function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IScheduledTask; overload; function SetParameter(const aName : string; aValue : TFlexValue) : IScheduledTask; overload; end; TTask = class(TInterfacedObject,ITask) private fIdTask : Int64; fNumWorker : Integer; fNumRetries : Integer; fParamList : TParamList; fInitializeProc : TTaskProc; fExecuteProc : TTaskProc; fExceptProc : TTaskExceptionProc; fTerminateProc : TTaskProc; fExpiredProc : TTaskProc; fTaskStatus : TWorkTaskStatus; fOwnedParams : Boolean; fEnabled : Boolean; fExecuteWithSync : Boolean; fExceptionWithSync : Boolean; fRetryProc : TTaskRetryProc; fTerminateWithSync : Boolean; fFaultControl : TFaultControl; fCustomFaultPolicy : Boolean; fResult : TFlexValue; function GetParam(aIndex : Integer) : TFlexValue; overload; function GetParam(const aName : string) : TFlexValue; overload; function GetParam2(aIndex : Integer) : PFlexValue; procedure SetParam(aIndex : Integer; Value : TFlexValue); overload; procedure SetParam(const aName : string; Value : TFlexValue); overload; procedure SetParam(const aName : string; Value : TFlexValue; aOwned : Boolean); overload; procedure DoInitialize; procedure DoExecute; procedure DoException(aException : Exception); procedure DoTerminate; function GetNumWorker : Integer; procedure SetNumWorker(Value : Integer); function GetIdTask : Int64; procedure SetIdTask(Value : Int64); function GetResult : TFlexValue; procedure SetResult(aValue : TFlexValue); protected property FaultControl : TFaultControl read fFaultControl write fFaultControl; property CustomFaultPolicy : Boolean read fCustomFaultPolicy write fCustomFaultPolicy; property ExecuteWithSync : Boolean read fExecuteWithSync write fExecuteWithSync; property TerminateWithSync : Boolean read fTerminateWithSync write fTerminateWithSync; property ExceptionWithSync : Boolean read fExceptionWithSync write fExceptionWithSync; procedure DoRetry(aRaisedException : Exception; var vStopRetries : Boolean); procedure SetFaultPolicy(aFaultPolicy : TFaultPolicy); procedure SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double); overload; procedure SetRetryPolicy(aWaitTimeMSArray : TArray<Integer>); overload; public constructor Create(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc); virtual; destructor Destroy; override; property IdTask : Int64 read GetIdTask; property OwnedParams : Boolean read fOwnedParams write fOwnedParams; function IsEnabled : Boolean; function TaskStatus : TWorkTaskStatus; function Done : Boolean; function Failed : Boolean; function NumRetries : Integer; function MaxRetries : Integer; function LastException : Exception; function CircuitBreaked : Boolean; procedure Disable; procedure Enable; end; TWorkTask = class(TTask,IWorkTask) public function OnInitialize(aTaskProc : TTaskProc) : IWorkTask; function OnException(aTaskProc : TTaskExceptionProc) : IWorkTask; virtual; function OnException_Sync(aTaskProc : TTaskExceptionProc) : IWorkTask; virtual; function OnTerminated(aTaskProc : TTaskProc) : IWorkTask; virtual; function OnTerminated_Sync(aTaskProc : TTaskProc) : IWorkTask; virtual; function OnRetry(aTaskProc : TTaskRetryProc) : IWorkTask; virtual; function Retry(aMaxRetries : Integer) : IWorkTask; function RetryForever : IWorkTask; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload; function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IWorkTask; overload; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IWorkTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IWorkTask; overload; function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IWorkTask; overload; function SetParameter(const aName : string; aValue : TFlexValue) : IWorkTask; overload; procedure Run; virtual; end; TTaskQueue = TThreadedQueueCS<IWorkTask>; TScheduledTask = class(TTask,IScheduledTask) private fName : string; fExecutionTimes : Integer; fScheduleMode : TScheduleMode; fTimeInterval : Integer; fTimeMeasure : TTimeMeasure; fStartDate : TDateTime; fLastExecution : TDateTime; fNextExecution : TDateTime; fExpirationDate : TDateTime; fExpirationTimes : Integer; fFinished : Boolean; fExpireWithSync: Boolean; procedure ClearSchedule; function CheckSchedule : Boolean; procedure DoExpire; function GetTaskName : string; function GetCurrentSchedule: TPair<TTimeMeasure, Integer>; protected property ExpireWithSync : Boolean read fExpireWithSync write fExpireWithSync; public property Name : string read fName write fName; function OnInitialize(aTaskProc : TTaskProc) : IScheduledTask; property CurrentSchedule : TPair<TTimeMeasure, Integer> read GetCurrentSchedule; function OnException(aTaskProc : TTaskExceptionProc) : IScheduledTask; virtual; function OnException_Sync(aTaskProc : TTaskExceptionProc) : IScheduledTask; virtual; function OnRetry(aTaskProc : TTaskRetryProc) : IScheduledTask; virtual; function OnTerminated(aTaskProc : TTaskProc) : IScheduledTask; virtual; function OnTerminated_Sync(aTaskProc : TTaskProc) : IScheduledTask; virtual; function OnExpired(aTaskProc : TTaskProc) : IScheduledTask; virtual; function OnExpired_Sync(aTaskProc : TTaskProc) : IScheduledTask; virtual; function StartAt(aStartDate : TDateTime) : IScheduledTask; function StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask; function StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask; function StartOnDayChange : IScheduledTask; function StartNow : IScheduledTask; function StartInMinutes(aMinutes : Word) : IScheduledTask; function StartInSeconds(aSeconds : Word) : IScheduledTask; procedure RunOnce; procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure); overload; procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); overload; procedure RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); overload; procedure RepeatEveryDay; procedure RepeatEveryWeek; function Retry(aMaxRetries : Integer) : IScheduledTask; function RetryForever : IScheduledTask; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload; function WaitAndRetry(aWaitTimeArray : TArray<Integer>) : IScheduledTask; overload; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : IScheduledTask; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : IScheduledTask; overload; function SetParameter(const aName : string; aValue : TFlexValue; aOwned : Boolean) : IScheduledTask; overload; function SetParameter(const aName : string; aValue : TFlexValue) : IScheduledTask; overload; function IsFinished : Boolean; procedure Cancel; end; TWorkerStatus = (wsIdle, wsWorking, wsSuspended); TWorker = class(TThread) protected fStatus : TWorkerStatus; fCurrentTask : ITask; fDefaultFaultPolicy : TFaultPolicy; procedure ExecuteTask; procedure TerminateTask; public constructor Create; destructor Destroy; override; property Status : TWorkerStatus read fStatus; procedure SetFaultPolicy(aTask : TTask); procedure Execute; override; end; TSimpleWorker = class(TWorker) private fRunOnce : Boolean; public constructor Create(aTask : ITask; aRunOnce : Boolean = True); procedure Execute; override; end; TQueueWorker = class(TWorker) private fCurrentIdTask : Integer; fNumWorker : Integer; fTaskQueue : TTaskQueue; public constructor Create(aNumWorker : Integer; aTaskQueue : TTaskQueue); property NumWorker : Integer read fNumWorker; procedure Execute; override; end; TScheduledWorker = class(TWorker) private procedure ExpireTask; public constructor Create(aNumWorker : Integer; aScheduledTask: IScheduledTask); procedure Execute; override; end; TWorkerPool = TObjectList<TWorker>; TRunTask = class public class function Execute(aTaskProc: TTaskProc): IWorkTask; overload; class function Execute(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; overload; class function Execute_Sync(aTaskProc: TTaskProc): IWorkTask; overload; class function Execute_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; overload; end; IAsyncTask = interface ['{90A27D06-6FCD-493C-8AA0-C52C5105ED8B}'] procedure Wait; overload; procedure Wait(const aTimeout : Cardinal); overload; end; TAsyncTask = class(TInterfacedObject,IAsyncTask) private fProcess : TSimpleThread; constructor Create(aAction : TProc); public class function Run(const aAction : TProc) : IAsyncTask; virtual; procedure Wait; overload; procedure Wait(const aTimeout : Cardinal); overload; destructor Destroy; override; end; {$IFNDEF FPC} IAsyncTask<T> = interface ['{8529BBD4-B5AD-4674-8E42-3C74F5156A97}'] function Result : T; overload; function Result(const aTimeout : Cardinal) : T; overload; end; TAsyncTask<T> = class(TInterfacedObject,IAsyncTask<T>) private fProcess : TSimpleThread; fTaskResult : T; fWaitForResult : Boolean; function Result : T; overload; function Result(const aTimeout : Cardinal) : T; overload; constructor Create(aAction : TFunc<T>); public class function Run(const aAction : TFunc<T>) : IAsyncTask<T>; virtual; destructor Destroy; override; end; {$ENDIF} TBackgroundTasks = class private fMaxQueue : Integer; fWorkerPool : TWorkerPool; fConcurrentWorkers : Integer; fInsertTimeout : Cardinal; fExtractTimeout : Cardinal; fTaskQueue : TTaskQueue; fNumPushedTasks : Int64; function GetTaskQueue : Cardinal; public constructor Create(aConcurrentWorkers : Integer; aInitialQueueSize : Integer = 100); destructor Destroy; override; property MaxQueue : Integer read fMaxQueue write fMaxQueue; property InsertTimeout : Cardinal read fInsertTimeout write fInsertTimeout; property ExtractTimeout : Cardinal read fExtractTimeout write fExtractTimeout; property TaskQueued : Cardinal read GetTaskQueue; property NumPushedTasks : Int64 read fNumPushedTasks; property ConcurrentWorkers : Integer read fConcurrentWorkers write fConcurrentWorkers; function AddTask(aTaskProc : TTaskProc) : IWorkTask; overload; function AddTask_Sync(aTaskProc : TTaskProc) : IWorkTask; overload; function AddTask(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; overload; function AddTask_Sync(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; overload; procedure Start; procedure CancelAll; end; TScheduledTaskList = TList<IScheduledTask>; TScheduler = class(TThread) private fListLock : TCriticalSection; fCondVar : TSimpleEvent; fTaskList : TScheduledTaskList; fRemoveTaskAfterExpiration : Boolean; public constructor Create(aTaskList : TScheduledTaskList); destructor Destroy; override; property RemoveTaskAfterExpiration : Boolean read fRemoveTaskAfterExpiration write fRemoveTaskAfterExpiration; procedure Execute; override; function Add(aTask : TScheduledTask) : Integer; function Get(aIdTask : Int64) : IScheduledTask; overload; function Get(const aTaskName : string) : IScheduledTask; overload; end; TScheduledTasks = class private fTaskList : TScheduledTaskList; fScheduler : TScheduler; fNumPushedTasks : Int64; fRemoveTaskAfterExpiration : Boolean; fIsStarted : Boolean; fFaultPolicy : TFaultPolicy; public constructor Create; destructor Destroy; override; property NumPushedTasks : Int64 read fNumPushedTasks; property RemoveTaskAfterExpiration : Boolean read fRemoveTaskAfterExpiration write fRemoveTaskAfterExpiration; property IsStarted : Boolean read fIsStarted; property FaultPolicy : TFaultPolicy read fFaultPolicy write fFaultPolicy; function AddTask(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; overload; function AddTask_Sync(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; overload; function AddTask(const aTaskName : string; aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IScheduledTask; overload; function AddTask_Sync(const aTaskName : string; aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IScheduledTask; overload; function GetTask(aIdTask : Int64) : IScheduledTask; overload; function GetTask(const aTaskName : string) : IScheduledTask; overload; procedure Start; procedure Stop; end; TBackgroundWorkers = class private fWorkerPool : TWorkerPool; fConcurrentWorkers : Integer; fWorkerInitProc : TTaskProc; fWorkerExecuteProc : TTaskProc; fWorkerRetryProc : TTaskRetryProc; fWorkerExceptionProc : TTaskExceptionProc; fWorkerTerminateProc : TTaskProc; fFaultPolicy : TFaultPolicy; procedure SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor: Double); public constructor Create(aConcurrentWorkers : Integer; aWorkerProc : TTaskProc); destructor Destroy; override; property ConcurrentWorkers : Integer read fConcurrentWorkers; function OnInitialize(aTaskProc : TTaskProc) : TBackgroundWorkers; function OnException(aTaskProc : TTaskExceptionProc) : TBackgroundWorkers; function OnRetry(aTaskProc : TTaskRetryProc) : TBackgroundWorkers; function OnTerminated(aTaskProc : TTaskProc) : TBackgroundWorkers; function Retry(aMaxRetries : Integer) : TBackgroundWorkers; function RetryForever : TBackgroundWorkers; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer) : TBackgroundWorkers; overload; function WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : TBackgroundWorkers; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer) : TBackgroundWorkers; overload; function WaitAndRetryForever(aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor : Double) : TBackgroundWorkers; overload; procedure Start; procedure Stop; end; implementation { TThreadedQueueCS<T> } procedure TThreadedQueueCS<T>.Clear; var obj : T; begin FQueueLock.Enter; try for obj in FQueue do begin if TypeInfo(T) = TypeInfo(TObject) then PObject(@obj){$IFNDEF FPC}.DisposeOf;{$ELSE}.Free;{$ENDIF} end; SetLength(FQueue,0); finally FQueueLock.Leave; end; {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; constructor TThreadedQueueCS<T>.Create(AQueueDepth: Integer = 16; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE); begin inherited Create; if AQueueDepth < 10 then raise Exception.Create('QueueDepth will be 10 or greater value'); SetLength(FQueue, AQueueDepth); FQueueLock := TCriticalSection.Create; {$IFDEF FPC} FQueueCondVar := TEventObject.Create(nil, True, False, 'TQCS'); {$ELSE} FQueueCondVar := TConditionVariableCS.Create; {$ENDIF} FPushTimeout := PushTimeout; FPopTimeout := PopTimeout; end; destructor TThreadedQueueCS<T>.Destroy; begin DoShutDown; FQueueLock.Free; FQueueCondVar.Free; inherited; end; procedure TThreadedQueueCS<T>.Grow(ADelta: Integer); begin FQueueLock.Enter; try SetLength(FQueue, Length(FQueue) + ADelta); finally FQueueLock.Leave; end; {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; function TThreadedQueueCS<T>.PopItem: T; var LQueueSize: Integer; begin PopItem(LQueueSize, Result); end; function TThreadedQueueCS<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; begin AItem := Default(T); FQueueLock.Enter; try Result := wrSignaled; while (Result = wrSignaled) and (FQueueSize = 0) and not FShutDown do begin {$IFDEF FPC} Result := FQueueCondVar.WaitFor(FPopTimeout); {$ELSE} Result := FQueueCondVar.WaitFor(FQueueLock, FPopTimeout); {$ENDIF} end; if (FShutDown and (FQueueSize = 0)) or (Result <> wrSignaled) then Exit; AItem := FQueue[FQueueOffset]; FQueue[FQueueOffset] := Default(T); if FQueueSize = Length(FQueue) then begin {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; Dec(FQueueSize); Inc(FQueueOffset); Inc(FTotalItemsPopped); if FQueueOffset = Length(FQueue) then FQueueOffset := 0; finally AQueueSize := FQueueSize; FQueueLock.Leave; end; end; function TThreadedQueueCS<T>.PopItem(var AItem: T): TWaitResult; var LQueueSize: Integer; begin Result := PopItem(LQueueSize, AItem); end; function TThreadedQueueCS<T>.PopItem(var AQueueSize: Integer): T; begin PopItem(AQueueSize, Result); end; function TThreadedQueueCS<T>.PushItem(const AItem: T): TWaitResult; var LQueueSize: Integer; begin Result := PushItem(AItem, LQueueSize); end; function TThreadedQueueCS<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; begin FQueueLock.Enter; try if FQueueSize >= High(FQueue) then begin if FQueueSize < 1024 then Grow(FQueueSize) else Grow(FQueueSize Div 2); end; Result := wrSignaled; while (Result = wrSignaled) and (FQueueSize = Length(FQueue)) and not FShutDown do begin {$IFDEF FPC} Result := FQueueCondVar.WaitFor(FPushTimeout); {$ELSE} Result := FQueueCondVar.WaitFor(FQueueLock, FPushTimeout); {$ENDIF} end; if FShutDown or (Result <> wrSignaled) then Exit; if FQueueSize = 0 then begin {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; FQueue[(FQueueOffset + FQueueSize) mod Length(FQueue)] := AItem; Inc(FQueueSize); Inc(FTotalItemsPushed); finally AQueueSize := FQueueSize; FQueueLock.Leave; end; end; procedure TThreadedQueueCS<T>.DoShutDown; begin FShutDown := True; {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; { TThreadedQueueList<T> } constructor TThreadedQueueList<T>.Create(AQueueDepth: Integer = 10; PushTimeout: Cardinal = INFINITE; PopTimeout: Cardinal = INFINITE); begin inherited Create; fQueue := TQueue<T>.Create; fQueue.Capacity := AQueueDepth; fQueueSize := 0; fQueueLock := TCriticalSection.Create; {$IFDEF FPC} FQueueCondVar := TSimpleEvent.Create; //TEventObject.Create(nil, False, False, 'TQL'); {$ELSE} fQueueCondVar := TConditionVariableCS.Create; {$ENDIF} fPushTimeout := PushTimeout; fPopTimeout := PopTimeout; end; destructor TThreadedQueueList<T>.Destroy; begin DoShutDown; fQueueCondVar.Free; fQueueLock.Free; //fQueueCondVar.Free; fQueue.Free; inherited; end; procedure TThreadedQueueList<T>.Grow(ADelta: Integer); begin fQueueLock.Enter; try fQueue.Capacity := fQueue.Capacity + ADelta; finally fQueueLock.Leave; end; {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; function TThreadedQueueList<T>.PopItem: T; var LQueueSize: Integer; begin PopItem(LQueueSize, Result); end; {$IFDEF FPC} function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; //var //crono : TChronometer; begin AItem := Default(T); //crono := TChronometer.Create(False); try Result := wrSignaled; //writeln('popitem'); //crono.Start; while (Result = wrSignaled) and (fQueueSize = 0) and not fShutDown do begin //crono.Start; Result := FQueueCondVar.WaitFor(FPopTimeout); //crono.Stop; //writeln('in: ' + crono.ElapsedTime); //if result = twaitresult.wrError then result := twaitresult.wrError; end; //crono.Stop; //writeln('out: ' + crono.ElapsedTime); fQueueLock.Enter; try if (FShutDown and (fQueueSize = 0)) or (Result <> wrSignaled) then Exit; AItem := fQueue.Extract; Dec(FQueueSize); Inc(fTotalItemsPopped); finally fQueueLock.Leave; end; finally AQueueSize := fQueueSize; end; end; {$ELSE} function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer; var AItem: T): TWaitResult; begin AItem := Default(T); fQueueLock.Enter; try Result := wrSignaled; while (Result = wrSignaled) and (fQueueSize = 0) and not fShutDown do begin Result := FQueueCondVar.WaitFor(FQueueLock, FPopTimeout); end; if (FShutDown and (fQueueSize = 0)) or (Result <> wrSignaled) then Exit; AItem := fQueue.Extract; if fQueueSize = fQueue.Count then begin FQueueCondVar.ReleaseAll; end; Dec(FQueueSize); Inc(fTotalItemsPopped); finally AQueueSize := fQueueSize; fQueueLock.Leave; end; end; {$ENDIF} function TThreadedQueueList<T>.PopItem(var AItem: T): TWaitResult; var LQueueSize: Integer; begin Result := PopItem(LQueueSize, AItem); end; function TThreadedQueueList<T>.PopItem(var AQueueSize: Integer): T; begin PopItem(AQueueSize, Result); end; function TThreadedQueueList<T>.PushItem(const AItem: T): TWaitResult; var LQueueSize: Integer; begin Result := PushItem(AItem, LQueueSize); end; {$IFDEF FPC} function TThreadedQueueList<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; begin FQueueLock.Enter; try if FQueueSize >= fQueue.Count then Grow(10); Result := wrSignaled; //while (Result = wrSignaled) and (fQueueSize = fQueue.Count) and not fShutDown do //begin // Result := fQueueCondVar.WaitFor(fQueueLock, fPushTimeout); //end; if fShutDown or (Result <> wrSignaled) then Exit; //if fQueueSize = 0 then //begin // FQueueCondVar.SetEvent; //end; fQueue.Enqueue(AItem); Inc(FQueueSize); Inc(fTotalItemsPushed); finally AQueueSize := fQueueSize; FQueueLock.Leave; //FQueueCondVar.SetEvent; end; end; {$ELSE} function TThreadedQueueList<T>.PushItem(const AItem: T; var AQueueSize: Integer): TWaitResult; begin FQueueLock.Enter; try Result := wrSignaled; //while (Result = wrSignaled) and (fQueueSize = fQueue.Count) and not fShutDown do //begin // Result := fQueueCondVar.WaitFor(fQueueLock, fPushTimeout); //end; if fShutDown or (Result <> wrSignaled) then Exit; if fQueueSize = 0 then FQueueCondVar.ReleaseAll; fQueue.Enqueue(AItem); Inc(FQueueSize); Inc(fTotalItemsPushed); finally AQueueSize := fQueueSize; FQueueLock.Leave; end; end; {$ENDIF} procedure TThreadedQueueList<T>.DoShutDown; begin fShutDown := True; {$IFDEF FPC} FQueueCondVar.SetEvent; {$ELSE} FQueueCondVar.ReleaseAll; {$ENDIF} end; {$IFNDEF FPC} { TThreadObjectList<T> } procedure TThreadObjectList<T>.Add(const Item: T); begin LockList; try if (Duplicates = dupAccept) or (fList.IndexOf(Item) = -1) then fList.Add(Item) else if Duplicates = dupError then raise EListError.CreateFmt(SDuplicateItem, [fList.ItemValue(Item)]); finally UnlockList; end; end; procedure TThreadObjectList<T>.Clear; begin LockList; try fList.Clear; finally UnlockList; end; end; constructor TThreadObjectList<T>.Create(OwnedObjects : Boolean); begin inherited Create; fLock := TObject.Create; fList := TObjectList<T>.Create; fDuplicates := dupIgnore; end; destructor TThreadObjectList<T>.Destroy; begin LockList; try fList.Free; inherited Destroy; finally UnlockList; fLock.Free; end; end; function TThreadObjectList<T>.GetItem(aIndex: Integer): T; begin LockList; try Result := fList[aIndex]; finally UnlockList; end; end; function TThreadObjectList<T>.LockList: TObjectList<T>; begin System.TMonitor.Enter(fLock); Result := fList; end; procedure TThreadObjectList<T>.Remove(const Item: T); begin RemoveItem(Item, TDirection.FromBeginning); end; procedure TThreadObjectList<T>.RemoveItem(const Item: T; Direction: TDirection); begin LockList; try fList.RemoveItem(Item, Direction); finally UnlockList; end; end; procedure TThreadObjectList<T>.SetItem(aIndex: Integer; aValue: T); begin LockList; try fList[aIndex] := aValue; finally UnlockList; end; end; procedure TThreadObjectList<T>.UnlockList; begin System.TMonitor.Exit(fLock); end; {$ENDIF} { TAnonymousThread } constructor TAnonymousThread.Create(aProc : TProc; aSynchronize : Boolean); begin fThread := TAdvThread.Create(aProc,aSynchronize); end; class function TAnonymousThread.Execute(aProc: TProc): IAnonymousThread; begin Result := TAnonymousThread.Create(aProc,False); end; class function TAnonymousThread.Execute_Sync(aProc: TProc): IAnonymousThread; begin Result := TAnonymousThread.Create(aProc,True); end; function TAnonymousThread.OnException(aProc: TAnonExceptionProc): IAnonymousThread; begin Result := Self; fThread.OnException(aProc); end; function TAnonymousThread.OnTerminate(aProc: TProc): IAnonymousThread; begin Result := Self; fThread.OnTerminate(aProc,False); end; function TAnonymousThread.OnTerminate_Sync(aProc: TProc): IAnonymousThread; begin Result := Self; fThread.OnTerminate(aProc,True); end; procedure TAnonymousThread.Start; begin fThread.Start; end; { TTask } constructor TTask.Create(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc); var i : Integer; begin fTaskStatus := TWorkTaskStatus.wtsPending; fCustomFaultPolicy := False; fNumRetries := 0; fExecuteWithSync := False; fTerminateWithSync := False; fExceptionWithSync := False; fFaultControl := TFaultControl.Create; fFaultControl.OnRetry := DoRetry; fOwnedParams := aOwnedParams; fParamList := TParamList.Create(True); for i := Low(aParamArray) to High(aParamArray) do begin fParamList.Add(TParamValue.Create(i.ToString,aParamArray[i],aOwnedParams)); {$IFDEF FPC} fParamList[i].Value._AddRef; {$ENDIF} end; fExecuteProc := aTaskProc; fEnabled := False; end; destructor TTask.Destroy; begin fFaultControl.Free; //free passed params fParamList.Free; if (not fResult.IsNullOrEmpty) and (fResult.IsObject) then fResult.AsObject.Free; inherited; end; procedure TTask.Disable; begin fEnabled := False; end; procedure TTask.DoException(aException : Exception); begin fTaskStatus := TWorkTaskStatus.wtsException; if Assigned(fExceptProc) then fExceptProc(Self,aException) else raise aException; end; procedure TTask.DoExecute; begin fTaskStatus := TWorkTaskStatus.wtsRunning; DoInitialize; repeat try if Assigned(fExecuteProc) then fExecuteProc(Self); fTaskStatus := TWorkTaskStatus.wtsDone; fFaultControl.SuccessExecution; except on E : Exception do begin fTaskStatus := TWorkTaskStatus.wtsException; {$IFNDEF FPC} {$IF DELPHIRX10_UP} fFaultControl.FailedExecution(AcquireExceptionObject as Exception); {$ELSE} fFaultControl.FailedExecution(Exception(AcquireExceptionObject)); {$ENDIF} {$ELSE} fFaultControl.FailedExecution(Exception(AcquireExceptionObject)); {$ENDIF} end; end; until not fFaultControl.NeedToRetry; end; procedure TTask.DoInitialize; begin try fFaultControl.Reset; if Assigned(fInitializeProc) then fInitializeProc(Self); except on E : Exception do begin raise ETaskInitializationError.CreateFmt('Task initialization failed: %s',[e.Message]); end; end; end; function TTask.Done: Boolean; begin Result := not fFaultControl.TaskFailed; end; function TTask.Failed: Boolean; begin Result := fFaultControl.TaskFailed; end; function TTask.CircuitBreaked: Boolean; begin Result := fFaultControl.CircuitBreaked; end; function TTask.LastException: Exception; begin Result := fFaultControl.LastException; end; function TTask.MaxRetries: Integer; begin Result := fFaultControl.MaxRetries; end; function TTask.NumRetries: Integer; begin Result := fFaultControl.NumRetries; end; procedure TTask.DoRetry(aRaisedException: Exception; var vStopRetries: Boolean); begin vStopRetries := False; if Assigned(fRetryProc) then fRetryProc(Self,aRaisedException,vStopRetries); end; procedure TTask.DoTerminate; begin if Assigned(fTerminateProc) then fTerminateProc(Self); end; procedure TTask.Enable; begin fEnabled := True; end; function TTask.GetIdTask: Int64; begin Result := fIdTask; end; procedure TTask.SetFaultPolicy(aFaultPolicy: TFaultPolicy); begin {$IFDEF FPC} if not Assigned(fFaultControl) then fFaultControl := TFaultControl.Create; {$ENDIF} fFaultControl.MaxRetries := aFaultPolicy.MaxRetries; fFaultControl.WaitTimeBetweenRetriesMS := aFaultPolicy.WaitTimeBetweenRetries; fFaultControl.WaitTimeMultiplierFactor := aFaultPolicy.WaitTimeMultiplierFactor; end; procedure TTask.SetIdTask(Value : Int64); begin fIdTask := Value; end; function TTask.GetNumWorker: Integer; begin Result := fNumWorker; end; function TTask.GetParam(aIndex: Integer): TFlexValue; begin Result := fParamList[aIndex].Value; end; function TTask.GetParam(const aName: string): TFlexValue; var paramvalue : TParamValue; begin for paramvalue in fParamList do begin if CompareText(paramvalue.Name,aName) = 0 then begin Exit(paramvalue.Value) end; end; //if not exists raise ETaskParamError.CreateFmt('Task param "%s" not found!',[aName]); end; function TTask.GetParam2(aIndex: Integer): PFlexValue; begin Result := @fParamList[aIndex].Value; end; function TTask.GetResult: TFlexValue; begin Result := fResult; end; function TTask.IsEnabled: Boolean; begin Result := fEnabled; end; procedure TTask.SetNumWorker(Value: Integer); begin fTaskStatus := TWorkTaskStatus.wtsAssigned; fNumWorker := Value; end; procedure TTask.SetParam(aIndex: Integer; Value: TFlexValue); begin if aIndex > fParamList.Count then raise ETaskParamError.CreateFmt('Task parameter index(%d) not found',[aIndex]); fParamList[aIndex].Value := Value; end; procedure TTask.SetParam(const aName: string; Value: TFlexValue; aOwned: Boolean); var paramvalue : TParamValue; begin //check if already exists parameter for paramvalue in fParamList do begin if CompareText(paramvalue.Name,aName) = 0 then begin paramvalue.Value := Value; Exit; end; end; //if not exists, create one fParamList.Add(TParamValue.Create(aName,Value,aOwned)); end; procedure TTask.SetParam(const aName: string; Value: TFlexValue); begin SetParam(aName,Value,False); end; procedure TTask.SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS : Integer; aWaitTimeMultiplierFactor: Double); begin fFaultControl.MaxRetries := aMaxRetries; fFaultControl.WaitTimeBetweenRetriesMS := aWaitTimeBetweenRetriesMS; fFaultControl.WaitTimeMultiplierFactor := aWaitTimeMultiplierFactor; fCustomFaultPolicy := True; end; procedure TTask.SetResult(aValue: TFlexValue); begin fResult := aValue; end; procedure TTask.SetRetryPolicy(aWaitTimeMSArray: TArray<Integer>); begin fFaultControl.MaxRetries := High(aWaitTimeMSArray) + 1; fFaultControl.WaitTimeBetweenRetriesMS := 0; fFaultControl.WaitTimeMultiplierFactor := 1; fFaultControl.WaitTimeMSArray := aWaitTimeMSArray; fCustomFaultPolicy := True; end; function TTask.TaskStatus: TWorkTaskStatus; begin Result := fTaskStatus; end; { TWorkTask } function TWorkTask.OnException(aTaskProc : TTaskExceptionProc) : IWorkTask; begin fExceptProc := aTaskProc; Result := Self; end; function TWorkTask.OnException_Sync(aTaskProc: TTaskExceptionProc): IWorkTask; begin fExceptionWithSync := True; Result := OnException(aTaskProc); end; function TWorkTask.OnInitialize(aTaskProc: TTaskProc): IWorkTask; begin fInitializeProc := aTaskProc; Result := Self; end; function TWorkTask.OnRetry(aTaskProc: TTaskRetryProc): IWorkTask; begin fRetryProc := aTaskProc; Result := Self; end; function TWorkTask.OnTerminated(aTaskProc: TTaskProc): IWorkTask; begin fTerminateProc := aTaskProc; Result := Self; end; function TWorkTask.OnTerminated_Sync(aTaskProc: TTaskProc): IWorkTask; begin fTerminateWithSync := True; Result := OnTerminated(aTaskProc); end; procedure TWorkTask.Run; begin fEnabled := True; end; function TWorkTask.SetParameter(const aName: string; aValue: TFlexValue): IWorkTask; begin Result := Self; SetParam(aName,aValue); end; function TWorkTask.SetParameter(const aName: string; aValue: TFlexValue; aOwned: Boolean): IWorkTask; begin Result := Self; SetParam(aName,aValue,aOwned); end; function TWorkTask.Retry(aMaxRetries: Integer): IWorkTask; begin Result := Self; SetRetryPolicy(aMaxRetries,0,1); end; function TWorkTask.RetryForever: IWorkTask; begin Result := Self; SetRetryPolicy(-1,0,1); end; function TWorkTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer): IWorkTask; begin Result := Self; SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,1); end; function TWorkTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor : Double): IWorkTask; begin Result := Self; SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor); end; function TWorkTask.WaitAndRetry(aWaitTimeArray: TArray<Integer>): IWorkTask; begin Result := Self; SetRetryPolicy(aWaitTimeArray); end; function TWorkTask.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer): IWorkTask; begin Result := Self; SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,1); end; function TWorkTask.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double): IWorkTask; begin Result := Self; SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor); end; { TBackgroundTasks } procedure TBackgroundTasks.CancelAll; begin fTaskQueue.Clear; end; constructor TBackgroundTasks.Create(aConcurrentWorkers : Integer; aInitialQueueSize : Integer = 100); begin fMaxQueue := 0; fConcurrentWorkers := aConcurrentWorkers; fInsertTimeout := INFINITE; fExtractTimeout := 5000; fNumPushedTasks := 0; fTaskQueue := TThreadedQueueCS<IWorkTask>.Create(aInitialQueueSize,fInsertTimeout,fExtractTimeout); end; destructor TBackgroundTasks.Destroy; begin CancelAll; fTaskQueue.DoShutDown; //while fTaskQueue.QueueSize > 0 do Sleep(0); if Assigned(fWorkerPool) then fWorkerPool.Free; if Assigned(fTaskQueue) then fTaskQueue.Free; inherited; end; function TBackgroundTasks.GetTaskQueue: Cardinal; begin Result := fTaskQueue.QueueSize; end; function TBackgroundTasks.AddTask(aTaskProc : TTaskProc) : IWorkTask; begin Result := AddTask([],False,aTaskProc); end; function TBackgroundTasks.AddTask(aParamArray : array of const; aOwnedParams : Boolean; aTaskProc : TTaskProc) : IWorkTask; var worktask : IWorkTask; begin if (fMaxQueue > 0) and (fTaskQueue.QueueSize >= fMaxQueue) then raise ETaskAddError.Create('Max queue reached: Task cannot be added'); worktask := TWorkTask.Create(aParamArray,aOwnedParams,aTaskProc); Inc(fNumPushedTasks); worktask.SetIdTask(fNumPushedTasks); if fTaskQueue.PushItem(worktask) = TWaitResult.wrSignaled then begin Result := worktask; end; end; function TBackgroundTasks.AddTask_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; begin Result := AddTask(aParamArray,aOwnedParams,aTaskProc); TTask(Result).ExecuteWithSync := True; end; function TBackgroundTasks.AddTask_Sync(aTaskProc: TTaskProc): IWorkTask; begin Result := AddTask_Sync([],False,aTaskProc); end; procedure TBackgroundTasks.Start; var i : Integer; worker : TWorker; begin //create workers if fWorkerPool <> nil then fWorkerPool.Free; fWorkerPool := TWorkerPool.Create(True); for i := 1 to fConcurrentWorkers do begin worker := TQueueWorker.Create(i,fTaskQueue); fWorkerPool.Add(worker); worker.Start; end; end; { TWorker } constructor TWorker.Create; begin inherited Create(True); fDefaultFaultPolicy := TFaultPolicy.Create; fStatus := TWorkerStatus.wsSuspended; FreeOnTerminate := False; end; destructor TWorker.Destroy; begin if Assigned(fDefaultFaultPolicy) then fDefaultFaultPolicy.Free; inherited; end; procedure TWorker.SetFaultPolicy(aTask: TTask); begin if not aTask.CustomFaultPolicy then aTask.SetFaultPolicy(fDefaultFaultPolicy); end; procedure TWorker.Execute; begin end; procedure TWorker.ExecuteTask; begin fCurrentTask.DoExecute; end; procedure TWorker.TerminateTask; begin fCurrentTask.DoTerminate; end; { TSimpleWorker } constructor TSimpleWorker.Create(aTask : ITask; aRunOnce : Boolean = True); begin inherited Create; fRunOnce := aRunOnce; fCurrentTask := aTask; FreeOnTerminate := True; end; procedure TSimpleWorker.Execute; begin fStatus := TWorkerStatus.wsIdle; while not Terminated do begin if (fCurrentTask <> nil) and (fCurrentTask.IsEnabled) then try fStatus := TWorkerStatus.wsWorking; try SetFaultPolicy(TTask(fCurrentTask)); if TTask(fCurrentTask).ExecuteWithSync then Synchronize(ExecuteTask) else fCurrentTask.DoExecute; except on E : Exception do begin if fCurrentTask <> nil then fCurrentTask.DoException(E) else raise ETaskExecutionError.Create(e.Message); end; end; finally fStatus := TWorkerStatus.wsIdle; try if TTask(fCurrentTask).TerminateWithSync then Synchronize(TerminateTask) else fCurrentTask.DoTerminate; except on E : Exception do if fCurrentTask <> nil then fCurrentTask.DoException(E) end; if fRunOnce then Terminate; end; end; fStatus := TWorkerStatus.wsSuspended end; { TQueueWorker } constructor TQueueWorker.Create(aNumWorker: Integer; aTaskQueue: TTaskQueue); begin inherited Create; fNumWorker := aNumWorker; fTaskQueue := aTaskQueue; end; procedure TQueueWorker.Execute; begin fStatus := TWorkerStatus.wsIdle; while not Terminated do begin fCurrentTask := fTaskQueue.PopItem; if fCurrentTask <> nil then try fStatus := TWorkerStatus.wsWorking; try fCurrentIdTask := fCurrentTask.GetIdTask; SetFaultPolicy(TTask(fCurrentTask)); if TTask(fCurrentTask).ExecuteWithSync then Synchronize(ExecuteTask) else fCurrentTask.DoExecute; except on E : Exception do begin if fCurrentTask <> nil then fCurrentTask.DoException(E) else raise ETaskExecutionError.Create(e.Message); end; end; finally if TTask(fCurrentTask).TerminateWithSync then Synchronize(TerminateTask) else fCurrentTask.DoTerminate; fStatus := TWorkerStatus.wsIdle; end; end; fStatus := TWorkerStatus.wsSuspended end; { TScheduledWorker } constructor TScheduledWorker.Create(aNumWorker : Integer; aScheduledTask: IScheduledTask); begin inherited Create; {$IFNDEF DELPHILINUX} NameThreadForDebugging(aScheduledTask.Name,aScheduledTask.IdTask); {$ENDIF} FreeOnTerminate := True; fCurrentTask := aScheduledTask; end; procedure TScheduledWorker.Execute; begin fStatus := TWorkerStatus.wsIdle; if Assigned(fCurrentTask) then begin try fStatus := TWorkerStatus.wsWorking; try SetFaultPolicy(TTask(fCurrentTask)); if TTask(fCurrentTask).ExecuteWithSync then Synchronize(ExecuteTask) else fCurrentTask.DoExecute; fStatus := TWorkerStatus.wsIdle; except on E : Exception do begin if fCurrentTask <> nil then fCurrentTask.DoException(E) else raise ETaskExecutionError.Create(e.Message); end; end; finally if TTask(fCurrentTask).TerminateWithSync then Synchronize(TerminateTask) else fCurrentTask.DoTerminate; //check if expired if (fCurrentTask as IScheduledTask).IsFinished then begin if TScheduledTask(fCurrentTask).ExpireWithSync then Synchronize(ExpireTask) else (fCurrentTask as IScheduledTask).DoExpire; end; end; end; fCurrentTask := nil; fStatus := TWorkerStatus.wsSuspended; end; procedure TScheduledWorker.ExpireTask; begin (fCurrentTask as IScheduledTask).DoExpire; end; { TScheduledTasks } function TScheduledTasks.AddTask(const aTaskName : string; aTaskProc : TTaskProc) : IScheduledTask; begin Result := AddTask(aTaskName,[],False,aTaskProc); end; function TScheduledTasks.AddTask(const aTaskName : string; aParamArray: array of const; aOwnedParams : Boolean; aTaskProc: TTaskProc): IScheduledTask; var scheduletask : TScheduledTask; begin scheduletask := TScheduledTask.Create(aParamArray,aOwnedParams,aTaskProc); scheduletask.Name := aTaskName; Inc(fNumPushedTasks); scheduletask.SetIdTask(fNumPushedTasks); fTaskList.Add(scheduletask); Result := scheduletask; end; function TScheduledTasks.AddTask_Sync(const aTaskName: string; aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IScheduledTask; begin Result := AddTask(aTaskName,aParamArray,aOwnedParams,aTaskProc); TTask(Result).ExecuteWithSync := True; end; function TScheduledTasks.AddTask_Sync(const aTaskName: string; aTaskProc: TTaskProc): IScheduledTask; begin Result := AddTask_Sync(aTaskName,[],False,aTaskProc); end; constructor TScheduledTasks.Create; begin fNumPushedTasks := 0; fIsStarted := False; fFaultPolicy := TFaultPolicy.Create; fTaskList := TScheduledTaskList.Create; end; destructor TScheduledTasks.Destroy; begin if Assigned(fScheduler) then begin fScheduler.Terminate; fScheduler.WaitFor; fScheduler.Free; end; if Assigned(fTaskList) then fTaskList.Free; if Assigned(fFaultPolicy) then fFaultPolicy.Free; inherited; end; function TScheduledTasks.GetTask(aIdTask: Int64): IScheduledTask; begin Result := fScheduler.Get(aIdTask); end; function TScheduledTasks.GetTask(const aTaskName: string): IScheduledTask; begin if not Assigned(fScheduler) then raise ETaskSchedulerError.Create('Scheduler must be started to get a task!'); Result := fScheduler.Get(aTaskName); end; procedure TScheduledTasks.Start; begin if fIsStarted then Exit; if not Assigned(fScheduler) then begin fScheduler := TScheduler.Create(fTaskList); fScheduler.RemoveTaskAfterExpiration := fRemoveTaskAfterExpiration; end; fScheduler.Start; fIsStarted := True; end; procedure TScheduledTasks.Stop; begin if Assigned(fScheduler) then fScheduler.Terminate; fIsStarted := False; end; { TScheduledTask } function TScheduledTask.SetParameter(const aName: string; aValue: TFlexValue): IScheduledTask; begin Result := Self; SetParam(aName,aValue); end; function TScheduledTask.SetParameter(const aName: string; aValue: TFlexValue; aOwned: Boolean): IScheduledTask; begin Result := Self; SetParam(aName,aValue); end; function TScheduledTask.StartAt(aStartDate: TDateTime) : IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := aStartDate; fNextExecution := aStartDate; end; function TScheduledTask.StartInMinutes(aMinutes: Word): IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := IncMinute(Now(),aMinutes); fNextExecution := fStartDate; end; function TScheduledTask.StartInSeconds(aSeconds: Word): IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := IncSecond(Now(),aSeconds); fNextExecution := fStartDate; end; function TScheduledTask.StartNow: IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := Now(); fNextExecution := fStartDate; end; function TScheduledTask.StartOnDayChange: IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := ChangeTimeOfADay(Tomorrow(),0,0,0); fNextExecution := fStartDate; end; function TScheduledTask.StartTodayAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := ChangeTimeOfADay(Now(),aHour,aMinute,aSecond); fNextExecution := fStartDate; end; function TScheduledTask.StartTomorrowAt(aHour, aMinute: Word; aSecond : Word = 0): IScheduledTask; begin Result := Self; ClearSchedule; fScheduleMode := TScheduleMode.smRunOnce; fStartDate := ChangeTimeOfADay(Tomorrow(),aHour,aMinute,aSecond); fNextExecution := fStartDate; end; function TScheduledTask.Retry(aMaxRetries: Integer): IScheduledTask; begin Result := Self; SetRetryPolicy(aMaxRetries,0,1); end; function TScheduledTask.RetryForever: IScheduledTask; begin Result := Self; SetRetryPolicy(-1,0,1); end; function TScheduledTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer): IScheduledTask; begin Result := Self; SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,1); end; function TScheduledTask.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor : Double): IScheduledTask; begin Result := Self; SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor); end; function TScheduledTask.WaitAndRetry(aWaitTimeArray: TArray<Integer>): IScheduledTask; begin Result := Self; SetRetryPolicy(aWaitTimeArray); end; function TScheduledTask.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer): IScheduledTask; begin Result := Self; SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,1); end; function TScheduledTask.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double): IScheduledTask; begin Result := Self; SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor); end; procedure TScheduledTask.RepeatEvery(aInterval: Integer; aTimeMeasure: TTimeMeasure); begin if fStartDate = 0.0 then ClearSchedule; fScheduleMode := TScheduleMode.smRepeatMode; fTimeMeasure := aTimeMeasure; fTimeInterval := aInterval; if fStartDate < Now() then fStartDate := Now(); fNextExecution := fStartDate; fEnabled := True; end; procedure TScheduledTask.RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aEndTime : TDateTime); begin if fStartDate = 0.0 then ClearSchedule; fScheduleMode := TScheduleMode.smRepeatMode; fTimeMeasure := aTimeMeasure; fTimeInterval := aInterval; if fStartDate < Now() then fStartDate := Now(); fExpirationDate := aEndTime; fNextExecution := fStartDate; fEnabled := True; end; procedure TScheduledTask.RepeatEveryDay; begin RepeatEvery(1,tmDays); end; procedure TScheduledTask.RepeatEveryWeek; begin RepeatEvery(7,tmDays); end; procedure TScheduledTask.RepeatEvery(aInterval : Integer; aTimeMeasure : TTimeMeasure; aRepeatTimes : Integer); begin if fStartDate = 0.0 then ClearSchedule; fScheduleMode := TScheduleMode.smRepeatMode; fTimeMeasure := aTimeMeasure; fTimeInterval := aInterval; if fStartDate < Now() then fStartDate := Now(); fExpirationTimes := aRepeatTimes; fNextExecution := fStartDate; fEnabled := True; end; procedure TScheduledTask.RunOnce; begin fScheduleMode := TScheduleMode.smRunOnce; if fStartDate < Now() then fStartDate := Now(); fNextExecution := fStartDate; fEnabled := True; end; procedure TScheduledTask.Cancel; begin fFinished := True; end; function TScheduledTask.CheckSchedule: Boolean; begin Result := False; if fTaskStatus = TWorkTaskStatus.wtsRunning then Exit; if fScheduleMode = TScheduleMode.smRunOnce then begin //if start date reached if (fExecutionTimes = 0) and (Now() >= fNextExecution) then begin fLastExecution := Now(); Inc(fExecutionTimes); fFinished := True; Result := True; end; end else begin //if next execution reached if Now() >= fNextExecution then begin //check expiration limits if ((fExpirationTimes > 0) and (fExecutionTimes > fExpirationTimes)) or ((fExpirationDate > 0.0) and (fNextExecution >= fExpirationDate)) then begin fFinished := True; Exit; end; //calculate next execution case fTimeMeasure of tmDays : fNextExecution := IncDay(fNextExecution,fTimeInterval); tmHours : fNextExecution := IncHour(fNextExecution,fTimeInterval); tmMinutes : fNextExecution := IncMinute(fNextExecution,fTimeInterval); tmSeconds : fNextExecution := IncSecond(fNextExecution,fTimeInterval); tmMilliseconds : fNextExecution := IncMilliSecond(fNextExecution, fTimeInterval); end; if Now() > fNextExecution then Result := False //avoid execution if system time was altered else begin fLastExecution := Now(); Inc(fExecutionTimes); Result := True; end; end; end; end; procedure TScheduledTask.ClearSchedule; begin inherited; fFinished := False; fStartDate := 0.0; fLastExecution := 0.0; fNextExecution := 0.0; fExpirationDate := 0.0; fScheduleMode := TScheduleMode.smRunOnce; fTimeMeasure := TTimeMeasure.tmSeconds; fTimeInterval := 0; end; procedure TScheduledTask.DoExpire; begin if Assigned(fExpiredProc) then fExpiredProc(Self); fEnabled := False; end; function TScheduledTask.GetCurrentSchedule: TPair<TTimeMeasure, Integer>; begin Result := TPair<TTimeMeasure, Integer>.Create(fTimeMeasure, fTimeInterval); end; function TScheduledTask.GetTaskName: string; begin Result := fName; end; function TScheduledTask.IsFinished: Boolean; begin Result := fFinished; end; function TScheduledTask.OnException(aTaskProc: TTaskExceptionProc): IScheduledTask; begin fExceptProc := aTaskProc; Result := Self; end; function TScheduledTask.OnException_Sync(aTaskProc: TTaskExceptionProc): IScheduledTask; begin Result := OnException(aTaskProc); TTask(Result).ExceptionWithSync := True; end; function TScheduledTask.OnRetry(aTaskProc: TTaskRetryProc): IScheduledTask; begin fRetryProc := aTaskProc; Result := Self; end; function TScheduledTask.OnExpired(aTaskProc: TTaskProc): IScheduledTask; begin fExpiredProc := aTaskProc; Result := Self; end; function TScheduledTask.OnExpired_Sync(aTaskProc: TTaskProc): IScheduledTask; begin Result := OnExpired(aTaskProc); TScheduledTask(Result).ExpireWithSync := True; end; function TScheduledTask.OnInitialize(aTaskProc: TTaskProc): IScheduledTask; begin fInitializeProc := aTaskProc; Result := Self; end; function TScheduledTask.OnTerminated(aTaskProc: TTaskProc): IScheduledTask; begin fTerminateProc := aTaskProc; Result := Self; end; function TScheduledTask.OnTerminated_Sync(aTaskProc: TTaskProc): IScheduledTask; begin Result := OnTerminated(aTaskProc); TTask(Result).TerminateWithSync := True; end; { TScheduler } constructor TScheduler.Create(aTaskList : TScheduledTaskList); begin inherited Create(True); FreeOnTerminate := False; fListLock := TCriticalSection.Create; fRemoveTaskAfterExpiration := False; fTaskList := aTaskList; {$IFDEF FPC} fCondVar := TSimpleEvent.Create; {$ELSE} fCondVar := TSimpleEvent.Create(nil,True,False,''); {$ENDIF} end; destructor TScheduler.Destroy; begin fCondVar.SetEvent; fCondVar.Free; fTaskList := nil; fListLock.Free; inherited; end; procedure TScheduler.Execute; var task : IScheduledTask; worker : TScheduledWorker; numworker : Int64; begin numworker := 0; while not Terminated do begin fListLock.Enter; try for task in fTaskList do begin if (task.IsEnabled) and (not task.IsFinished) then begin if task.CheckSchedule then begin Inc(numworker); worker := TScheduledWorker.Create(numworker,task); worker.Start; end; end else begin if (not task.IsEnabled) and (fRemoveTaskAfterExpiration) then fTaskList.Remove(task); end; end; task := nil; finally fListLock.Leave; end; fCondVar.WaitFor(250); end; end; function TScheduler.Add(aTask: TScheduledTask): Integer; begin Result := fTaskList.Add(aTask); end; function TScheduler.Get(aIdTask: Int64): IScheduledTask; var task : IScheduledTask; begin fListLock.Enter; try for task in fTaskList do begin if task.IdTask = aIdTask then Exit(task); end; finally fListLock.Leave; end; end; function TScheduler.Get(const aTaskName: string): IScheduledTask; var task : IScheduledTask; begin fListLock.Enter; try for task in fTaskList do begin if CompareText(task.Name,aTaskName) = 0 then Exit(task); end; finally fListLock.Leave; end; end; { TAdvThread } constructor TAdvThread.Create(aProc : TProc; aSynchronize : Boolean); begin inherited Create(True); FreeOnTerminate := True; fExecuteWithSync := aSynchronize; fExecuteProc := aProc; end; procedure TAdvThread.DoExecute; begin try if Assigned(fExecuteProc) then fExecuteProc; except on E : Exception do begin {$IFNDEF FPC} {$IF DELPHIRX10_UP} if Assigned(fExceptionProc) then fExceptionProc(AcquireExceptionObject as Exception) {$ELSE} if Assigned(fExceptionProc) then fExceptionProc(Exception(AcquireExceptionObject)) {$ENDIF} {$ELSE} if Assigned(fExceptionProc) then fExceptionProc(Exception(AcquireExceptionObject)) {$ENDIF} else raise; end; end; end; procedure TAdvThread.CallToTerminate; begin if Assigned(fTerminateProc) then fTerminateProc; end; procedure TAdvThread.DoTerminate; begin if fTerminateWithSync then Synchronize(CallToTerminate) else CallToTerminate; end; procedure TAdvThread.Execute; begin if fExecuteWithSync then Synchronize(DoExecute) else DoExecute; end; procedure TAdvThread.OnException(aProc: TAnonExceptionProc); begin fExceptionProc := aProc; end; procedure TAdvThread.OnTerminate(aProc: TProc; aSynchronize: Boolean); begin fTerminateWithSync := aSynchronize; fTerminateProc := aProc; end; { TRunTask } class function TRunTask.Execute(aTaskProc: TTaskProc): IWorkTask; begin Result := Execute([],False,aTaskProc); end; class function TRunTask.Execute_Sync(aTaskProc: TTaskProc): IWorkTask; begin Result := Execute_Sync([],False,aTaskProc); end; class function TRunTask.Execute(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; var task : TWorkTask; worker : TSimpleWorker; begin task := TWorkTask.Create(aParamArray,aOwnedParams,aTaskProc); task.ExecuteWithSync := False; Result := task; worker := TSimpleWorker.Create(task); worker.Start; end; class function TRunTask.Execute_Sync(aParamArray: array of const; aOwnedParams: Boolean; aTaskProc: TTaskProc): IWorkTask; var task : TWorkTask; worker : TSimpleWorker; begin task := TWorkTask.Create(aParamArray,aOwnedParams,aTaskProc); task.ExecuteWithSync := True; Result := task; worker := TSimpleWorker.Create(task); worker.Start; end; { TAsyncTask } constructor TAsyncTask.Create(aAction : TProc); begin fProcess := TSimpleThread.Create(aAction,False,True); end; destructor TAsyncTask.Destroy; begin inherited; end; class function TAsyncTask.Run(const aAction : TProc) : IAsyncTask; begin Result := TAsyncTask.Create(aAction); end; procedure TAsyncTask.Wait(const aTimeout: Cardinal); begin if aTimeout = 0 then fProcess.WaitFor else fProcess.WaitFor(aTimeout); end; procedure TAsyncTask.Wait; begin fProcess.WaitFor; end; { TAsyncTask<T> } {$IFNDEF FPC} constructor TAsyncTask<T>.Create(aAction: TFunc<T>); begin fWaitForResult := False; fProcess := TSimpleThread.Create(procedure begin fTaskResult := aAction(); end,False,False); end; destructor TAsyncTask<T>.Destroy; begin if not fWaitForResult then fProcess.FreeOnTerminate := True; inherited; end; class function TAsyncTask<T>.Run(const aAction: TFunc<T>): IAsyncTask<T>; begin Result := TAsyncTask<T>.Create(aAction); end; function TAsyncTask<T>.Result: T; begin fWaitForResult := True; fProcess.WaitFor; Result := fTaskResult; fProcess.Free; end; function TAsyncTask<T>.Result(const aTimeout: Cardinal): T; begin fWaitForResult := True; fProcess.WaitFor(aTimeout); Result := fTaskResult; fProcess.Free; end; {$ENDIF} { TParamValue } constructor TParamValue.Create(const aName: string; aValue: TFlexValue; aOwnedValue: Boolean); begin inherited Create; fName := aName; fValue := aValue; fOwned := aOwnedValue; end; constructor TParamValue.Create(const aName: string; aValue: TVarRec; aOwnedValue: Boolean); begin inherited Create; fName := aName; fValue := aValue; fOwned := aOwnedValue; end; constructor TParamValue.Create; begin fName := ''; fOwned := False; end; destructor TParamValue.Destroy; begin {$IFDEF FPC} fValue._Release; {$ENDIF} if (fOwned) and (fValue.IsObject) and (fValue.AsObject <> nil) then fValue.AsObject.Free; inherited; end; { TBackgroundWorkers } constructor TBackgroundWorkers.Create(aConcurrentWorkers : Integer; aWorkerProc : TTaskProc); begin fConcurrentWorkers := aConcurrentWorkers; fWorkerExecuteProc := aWorkerProc; fWorkerPool := TWorkerPool.Create(True); end; destructor TBackgroundWorkers.Destroy; begin fWorkerPool.Free; inherited; end; procedure TBackgroundWorkers.Start; var i : Integer; worker : TWorker; task : IWorkTask; begin for i := 1 to fConcurrentWorkers do begin task := TWorkTask.Create([],False,fWorkerExecuteProc) .OnInitialize(fWorkerInitProc) .OnRetry(fWorkerRetryProc) .OnException(fWorkerExceptionProc) .OnTerminated(fWorkerTerminateProc); task.NumWorker := i; task.Run; worker := TSimpleWorker.Create(task,False); fWorkerPool.Add(worker); worker.Start; end; end; procedure TBackgroundWorkers.Stop; var worker : TWorker; begin for worker in fWorkerPool do begin worker.Terminate; worker.WaitFor; fWorkerPool.Remove(worker); end; end; function TBackgroundWorkers.OnException(aTaskProc: TTaskExceptionProc): TBackgroundWorkers; begin Result := Self; fWorkerExceptionProc := aTaskProc; end; function TBackgroundWorkers.OnInitialize(aTaskProc: TTaskProc): TBackgroundWorkers; begin Result := Self; fWorkerInitProc := aTaskProc; end; function TBackgroundWorkers.OnRetry(aTaskProc: TTaskRetryProc): TBackgroundWorkers; begin Result := Self; fWorkerRetryProc := aTaskProc; end; function TBackgroundWorkers.OnTerminated(aTaskProc: TTaskProc): TBackgroundWorkers; begin Result := Self; fWorkerTerminateProc := aTaskProc; end; function TBackgroundWorkers.Retry(aMaxRetries: Integer): TBackgroundWorkers; begin Result := Self; SetRetryPolicy(aMaxRetries,0,1); end; function TBackgroundWorkers.RetryForever: TBackgroundWorkers; begin Result := Self; SetRetryPolicy(-1,0,1); end; procedure TBackgroundWorkers.SetRetryPolicy(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double); begin fFaultPolicy.MaxRetries := aMaxRetries; fFaultPolicy.WaitTimeBetweenRetries := aWaitTimeBetweenRetriesMS; fFaultPolicy.WaitTimeMultiplierFactor := aWaitTimeMultiplierFactor; end; function TBackgroundWorkers.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double): TBackgroundWorkers; begin Result := Self; SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor); end; function TBackgroundWorkers.WaitAndRetry(aMaxRetries, aWaitTimeBetweenRetriesMS: Integer): TBackgroundWorkers; begin Result := Self; SetRetryPolicy(aMaxRetries,aWaitTimeBetweenRetriesMS,1); end; function TBackgroundWorkers.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer): TBackgroundWorkers; begin Result := Self; SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,1); end; function TBackgroundWorkers.WaitAndRetryForever(aWaitTimeBetweenRetriesMS: Integer; aWaitTimeMultiplierFactor: Double): TBackgroundWorkers; begin Result := Self; SetRetryPolicy(-1,aWaitTimeBetweenRetriesMS,aWaitTimeMultiplierFactor); end; { TSimpleThread } constructor TSimpleThread.Create(aProc: TProc; aCreateSuspended, aFreeOnTerminate : Boolean); begin if not Assigned(aProc) then raise EArgumentNilException.Create('param cannot be nil!'); {$IFNDEF FPC} fTimeoutFlag := TLightweightEvent.Create; {$ELSE} fTimeoutFlag := TSimpleEvent.Create; {$ENDIF} fTimeoutFlag.ResetEvent; fExecuteProc := aProc; inherited Create(aCreateSuspended); Self.FreeOnTerminate := aFreeOnTerminate; end; destructor TSimpleThread.Destroy; begin if Assigned(fTimeoutFlag) then begin fTimeoutFlag.Release; fTimeoutFlag.Free; end; inherited; end; procedure TSimpleThread.Execute; begin fExecuteProc; fTimeoutFlag.SetEvent; end; function TSimpleThread.WaitFor(const aTimeout: Cardinal) : TWaitResult; begin Result := fTimeoutFlag.WaitFor(aTimeout); if Result = TWaitResult.wrTimeout then raise Exception.Create('Timeout'); end; end.
unit OEncoding; { Author: Ondrej Pokorny, http://www.kluug.net All Rights Reserved. License: CPAL 1.0 or commercial Please see the /license.txt file for more information. } { OEncoding.pas Convert buffers to strings and back with encoding classes. } {$I OXml.inc} {$IFDEF O_DELPHI_XE4_UP} {$ZEROBASEDSTRINGS OFF} {$ENDIF} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$BOOLEVAL OFF} interface uses {$IFDEF O_NAMESPACES} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} OWideSupp; const //see http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756%28v=vs.85%29.aspx //single-byte CP_WIN_1250 = 1250;//ANSI Central European; Central European (Windows) CP_WIN_1251 = 1251;//ANSI Cyrillic; Cyrillic (Windows) CP_WIN_1252 = 1252;//ANSI Latin 1; Western European (Windows) CP_WIN_1253 = 1253;//ANSI Greek; Greek (Windows) CP_WIN_1254 = 1254;//ANSI Turkish; Turkish (Windows) CP_WIN_1255 = 1255;//ANSI Hebrew; Hebrew (Windows) CP_WIN_1256 = 1256;//ANSI Arabic; Arabic (Windows) CP_WIN_1257 = 1257;//ANSI Baltic; Baltic (Windows) CP_WIN_1258 = 1258;//ANSI/OEM Vietnamese; Vietnamese (Windows) CP_ISO_8859_1 = 28591;//ISO 8859-1 Latin 1; Western European (ISO) CP_ISO_8859_2 = 28592;//ISO 8859-2 Central European; Central European (ISO) CP_ISO_8859_3 = 28593;//ISO 8859-3 Latin 3 CP_ISO_8859_4 = 28594;//ISO 8859-4 Baltic CP_ISO_8859_5 = 28595;//ISO 8859-5 Cyrillic CP_ISO_8859_6 = 28596;//ISO 8859-6 Arabic CP_ISO_8859_7 = 28597;//ISO 8859-7 Greek CP_ISO_8859_8 = 28598;//ISO 8859-8 Hebrew; Hebrew (ISO-Visual) CP_ISO_8859_9 = 28599;//ISO 8859-9 Turkish CP_ISO_8859_13 = 28603;//ISO 8859-13 Estonian CP_ISO_8859_15 = 28605;//ISO 8859-15 Latin 9 CP_ISO_2022 = 50220;//ISO 2022 Japanese with no halfwidth Katakana; Japanese (JIS) CP_EUC_JP = 51932;//ISO 2022 Japanese with no halfwidth Katakana; Japanese (JIS) CP_KOI8_R = 20866;//Russian (KOI8-R); Cyrillic (KOI8-R) CP_KOI8_U = 21866;//Ukrainian (KOI8-U); Cyrillic (KOI8-U) CP_IBM_437 = 437;//OEM United States CP_IBM_850 = 850;//OEM Multilingual Latin 1; Western European (DOS) CP_IBM_852 = 852;//OEM Latin 2; Central European (DOS) CP_IBM_866 = 866;//OEM Russian; Cyrillic (DOS) CP_WIN_874 = 874;//ANSI/OEM Thai (ISO 8859-11); Thai (Windows) CP_IBM_932 = 932;//ANSI/OEM Japanese; Japanese (Shift-JIS) CP_US_ASCII = 20127;//US-ASCII (7-bit) //multi-byte CP_UNICODE = 1200;//Unicode UTF-16, little endian byte order CP_UNICODE_BE = 1201;//Unicode UTF-16, big endian byte order CP_UTF7 = 65000;//Unicode (UTF-7) CP_UTF8 = 65001;//Unicode (UTF-8) {$IFDEF O_DELPHI_2009_UP} type TEncodingBuffer = TBytes; const TEncodingBuffer_FirstElement = 0; {$ELSE} //AnsiString is a better "byte buffer" than "Array of Byte" for non-unicode Delphi / FPC: // Delphi 7: everybody uses it... // FPC: default routines CP437ToUTF8 etc use AnsiString and not Array of Byte! type TEncodingBuffer = AnsiString; const TEncodingBuffer_FirstElement = 1; {$ENDIF} {$IFNDEF O_DELPHI_2009_UP} type TEncoding = class(TObject) public //functions that convert strings to buffers and vice versa function BufferToString(const aBytes: TEncodingBuffer): OWideString; overload; function BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; overload; virtual; abstract;//faster in D7 and FPC than "function BufferToString" function StringToBuffer(const S: OWideString): TEncodingBuffer; overload; procedure StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); overload; virtual; abstract;//faster in D7 and FPC than "function StringToBuffer" public //functions that get information about current encoding object class function IsSingleByte: Boolean; virtual; abstract; class function IsStandardEncoding(aEncoding: TEncoding): Boolean; function EncodingName: OWideString; virtual; abstract; function EncodingAlias: OWideString; function EncodingCodePage: Cardinal; function Clone: TEncoding; virtual; function CloneIfNotStandard: TEncoding; public //class functions for finding correct encoding from BOM, code page, alias etc. class function GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding): Integer; overload; class function GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding; aDefaultEncoding: TEncoding): Integer; overload; function GetBOM: TEncodingBuffer; virtual; abstract; class function EncodingFromCodePage(aCodePage: Integer): TEncoding; class function EncodingFromAlias(const aAlias: OWideString; var outEncoding: TEncoding): Boolean; class function AliasToCodePage(const aAlias: OWideString): Cardinal; class function CodePageToAlias(const aCodePage: Cardinal): OWideString; public //retrieve standard encodings class function Default: TEncoding; class function Unicode: TEncoding; class function UTF8: TEncoding; class function ANSI: TEncoding; class function ASCII: TEncoding; class function OWideStringEncoding: TEncoding; public destructor Destroy; override; end; TUnicodeEncoding = class(TEncoding) public function GetBOM: TEncodingBuffer; override; function BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; override; procedure StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); override; class function IsSingleByte: Boolean; override; function EncodingName: OWideString; override; function Clone: TEncoding; override; end; TUTF8Encoding = class(TEncoding) public function GetBOM: TEncodingBuffer; override; function BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; override; procedure StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); override; class function IsSingleByte: Boolean; override; function EncodingName: OWideString; override; function Clone: TEncoding; override; end; TMBCSEncoding = class(TEncoding) private fCodePage: Cardinal; public constructor Create(aCodePage: Cardinal); public function GetBOM: TEncodingBuffer; override; function BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; override; procedure StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); override; class function IsSingleByte: Boolean; override; function EncodingName: OWideString; override; function Clone: TEncoding; override; public property CodePage: Cardinal read fCodePage; end; {$ENDIF O_DELPHI_2009_UP} {$IFDEF O_DELPHI_2009_UP} //Delphi 2009 to 2010 type TEncodingHelper = class helper for TEncoding public function EncodingAlias: String; function EncodingCodePage: Cardinal; {$IFNDEF O_DELPHI_XE_UP} function EncodingName: String; function Clone: TEncoding; {$ENDIF} {$IFNDEF O_DELPHI_XE2_UP} class function ANSI: TEncoding; {$ENDIF} class function OWideStringEncoding: TEncoding; class function EncodingFromCodePage(aCodePage: Integer): TEncoding; class function EncodingFromAlias(const aAlias: OWideString; var outEncoding: TEncoding): Boolean; class function AliasToCodePage(const aAlias: OWideString): Cardinal; class function CodePageToAlias(const aCodePage: Cardinal): OWideString; class function GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding): Integer; overload; class function GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding; aDefaultEncoding: TEncoding): Integer; overload; function GetBOM: TEncodingBuffer; function BufferToString(const aBytes: TEncodingBuffer): OWideString; overload; {$IFDEF O_INLINE}inline;{$ENDIF} function BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; overload; {$IFDEF O_INLINE}inline;{$ENDIF} function StringToBuffer(const S: OWideString): TEncodingBuffer; overload; {$IFDEF O_INLINE}inline;{$ENDIF} procedure StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); overload; {$IFDEF O_INLINE}inline;{$ENDIF} function CloneIfNotStandard: TEncoding; end; TMBCSEncodingHelper = class helper for TMBCSEncoding public function GetCodePage: Cardinal; end; {$ENDIF} implementation {$IFNDEF O_DELPHI_2009_UP} {$IFDEF MSWINDOWS} uses Windows; {$ELSE} {$IFDEF FPC} uses LConvEncoding; {$ENDIF} {$ENDIF} {$ENDIF NOT O_DELPHI_2009_UP} type TCodePage = record CodePage: Word; CPAlias: OWideString; end; TCodePages = array[0..34] of TCodePage; const CodePages: TCodePages = ( (CodePage: CP_WIN_1250; CPAlias: 'windows-1250'), (CodePage: CP_WIN_1251; CPAlias: 'windows-1251'), (CodePage: CP_WIN_1252; CPAlias: 'windows-1252'), (CodePage: CP_WIN_1253; CPAlias: 'windows-1253'), (CodePage: CP_WIN_1254; CPAlias: 'windows-1254'), (CodePage: CP_WIN_1255; CPAlias: 'windows-1255'), (CodePage: CP_WIN_1256; CPAlias: 'windows-1256'), (CodePage: CP_WIN_1257; CPAlias: 'windows-1257'), (CodePage: CP_WIN_1258; CPAlias: 'windows-1258'), (CodePage: CP_ISO_8859_1; CPAlias: 'iso-8859-1'), (CodePage: CP_ISO_8859_2; CPAlias: 'iso-8859-2'), (CodePage: CP_ISO_8859_3; CPAlias: 'iso-8859-3'), (CodePage: CP_ISO_8859_4; CPAlias: 'iso-8859-4'), (CodePage: CP_ISO_8859_5; CPAlias: 'iso-8859-5'), (CodePage: CP_ISO_8859_6; CPAlias: 'iso-8859-6'), (CodePage: CP_ISO_8859_7; CPAlias: 'iso-8859-7'), (CodePage: CP_ISO_8859_8; CPAlias: 'iso-8859-8'), (CodePage: CP_ISO_8859_9; CPAlias: 'iso-8859-9'), (CodePage: CP_ISO_8859_13; CPAlias: 'iso-8859-13'), (CodePage: CP_ISO_8859_15; CPAlias: 'iso-8859-15'), (CodePage: CP_ISO_2022; CPAlias: 'iso-2022-jp'), (CodePage: CP_EUC_JP; CPAlias: 'euc-jp'), (CodePage: CP_KOI8_R; CPAlias: 'koi8-r'), (CodePage: CP_KOI8_U; CPAlias: 'koi8-u'), (CodePage: CP_IBM_437; CPAlias: 'ibm437'), (CodePage: CP_IBM_850; CPAlias: 'ibm850'), (CodePage: CP_IBM_852; CPAlias: 'ibm852'), (CodePage: CP_IBM_866; CPAlias: 'cp866'), (CodePage: CP_WIN_874; CPAlias: 'windows-874'), (CodePage: CP_IBM_932; CPAlias: 'shift-jis'), (CodePage: CP_US_ASCII; CPAlias: 'us-ascii'), (CodePage: CP_UNICODE; CPAlias: 'utf-16'), (CodePage: CP_UNICODE_BE; CPAlias: 'utf-16be'), (CodePage: CP_UTF7; CPAlias: 'utf-7'), (CodePage: CP_UTF8; CPAlias: 'utf-8') ); {$IFNDEF O_DELPHI_2009_UP} var fxANSIEncoding: TEncoding = nil; fxUTF8Encoding: TEncoding = nil; fxUnicodeEncoding: TEncoding = nil; fxASCIIEncoding: TEncoding = nil; {$IFDEF MSWINDOWS} type _cpinfoExW = record MaxCharSize: UINT; { max length (bytes) of a char } DefaultChar: array[0..MAX_DEFAULTCHAR - 1] of Byte; { default character } LeadByte: array[0..MAX_LEADBYTES - 1] of Byte; { lead byte ranges } UnicodeDefaultChar: WideChar; Codepage: UINT; CodePageName: array[0..MAX_PATH -1] of WideChar; end; TCPInfoExW = _cpinfoExW; function GetCPInfoExW(CodePage: UINT; dwFlags: LongWord; var lpCPInfoEx: TCPInfoExW): BOOL; stdcall; external kernel32 name 'GetCPInfoExW';// AUTOMATIC CONVERT APPLIED :: DWORD->: LongWord {$ENDIF} {$IFDEF FPC}{$IFNDEF MSWINDOWS} function UTF8ToCodePage(const S: OWideString; aCodePage: Cardinal): AnsiString; begin case aCodePage of CP_IBM_437, CP_US_ASCII: Result := UTF8ToCP437(S); CP_IBM_850: Result := UTF8ToCP850(S); CP_IBM_852: Result := UTF8ToCP852(S); CP_IBM_866: Result := UTF8ToCP866(S); CP_WIN_874: Result := UTF8ToCP874(S); CP_IBM_932: Result := UTF8ToCP932(S); CP_WIN_1250: Result := UTF8ToCP1250(S); CP_WIN_1251: Result := UTF8ToCP1251(S); CP_WIN_1252: Result := UTF8ToCP1252(S); CP_WIN_1253: Result := UTF8ToCP1253(S); CP_WIN_1254: Result := UTF8ToCP1254(S); CP_WIN_1255: Result := UTF8ToCP1255(S); CP_WIN_1256: Result := UTF8ToCP1256(S); CP_WIN_1257: Result := UTF8ToCP1257(S); CP_WIN_1258: Result := UTF8ToCP1258(S); CP_ISO_8859_1: Result := UTF8ToISO_8859_1(S); CP_ISO_8859_2: Result := UTF8ToISO_8859_2(S); CP_KOI8_R, CP_KOI8_U: Result := UTF8ToKOI8(S); else Result := S;//Encoding not supported by lazarus end; end; function CodePageToUTF8(const S: AnsiString; aCodePage: Cardinal): OWideString; begin case aCodePage of CP_IBM_437, CP_US_ASCII: Result := CP437ToUTF8(S); CP_IBM_850: Result := CP850ToUTF8(S); CP_IBM_852: Result := CP852ToUTF8(S); CP_IBM_866: Result := CP866ToUTF8(S); CP_WIN_874: Result := CP874ToUTF8(S); CP_IBM_932: Result := CP932ToUTF8(S); CP_WIN_1250: Result := CP1250ToUTF8(S); CP_WIN_1251: Result := CP1251ToUTF8(S); CP_WIN_1252: Result := CP1252ToUTF8(S); CP_WIN_1253: Result := CP1253ToUTF8(S); CP_WIN_1254: Result := CP1254ToUTF8(S); CP_WIN_1255: Result := CP1255ToUTF8(S); CP_WIN_1256: Result := CP1256ToUTF8(S); CP_WIN_1257: Result := CP1257ToUTF8(S); CP_WIN_1258: Result := CP1258ToUTF8(S); CP_ISO_8859_1: Result := ISO_8859_1ToUTF8(S); CP_ISO_8859_2: Result := ISO_8859_2ToUTF8(S); CP_KOI8_R, CP_KOI8_U: Result := KOI8ToUTF8(S); else Result := S;//Encoding not supported by lazarus end; end; {$ENDIF}{$ENDIF} { TEncoding } class function TEncoding.ANSI: TEncoding; begin if not Assigned(fxANSIEncoding) then begin {$IFDEF MSWINDOWS} fxANSIEncoding := TMBCSEncoding.Create(GetACP); {$ELSE} fxANSIEncoding := TMBCSEncoding.Create(CP_WIN_1252); {$ENDIF} end; Result := fxANSIEncoding; end; class function TEncoding.ASCII: TEncoding; {$IFDEF MSWINDOWS} var xCPInfo: TCPInfo; {$ENDIF} begin if not Assigned(fxASCIIEncoding) then begin {$IFDEF MSWINDOWS} if GetCPInfo(CP_US_ASCII, {%H-}xCPInfo) then fxASCIIEncoding := TMBCSEncoding.Create(CP_US_ASCII) else fxASCIIEncoding := TMBCSEncoding.Create(CP_IBM_437); {$ELSE} fxASCIIEncoding := TMBCSEncoding.Create(CP_IBM_437); {$ENDIF} end; Result := fxASCIIEncoding; end; class function TEncoding.Default: TEncoding; begin {$IFDEF MSWINDOWS} Result := ANSI; {$ELSE} Result := UTF8; {$ENDIF} end; class function TEncoding.GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding): Integer; begin Result := GetEncodingFromBOM(aBuffer, outEncoding, Default); end; class function TEncoding.GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding; aDefaultEncoding: TEncoding): Integer; begin if (Length(aBuffer) >= 3) and (aBuffer[TEncodingBuffer_FirstElement+0] = #$EF) and (aBuffer[TEncodingBuffer_FirstElement+1] = #$BB) and (aBuffer[TEncodingBuffer_FirstElement+2] = #$BF) then begin outEncoding := UTF8; Result := 3; end else if (Length(aBuffer) >= 2) and (aBuffer[TEncodingBuffer_FirstElement+0] = #$FF) and (aBuffer[TEncodingBuffer_FirstElement+1] = #$FE) then begin outEncoding := Unicode; Result := 2; end else begin outEncoding := aDefaultEncoding; Result := 0; end; end; function TEncoding.BufferToString(const aBytes: TEncodingBuffer): OWideString; begin BufferToString(aBytes, {%H-}Result); end; function TEncoding.StringToBuffer(const S: OWideString): TEncodingBuffer; begin StringToBuffer(S, {%H-}Result); end; class function TEncoding.Unicode: TEncoding; begin if not Assigned(fxUnicodeEncoding) then fxUnicodeEncoding := TUnicodeEncoding.Create; Result := fxUnicodeEncoding; end; class function TEncoding.UTF8: TEncoding; begin if not Assigned(fxUTF8Encoding) then fxUTF8Encoding := TUTF8Encoding.Create; Result := fxUTF8Encoding; end; class function TEncoding.IsStandardEncoding(aEncoding: TEncoding): Boolean; begin Result := Assigned(aEncoding) and ( (aEncoding = fxANSIEncoding) or (aEncoding = fxUTF8Encoding) or (aEncoding = fxUnicodeEncoding) or (aEncoding = fxASCIIEncoding)); end; class function TEncoding.OWideStringEncoding: TEncoding; begin {$IFDEF FPC} Result := UTF8; {$ELSE} Result := Unicode; {$ENDIF} end; function TEncoding.EncodingAlias: OWideString; var xCodePage, I: Integer; begin xCodePage := EncodingCodePage; for I := Low(CodePages) to High(CodePages) do if CodePages[I].CodePage = xCodePage then begin Result := CodePages[I].CPAlias; Exit; end; Result := IntToStr(xCodePage); end; function TEncoding.EncodingCodePage: Cardinal; begin if Self is TMBCSEncoding then Result := TMBCSEncoding(Self).CodePage else if Self is TUnicodeEncoding then Result := CP_UNICODE else if Self is TUTF8Encoding then Result := CP_UTF8 else Result := 0; end; function TEncoding.Clone: TEncoding; begin Result := nil; end; function TEncoding.CloneIfNotStandard: TEncoding; begin if IsStandardEncoding(Self) then Result := Self else Result := Clone; end; destructor TEncoding.Destroy; begin if (Self = fxANSIEncoding) then fxANSIEncoding := nil else if (Self = fxUTF8Encoding) then fxUTF8Encoding := nil else if (Self = fxUnicodeEncoding) then fxUnicodeEncoding := nil else if (Self = fxASCIIEncoding) then fxASCIIEncoding := nil; inherited; end; { TMBCSEncoding } constructor TMBCSEncoding.Create(aCodePage: Cardinal); begin inherited Create; fCodePage := aCodePage; end; function TMBCSEncoding.EncodingName: OWideString; {$IFDEF MSWINDOWS} var xCPInfo: TCPInfoExW; begin if GetCPInfoExW(fCodePage, 0, xCPInfo{%H-}) then Result := xCPInfo.CodePageName else Result := IntToStr(fCodePage); end; {$ELSE} begin Result := IntToStr(fCodePage); end; {$ENDIF} function TMBCSEncoding.Clone: TEncoding; begin Result := TMBCSEncoding.Create(fCodePage); end; procedure TMBCSEncoding.StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); {$IFDEF MSWINDOWS} procedure _Convert(const aWS: PWideChar); var xLength: integer; begin //IMPORTANT: S is WITH a NULL TERMINATOR -> xCharCount is ALSO WITH NULL TERMINATOR!!! xLength := WideCharToMultiByte(fCodePage, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, PWideChar(aWS), -1, nil, 0, nil, nil); SetLength(outBuffer, xLength-1); if xLength > 1 then WideCharToMultiByte(codePage, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, PWideChar(aWS), -1, @outBuffer[TEncodingBuffer_FirstElement], xLength-1, nil, nil); end; {$IFDEF FPC} var xUS: UnicodeString; {$ENDIF} {$ENDIF} begin if S = '' then begin SetLength(outBuffer, 0); Exit; end; {$IFDEF MSWINDOWS} {$IFDEF FPC} xUS := UTF8Decode(S); _Convert(@xUS[1]); {$ELSE} _Convert(@S[1]); {$ENDIF} {$ELSE} outBuffer := UTF8ToCodePage(S, fCodePage); {$ENDIF} end; function TMBCSEncoding.GetBOM: TEncodingBuffer; begin SetLength(Result, 0); end; function TMBCSEncoding.BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; {$IFDEF MSWINDOWS} procedure _Convert(var _ioWS: OUnicodeString); var xLength, xByteCount: Integer; begin //IMPORTANT: S is WITHOUT a NULL TERMINATOR -> xCharCount is ALSO WITHOUT NULL TERMINATOR!!! xByteCount := Length(aBytes); xLength := MultiByteToWideChar(fCodePage, MB_PRECOMPOSED, PAnsiChar(@aBytes[TEncodingBuffer_FirstElement]), xByteCount, nil, 0); SetLength(_ioWS, xLength); if xLength > 0 then MultiByteToWideChar(CodePage, MB_PRECOMPOSED, PAnsiChar(@aBytes[TEncodingBuffer_FirstElement]), xByteCount, PWideChar(@_ioWS[1]), xLength); end; {$IFDEF FPC} var xUS: UnicodeString; {$ENDIF} {$ENDIF} begin if Length(aBytes) = 0 then begin outString := ''; Result := True; Exit; end; {$IFDEF MSWINDOWS} {$IFDEF FPC} _Convert({%H-}xUS); outString := UTF8Encode(xUS); {$ELSE} _Convert(outString); {$ENDIF} {$ELSE} outString := CodePageToUTF8(aBytes, fCodePage); {$ENDIF} Result := outString <> ''; end; class function TMBCSEncoding.IsSingleByte: Boolean; begin Result := True; end; { TUnicodeEncoding } function TUnicodeEncoding.EncodingName: OWideString; begin {$IFDEF MSWINDOWS} Result := '1200 (Unicode)'; {$ELSE} Result := 'Unicode (UTF-16LE)'; {$ENDIF} end; function TUnicodeEncoding.Clone: TEncoding; begin Result := TUnicodeEncoding.Create; end; procedure TUnicodeEncoding.StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); var xCharCount: Integer; {$IFDEF FPC} xUS: UnicodeString; {$ENDIF} begin {$IFDEF FPC} //FPC xUS := UTF8Decode(S); xCharCount := Length(xUS); SetLength(outBuffer, xCharCount*2); if xCharCount > 0 then begin Move(xUS[1], outBuffer[TEncodingBuffer_FirstElement], xCharCount*2); end; {$ELSE} //DELPHI xCharCount := Length(S); SetLength(outBuffer, xCharCount*2); if xCharCount > 0 then Move(S[1], outBuffer[TEncodingBuffer_FirstElement], xCharCount*2); {$ENDIF} end; function TUnicodeEncoding.GetBOM: TEncodingBuffer; begin SetLength(Result, 2); Result[TEncodingBuffer_FirstElement+0] := #$FF; Result[TEncodingBuffer_FirstElement+1] := #$FE; end; function TUnicodeEncoding.BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; var xByteCount: Integer; {$IFDEF FPC} xUS: UnicodeString; {$ENDIF} begin xByteCount := Length(aBytes); if xByteCount = 0 then begin outString := ''; Result := True; Exit; end; {$IFDEF FPC} //FPC SetLength(xUS, xByteCount div 2); Move(aBytes[TEncodingBuffer_FirstElement], xUS[1], xByteCount); outString := UTF8Encode(xUS); {$ELSE} //DELPHI SetLength(outString, xByteCount div 2); Move(aBytes[TEncodingBuffer_FirstElement], outString[1], xByteCount); {$ENDIF} Result := outString <> ''; end; class function TUnicodeEncoding.IsSingleByte: Boolean; begin Result := False; end; { TUTF8Encoding } function TUTF8Encoding.EncodingName: OWideString; {$IFDEF MSWINDOWS} var xCPInfo: TCPInfoExW; begin if GetCPInfoExW(CP_UTF8, 0, xCPInfo{%H-}) then Result := xCPInfo.CodePageName else Result := '65001 (UTF-8)'; end; {$ELSE} begin Result := 'UTF-8'; end; {$ENDIF} function TUTF8Encoding.Clone: TEncoding; begin Result := TUTF8Encoding.Create; end; procedure TUTF8Encoding.StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); var xCharCount: Integer; begin {$IFDEF FPC} xCharCount := Length(S); SetLength(outBuffer, xCharCount); if xCharCount > 0 then Move(S[1], outBuffer[TEncodingBuffer_FirstElement], xCharCount); {$ELSE} {$IFDEF MSWINDOWS} //IMPORTANT: S is WITH a NULL TERMINATOR -> xCharCount is ALSO WITH NULL TERMINATOR!!! xCharCount := WideCharToMultiByte(CP_UTF8, 0, PWideChar(S), -1, nil, 0, nil, nil); SetLength(outBuffer, xCharCount-1); if xCharCount > 1 then WideCharToMultiByte(CP_UTF8, 0, PWideChar(S), -1, PAnsiChar(@outBuffer[TEncodingBuffer_FirstElement]), xCharCount-1, nil, nil); {$ELSE} if S = '' then begin SetLength(outBuffer, 0); Exit; end; SetLength(outBuffer, Length(S) * 3 + 1); xCharCount := UnicodeToUtf8(@outBuffer[TEncodingBuffer_FirstElement], Length(outBuffer), PWideChar(S), Length(S)); if xCharCount > 0 then SetLength(outBuffer, xCharCount-1) else SetLength(outBuffer, 0); {$ENDIF} {$ENDIF} end; function TUTF8Encoding.GetBOM: TEncodingBuffer; begin SetLength(Result, 3); Result[TEncodingBuffer_FirstElement+0] := #$EF; Result[TEncodingBuffer_FirstElement+1] := #$BB; Result[TEncodingBuffer_FirstElement+2] := #$BF; end; function TUTF8Encoding.BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; var {$IFNDEF FPC} xCharCount: Integer; {$ENDIF} xByteCount: Integer; begin if Length(aBytes) = 0 then begin outString := ''; Result := True; Exit; end; xByteCount := Length(aBytes); {$IFDEF FPC} //FPC SetLength(outString, xByteCount); Move(aBytes[TEncodingBuffer_FirstElement], outString[1], xByteCount); {$ELSE} //DELPHI {$IFDEF MSWINDOWS} //IMPORTANT: xByteCount is WITHOUT the NULL character -> xCharCount is ALSO WITHOUT the NULL CHARACTER!!! xCharCount := MultiByteToWideChar(CP_UTF8, 0, PAnsiChar(@aBytes[TEncodingBuffer_FirstElement]), xByteCount, nil, 0); SetLength(outString, xCharCount); if xCharCount > 0 then MultiByteToWideChar(CP_UTF8, 0, PAnsiChar(@aBytes[TEncodingBuffer_FirstElement]), xByteCount, PWideChar(outString), xCharCount); {$ELSE} SetLength(outString, xByteCount); xCharCount := Utf8ToUnicode(PWideChar(outString), Length(outString)+1, @aBytes[TEncodingBuffer_FirstElement], xByteCount); if xCharCount > 0 then SetLength(outString, xCharCount-1) else outString := ''; {$ENDIF} {$ENDIF} Result := outString <> ''; end; class function TUTF8Encoding.IsSingleByte: Boolean; begin Result := False; end; {$ENDIF NOT O_DELPHI_2009_UP} {$IFDEF O_DELPHI_2009_UP} class function TEncodingHelper.EncodingFromCodePage(aCodePage: Integer): TEncoding; {$ELSE} class function TEncoding.EncodingFromCodePage(aCodePage: Integer): TEncoding; {$ENDIF} begin case aCodePage of CP_UNICODE: Result := Unicode; {$IFDEF O_DELPHI_2009_UP} CP_UNICODE_BE: Result := BigEndianUnicode; CP_UTF7: Result := UTF7; {$ENDIF} CP_UTF8: Result := UTF8; else Result := TMBCSEncoding.Create(aCodePage); end; end; {$IFDEF O_DELPHI_2009_UP} class function TEncodingHelper.EncodingFromAlias(const aAlias: OWideString; var outEncoding: TEncoding): Boolean; {$ELSE} class function TEncoding.EncodingFromAlias(const aAlias: OWideString; var outEncoding: TEncoding): Boolean; {$ENDIF} var xCP: Cardinal; begin xCP := AliasToCodePage(aAlias); Result := (xCP <> 0); if Result then outEncoding := TEncoding.EncodingFromCodePage(xCP) else outEncoding := nil; end; {$IFDEF O_DELPHI_2009_UP} class function TEncodingHelper.AliasToCodePage(const aAlias: OWideString): Cardinal; {$ELSE} class function TEncoding.AliasToCodePage(const aAlias: OWideString): Cardinal; {$ENDIF} var I: Integer; begin for I := Low(CodePages) to High(CodePages) do if OSameText(aAlias, CodePages[I].CPAlias) then begin Result := CodePages[I].CodePage; Exit; end; Result := 0; end; {$IFDEF O_DELPHI_2009_UP} class function TEncodingHelper.CodePageToAlias(const aCodePage: Cardinal): OWideString; {$ELSE} class function TEncoding.CodePageToAlias(const aCodePage: Cardinal): OWideString; {$ENDIF} var I: Integer; begin for I := Low(CodePages) to High(CodePages) do if aCodePage = CodePages[I].CodePage then begin Result := CodePages[I].CPAlias; Exit; end; Result := ''; end; {$IFDEF O_DELPHI_2009_UP} { TEncodingHelper } {$IFNDEF O_DELPHI_XE_UP} function TEncodingHelper.EncodingName: String; begin if Self is TMBCSEncoding then Result := IntToStr(TMBCSEncoding(Self).GetCodePage) else if Self is TUnicodeEncoding then Result := IntToStr(CP_UNICODE) else if Self is TBigEndianUnicodeEncoding then Result := IntToStr(CP_UNICODE_BE) else Result := ''; end; type TMyMBCSEncoding = class(TEncoding) private FCodePage: Cardinal; end; function TEncodingHelper.Clone: TEncoding; begin if Self is TMBCSEncoding then Result := TMBCSEncoding(Self).Create(TMyMBCSEncoding(Self).FCodePage) else Result := TEncoding(Self.ClassType.Create); end; {$ENDIF} {$IFNDEF O_DELPHI_XE2_UP} class function TEncodingHelper.ANSI: TEncoding; begin {$IFDEF MSWINDOWS} Result := Default; {$ELSE} Result := TMBCSEncoding.Create(CP_WIN_1252); {$ENDIF} end; {$ENDIF O_DELPHI_XE2_UP} class function TEncodingHelper.OWideStringEncoding: TEncoding; begin {$IFDEF FPC} Result := UTF8; {$ELSE} Result := Unicode; {$ENDIF} end; function TEncodingHelper.EncodingAlias: String; var xCodePage, I: Integer; begin xCodePage := EncodingCodePage; for I := Low(CodePages) to High(CodePages) do if CodePages[I].CodePage = xCodePage then begin Result := CodePages[I].CPAlias; Exit; end; Result := IntToStr(xCodePage); end; class function TEncodingHelper.GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding): Integer; begin outEncoding := nil;//must be here: otherwise if outEncoding<>nil, GetBufferEncoding would check only towards outEncoding Result := Self.GetBufferEncoding(aBuffer, outEncoding); end; class function TEncodingHelper.GetEncodingFromBOM(const aBuffer: TEncodingBuffer; var outEncoding: TEncoding; aDefaultEncoding: TEncoding): Integer; begin outEncoding := nil;//must be here: otherwise if outEncoding<>nil, GetBufferEncoding would check only towards outEncoding {$IFDEF O_DELPHI_XE_UP} Result := Self.GetBufferEncoding(aBuffer, outEncoding, aDefaultEncoding); {$ELSE} Result := Self.GetBufferEncoding(aBuffer, outEncoding); if Result = 0 then//BOM not found outEncoding := aDefaultEncoding; {$ENDIF} end; function TEncodingHelper.GetBOM: TEncodingBuffer; begin Result := GetPreamble; end; function TEncodingHelper.CloneIfNotStandard: TEncoding; begin if IsStandardEncoding(Self) then Result := Self else Result := Clone; end; function TEncodingHelper.EncodingCodePage: Cardinal; begin if Self is TMBCSEncoding then Result := TMBCSEncoding(Self).GetCodePage else if Self is TUnicodeEncoding then Result := CP_UNICODE else if Self is TBigEndianUnicodeEncoding then Result := CP_UNICODE_BE else Result := 0; end; function TEncodingHelper.BufferToString(const aBytes: TEncodingBuffer): OWideString; begin BufferToString(aBytes, Result); end; function TEncodingHelper.BufferToString(const aBytes: TEncodingBuffer; var outString: OWideString): Boolean; var xByteCount, xLength: Integer; begin xByteCount := Length(aBytes); if xByteCount = 0 then begin outString := ''; Result := True; Exit; end; xLength := GetCharCount(aBytes, 0, xByteCount); SetLength(outString, xLength); Result := (xLength > 0); if Result then GetChars(@aBytes[0], xByteCount, PChar(outString), xLength); end; function TEncodingHelper.StringToBuffer(const S: OWideString): TEncodingBuffer; begin Result := GetBytes(S); end; procedure TEncodingHelper.StringToBuffer(const S: OWideString; var outBuffer: TEncodingBuffer); begin outBuffer := GetBytes(S); end; { TMBCSEncodingHelper } function TMBCSEncodingHelper.GetCodePage: Cardinal; begin Result := Self.FCodePage; end; {$ENDIF O_DELPHI_2009_UP} {$IFNDEF O_DELPHI_2009_UP} initialization finalization fxANSIEncoding.Free; fxUTF8Encoding.Free; fxUnicodeEncoding.Free; fxASCIIEncoding.Free; {$ENDIF O_DELPHI_2009_UP} end.
unit Progress; { $Id: PROGRESS.PAS,v 1.5 2005/05/27 15:23:28 lulin Exp $ } interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, W95Meter, VConst, OvcBase; type TProgressDlg = class(TForm) CancelBtn : TBitBtn; PercentMeter : TW95Meter; MsgLabel : TLabel; private { Private declarations } public constructor CreateParam(AOwner : TComponent; aCaption : String); procedure ProgressProc (aState: Byte; aPercent: Integer; aValue: Longint; const aMsg: string); end; implementation {$R *.DFM} constructor TProgressDlg.CreateParam(AOwner : TComponent; aCaption : String); Begin Inherited Create(AOwner); Caption:=aCaption; end; procedure TProgressDlg.ProgressProc (aState: Byte; aPercent: Integer; aValue: Longint; const aMsg: string); Begin Case aState of piStart : Try Show; except end; piCurrent : Begin PercentMeter.Percent:=aPercent; MsgLabel.Caption:=aMsg; end; piEnd : Close; end; end; end.
unit TwoSpaceForOneReplacerTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Модуль: "w:/common/components/gui/Garant/Daily/TwoSpaceForOneReplacerTest.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TTwoSpaceForOneReplacerTest // // Тест замены одного пробела на один // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses SearchAndReplacePrimTest, nevTools, evTypes ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TTwoSpaceForOneReplacerTest = {abstract} class(TSearchAndReplacePrimTest) {* Тест замены одного пробела на один } protected // realized methods function Searcher: IevSearcher; override; function Replacer: IevReplacer; override; function Options: TevSearchOptionSet; override; protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TTwoSpaceForOneReplacerTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses SysUtils, evSearch, TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TTwoSpaceForOneReplacerTest function TTwoSpaceForOneReplacerTest.Searcher: IevSearcher; //#UC START# *4C288BAA0058_4C3C4853033E_var* var l_Searcher : TevBMTextSearcher; //#UC END# *4C288BAA0058_4C3C4853033E_var* begin //#UC START# *4C288BAA0058_4C3C4853033E_impl* l_Searcher := TevBMTextSearcher.Create; try l_Searcher.Options := Options; //l_Searcher.Multiblock := True; l_Searcher.Text := ' '; Result := l_Searcher; finally FreeAndNil(l_Searcher); end;//try..finally //#UC END# *4C288BAA0058_4C3C4853033E_impl* end;//TTwoSpaceForOneReplacerTest.Searcher function TTwoSpaceForOneReplacerTest.Replacer: IevReplacer; //#UC START# *4C288BFC002C_4C3C4853033E_var* //#UC END# *4C288BFC002C_4C3C4853033E_var* begin //#UC START# *4C288BFC002C_4C3C4853033E_impl* Result := TevTextReplacer.Make(' ', Options); //#UC END# *4C288BFC002C_4C3C4853033E_impl* end;//TTwoSpaceForOneReplacerTest.Replacer function TTwoSpaceForOneReplacerTest.Options: TevSearchOptionSet; //#UC START# *4C288CC60231_4C3C4853033E_var* //#UC END# *4C288CC60231_4C3C4853033E_var* begin //#UC START# *4C288CC60231_4C3C4853033E_impl* Result := [ev_soGlobal, ev_soReplace, ev_soReplaceAll]; //#UC END# *4C288CC60231_4C3C4853033E_impl* end;//TTwoSpaceForOneReplacerTest.Options function TTwoSpaceForOneReplacerTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TTwoSpaceForOneReplacerTest.GetFolder function TTwoSpaceForOneReplacerTest.GetModelElementGUID: AnsiString; {-} begin Result := '4C3C4853033E'; end;//TTwoSpaceForOneReplacerTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerInteger; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpCryptoLibTypes, ClpBigInteger, ClpAsn1Object, ClpIProxiedInterface, ClpIAsn1TaggedObject, ClpAsn1OctetString, ClpDerOutputStream, ClpAsn1Tags, ClpArrayUtils, ClpIDerInteger; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SObjectNil = ' "obj" Can''t be Nil'; SValueNil = ' "value" Can''t be Nil'; SMalformedInteger = 'Malformed Integer'; type TDerInteger = class sealed(TAsn1Object, IDerInteger) strict private var Fbytes: TCryptoLibByteArray; function GetBytes: TCryptoLibByteArray; inline; function GetPositiveValue: TBigInteger; inline; function GetValue: TBigInteger; inline; strict protected function Asn1GetHashCode(): Int32; override; function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public constructor Create(value: Int32); overload; constructor Create(const value: TBigInteger); overload; constructor Create(const bytes: TCryptoLibByteArray); overload; property value: TBigInteger read GetValue; property PositiveValue: TBigInteger read GetPositiveValue; property bytes: TCryptoLibByteArray read GetBytes; procedure Encode(const derOut: TStream); override; function ToString(): String; override; // /** // * return an integer from the passed in object // * // * @exception ArgumentException if the object cannot be converted. // */ class function GetInstance(const obj: TObject): IDerInteger; overload; static; // /** // * return an Integer from a tagged object. // * // * @param obj the tagged object holding the object we want // * @param isExplicit true if the object is meant to be explicitly // * tagged false otherwise. // * @exception ArgumentException if the tagged object cannot // * be converted. // */ class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerInteger; overload; static; inline; end; implementation { TDerInteger } function TDerInteger.GetBytes: TCryptoLibByteArray; begin Result := Fbytes; end; class function TDerInteger.GetInstance(const obj: TObject): IDerInteger; begin if ((obj = Nil) or (obj is TDerInteger)) then begin Result := obj as TDerInteger; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; function TDerInteger.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerInteger; begin if (not Supports(asn1Object, IDerInteger, other)) then begin Result := false; Exit; end; Result := TArrayUtils.AreEqual(bytes, other.bytes); end; function TDerInteger.Asn1GetHashCode: Int32; begin Result := TArrayUtils.GetArrayHashCode(Fbytes); end; constructor TDerInteger.Create(const value: TBigInteger); begin inherited Create(); if (not value.IsInitialized) then begin raise EArgumentNilCryptoLibException.CreateRes(@SValueNil); end; Fbytes := value.ToByteArray(); end; constructor TDerInteger.Create(value: Int32); begin inherited Create(); Fbytes := TBigInteger.ValueOf(value).ToByteArray(); end; constructor TDerInteger.Create(const bytes: TCryptoLibByteArray); begin inherited Create(); if (System.Length(bytes) > 1) then begin if ((bytes[0] = 0) and ((bytes[1] and $80) = 0)) then begin raise EArgumentCryptoLibException.CreateRes(@SMalformedInteger); end; if ((bytes[0] = Byte($FF)) and ((bytes[1] and $80) <> 0)) then begin raise EArgumentCryptoLibException.CreateRes(@SMalformedInteger); end; end; Fbytes := System.Copy(bytes); end; procedure TDerInteger.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Integer, Fbytes); end; class function TDerInteger.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerInteger; var o: IAsn1Object; begin if (obj = Nil) then raise EArgumentNilCryptoLibException.CreateRes(@SObjectNil); o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerInteger))) then begin Result := GetInstance(o as TAsn1Object); Exit; end; Result := TDerInteger.Create(TAsn1OctetString.GetInstance(o as TAsn1Object) .GetOctets()); end; function TDerInteger.GetPositiveValue: TBigInteger; begin Result := TBigInteger.Create(1, Fbytes); end; function TDerInteger.GetValue: TBigInteger; begin Result := TBigInteger.Create(Fbytes); end; function TDerInteger.ToString: String; begin Result := value.ToString(); end; end.
unit GetAvoidanceZoneUnit; interface uses SysUtils, BaseExampleUnit; type TGetAvoidanceZone = class(TBaseExample) public procedure Execute(TerritoryId: String); end; implementation uses AvoidanceZoneUnit; procedure TGetAvoidanceZone.Execute(TerritoryId: String); var ErrorString: String; AvoidanceZone: TAvoidanceZone; begin AvoidanceZone := Route4MeManager.AvoidanceZone.Get(TerritoryId, ErrorString); try WriteLn(''); if (AvoidanceZone <> nil) then begin WriteLn('GetAvoidanceZone executed successfully'); WriteLn(Format('Territory ID: %s', [AvoidanceZone.TerritoryId.Value])); end else WriteLn(Format('GetAvoidanceZone error: %s', [ErrorString])); finally FreeAndNil(AvoidanceZone); end; end; end.
unit vtNavigatorUtils; (*----------------------------------------------------------------------------- Название: npUtils Автор: М. Морозов Назначение: История: $Id: vtNavigatorUtils.pas,v 1.23 2015/09/04 13:51:07 kostitsin Exp $ $Log: vtNavigatorUtils.pas,v $ Revision 1.23 2015/09/04 13:51:07 kostitsin {requestlink: 606434039 } Revision 1.22 2015/04/21 11:41:09 morozov {RequestLink: 595974185} Revision 1.21 2015/04/02 07:25:35 morozov {RequestLink: 595963346} Revision 1.20 2015/03/31 16:47:54 lulin - правим руками для NoTabs. Revision 1.19 2015/03/31 16:41:05 lulin - правим руками для NoTabs. Revision 1.18 2015/03/31 16:39:54 lulin - правим руками для NoTabs. Revision 1.17 2015/01/30 11:29:31 morozov {RequestLink: 587161831} Revision 1.16 2014/12/04 12:15:53 morozov {RequestLink: 570120392} Revision 1.15 2014/11/10 09:04:36 morozov {RequestLink: 570120392} Revision 1.14 2014/08/11 12:12:30 morozov {RequestLink: 554580040} Revision 1.13 2014/08/11 11:57:01 morozov {RequestLink: 554580040} Revision 1.12 2014/01/16 11:00:56 morozov {RequestLink: 508187704} Revision 1.11 2014/01/15 09:37:49 morozov {RequestLink: 508187704} Revision 1.10 2014/01/10 16:24:52 kostitsin [$510593012] Revision 1.9 2009/07/29 06:59:02 oman - new: {RequestLink:158336069} Revision 1.8 2009/07/29 06:56:43 oman - new: {RequestLink:158336069} Revision 1.7 2008/06/27 11:13:12 oman - fix: Боремся с балончиками (cq29470) Revision 1.6 2008/06/27 10:37:03 oman - fix: Боремся с балончиками (cq29470) Revision 1.5 2007/08/15 15:15:19 lulin - не передаем лишний параметр. Revision 1.4 2007/08/14 19:31:40 lulin - оптимизируем очистку памяти. Revision 1.3 2005/12/01 14:11:01 mmorozov - bugfix: function npIsWindowMinimized (cq: 00018418); Revision 1.2 2005/07/07 08:44:43 mmorozov new: global function npIsWindowMinimized; Revision 1.1 2005/06/09 09:47:51 mmorozov - компоненты перенесены в библиотеку VT; Revision 1.8 2005/01/28 17:33:05 mmorozov remove: не используемый модуль; Revision 1.7 2005/01/28 17:30:37 mmorozov new: function npIsFloatingForm; new: function npIsInFloatNavigator; Revision 1.6 2004/10/01 09:19:41 mmorozov change: для Немезиса npIsModalForm использует IvcmEntityForm.IsModalForm; Revision 1.5 2004/09/30 07:21:42 mmorozov new: method npIsParentWindow; new: method npIsModalForm; Revision 1.4 2004/09/17 12:19:11 mmorozov new: overload npIsOwnerWindow; Revision 1.3 2004/08/23 11:34:01 mmorozov no message Revision 1.2 2004/08/23 11:33:19 mmorozov - add cvs log; -----------------------------------------------------------------------------*) {$Include vtDefine.inc} interface uses Classes, Controls, vtNavigator ; function npIsOwnerWindow(aOwner : TComponent; var aControl : TWinControl; aHandle : THandle) : Boolean; overload; {* - проверяет является ли aOwner прародителем окна с описателем aHandle. } function npIsOwnerWindow(aOwner : TComponent; aHandle : THandle) : Boolean; overload; {* - проверяет является ли aOwner прародителем окна с описателем aHandle. } function npIsParentWindow(aParent : TWinControl; aHandle : THandle) : Boolean; {* - определяет является ли aParent родителем aHandle. } function npFindWindow(aComponent : TComponent; aHandle : THandle) : TWinControl; {* - поиск в aComponent окна с описателем aHandle. При поиске проверяются Components и Controls всех вложенных компонентов. } function npIsModalForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle модальной формой. } function npIsFloatingForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle плавающей формой. } function npIsInFloatNavigator(aHandle : THandle) : Boolean; {* - окно находится в плавающем навигаторе. } function npIsWindowMinimized(const aWindow : TWinControl) : Boolean; {* - определяет является ли aWindow минимизированным. } function npGetActivationValue(aNavigator: TWinControl; aMainForm: TWinControl; aWindowWithActivation: THandle): Boolean; {* - возвращает флаг активации - нужно ли скрыть или показать навигатор. } procedure DoNotifyControls(aOwner : TComponent; aMsg : Integer; aWParam : Integer; aLParam : Integer); implementation uses Forms, Windows, {$IfDef Nemesis} SysUtils, vcmInterfaces, {$If not defined(NoTabs) AND not defined(nsTest)} l3TabbedContainersDispatcher, {$IfEnd} {$EndIf Nemesis} l3Base ; procedure DoNotifyControls(aOwner : TComponent; aMsg : Integer; aWParam : Integer; aLParam : Integer); var l_Index : Integer; begin with aOwner do for l_Index := 0 to Pred(ComponentCount) do begin if Components[l_Index] is TWinControl then with TWinControl(Components[l_Index]) do SendMessage(Handle, aMsg, aWParam, aLParam); DoNotifyControls(Components[l_Index], aMsg, aWParam, aLParam); end;//for l_Index end; function npIsWindowMinimized(const aWindow : TWinControl) : Boolean; {* - определяет является ли aWindow минимизированным. } var lWP : TWindowPlacement; begin Result := False; if Assigned(aWindow) and aWindow.HandleAllocated then begin l3FillChar(lWP, SizeOf(lWP)); lWP.length := SizeOf(lWP); Windows.GetWindowPlacement(aWindow.Handle, @lWP); Result := lWP.showCmd = SW_SHOWMINIMIZED; end; end; function npGetActivationValue(aNavigator: TWinControl; aMainForm: TWinControl; aWindowWithActivation: THandle): Boolean; var l_Control: TWinControl; l_ControlParentForm: TCustomForm; begin Result := npIsOwnerWindow(aMainForm, aWindowWithActivation); {$IfDef Nemesis} {$If not defined(nsTest)} {$If not defined(NoTabs)} if Tl3TabbedContainersDispatcher.Instance.NeedUseTabs then begin if (not Result) then begin l_Control := FindControl(aWindowWithActivation); if (l_Control <> nil) then begin if (l_Control.Owner <> nil) and (l_Control.Owner is TControl) then begin l_ControlParentForm := GetParentForm(TControl(l_Control.Owner)); if ((l_ControlParentForm = GetParentForm(aNavigator)) or ((aNavigator.Owner <> nil) and (aNavigator.Owner is TControl) and (l_ControlParentForm = GetParentForm(TControl(aNavigator.Owner)))) or ((l_ControlParentForm = aMainForm) and aMainForm.Visible)) then // - http://mdp.garant.ru/pages/viewpage.action?pageId=570120392, // - http://mdp.garant.ru/pages/viewpage.action?pageId=595963346 Result := True; end; end; end else Result := Result and aMainForm.Visible; // - http://mdp.garant.ru/pages/viewpage.action?pageId=587161831 // Вроде бы незачем показывать навигатор, если форма еще не показывается end;//Tl3TabbedContainersDispatcher.Instance.NeedUseTabs {$IfEnd} {$IfEnd} {$EndIf Nemesis} end; function npIsInFloatNavigator(aHandle : THandle) : Boolean; {* - окно находится в плавающем навигаторе. } var lControl : TWinControl; begin Result := False; lControl := FindControl(aHandle); if Assigned(lControl) then begin while Assigned(lControl) do begin if lControl is TnpFloatingWindow then begin Result := True; Break; end; lControl := lControl.Parent; end; end; end; function npIsModalForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle модальной формой. } var lControl : TWinControl; {$IfDef Nemesis} lForm : IvcmEntityForm; {$EndIf Nemesis} begin lControl := FindControl(aHandle); Result := Assigned(lControl) and (lControl is TCustomForm); if Result then {$IfDef Nemesis} if Supports(lControl, IvcmEntityForm, lForm) then try Result := lForm.IsModalForm; finally lForm := nil; end else Result := (fsModal in TCustomForm(lControl).FormState); {$Else} Result := (fsModal in TCustomForm(lControl).FormState); {$EndIf Nemesis} end; function npIsFloatingForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle плавающей формой. } var lControl : TWinControl; {$IfDef Nemesis} lForm : IvcmEntityForm; {$EndIf Nemesis} begin lControl := FindControl(aHandle); Result := Assigned(lControl) and (lControl is TCustomForm); if Result then {$IfDef Nemesis} if Supports(lControl, IvcmEntityForm, lForm) then try Result := (lForm.ZoneType in [vcm_ztFloating, vcm_ztSimpleFloat]); finally lForm := nil; end; {$Else} Result := TCustomForm(lControl).Owner = Application; {$EndIf Nemesis} end; function npIsOwnerWindow(aOwner : TComponent; aHandle : THandle) : Boolean; {* - проверяет является ли aOwner прародителем окна с описателем aHandle. } var lControl : TWinControl; begin Result := npIsOwnerWindow(aOwner, lControl, aHandle); end; function npIsOwnerWindow(aOwner : TComponent; var aControl : TWinControl; aHandle : THandle) : Boolean; var lOwner : TComponent; begin Result := False; aControl := FindControl(aHandle); if Assigned(aControl) then begin {$IfDef Nemesis} {$If not defined(nsTest)} {$If not defined(NoTabs)} if Tl3TabbedContainersDispatcher.Instance.NeedUseTabs and (aControl <> aOwner) AND (aOwner is TForm) AND (aControl <> nil) AND (aControl is TForm) then Result := Tl3TabbedContainersDispatcher.Instance.IsFormInContainer(TForm(aOwner), TForm(aControl)); // - http://mdp.garant.ru/pages/viewpage.action?pageId=554580040 {$IfEnd} {$IfEnd} {$EndIf Nemesis} if (not Result) then begin if aControl = aOwner then Result := True else begin lOwner := aControl.Owner; while Assigned(lOwner) do begin if (lOwner = aOwner) then begin Result := True; Break; end else lOwner := lOwner.Owner; end; end; end; end; end; function npIsParentWindow(aParent : TWinControl; aHandle : THandle) : Boolean; {* - определяет является ли aParent родителем aHandle. } var lControl : TWinControl; lParent : TWinControl; begin Result := False; lControl := FindControl(aHandle); if Assigned(lControl) then begin lParent := lControl.Parent; while Assigned(lParent) and (lParent <> aParent) do lParent := lParent.Parent; Result := Assigned(lParent); end; end; function npFindWindow(aComponent : TComponent; aHandle : THandle) : TWinControl; var lIndex, J : Integer; lControl : TWinControl; begin Result := nil; with aComponent do for lIndex := 0 to Pred(ComponentCount) do begin (* ребенок и есть искомое окно *) if (Components[lIndex] is TWinControl) then begin lControl := TWinControl(Components[lIndex]); if lControl.HandleAllocated and (lControl.Handle = aHandle) then Result := lControl; (* поищем в компонентах, которые на нём лежат *) if not Assigned(Result) then for J := 0 to Pred(lControl.ControlCount) do begin if (lControl.Controls[J] is TWinControl) and TWinControl(lControl.Controls[J]).HandleAllocated and (TWinControl(lControl.Controls[J]).Handle = aHandle) then Result := TWinControl(lControl.Controls[J]) else Result := npFindWindow(lControl.Controls[J], aHandle); if Assigned(Result) then Break; end; end; (* поищем в детях ребенка *) if not Assigned(Result) and (Components[lIndex].ComponentCount > 0) then Result := npFindWindow(Components[lIndex], aHandle); (* окно найдено, выходим *) if Assigned(Result) then Break; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.1 1/21/2004 4:03:14 PM JPMugaas InitComponent Rev 1.0 11/13/2002 08:00:16 AM JPMugaas } unit IdSASLExternal; interface {$i IdCompilerDefines.inc} uses IdSASL, IdTCPConnection; { Implements RFC 2222: External SASL Mechanism Added 2002-08 } type TIdSASLExternal = class(TIdSASL) protected FAuthIdentity: String; procedure InitComponent; override; public function IsReadyToStart: Boolean; override; class function ServiceName: TIdSASLServiceName; override; function StartAuthenticate(const AChallenge, AHost, AProtocolName: String): String; override; published property AuthorizationIdentity : String read FAuthIdentity write FAuthIdentity; end; implementation { TIdSASLExternal } procedure TIdSASLExternal.InitComponent; begin inherited; FSecurityLevel := 0; // unknown, depends on what the server does end; function TIdSASLExternal.IsReadyToStart: Boolean; begin Result := (AuthorizationIdentity <> ''); end; class function TIdSASLExternal.ServiceName: TIdSASLServiceName; begin Result := 'EXTERNAL'; {Do not translate} end; function TIdSASLExternal.StartAuthenticate( const AChallenge, AHost, AProtocolName: String): String; begin Result := AuthorizationIdentity; end; end.
unit UDataSources; {$mode delphi} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, UAccounts, UNode, UBlockchain, UCoreObjects, UCommon, UMemory, UConst, UCommon.Data, UCommon.Collections, Generics.Collections, Generics.Defaults, syncobjs; type { TAccountsDataSourceBase } TAccountsDataSourceBase = class(TCustomDataSource<TAccount>) protected function GetColumns : TDataColumns; override; public function GetItemField(constref AItem: TAccount; const ABindingName : AnsiString) : Variant; override; end; { TAccountsDataSource } TAccountsDataSource = class(TAccountsDataSourceBase) protected FIncludePending : boolean; FKeys : TSortedHashSet<TAccountKey>; function GetFilterKeys : TArray<TAccountKey>; procedure SetFilterKeys (const AKeys : TArray<TAccountKey>); public property IncludePending : boolean read FIncludePending write FIncludePending; property FilterKeys : TArray<TAccountKey> read GetFilterKeys write SetFilterKeys; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure FetchAll(const AContainer : TList<TAccount>); override; end; { TMyAccountsDataSource } TMyAccountsDataSource = class(TAccountsDataSource) public procedure FetchAll(const AContainer : TList<TAccount>); override; end; { TOperationsDataSourceBase } TOperationsDataSourceBase = class(TCustomDataSource<TOperationResume>) private FStart, FEnd : Cardinal; function GetTimeSpan : TTimeSpan; procedure SetTimeSpan(const ASpan : TTimeSpan); protected function GetColumns : TDataColumns; override; public constructor Create(AOwner: TComponent); override; property TimeSpan : TTimeSpan read GetTimeSpan write SetTimeSpan; property StartBlock : Cardinal read FStart write FStart; property EndBlock : Cardinal read FEnd write FEnd; function GetItemField(constref AItem: TOperationResume; const ABindingName : AnsiString) : Variant; override; end; { TAccountsOperationsDataSource } TAccountsOperationsDataSource = class(TOperationsDataSourceBase) private FAccounts : TSortedHashSet<Cardinal>; function GetAccounts : TArray<Cardinal> ; procedure SetAccounts(const AAccounts : TArray<Cardinal>); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Accounts : TArray<Cardinal> read GetAccounts write SetAccounts; procedure FetchAll(const AContainer : TList<TOperationResume>); override; end; { TPendingOperationsDataSource } TPendingOperationsDataSource = class(TOperationsDataSourceBase) public procedure FetchAll(const AContainer : TList<TOperationResume>); override; end; { TOperationsDataSource } TOperationsDataSource = class(TOperationsDataSourceBase) public procedure FetchAll(const AContainer : TList<TOperationResume>); override; end; implementation uses math, UCoreUtils, UWallet, UTime; { TAccountsDataSourceBase } function TAccountsDataSourceBase.GetColumns : TDataColumns; begin Result := TDataColumns.Create( TDataColumn.From('AccountNumber', true), TDataColumn.From('Account'), TDataColumn.From('Name'), TDataColumn.From('Display'), TDataColumn.From('Balance'), TDataColumn.From('BalanceDecimal'), TDataColumn.From('Key'), TDataColumn.From('Type'), TDataColumn.From('State'), TDataColumn.From('Price'), TDataColumn.From('PriceDecimal'), TDataColumn.From('LockedUntil') ); end; function TAccountsDataSourceBase.GetItemField(constref AItem: TAccount; const ABindingName : AnsiString) : Variant; var index : Integer; begin if ABindingName = 'AccountNumber' then Result := AItem.account else if ABindingName = 'Account' then Result := AItem.AccountString else if ABindingName = 'Name' then Result := AItem.name else if ABindingName = 'Display' then Result := AItem.DisplayString else if ABindingName = 'Balance' then Result := AItem.Balance else if ABindingName = 'BalanceDecimal' then Result := TAccountComp.FormatMoneyDecimal(AItem.Balance) else if ABindingName = 'Key' then Result := TAccountComp.AccountPublicKeyExport(AItem.accountInfo.accountKey) else if ABindingName = 'Type' then Result := AItem.account_type else if ABindingName = 'State' then Result := AItem.accountInfo.state else if ABindingName = 'Price' then Result := AItem.accountInfo.price else if ABindingName = 'PriceDecimal' then Result := TAccountComp.FormatMoneyDecimal(AItem.accountInfo.price) else if ABindingName = 'LockedUntil' then Result := AItem.accountInfo.locked_until_block else raise Exception.Create(Format('Field not found "%s"', [ABindingName])); end; { TAccountsDataSource } constructor TAccountsDataSource.Create(AOwner: TComponent); begin inherited Create(AOwner); FKeys := TSortedHashSet<TAccountKey>.Create(TAccountKeyComparer.Create, TAccountKeyEqualityComparer.Create); end; destructor TAccountsDataSource.Destroy; begin FKeys.Free; end; function TAccountsDataSource.GetFilterKeys : TArray<TAccountKey>; begin Result := FKeys.ToArray; end; procedure TAccountsDataSource.SetFilterKeys (const AKeys : TArray<TAccountKey>); var i : Integer; begin FKeys.Clear; for i := Low(AKeys) to High(AKeys) do FKeys.Add(AKeys[i]); end; procedure TAccountsDataSource.FetchAll(const AContainer : TList<TAccount>); var i : integer; acc : TAccount; safeBox : TPCSafeBox; begin safeBox := TNode.Node.Bank.SafeBox; safeBox.StartThreadSafe; try if FKeys.Count = 0 then for i := 0 to safeBox.AccountsCount - 1 do AContainer.Add(safeBox.Account(i)) // Load all accounts else for i := 0 to safeBox.AccountsCount - 1 do begin // Load key-matching accounts if FIncludePending then acc := TNode.Node.Operations.SafeBoxTransaction.Account(i) else acc := safeBox.Account(i); if FKeys.Contains(acc.accountInfo.accountKey) then AContainer.Add(acc) end; finally safeBox.EndThreadSave; end; end; { TMyAccountsDataSource } procedure TMyAccountsDataSource.FetchAll(const AContainer : TList<TAccount>); var i : integer; LAccs : TArray<TAccount>; begin LAccs := TWallet.Keys.AccountsKeyList.GetAccounts(FIncludePending); if FKeys.Count > 0 then begin for i := Low(LAccs) to High(LAccs) do if FKeys.Contains(LAccs[i].accountInfo.accountKey) then AContainer.Add(LAccs[i]); end else AContainer.AddRange(LAccs); end; { TOperationsDataSourceBase } constructor TOperationsDataSourceBase.Create(AOwner:TComponent); var node : TNode; begin inherited Create(AOwner); node := TNode.Node; if Assigned(Node) then begin FStart := 0; FEnd := node.Bank.BlocksCount - 1; end else begin FStart := 0; FEnd := 0; end; end; function TOperationsDataSourceBase.GetTimeSpan : TTimeSpan; begin Result := TTimeSpan.FromSeconds( CT_NewLineSecondsAvg * (FEnd - FStart + 1) ); end; procedure TOperationsDataSourceBase.SetTimeSpan(const ASpan : TTimeSpan); var node : TNode; begin node := TNode.Node; if Not Assigned(Node) then exit; FEnd := node.Bank.BlocksCount - 1; FStart := ClipValue(FEnd - (ASpan.TotalBlockCount + 1), 0, FEnd); end; function TOperationsDataSourceBase.GetColumns : TDataColumns; begin Result := TDataColumns.Create( TDataColumn.From('OPHASH', true), TDataColumn.From('UnixTime'), TDataColumn.From('Time'), TDataColumn.From('Block'), TDataColumn.From('Index'), TDataColumn.From('BlockLocation'), TDataColumn.From('BlockLocationSortable'), TDataColumn.From('Account'), TDataColumn.From('AccountNumber'), TDataColumn.From('Type'), TDataColumn.From('SubType'), TDataColumn.From('Amount'), TDataColumn.From('AmountDecimal'), TDataColumn.From('Fee'), TDataColumn.From('FeeDecimal'), TDataColumn.From('Balance'), TDataColumn.From('BalanceDecimal'), TDataColumn.From('Payload'), TDataColumn.From('Description') ); end; function TOperationsDataSourceBase.GetItemField(constref AItem: TOperationResume; const ABindingName : AnsiString) : Variant; var index : Integer; begin if ABindingName = 'OPHASH' then Result := TPCOperation.OperationHashAsHexa(AItem.OperationHash) else if ABindingName = 'UnixTime' then Result := AItem.Time else if ABindingName = 'Time' then Result := UnixTimeToLocalStr(AItem.time) else if ABindingName = 'Block' then Result := AItem.Block else if ABindingName = 'Index' then Result := AItem.NOpInsideBlock else if ABindingName = 'BlockLocation' then Result := IIF(AItem.OpType <> CT_PseudoOp_Reward, Inttostr(AItem.Block) + '/' + Inttostr(AItem.NOpInsideBlock+1), Inttostr(AItem.Block)) else if ABindingName = 'BlockLocationSortable' then Result := IIF(AItem.OpType <> CT_PseudoOp_Reward, UInt64(AItem.Block) * 4294967296 + UInt32(AItem.NOpInsideBlock), 0) // number pattern = [block][opindex] else if ABindingName = 'Account' then Result := TAccountComp.AccountNumberToAccountTxtNumber(AItem.AffectedAccount) else if ABindingName = 'AccountNumber' then Result := AItem.AffectedAccount else if ABindingName = 'Type' then Result := AItem.OpType else if ABindingName = 'SubType' then Result := AItem.OpSubtype else if ABindingName = 'Amount' then Result := AItem.Amount else if ABindingName = 'AmountDecimal' then Result := TAccountComp.FormatMoneyDecimal(AItem.Amount) else if ABindingName = 'Fee' then Result := AItem.Fee else if ABindingName = 'FeeDecimal' then Result := TAccountComp.FormatMoneyDecimal(AItem.Fee) else if ABindingName = 'Balance' then Result := AItem.Balance else if ABindingName = 'BalanceDecimal' then Result := TAccountComp.FormatMoneyDecimal(AItem.Balance) else if ABindingName = 'Payload' then Result := AItem.PrintablePayload else if ABindingName = 'Description' then Result := AItem.OperationTxt else raise Exception.Create(Format('Field not found [%s]', [ABindingName])); end; { TAccountsOperationsDataSource } constructor TAccountsOperationsDataSource.Create(AOwner:TComponent); begin inherited Create(AOwner); FAccounts := TSortedHashSet<Cardinal>.Create; end; destructor TAccountsOperationsDataSource.Destroy; begin Inherited; FAccounts.Free; end; function TAccountsOperationsDataSource.GetAccounts : TArray<Cardinal> ; begin Result := FAccounts.ToArray; end; procedure TAccountsOperationsDataSource.SetAccounts(const AAccounts : TArray<Cardinal>); begin FAccounts.Clear; FAccounts.AddRange(AAccounts); end; procedure TAccountsOperationsDataSource.FetchAll(const AContainer : TList<TOperationResume>); var block, i, keyIndex : integer; OPR : TOperationResume; accountBlockOps : TOperationsResumeList; node : TNode; list : Classes.TList; Op : TPCOperation; acc : Cardinal; GC : TDisposables; begin if FAccounts.Count = 0 then exit; node := TNode.Node; if Not Assigned(Node) then exit; TNode.Node.Bank.SafeBox.StartThreadSafe; try accountBlockOps := GC.AddObject(TOperationsResumeList.Create ) as TOperationsResumeList; list := GC.AddObject( Classes.TList.Create ) as Classes.TList; for acc in FAccounts do begin // Load pending operations first list.Clear; accountBlockOps.Clear; Node.Operations.OperationsHashTree.GetOperationsAffectingAccount( acc, list ); if list.Count > 0 then for i := list.Count - 1 downto 0 do begin Op := node.Operations.OperationsHashTree.GetOperation( PtrInt( list[i] ) ); If TPCOperation.OperationToOperationResume( 0, Op, false, acc, OPR ) then begin OPR.NOpInsideBlock := i; OPR.Block := Node.Operations.OperationBlock.block; ; OPR.Balance := Node.Operations.SafeBoxTransaction.Account( acc {Op.SignerAccount} ).balance; AContainer.Add(OPR); end; end; // Load block ops Node.GetStoredOperationsFromAccount(accountBlockOps, acc, MaxInt, 0, MaxInt); for i := 0 to accountBlockOps.Count - 1 do AContainer.Add(accountBlockOps[i]); end; finally TNode.Node.Bank.SafeBox.EndThreadSave; end; end; { TPendingOperationsDataSource } procedure TPendingOperationsDataSource.FetchAll(const AContainer : TList<TOperationResume>); var i : integer; node : TNode; Op : TPCOperation; OPR : TOperationResume; begin node := TNode.Node; if Not Assigned(Node) then exit; for i := Node.Operations.Count - 1 downto 0 do begin Op := Node.Operations.OperationsHashTree.GetOperation(i); If TPCOperation.OperationToOperationResume(0,Op, false, Op.SignerAccount,OPR) then begin OPR.NOpInsideBlock := i; OPR.Block := Node.Bank.BlocksCount; OPR.Balance := Node.Operations.SafeBoxTransaction.Account(Op.SignerAccount).balance; AContainer.Add(OPR); end; end; end; { TOperationsDataSource } procedure TOperationsDataSource.FetchAll(const AContainer : TList<TOperationResume>); var block, i, j, keyIndex : integer; OPR : TOperationResume; blockOps : TPCOperationsComp; node : TNode; GC : TDisposables; begin node := TNode.Node; if Not Assigned(Node) then exit; blockOps := GC.AddObject(TPCOperationsComp.Create(Nil)) as TPCOperationsComp; for block := FEnd downto FStart do begin /// iterate blocks correctly opr := CT_TOperationResume_NUL; if (Node.Bank.Storage.LoadBlockChainBlock(blockOps, block)) then begin AContainer.Add( blockOps.GetMinerRewardPseudoOperation ); if blockOps.Count = 0 then exit; for i := blockOps.Count - 1 downto 0 do begin // reverse order if TPCOperation.OperationToOperationResume(block, blockOps.Operation[i], false, blockOps.Operation[i].SignerAccount, opr) then begin opr.NOpInsideBlock := i; opr.Block := block; opr.time := blockOps.OperationBlock.timestamp; AContainer.Add(opr); end; end; end else break; end; end; end.
unit l3IterateComponentParents; // Модуль: "w:\common\components\rtl\Garant\L3\l3IterateComponentParents.pas" // Стереотип: "Service" // Элемент модели: "Tl3IterateComponentParents" MUID: (551AA9BD01EE) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface {$If NOT Defined(NoVCL)} uses l3IntfUses , l3ProtoObject , Classes ; type Ml3IterateComponentParents_IterateF_Action = function(anItem: TComponent): Boolean; {* Тип подитеративной функции для Ml3IterateComponentParents.IterateF } (* Ml3IterateComponentParents = interface {* Контракт сервиса Tl3IterateComponentParents } procedure IterateF(anAction: Ml3IterateComponentParents_IterateF_Action; aComponent: TComponent); end;//Ml3IterateComponentParents *) Il3IterateComponentParents = interface {* Интерфейс сервиса Tl3IterateComponentParents } procedure IterateF(anAction: Ml3IterateComponentParents_IterateF_Action; aComponent: TComponent); end;//Il3IterateComponentParents Tl3IterateComponentParents = {final} class(Tl3ProtoObject) private f_Alien: Il3IterateComponentParents; {* Внешняя реализация сервиса Il3IterateComponentParents } protected procedure pm_SetAlien(const aValue: Il3IterateComponentParents); procedure ClearFields; override; public procedure IterateF(anAction: Ml3IterateComponentParents_IterateF_Action; aComponent: TComponent); class function Instance: Tl3IterateComponentParents; {* Метод получения экземпляра синглетона Tl3IterateComponentParents } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: Il3IterateComponentParents write pm_SetAlien; {* Внешняя реализация сервиса Il3IterateComponentParents } end;//Tl3IterateComponentParents function L2Ml3IterateComponentParentsIterateFAction(anAction: Pointer): Ml3IterateComponentParents_IterateF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для Ml3IterateComponentParents.IterateF } {$IfEnd} // NOT Defined(NoVCL) implementation {$If NOT Defined(NoVCL)} uses l3ImplUses , Controls , SysUtils , l3Base //#UC START# *551AA9BD01EEimpl_uses* //#UC END# *551AA9BD01EEimpl_uses* ; var g_Tl3IterateComponentParents: Tl3IterateComponentParents = nil; {* Экземпляр синглетона Tl3IterateComponentParents } function L2Ml3IterateComponentParentsIterateFAction(anAction: Pointer): Ml3IterateComponentParents_IterateF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для Ml3IterateComponentParents.IterateF } asm jmp l3LocalStub end;//L2Ml3IterateComponentParentsIterateFAction procedure Tl3IterateComponentParentsFree; {* Метод освобождения экземпляра синглетона Tl3IterateComponentParents } begin l3Free(g_Tl3IterateComponentParents); end;//Tl3IterateComponentParentsFree procedure Tl3IterateComponentParents.pm_SetAlien(const aValue: Il3IterateComponentParents); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//Tl3IterateComponentParents.pm_SetAlien procedure Tl3IterateComponentParents.IterateF(anAction: Ml3IterateComponentParents_IterateF_Action; aComponent: TComponent); //#UC START# *551AAAFB036B_551AA9BD01EE_var* var Hack : Pointer absolute anAction; l_C: TControl; //#UC END# *551AAAFB036B_551AA9BD01EE_var* begin //#UC START# *551AAAFB036B_551AA9BD01EE_impl* if Assigned(f_Alien) then f_Alien.IterateF(anAction, aComponent) else begin try anAction(aComponent); if aComponent is TControl then begin l_C := TControl(aComponent); while Assigned(l_C.Parent) do begin l_C := l_C.Parent; anAction(l_C); end; end; finally l3FreeLocalStub(Hack); end;//try..finally end;//f_Alien <> nil //#UC END# *551AAAFB036B_551AA9BD01EE_impl* end;//Tl3IterateComponentParents.IterateF class function Tl3IterateComponentParents.Instance: Tl3IterateComponentParents; {* Метод получения экземпляра синглетона Tl3IterateComponentParents } begin if (g_Tl3IterateComponentParents = nil) then begin l3System.AddExitProc(Tl3IterateComponentParentsFree); g_Tl3IterateComponentParents := Create; end; Result := g_Tl3IterateComponentParents; end;//Tl3IterateComponentParents.Instance class function Tl3IterateComponentParents.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tl3IterateComponentParents <> nil; end;//Tl3IterateComponentParents.Exists procedure Tl3IterateComponentParents.ClearFields; begin Alien := nil; inherited; end;//Tl3IterateComponentParents.ClearFields {$IfEnd} // NOT Defined(NoVCL) end.
unit UAAPIviacep; interface uses System.SysUtils, System.Classes, System.json, VCL.Forms, IdTCPConnection, IdTCPClient, IdHTTP, IdSSLOpenSSL, IdSSLOpenSSLHeaders; type TAPIViacep = class RespCode: Integer; Logradouro, Complemento, Bairro, Localidade, UF, IBGE, Gia, Unidade : String; procedure BuscarCep(pCep: String); procedure LerJson(pJson: String); function GetRespCode: Integer; function GetLogradouro : String; function GetComplemento : String; function GetBairro : String; function GetLocalidade : String; function GetUF : String; function GetIBGE : String; function GetGia : String; function GetUnidade : String; constructor Create(pCEP : String); end; implementation { TAPIwebm } procedure TAPIViacep.BuscarCep(pCEP: String); var IdHTTP: TIdHTTP; LHandler: TIdSSLIOHandlerSocketOpenSSL; Response: TStringStream; begin IdHTTP := TIdHTTP.Create(nil); LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); LHandler.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2]; IdHTTP.IOHandler := LHandler; Response := TStringStream.Create; try try IdOpenSSLSetLibPath(ExtractFilePath(Application.ExeName)); IdHTTP.Get('https://viacep.com.br/ws/' + pCEP + '/json/', Response); RespCode := IdHTTP.ResponseCode; except RespCode := IdHTTP.ResponseCode; exit; end; finally FreeAndNil(IdHTTP); FreeAndNil(LHandler); FreeAndNil(Response); end; LerJson(Response.DataString); end; constructor TAPIViacep.Create(pCEP: String); begin BuscarCep(pCEP); end; function TAPIViacep.GetBairro: String; begin Result := Bairro; end; function TAPIViacep.GetComplemento: String; begin Result := Complemento; end; function TAPIViacep.GetGia: String; begin Result := Gia; end; function TAPIViacep.GetIBGE: String; begin Result := IBGE; end; function TAPIViacep.GetLocalidade: String; begin Result := Localidade; end; function TAPIViacep.GetLogradouro: String; begin Result := Logradouro; end; function TAPIViacep.GetRespCode: Integer; begin Result := RespCode; end; function TAPIViacep.GetUF: String; begin Result := UF; end; function TAPIViacep.GetUnidade: String; begin Result := Unidade; end; procedure TAPIViacep.LerJson(pJson: String); var umJSONObject : TJSONObject; begin try umJSONObject:= TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(pJson), 0) as TJSONObject; Logradouro := umJSONObject.Get('logradouro').JsonValue.Value; Bairro := umJSONObject.Get('bairro').JsonValue.Value; Localidade := umJSONObject.Get('localidade').JsonValue.Value; Complemento := umJSONObject.Get('complemento').JsonValue.Value; Unidade := umJSONObject.Get('unidade').JsonValue.Value; IBGE := umJSONObject.Get('ibge').JsonValue.Value; UF := umJSONObject.Get('uf').JsonValue.Value; Gia := umJSONObject.Get('gia').JsonValue.Value; finally FreeAndNil(umJSONObject); end; end; end.
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} (* Sorting Array of TIA using an array for weight! *) procedure __SortATIA(var Arr:T2DIntArray; Weight:TIntArray; Left, Right:Integer); var i,j,pivot: Integer; tmp:TIntArray; begin i:=Left; j:=Right; pivot := Weight[(left+right) shr 1]; repeat while pivot > Weight[i] do i:=i+1; while pivot < Weight[j] do j:=j-1; if i<=j then begin tmp:= Arr[i]; Arr[i] := Arr[j]; Arr[j] := tmp; Exch(Weight[i], Weight[j]); j:=j-1; i:=i+1; end; until (i>j); if (Left < j) then __SortATIA(Arr, Weight, Left,j); if (i < Right) then __SortATIA(Arr, Weight, i,Right); end; procedure SortATIAByLength(var Arr:T2DIntArray); var i,Hi: Integer; Weight:TIntArray; begin Hi := Length(Arr); if Hi <= 1 then Exit; SetLength(Weight, Hi); for i := 0 to Hi-1 do Weight[i] := Length(Arr[i]); __SortATIA(Arr, Weight, Low(Arr), High(Arr)); SetLength(Weight, 0); end; procedure SortATIAByMean(var Arr:T2DIntArray); var i,Hi: Integer; Weight:TIntArray; begin Hi := Length(Arr); if Hi <= 1 then Exit; SetLength(Weight, Hi); for i := 0 to Hi-1 do Weight[i] := Round(SumTIA(Arr[i]) / Length(Arr[i])); __SortATIA(Arr, Weight, Low(Arr), High(Arr)); SetLength(Weight, 0); end; procedure SortATIAByFirst(var Arr:T2DIntArray); var i,Hi: Integer; Weight:TIntArray; begin Hi := Length(Arr); if Hi <= 1 then Exit; SetLength(Weight, Hi); for i := 0 to Hi-1 do Weight[i] := Arr[i][0]; __SortATIA(Arr, Weight, Low(Arr), High(Arr)); SetLength(Weight, 0); end; procedure SortATIAByIndex(var Arr:T2DIntArray; index:Int32); var i,Hi,M: Integer; Weight:TIntArray; begin Hi := Length(Arr); if Hi <= 1 then Exit; SetLength(Weight, Hi); for i := 0 to Hi-1 do begin if index <= -1 then M := Max(0,High(Arr[i]) + index) else M := Min(High(Arr[i]), index); Weight[i] := Arr[i][M]; end; __SortATIA(Arr, Weight, Low(Arr), High(Arr)); SetLength(Weight, 0); end;
unit nmzIrfanXnView; // ----------------------------------------------------------------------------- // Class Name: TIrfanXnView // Module: nmzIrfanXnView // Description: Implements support for IrfanView and XnView. // Usage: IrfanXnView := TIrfanXnView.Create('C:\Program Files\IrfanView\i_view32.exe'); // IrfanXnView.GetImage('c:\somepick.psd', Bitmap); // Version: 1.1 // Date: 26-SEP-2006 // Target: Win32, Delphi // Author: Nikolay M. Zhukov, http://www.nmzlabs.com, manager@nmzlabs.com // Copyright: © 2006 Nikolay M. Zhukov // License: Freeware // ----------------------------------------------------------------------------- // ----------------------------------------------------------------- // Minor changes: // Sep 2007 by Alexey Torgashin (marked by '//AT') // ----------------------------------------------------------------- interface uses Windows, SysUtils, Messages, Controls, Graphics, Forms; type TIrfanXnView = class(TObject) private FWindow : HWND; FPath : AnsiString; FForm : TForm; FOldWndProc : TWndMethod; FHostLoaded : Boolean; FBitmapHandle : HBitmap; //AT FProcessInfo: TProcessInformation; procedure WndProc(var Message: TMessage); procedure LoadHost; procedure CloseHost; procedure SetHost(const Value: AnsiString); public // This class is not thread-safe!!! Do not call this function from different // threads! Create another instance of the TIrfanXnView and use it. constructor Create(const APath : AnsiString); destructor Destroy; override; function GetBitmap(const AFileName : AnsiString): HBitmap; //AT property Host : AnsiString read FPath write SetHost; end; implementation const IrfanXnClassName = 'IrfanView'; ParamHidden = ' /hidden'; type TImgBufHeader = packed record copydatahandle : HWND; width : integer; height : integer; bits : AnsiChar; end; PImgBufHeader = ^TImgBufHeader; { TIrfanXnView } procedure TIrfanXnView.CloseHost; begin if FProcessInfo.hProcess <> 0 then begin FHostLoaded := False; TerminateProcess(FProcessInfo.hProcess, 0); end; end; constructor TIrfanXnView.Create(const APath : AnsiString); begin inherited Create; FPath := APath; FForm := TForm.Create(nil); FOldWndProc := FForm.WindowProc; FForm.WindowProc := WndProc; ZeroMemory(@FProcessInfo, SizeOf(FProcessInfo)); end; destructor TIrfanXnView.Destroy; begin if FHostLoaded then CloseHost; FForm.WindowProc := FOldWndProc; //AT FOldWndProc := nil; //AT FForm.Release; //AT, was FForm.Free FForm := nil; //AT inherited; end; function TIrfanXnView.GetBitmap(const AFileName : AnsiString): HBitmap; var CopyData : TCopyDataStruct; ShortName : AnsiString; ImgBuf : TImgBufHeader; Data, Temp: PAnsiChar; DataSize : Integer; begin Result := 0; //AT FBitmapHandle := 0; if not FHostLoaded then LoadHost; if not FHostLoaded then Exit; ZeroMemory(@CopyData, SizeOf(CopyData)); CopyData.dwData := 1; CopyData.cbData := 512; ShortName := ExtractShortPathName(AFileName); //AT ImgBuf.copydatahandle := FForm.Handle; ImgBuf.width := 0; ImgBuf.height := 0; DataSize := SizeOf(ImgBuf) + Length(ShortName) + 1; Data := GetMemory(DataSize); Temp := Data; ZeroMemory(Data, DataSize); CopyMemory(Data, PAnsiChar(ShortName), Length(ShortName)); Inc(Data, Length(ShortName) + 1); CopyMemory(Data, @ImgBuf, SizeOf(ImgBuf)); CopyData.lpData := Temp; SendMessage(FWindow, WM_COPYDATA, FForm.Handle, Integer(@CopyData)); Result := FBitmapHandle; //AT end; procedure TIrfanXnView.LoadHost; var StartupInfo : _StartupInfoA; Wnd : HWND; ThreadID : DWORD; begin ZeroMemory(@FProcessInfo, SizeOf(TProcessInformation)); ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_HIDE; if CreateProcessA(PAnsiChar(FPath), ParamHidden, nil, nil, False, 0, nil, PAnsiChar(ExtractFileDir(FPath)), StartupInfo, FProcessInfo) then begin // We need wait until host application completely loaded. WaitForInputIdle(FProcessInfo.hProcess, INFINITE); // Now we need find window. Wnd := FindWindow(IrfanXnClassName, nil); while Wnd <> 0 do begin // We can use only window which we create by ourself! ThreadID := GetWindowThreadProcessId(Wnd, nil); if ThreadID = FProcessInfo.dwThreadId then begin FWindow := Wnd; FHostLoaded := True; Exit; end; Wnd := FindWindow(IrfanXnClassName, nil); end; // We can't find main host window, because somthing wrong... Close host process CloseHost; end; end; procedure TIrfanXnView.SetHost(const Value: AnsiString); begin if Value <> FPath then begin FPath := Value; CloseHost; end; end; procedure TIrfanXnView.WndProc(var Message: TMessage); var ImgBits : PAnsiChar; TmpPtr : PAnsiChar; CopyData : PCopyDataStruct; BitmapInfo : PBITMAPINFO; HeaderSize : Integer; ImageSize : Integer; begin // Irfan/XnView send result bitmap to our window, using WM_COPYDATA if Message.Msg = WM_COPYDATA then begin CopyData := PCopyDataStruct(Message.LParam); BitmapInfo := PBITMAPINFO(CopyData^.lpdata); HeaderSize := BitmapInfo.bmiHeader.biSize + BitmapInfo.bmiHeader.biClrUsed * SizeOf(TRGBQUAD); // XnView returns image size in the BitmapInfo.bmiHeader.biSizeImage, but // IrfanView always return 0. So, we need to calculate image size by itself. ImageSize := ((((BitmapInfo.bmiheader.biWidth * BitmapInfo.bmiheader.biBitCount) + 31) and (not 31)) div 8) * BitmapInfo.bmiheader.biHeight; if (BitmapInfo.bmiHeader.biWidth > 0) and (BitmapInfo.bmiHeader.biHeight > 0) then begin FBitmapHandle := CreateDIBSection(0, BitmapInfo^, DIB_RGB_COLORS, Pointer(ImgBits), 0, 0); if FBitmapHandle <> 0 then begin GDIFlush; TmpPtr := CopyData^.lpdata; Inc(tmpptr, HeaderSize); move(TmpPtr[0], ImgBits[0], ImageSize); end; end; end else begin if Assigned(FOldWndProc) then //AT FOldWndProc(Message); end; end; end.
unit PageControlWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\PageControlWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "PageControlWordsPack" MUID: (552E49070307) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ElPgCtl , tfwClassLike , tfwScriptingInterfaces , l3Interfaces , TypInfo , l3String , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *552E49070307impl_uses* //#UC END# *552E49070307impl_uses* ; type TkwPopPageControlFindPageByCaption = {final} class(TtfwClassLike) {* Слово скрипта pop:PageControl:FindPageByCaption } private function FindPageByCaption(const aCtx: TtfwContext; aPageControl: TElCustomPageControl; const aCaption: Il3CString): Integer; {* Реализация слова скрипта pop:PageControl:FindPageByCaption } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopPageControlFindPageByCaption TkwPopPageControlPageCaptionByIndex = {final} class(TtfwClassLike) {* Слово скрипта pop:PageControl:PageCaptionByIndex } private function PageCaptionByIndex(const aCtx: TtfwContext; aPageControl: TElCustomPageControl; anIndex: Integer): AnsiString; {* Реализация слова скрипта pop:PageControl:PageCaptionByIndex } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopPageControlPageCaptionByIndex TkwPopPageControlPageByIndex = {final} class(TtfwClassLike) {* Слово скрипта pop:PageControl:PageByIndex } private function PageByIndex(const aCtx: TtfwContext; aPageControl: TElCustomPageControl; anIndex: Integer): TElTabSheet; {* Реализация слова скрипта pop:PageControl:PageByIndex } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopPageControlPageByIndex TkwPopPageControlGetAllPageCaptions = {final} class(TtfwClassLike) {* Слово скрипта pop:PageControl:GetAllPageCaptions } private function GetAllPageCaptions(const aCtx: TtfwContext; aPageControl: TElCustomPageControl): AnsiString; {* Реализация слова скрипта pop:PageControl:GetAllPageCaptions } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopPageControlGetAllPageCaptions function TkwPopPageControlFindPageByCaption.FindPageByCaption(const aCtx: TtfwContext; aPageControl: TElCustomPageControl; const aCaption: Il3CString): Integer; {* Реализация слова скрипта pop:PageControl:FindPageByCaption } //#UC START# *552E497A03E2_552E497A03E2_4E36C0C3014B_Word_var* var I, l_PageNum: Integer; //#UC END# *552E497A03E2_552E497A03E2_4E36C0C3014B_Word_var* begin //#UC START# *552E497A03E2_552E497A03E2_4E36C0C3014B_Word_impl* l_PageNum := 0; for I := 0 to aPageControl.PageCount - 1 do if aPageControl.Pages[I].TabVisible then begin if l3Same(aPageControl.Pages[I].Caption, aCaption) then begin Result := l_PageNum; Exit; end; Inc(l_PageNum); end; RunnerError('Вкладка не найдена!', aCtx); Result := -1; //#UC END# *552E497A03E2_552E497A03E2_4E36C0C3014B_Word_impl* end;//TkwPopPageControlFindPageByCaption.FindPageByCaption class function TkwPopPageControlFindPageByCaption.GetWordNameForRegister: AnsiString; begin Result := 'pop:PageControl:FindPageByCaption'; end;//TkwPopPageControlFindPageByCaption.GetWordNameForRegister function TkwPopPageControlFindPageByCaption.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwPopPageControlFindPageByCaption.GetResultTypeInfo function TkwPopPageControlFindPageByCaption.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopPageControlFindPageByCaption.GetAllParamsCount function TkwPopPageControlFindPageByCaption.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TElCustomPageControl), @tfw_tiString]); end;//TkwPopPageControlFindPageByCaption.ParamsTypes procedure TkwPopPageControlFindPageByCaption.DoDoIt(const aCtx: TtfwContext); var l_aPageControl: TElCustomPageControl; var l_aCaption: Il3CString; begin try l_aPageControl := TElCustomPageControl(aCtx.rEngine.PopObjAs(TElCustomPageControl)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aPageControl: TElCustomPageControl : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aCaption := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aCaption: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(FindPageByCaption(aCtx, l_aPageControl, l_aCaption)); end;//TkwPopPageControlFindPageByCaption.DoDoIt function TkwPopPageControlPageCaptionByIndex.PageCaptionByIndex(const aCtx: TtfwContext; aPageControl: TElCustomPageControl; anIndex: Integer): AnsiString; {* Реализация слова скрипта pop:PageControl:PageCaptionByIndex } //#UC START# *552E49BC0078_552E49BC0078_4E36C0C3014B_Word_var* var I : Integer; //#UC END# *552E49BC0078_552E49BC0078_4E36C0C3014B_Word_var* begin //#UC START# *552E49BC0078_552E49BC0078_4E36C0C3014B_Word_impl* RunnerAssert(anIndex >= 0, 'Давай положительное число!', aCtx); RunnerAssert(anIndex < aPageControl.PageCount, 'На PageControl меньше вкладок!', aCtx); for I := 0 to aPageControl.PageCount - 1 do if aPageControl.Pages[I].TabVisible then begin if anIndex = 0 then begin Result := aPageControl.Pages[I].Caption; Break; end; Dec(anIndex); end; //#UC END# *552E49BC0078_552E49BC0078_4E36C0C3014B_Word_impl* end;//TkwPopPageControlPageCaptionByIndex.PageCaptionByIndex class function TkwPopPageControlPageCaptionByIndex.GetWordNameForRegister: AnsiString; begin Result := 'pop:PageControl:PageCaptionByIndex'; end;//TkwPopPageControlPageCaptionByIndex.GetWordNameForRegister function TkwPopPageControlPageCaptionByIndex.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopPageControlPageCaptionByIndex.GetResultTypeInfo function TkwPopPageControlPageCaptionByIndex.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopPageControlPageCaptionByIndex.GetAllParamsCount function TkwPopPageControlPageCaptionByIndex.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TElCustomPageControl), TypeInfo(Integer)]); end;//TkwPopPageControlPageCaptionByIndex.ParamsTypes procedure TkwPopPageControlPageCaptionByIndex.DoDoIt(const aCtx: TtfwContext); var l_aPageControl: TElCustomPageControl; var l_anIndex: Integer; begin try l_aPageControl := TElCustomPageControl(aCtx.rEngine.PopObjAs(TElCustomPageControl)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aPageControl: TElCustomPageControl : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(PageCaptionByIndex(aCtx, l_aPageControl, l_anIndex)); end;//TkwPopPageControlPageCaptionByIndex.DoDoIt function TkwPopPageControlPageByIndex.PageByIndex(const aCtx: TtfwContext; aPageControl: TElCustomPageControl; anIndex: Integer): TElTabSheet; {* Реализация слова скрипта pop:PageControl:PageByIndex } //#UC START# *552E49E00306_552E49E00306_4E36C0C3014B_Word_var* //#UC END# *552E49E00306_552E49E00306_4E36C0C3014B_Word_var* begin //#UC START# *552E49E00306_552E49E00306_4E36C0C3014B_Word_impl* RunnerAssert(anIndex >= 0, 'Давай положительное число!', aCtx); RunnerAssert(anIndex < aPageControl.PageCount, 'На PageControl меньше вкладок!', aCtx); Result := aPageControl.Pages[anIndex]; //#UC END# *552E49E00306_552E49E00306_4E36C0C3014B_Word_impl* end;//TkwPopPageControlPageByIndex.PageByIndex class function TkwPopPageControlPageByIndex.GetWordNameForRegister: AnsiString; begin Result := 'pop:PageControl:PageByIndex'; end;//TkwPopPageControlPageByIndex.GetWordNameForRegister function TkwPopPageControlPageByIndex.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TElTabSheet); end;//TkwPopPageControlPageByIndex.GetResultTypeInfo function TkwPopPageControlPageByIndex.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopPageControlPageByIndex.GetAllParamsCount function TkwPopPageControlPageByIndex.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TElCustomPageControl), TypeInfo(Integer)]); end;//TkwPopPageControlPageByIndex.ParamsTypes procedure TkwPopPageControlPageByIndex.DoDoIt(const aCtx: TtfwContext); var l_aPageControl: TElCustomPageControl; var l_anIndex: Integer; begin try l_aPageControl := TElCustomPageControl(aCtx.rEngine.PopObjAs(TElCustomPageControl)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aPageControl: TElCustomPageControl : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(PageByIndex(aCtx, l_aPageControl, l_anIndex)); end;//TkwPopPageControlPageByIndex.DoDoIt function TkwPopPageControlGetAllPageCaptions.GetAllPageCaptions(const aCtx: TtfwContext; aPageControl: TElCustomPageControl): AnsiString; {* Реализация слова скрипта pop:PageControl:GetAllPageCaptions } //#UC START# *552E4A5E02C9_552E4A5E02C9_4E36C0C3014B_Word_var* var l_Captions: AnsiString; I: Integer; //#UC END# *552E4A5E02C9_552E4A5E02C9_4E36C0C3014B_Word_var* begin //#UC START# *552E4A5E02C9_552E4A5E02C9_4E36C0C3014B_Word_impl* l_Captions := ''; for I := 0 to aPageControl.PageCount - 1 do if aPageControl.Pages[I].TabVisible then if (Length(l_Captions) > 0) then l_Captions := l_Captions + ' | ' + l3Str(aPageControl.Pages[I].Caption) else l_Captions := l3Str(aPageControl.Pages[I].Caption); Result := l_Captions; //#UC END# *552E4A5E02C9_552E4A5E02C9_4E36C0C3014B_Word_impl* end;//TkwPopPageControlGetAllPageCaptions.GetAllPageCaptions class function TkwPopPageControlGetAllPageCaptions.GetWordNameForRegister: AnsiString; begin Result := 'pop:PageControl:GetAllPageCaptions'; end;//TkwPopPageControlGetAllPageCaptions.GetWordNameForRegister function TkwPopPageControlGetAllPageCaptions.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopPageControlGetAllPageCaptions.GetResultTypeInfo function TkwPopPageControlGetAllPageCaptions.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopPageControlGetAllPageCaptions.GetAllParamsCount function TkwPopPageControlGetAllPageCaptions.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TElCustomPageControl)]); end;//TkwPopPageControlGetAllPageCaptions.ParamsTypes procedure TkwPopPageControlGetAllPageCaptions.DoDoIt(const aCtx: TtfwContext); var l_aPageControl: TElCustomPageControl; begin try l_aPageControl := TElCustomPageControl(aCtx.rEngine.PopObjAs(TElCustomPageControl)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aPageControl: TElCustomPageControl : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(GetAllPageCaptions(aCtx, l_aPageControl)); end;//TkwPopPageControlGetAllPageCaptions.DoDoIt initialization TkwPopPageControlFindPageByCaption.RegisterInEngine; {* Регистрация pop_PageControl_FindPageByCaption } TkwPopPageControlPageCaptionByIndex.RegisterInEngine; {* Регистрация pop_PageControl_PageCaptionByIndex } TkwPopPageControlPageByIndex.RegisterInEngine; {* Регистрация pop_PageControl_PageByIndex } TkwPopPageControlGetAllPageCaptions.RegisterInEngine; {* Регистрация pop_PageControl_GetAllPageCaptions } TtfwTypeRegistrator.RegisterType(TypeInfo(TElCustomPageControl)); {* Регистрация типа TElCustomPageControl } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(TypeInfo(TElTabSheet)); {* Регистрация типа TElTabSheet } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа Il3CString } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit delphi_rounded_corners; interface uses Winapi.Windows; type TRoundedWindowCornerType = (RoundedCornerDefault, RoundedCornerOff, RoundedCornerOn, RoundedCornerSmall); //////////////////////////////////////////////////////////////////////////// // // Originally written by Ian Barker // https://github.com/checkdigits // https://about.me/IanBarker // ian.barker@gmail.com // // Based on an example in an answer during the RAD Studio 11 Launch Q & A // // // Free software - use for any purpose including commercial use. // //////////////////////////////////////////////////////////////////////////// // // Set or prevent Windows 11 from rounding the corners or your application // // Usage: // SetRoundedCorners(Self.Handle, RoundedCornerSmall); // //////////////////////////////////////////////////////////////////////////// /// procedure SetRoundedCorners(const TheHandle: HWND; const CornerType: TRoundedWindowCornerType); implementation uses Winapi.Dwmapi; const // // More information: // https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/apply-rounded-corners // https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute // https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/nf-dwmapi-dwmsetwindowattribute // DWMWCP_DEFAULT = 0; // Let the system decide whether or not to round window corners DWMWCP_DONOTROUND = 1; // Never round window corners DWMWCP_ROUND = 2; // Round the corners if appropriate DWMWCP_ROUNDSMALL = 3; // Round the corners if appropriate, with a small radius DWMWA_WINDOW_CORNER_PREFERENCE = 33; // [set] WINDOW_CORNER_PREFERENCE, Controls the policy that rounds top-level window corners procedure SetRoundedCorners(const TheHandle: HWND; const CornerType: TRoundedWindowCornerType); var DWM_WINDOW_CORNER_PREFERENCE: Cardinal; begin case CornerType of RoundedCornerOff: DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_DONOTROUND; RoundedCornerOn: DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_ROUND; RoundedCornerSmall: DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_ROUNDSMALL; else DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_DEFAULT; end; Winapi.Dwmapi.DwmSetWindowAttribute(TheHandle, DWMWA_WINDOW_CORNER_PREFERENCE, @DWM_WINDOW_CORNER_PREFERENCE, sizeof(DWM_WINDOW_CORNER_PREFERENCE)); end; end.
unit commands_http; interface uses commandprocessor, httpclient, sysutils, tickcount, https; type Tcmd_HTTPDownload = class(TCommand) private FURL: string; FClient: THTTPSCLient; FTimeout: ticker; function GetTimeout: ticker; procedure SetTimeout(const Value: ticker); public constructor Create;override; destructor Destroy;override; property URL: string read FURL write FURL; property Client: THTTPCLient read FClient; procedure DoExecute;override; procedure OnHTTPProgress(pos, max: int64); property Timeout: ticker read GetTimeout write SetTimeout; end; Tcmd_HTTPDownLoadToFile = class(Tcmd_HTTPDownload) private FFile: string; public IgnoreIfTargetExists: boolean; procedure InitExpense;override; procedure DoExecute;override; property LocalFile: string read FFile write FFile; end; implementation { Tcmd_HTTPDownload } constructor Tcmd_HTTPDownload.Create; begin inherited; FClient := THTTPCLient.create; FTimeout := 300000; end; destructor Tcmd_HTTPDownload.Destroy; begin FClient.free; inherited; end; procedure Tcmd_HTTPDownload.DoExecute; begin inherited; FClient.OnProgress := self.OnHTTPProgress; FClient.TimeOut := Timeout; FClient.Get(URL, ''); // beeper.beep(1000,100); end; function Tcmd_HTTPDownload.GetTimeout: ticker; begin result := FTimeout; end; procedure Tcmd_HTTPDownload.OnHTTPProgress(pos, max: int64); begin self.Step := pos; self.StepCount := max; self.NotifyProgress; end; procedure Tcmd_HTTPDownload.SetTimeout(const Value: ticker); begin FTimeout := value; end; { THTTPDownLoadToFileCommand } procedure Tcmd_HTTPDownLoadToFile.DoExecute; begin if (not IgnoreIfTargetExists) or (not FileExists(localfile)) then begin inherited; Client.SaveToFile(LocalFile); end; end; procedure Tcmd_HTTPDownLoadToFile.InitExpense; begin // inherited; NetworkExpense := 1/8; end; end.
unit FET; interface uses complex2,stringe,math; type sparm = array[1..4] of Tc; Tdata = record parm : Sparm; freq : real; end; Tnoise = record freq,Fmin,Rn : real; Topt : tc; Gn : real; Ycor : tc; n1,n2 : double; nC : tc; V0,V2,V3 : tc; end; transistor = object Re,Rc,Rb : tc; data : array[1..3000] of Tdata; noise : array[1..1000] of Tnoise; hoefdata,hoefNoise : integer; filename : string; procedure laaiS(leer : string); function kryfreq(freq : double) : sparm; function kryY(freq : double) : sparm; function kryNfreq(freq : double) : Tnoise; Procedure DAnoise(freq : real;var ki,ku : double;var C : tc); function ZZb(Sp : sparm) : Tc; function ZZe(Sp : sparm) : Tc; function ZZc(Sp : sparm) : Tc; Procedure Isrc(w : double;var V : array of tc); Procedure calcnoise(var N1 : tnoise); end; Ptransistor = ^transistor; function loadFET(s : string) : transistor; implementation uses consts,sysutils; var FETS : array of Transistor; nFET : integer; function loadFET(s : string) : transistor; var x : integer; begin for x:=0 to nFET-1 do if FETS[x].filename=s then begin loadFET:=FETS[x]; exit; end; setlength(FETS,nFET+1); FETS[nFET].laaiS(s); loadFET:=FETS[nFET]; inc(nFET); end; function inverse(Z : sparm) : sparm; var res : sparm; Q : Tc; begin Q:=1.0/(Z[1]*Z[4]-z[2]*z[3]); res[1]:=Z[4]*Q; res[2]:=-z[3]*Q; res[3]:=-z[2]*Q; res[4]:=Z[1]*Q; inverse:=res; end; function SnaZ(Z : sparm) : sparm; var S : sparm; a,Z11m,z11p,z22m,z22p,onder : tc; begin // for i:=1 to 4 do Z[i]:=crmaal(z2[i],1/50.0); a:=Z[2]*Z[3]; z11m := 1-Z[1]; Z11p := Z[1]+1; z22m := 1-Z[4]; Z22p := 1+Z[4]; onder:=1/(z11m*z22m-a); S[1]:=(z11p*z22m+a)*onder; S[2]:=Z[2]*2*onder; S[3]:=Z[3]*2*onder; S[4]:=(z11m*z22p+a)*onder; SnaZ:=S; end; function SnaY(S : sparm) : sparm; var Y : sparm; onder : tc; begin onder:=(1+S[1])*(1+S[4])-S[2]*S[3]; onder:=1/50/onder; Y[1]:=(S[2]*S[3]+(1-S[1])*(1+S[4]))*onder; Y[4]:=(S[2]*S[3]+(1+S[1])*(1-S[4]))*onder; Y[2]:=S[2]*onder*(-2); Y[3]:=S[3]*onder*(-2); SnaY:=Y; end; Procedure Nparam2RG(var Rn,Gn : double;var Ycor : tc;x,y : real;A : tc); var Ymin : tc; begin Ymin:=(1-A)/(1+A)/50; // Cwrite(Ymin*1000);writeln; // x:=(power(10,(x/10))-1); // writeln('Fmin=',x); Rn:=y{*50}; if Rn=0 then Ycor:=czero else if Rn<0 then begin Gn:=-1; rn:=-rn; Ycor:=czero; end else begin Ycor[1]:=x/(2*Rn)-Ymin[1]; Ycor[2]:=-Ymin[2]; // Cwrite(Ycor*1000);writeln; Gn:=(sqr(Ymin[1])-sqr(Ycor[1]))*Rn; if Gn<0 then Gn:=0; end; // writeln({freq:3:1,}' Rn=',Rn:3:1,' Gn=',Gn*1e3:6:4,'Gcor=',Ycor[1]*1e3:6:4,' Bcor=',Ycor[2]*1e3:6:4,' fmin=',2*(rn*Ycor[1]+sqrt(rn*gn+sqr(Rn*Ycor[1]))):6:4); end; Procedure transistor.calcnoise(var N1 : tnoise); var // N : tnoise2; i,u : double; Y : sparm; begin with N1 do begin Y:={SnaY}(kryfreq(freq)); Nparam2RG(Rn,Gn,Ycor,Fmin,Rn,Topt); u:=sqrt(k4*Rn*290); if Gn<0 then begin V0:=czero; V2:=czero; V3:=-r2c(u,0);//*Y[2]; end else begin i:=sqrt(k4*Gn*290); V0:=r2c(i,0); V2:=u*Ycor-u*Y[1]; V3:=-r2c(u,0)*Y[2]; end; n1:=sqrt(cabs2(V0)+cabs2(V2)); n2:=sqrt(cabs2(V3)); nc:=V2*ccomp(V3); end;end; Procedure transistor.Isrc(w : double;var V : array of tc); var Y : sparm; // N : Tnoise2; N1 : tnoise; i,u,A : double; // Cor : tc; x : integer; begin //write('Isrc; '); w:=w/twopi/1e9; //write('kryfreq; '); Y:={SnaY}(kryfreq(w)); //write('kryNfreq; '); N1:=kryNfreq(w); //with N1 do Nparam2RG(N,Fmin,Rn,Topt); with N1 do begin // Nparam2RG(Rn,Gn,Ycor,Fmin,Rn,Topt); //write('N1=',N1,' N2=',N2,' NC=');cwrite(NC);writeln; { A:=N1*N1-cabs2(NC)/(N2*N2); if A<=0 then V[0]:=czero else V[0]:=r2c(sqrt(N1*N1-cabs2(NC)/(N2*N2)),0); V[1]:=czero; V[2]:=NC/N2; V[3]:=r2c(N2,0); write('Inoise='); for x:=0 to 3 do cwrite(V[x]);writeln;} //Ycor:=Y[1]-nC/rn/ccomp(Y[2]); //write('Rn=',Rn,' Gn=',Gn,' Ycor=');cwrite(Ycor);writeln; u:=sqrt(k4*Rn*290); if Gn<0 then begin V[0]:=czero; V[1]:=czero; V[2]:=czero; V[3]:=-r2c(u,0)*Y[2]; end else begin i:=sqrt(k4*Gn*290); V[0]:=r2c(i,0); V[1]:=czero; V[2]:=u*Ycor-u*Y[1]; V[3]:=-r2c(u,0)*Y[2]; end; {write('Inoise='); for x:=0 to 3 do cwrite(V[x]);writeln;} // V[2]:=V[2]/V[3]*sqrt(cabs2(v[3])); // V[3]:=r2c(sqrt(cabs2(V[3])),0); //V[0]:=V0; //V[1]:=czero; //V[2]:=V2; //V[3]:=V3; end; //write('Inoise='); //for x:=0 to 3 do cwrite(V[x]);writeln; //Cor:=V[0]*V[1]+V[2]*V[3]; //Cor:=Cor/sqrt( (cabs2(V[0])+cabs2(V[2])) * (cabs2(V[1])+cabs2(V[3]))); //write('Cor=');cwrite(Cor); //write('Y='); //for x:=1 to 4 do cwrite(Y[x]);writeln; end; function par(A,B : tc) : tc; begin par:=A*B/(A+B); end; Procedure Transistor.DAnoise(freq : real;var ki,ku : double;var C : tc); {var Y : Sparm; N1 : Tnoise; N : Tnoise2; x : integer; Cgs,C1,w : double; Zin,Zin2,ZL,ZLC,Zuit,Zt : tc; Zloss,L : tc; kig,kir,kug,kur : tc; X1,XF : tc; vv,vg : tc; Zu,Zi,onder,L2 : double; }begin {Zu:=1; Zi:=50; {Y:=kryfreq(freq); for x:=1 to 4 do cwrite(Y[x]); writeln; } Y:={SnaY}(kryfreq(freq)); {for x:=1 to 4 do cwrite(Y[x]); writeln; } N1:=kryNfreq(freq); //cwrite(N1.Topt);writeln(N1.fmin:6:4); w:=freq*2*pi*1e9; with n1 do Nparam2RG(N,Fmin,Rn,Topt); with N do begin Cgs:=1e-12; C1:=10e-12; X1:=R2C(0,-1/(W*C1)); X1:=R2C(0,0); Zin:=1/(Y[1]+Zu*Y[2]*Y[3]/(2-Y[4]*Zu)); Y[1,2]:=Y[1,2]-w*Cgs; Zin2:=1/(Y[1]+Zu*Y[2]*Y[3]/(2-Y[4]*Zu)); XF:=R2C(0,-1/(W*Cgs)); ZL:=par(R2C(Zi/2,0),-X1-Xf); ZLC:=ZL+X1; Zuit:=par(ZLC,Xf); //Impedansie as vanaf hek kyk na intree voerlyn Zt:=par(Zin,ZLC); //Vg:=zt*I //I=sqrt(gn)+(Ycor-1/Zin)sqrt(Rn) Vv:=Zt*ZLC/(ZLC+X1); //I-bron na v-bron, v-bron na voerlyn. Sein v2=kTBZi vs i2=4kTBGn kig:=2/sqrt(Zi)*{vv=}Zl/(Zlc+Zin)*{v=}Zin*sqrt(gn); //I-bron na v-bron - vbron kir:=2/sqrt(Zi)*Zl/(Zl+x1+Zin)*sqrt(rn)*(Ycor*Zin-1); vg:=Zin/(Zin+ZLC);//*V=ZLC*sqrt(gn)+(ZLC*Ycor+1)sqrt(Rn) cwrite((Zin)/Zt);writeln; write('Zin=');cwrite(Zin);writeln; write('ZL =');cwrite( ZL);writeln; write('ZLC=');cwrite(ZLC);writeln; write('Zt =');cwrite( Zt);writeln; write('Vv =');cwrite( vv);writeln; //vgs = Zin / (Zin + X1) sqrt(kTBZi) //Vgi = Zin / (Zin + ZLc)* ZLC * sqrt(4kTBGn) //I-bron na v-bron, verg vg a.g.v. sein kug:=2/sqrt(Zi)*(Zin+X1)/(Zin+Zlc)*{v=}ZLC*sqrt(gn); kur:=2/sqrt(Zi)*(Zin+X1)/(Zin+Zlc)*(ZLC*Ycor+1)*sqrt(Rn); ki:=sqrt(cabs2(kig)+cabs2(kir)); ku:=sqrt(cabs2(kug)+cabs2(kur)); C:=(kig*kug+kir*kur)/(ki*ku); write(' kir=');cwrite(kir/ki); write(' kig=');cwrite(kig/ki);writeln; write(' kur=');cwrite(kur/ku); write(' kug=');cwrite(kug/ku);writeln; write(' ki=',ki:5:2,' ku=',ku:5:2,' C=');cwrite(C); writeln; writeln('Tg=',ki*ki*290:5:1); writeln('Td=',ku*ku*290:5:1); //loss Zloss:=par(par(Zin+X1,-X1-Xf),R2C(Zi,0)); L:=2*Zloss/(Zloss+Zi); L2:=sqrt(cabs2(L)); write('L=',L2:8:4,' = ');cwrite(l);writeln; //halt; end;} end; procedure Transistor.laaiS(leer : string); var f : text; s : string; s2 : Tstrings; vv,ii : string; x,y : real; d : integer; A : tc; freqfac : double; db : boolean; begin assign(f,leer); filename:=leer; {$i-} reset(f); {$i+} if ioresult<>0 then begin writeln('Can''t load ',leer); halt(1); end; writeln('Load: ',leer); hoefdata:=0;hoefnoise:=0; freqfac:=1;db:=false; while not(eof(f)) do begin readln(f,s); if (s<>'') and (s[1]='#') then begin s:=uppercase(s); if pos('GHZ',s)>0 then freqfac:=1e9; if pos('MHZ',s)>0 then freqfac:=1e6; if pos('DB',s)>0 then db:=true; //writeln('freqfac=',freqfac); //if db then writeln('DB'); end; subs(s,#9,' '); s2:=strtostrs(s); //writeln('l=',len(s2)); if (s='') or (s[1]='!') then else if len(s2)=2 then begin vv:=s2[1]; ii:=s2[2]; end else if len(s2)=5 then begin inc(hoefnoise); with noise[hoefnoise] do begin val(s2[3],x,d); val(s2[4],y,d); Topt:=rh2c(x,y/180*pi); val(s2[2],x,d); Fmin:=power(10,x/10)-1; val(s2[5],y,d); Rn:=y*50; val(s2[1],freq,d); freq:=freq*(freqfac/1e9); end; calcnoise(noise[hoefnoise]); end else if len(s2)>=11 then begin inc(hoefdata); with data[hoefdata] do begin val(s2[2],x,d);if db then x:=power(10,(x/20)); val(s2[3],y,d); parm[1]:=rh2c(x,y/180*pi); //write('-',s2[2],'-',x,' '); val(s2[5],x,d);if db then x:=power(10,x/20); val(s2[6],y,d); parm[2]:=rh2c(x,y/180*pi); val(s2[8],x,d);if db then x:=power(10,x/20); val(s2[9],y,d); parm[3]:=rh2c(x,y/180*pi); val(s2[10],x,d);if db then x:=power(10,x/20); val(s2[11],y,d); parm[4]:=rh2c(x,y/180*pi); val(s2[1],freq,d); freq:=freq*(freqfac/1e9); parm:=SnaY(parm); // V:=vv;i:=ii; end; end else if len(s2)>=9 then begin inc(hoefdata); with data[hoefdata] do begin val(s2[2],x,d);if db then x:=power(10,x/20);val(s2[3],y,d); parm[1]:=rh2c(x,y/180*pi); //write('-',s2[2],'-',x,' '); val(s2[4],x,d);if db then x:=power(10,x/20); val(s2[5],y,d); parm[2]:=rh2c(x,y/180*pi); //writeln('p2=',parm[2,1],' x=',x,' y=',y,' hd=',hoefdata); val(s2[6],x,d);if db then x:=power(10,x/20); val(s2[7],y,d); parm[3]:=rh2c(x,y/180*pi); val(s2[8],x,d);if db then x:=power(10,x/20); val(s2[9],y,d); parm[4]:=rh2c(x,y/180*pi); val(s2[1],freq,d); freq:=freq*(freqfac/1e9); parm:=SnaY(parm); // V:=vv;i:=ii; end; end; end; close(f); //if hoefnoise=0 then nnoise:=0; // writeln('loaded: S = ',hoefdata); // writeln(' N = ',hoefnoise); end; function transistor.kryfreq(freq : double) : sparm; var min,max,i : integer; P1,P2,P : sparm; w,w1,w2 : double; begin min:=0; while (min<hoefdata) and (data[min+1].freq<=freq) do inc(min); max:=hoefdata+1; while (max>1) and (data[max-1].freq>=freq) do dec(max); // writeln('min=',min,' max=',max); if min=0 then kryfreq:=data[1].parm else if max=hoefdata+1 then kryfreq:=data[hoefdata].parm else if min>=max then kryfreq:=data[min].parm else begin P1:=data[min].parm; P2:=data[max].parm; w:=data[max].freq-data[min].freq; w1:=(data[max].freq-freq)/w; w2:=(freq-data[min].freq)/w; for i:=1 to 4 do P[i]:=P1[i]*w1+P2[i]*w2; kryfreq:=P; end; end; Function transistor.kryY(freq : double) : sparm; var S : sparm; x : integer; begin S:=kryfreq(freq/1e9); //writeln('freq=',freq/1e9,'GHz'); //S:=SnaY(S); kryY:=S; //for x:=1 to 4 do cwrite(S[x]);writeln; //writeln('done'); end; function Cinter(C1,C2 : tc;w1,w2 : double) : tc; begin Cinter:=C1*w1+C2*w2; end; function transistor.kryNfreq(freq : double) : Tnoise; var min,max,i : integer; P1,P2,P : Tnoise; w,w1,w2,tmp : double; Z : Tnoise; begin min:=0; Z.freq:=freq; while (min<hoefnoise) and (noise[min+1].freq<=freq) do inc(min); max:=hoefnoise+1; while (max>1) and (noise[max-1].freq>=freq) do dec(max); if min=0 then kryNfreq:=noise[1] else if max=hoefnoise+1 then kryNfreq:=noise[hoefnoise] else if min>=max then kryNfreq:=noise[min] else with z do begin w:=noise[max].freq-noise[min].freq; w1:=(noise[max].freq-freq)/w; w2:=(freq-noise[min].freq)/w; P1:=noise[min]; P2:=noise[max]; // Fmin:=p1.Fmin*w1+p2.Fmin*w2; // Rn:=p1.Rn*w1+p2.Rn*w2; Topt:=p1.Topt*w1+p2.Topt*w2; // V0:=p1.V0*w1+p2.V0*w2; // V2:=p1.V2*w1+p2.V2*w2; //V3:=p1.V3*w1+p2.V3*w2; N1:=p1.N1*w1+p2.N1*w2; N2:=p1.N2*w1+p2.N2*w2; NC:=czero; if P1.N1>0 then NC:=NC+p1.NC*w1/(p1.N1*p1.N2); if P2.N1>0 then NC:=NC+p2.NC*w2/(p2.N1*p2.N2); NC:=Nc*N1*N2; Rn:=p1.Rn*w1+p2.Rn*w2; Fmin:=p1.Fmin*w1+p2.Fmin*w2; // Gn:=p1.Gn*w1+p2.Gn*w2; // Ycor:=p1.Ycor*w1+p2.Ycor*w2; Ycor:=(p1.Ycor*w1*p1.Rn+p2.Ycor*w2*P2.Rn)/Rn; with p1 do tmp:=w1*sqrt(Gn*Rn+sqr(Rn*Ycor[1])); with p2 do tmp:=tmp+w2*sqrt(Gn*Rn+sqr(Rn*Ycor[1])); Gn:=(sqr(tmp)-sqr(Rn*Ycor[1]))/Rn; kryNfreq:=z; end; end; { function transistor.kryN2freq(freq : double) : Tnoise2; var min,max,i : integer; P1,P2,P : Tnoise; w,w1,w2 : double; Z : Tnoise; begin //with N1 do Nparam2RG(N,Fmin,Rn,Topt); min:=0; Z.freq:=freq; while (min<hoefnoise) and (noise[min+1].freq<=freq) do inc(min); max:=hoefnoise+1; while (max>1) and (noise[max-1].freq>=freq) do dec(max); if min=0 then kryNfreq:=noise[1] else if max=hoefdata+1 then kryNfreq:=noise[hoefdata] else if min>=max then kryNfreq:=noise[min] else with z do begin w:=noise[max].freq-noise[min].freq; w1:=(noise[max].freq-freq)/w; w2:=(freq-noise[min].freq)/w; P1:=noise[min]; P2:=noise[max]; Fmin:=p1.Fmin*w1+p2.Fmin*w2; Rn:=p1.Rn*w1+p2.Rn*w2; Topt:=p1.Topt*w1+p2.Topt*w2; kryNfreq:=z; end; end; } function form1(zb,ze,S11,S12,S21,S22 : TC) : Tc; const w = 1; var a,b,c,d,v,i : Tc; begin a:= (zb+ze-w)-S11*(zb+ze+w)-S12*ze; b:= Ze - S11*(Ze) - S12*(Ze+w); c:= Ze - S21*(Zb+Ze+w)-S22*(Ze); d:= Ze-w-S21*(Ze)-S22*(Ze+w); V:=B*C - D*A; I:=S12*C - A*(S22-1); form1:=V/I; end; function form2(zb,zc,S11,S12,S21,S22 : Tc) : Tc; const w = 1; var x1,x2,x3,x4,a,b,c,d,v,i : Tc; begin x1:=w-Zb; x2:=-w-zb; x3:=Zc+w; x4:=Zc-w; b :=x1-S11*x2; // //(-zb+W)-S11(-Zb-w) a :=b-S12*x3; //(-zb+W)-S11(-Zb-w)-S12(Zc+w) d :=S21*(Zb+w); c :=x4-S21*x2-S22*x3; // (Zx-w)-S21(-Zb-w)-S22(Zc+w) V := A*D - B*C; I := C*(S11+S12-1) - A*(S21+S22-1); form2:=V/I; end; function ZnaS(Z : sparm) : sparm; var S,S2 : sparm; a,Z11m1,z11p1,z22m1,z22p1,onder : tc; i : integer; begin a:=Z[2]*Z[3]; z11m1 := Z[1]-1; Z11p1 := Z[1]+1; z22m1 := Z[4]-1; Z22p1 := Z[4]+1; onder:=1/(z11p1*z22p1-a); S[1]:= (z11m1*z22p1-a)*onder; S[2]:= Z[2]*2*onder; S[3]:= Z[3]*2*onder; S[4]:=(z11p1*z22m1-a)*onder; ZnaS:=S; end; function transistor.ZZb(Sp : sparm) : tc; begin ZZb:=form1(Rc,Re,sp[4],sp[3],sp[2],sp[1]); end; function transistor.ZZe(Sp : sparm) : tc; begin ZZe:=form2(Rb,Rc,sp[1],sp[2],sp[3],sp[4]); end; function transistor.ZZc(Sp : sparm) : tc; begin ZZc:=form1(Rb,Re,sp[1],sp[2],sp[3],sp[4]); end; function Z12naZ13(Z : sparm) : sparm; var res : sparm; begin res[1]:=Z[4]+Z[1]-(Z[2]+Z[3]); res[2]:=Z[4]-Z[2]; res[3]:=Z[4]-Z[3]; res[4]:=Z[4]; Z12naZ13:=res; end; {var NE : transistor; ki,ku : double; C : tc; begin NE.laaiS('atf38143l.s2p'); NE.DAnoise(1,ki,ku,C); write('ki=',ki*1000:5:3,'k ku=',ku:3:2,' C=');cwrite(C);writeln; } begin nFET:=0; end.
unit PasswordOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, Mask, TTSPasswordOptionsTable, sButton, sComboBox, sGroupBox, sMaskEdit, sCheckBox, sLabel, sPageControl; type TfrmPasswordOptions = class(TForm) PageControl1: TsPageControl; TabSheet1: TsTabSheet; TabSheet2: TsTabSheet; TabSheet3: TsTabSheet; Label1: TsLabel; Label2: TsLabel; Label3: TsLabel; Label4: TsLabel; Label5: TsLabel; CheckBox1: TsCheckBox; passwordValidDays: TsMaskEdit; historySize: TsMaskEdit; minPasswordLength: TsMaskEdit; minChangedChars: TsMaskEdit; allowChangeAfter: TsMaskEdit; Label6: TsLabel; GroupBox1: TsGroupBox; cb_Numeric: TsCheckBox; cb_Symbol: TsCheckBox; cb_alpha: TsCheckBox; cb_Uppercase: TsCheckBox; cb_LowerCase: TsCheckBox; GroupBox2: TsGroupBox; Label7: TsLabel; maxLoginAttempts: TsMaskEdit; CheckBox2: TsCheckBox; Label8: TsLabel; autoUnlockPeriod: TsMaskEdit; unlockUnits: TsComboBox; minUniqueCriteria: TsMaskEdit; btn_cancel: TsButton; btn_ok: TsButton; procedure btn_okClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cb_alphaClick(Sender: TObject); procedure cb_UppercaseClick(Sender: TObject); procedure cb_LowerCaseClick(Sender: TObject); procedure minPasswordLengthExit(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmPasswordOptions: TfrmPasswordOptions; recpo: TTTSPasswordOptionsRecord; implementation uses datamod, TicklerTypes, ffsutils; {$R *.DFM} procedure TfrmPasswordOptions.btn_okClick(Sender: TObject); var criteria: integer; criteriachecked: integer; begin criteria := 0; criteriachecked := 0; recpo.PExpireDays := strtointdef(trim(passwordValidDays.text), 0); recpo.PHistorySize := strtointdef(trim(historySize.text), 0); recpo.PMinLength := strtointdef(trim(minPasswordLength.text), 0); recpo.PMinChangedChars := strtointdef(trim(minChangedChars.text), 0); recpo.PMinDaysUsage := strtointdef(trim(allowChangeAfter.text), 0); if (CheckBox1.Checked = true) then recpo.PNameInPassword := 'YES' else recpo.PNameInPassword := 'NO'; if (cb_alpha.Checked = true) then begin criteria := criteria + ALPHA_CHAR; criteriachecked := criteriachecked + 1; end; if (cb_Uppercase.Checked = true) then begin criteria := criteria + UPPER_CHAR; criteriachecked := criteriachecked + 1; end; if (cb_LowerCase.Checked = true) then begin criteria := criteria + LOWER_CHAR; criteriachecked := criteriachecked + 1; end; if (cb_Symbol.Checked = true) then begin criteria := criteria + SYMBOL_CHAR; criteriachecked := criteriachecked + 1; end; if (cb_Numeric.Checked = true) then begin criteria := criteria + NUMERIC_CHAR; criteriachecked := criteriachecked + 1; end; if (criteriachecked < strtointdef(trim(minUniqueCriteria.text), 0)) then begin TrMsgInformation('Minimum Unique Criteria cannot be less than number of unique criterias checked'); exit; end; recpo.PCriteria := criteria; recpo.PMaxLoginAttempts := strtointdef(trim(maxLoginAttempts.text), 0); if (CheckBox2.Checked = true) then recpo.PAutoReset := 'YES' else recpo.PAutoReset := 'NO'; recpo.PAutoResetPeriod := strtointdef(trim(autoUnlockPeriod.text), 0); if (unlockUnits.ItemIndex = 0) then recpo.PAutoResetUnit := 'D'; if (unlockUnits.ItemIndex = 1) then recpo.PAutoResetUnit := 'H'; if (unlockUnits.ItemIndex = 2) then recpo.PAutoResetUnit := 'M'; recpo.PCriteriaCount := strtointdef(trim(minUniqueCriteria.text), 0); daapi.PasswordOptionsUpdateRecord(recpo); end; procedure TfrmPasswordOptions.FormShow(Sender: TObject); begin recpo := daapi.PasswordOptionsGetRecord; passwordValidDays.text := inttostr(recpo.PExpireDays); historySize.text := inttostr(recpo.PHistorySize); minPasswordLength.text := inttostr(recpo.PMinLength); minChangedChars.text := inttostr(recpo.PMinChangedChars); allowChangeAfter.text := inttostr(recpo.PMinDaysUsage); if uppercase(recpo.PNameInPassword) = 'YES' then CheckBox1.Checked := true else CheckBox1.Checked := false; if ((ALPHA_CHAR and recpo.PCriteria) > 0) then cb_alpha.Checked := true else cb_alpha.Checked := false; if ((UPPER_CHAR and recpo.PCriteria) > 0) then cb_Uppercase.Checked := true else cb_Uppercase.Checked := false;; if ((LOWER_CHAR and recpo.PCriteria) > 0) then cb_LowerCase.Checked := true else cb_LowerCase.Checked := false; if ((SYMBOL_CHAR and recpo.PCriteria) > 0) then cb_Symbol.Checked := true else cb_Symbol.Checked := false; if ((NUMERIC_CHAR and recpo.PCriteria) > 0) then cb_Numeric.Checked := true else cb_Numeric.Checked := false; maxLoginAttempts.text := inttostr(recpo.PMaxLoginAttempts); if (uppercase(trim(recpo.PAutoReset)) = 'NO') then CheckBox2.Checked := false else begin autoUnlockPeriod.text := inttostr(recpo.PAutoResetPeriod); CheckBox2.Checked := true; if (uppercase(recpo.PAutoResetUnit) = 'D') then unlockUnits.ItemIndex := 0; if (uppercase(recpo.PAutoResetUnit) = 'H') then unlockUnits.ItemIndex := 1; if (uppercase(recpo.PAutoResetUnit) = 'M') then unlockUnits.ItemIndex := 2; end; minUniqueCriteria.text := inttostr(recpo.PCriteriaCount); end; procedure TfrmPasswordOptions.cb_alphaClick(Sender: TObject); begin if (cb_alpha.Checked) then begin cb_Uppercase.Checked := false; cb_LowerCase.Checked := false; end; end; procedure TfrmPasswordOptions.cb_UppercaseClick(Sender: TObject); begin if cb_Uppercase.Checked then cb_alpha.Checked := false; end; procedure TfrmPasswordOptions.cb_LowerCaseClick(Sender: TObject); begin if cb_LowerCase.Checked then cb_alpha.Checked := false; end; procedure TfrmPasswordOptions.minPasswordLengthExit(Sender: TObject); begin // TO MAINTAIN PASSWORD LENGTHS OF le 10 If strtointdef(trim(minPasswordLength.text), 0) > 10 then begin TrMsgInformation('Minimum Password length cannot be grater than 10'); minPasswordLength.text := inttostr(recpo.PMinLength); end; end; end.
unit SavedQuery; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "DT" // Модуль: "w:/common/components/rtl/Garant/DT/NOT_FINISHED_SavedQuery.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi For Archi::DT::Query::TSavedQuery // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {$Include ..\DT\DtDefine.inc} interface uses l3ProtoObject, dt_Types, dt_Query ; type TSavedQuery = class(Tl3ProtoObject) private fName : String; fFamily : Longint; f_FileName: TPathStr; public constructor CreateFromFile(aFileName : TPathStr); constructor Create(aName : String); function CompareWith(anObject: TSavedQuery): Integer; {* функция сравнения объекта с другим объектом. } procedure LoadHeader; procedure Save(aQuery : TdtQuery); function MakeQuery : TdtQuery; procedure DeletePersist; property Name : String read fName write fName; property FileName: TPathStr read f_FileName write f_FileName; property Family : Longint read fFamily; end;//TSavedQuery implementation uses Classes, l3String, l3Stream, l3Types, SysUtils ; {TSavedQuery} constructor TSavedQuery.CreateFromFile(aFileName : TPathStr); begin inherited Create; f_FileName := aFileName; LoadHeader; end; constructor TSavedQuery.Create(aName : String); begin inherited Create; fFamily := 1; fName := aName; end; function TSavedQuery.CompareWith(anObject: TSavedQuery): Integer; begin Result := l3Compare(fName, TSavedQuery(anObject).Name); end; procedure TSavedQuery.LoadHeader; var aStream : Tl3FileStream; lVersion : Longint; lHeaderLen : Longint; lNameLen : Longint; begin Assert(f_FileName <> ''); aStream := Tl3FileStream.Create(f_FileName, l3_fmReadWrite); try aStream.Read(lVersion, SizeOf(Longint)); aStream.Read(lHeaderLen, SizeOf(Longint)); aStream.Read(fFamily, SizeOf(Longint)); aStream.Read(lNameLen, SizeOf(Longint)); SetLength(fName, lNameLen); if lNameLen > 0 then aStream.Read(fName[1], lNameLen); finally FreeAndNil(aStream); end; end; function TSavedQuery.MakeQuery : TdtQuery; var lStream : Tl3FileStream; lVersion : Longint; lHeaderLen : Longint; lNameLen : Longint; begin Assert(f_FileName <> ''); lStream := Tl3FileStream.Create(f_FileName, l3_fmReadWrite); try lStream.Read(lVersion, SizeOf(Longint)); lStream.Read(lHeaderLen, SizeOf(Longint)); lStream.Seek(lHeaderLen, soBeginning); Result := g_dtLoadQuery(lStream); finally FreeAndNil(lStream); end; end; procedure TSavedQuery.Save(aQuery : TdtQuery); var lStream : Tl3FileStream; lVersion : Longint; lHeaderLen : Longint; lNameLen : Longint; begin Assert(f_FileName <> '', 'Нельзя сохранять запрос без имени файла'); lStream := Tl3FileStream.Create(f_FileName, l3_fmCreateReadWrite); try lVersion := 0; lStream.Write(lVersion, SizeOf(Longint)); lNameLen := Length(fName); lHeaderLen := SizeOf(Longint) {lVersion} + SizeOf(Longint) {lHeaderLen} + SizeOf(Longint) {fFamily} + SizeOf(Longint) {lNameLen} + lNameLen; lStream.Write(lHeaderLen, SizeOf(Longint)); lStream.Write(fFamily, SizeOf(Longint)); lStream.Write(lNameLen, SizeOf(Longint)); lStream.Write(fName[1], lNameLen); g_dtSaveQuery(aQuery, lStream); finally FreeAndNil(lStream); end; end; procedure TSavedQuery.DeletePersist; begin if f_FileName <> '' then SysUtils.DeleteFile(f_FileName); end; end.
unit m0DTFLib; (* // // module: m0dtflib.pas // author: Mickael P. Golovin // // Copyright (c) 1997-2000 by Archivarius Team, free for non commercial use. // // $Id: m0dtflib.pas,v 1.1 2014/08/20 16:31:25 lulin Exp $ // *) {$I m0Define.inc} interface uses Windows, Messages, SysUtils, Consts, Classes, m0Const{, m0AddTyp} ; procedure m0DTFSave(); procedure m0DTFLoad(); procedure m0DTFRest(); function m0DTFDateToStr(ADateTime: TDateTime): string; function m0DTFTimeToStr(ADateTime: TDateTime): string; function m0DTFDateTimeToStr(ADateTime: TDateTime): string; function m0DTFStrToDate(const AString: string): TDateTime; function m0IsValidStrDate(const AString: string): Boolean; { Проверяет переданное строковое представление даты на правильность } function m0DTFStrToTime(const AString: string): TDateTime; function m0DTFStrToDateTime(const AString: string): TDateTime; implementation { -- unit.private -- } var GThreadSafe: TRTLCriticalSection; GDateSeparator: Char; GLongDateFormat: string; GLongTimeFormat: string; GShortDateFormat: string; GShortTimeFormat: string; GTimeSeparator: Char; procedure _Initialization(); begin InitializeCriticalSection(GThreadSafe); end; procedure _Finalization(); begin DeleteCriticalSection(GThreadSafe); end; { -- unit.public -- } procedure m0DTFSave(); begin if IsMultiThread then begin EnterCriticalSection(GThreadSafe); end; GDateSeparator := {$ifDef XE}FormatSettings.{$EndIf}DateSeparator; GTimeSeparator := {$ifDef XE}FormatSettings.{$EndIf}TimeSeparator; GLongDateFormat := {$ifDef XE}FormatSettings.{$EndIf}LongDateFormat; GLongTimeFormat := {$ifDef XE}FormatSettings.{$EndIf}LongTimeFormat; GShortDateFormat := {$ifDef XE}FormatSettings.{$EndIf}ShortDateFormat; GShortTimeFormat := {$ifDef XE}FormatSettings.{$EndIf}ShortTimeFormat; end; procedure m0DTFLoad(); begin {$ifDef XE}FormatSettings.{$EndIf}DateSeparator := Cm0DateSeparator; {$ifDef XE}FormatSettings.{$EndIf}TimeSeparator := Cm0TimeSeparator; {$ifDef XE}FormatSettings.{$EndIf}LongDateFormat := Cm0LongDateFormat; {$ifDef XE}FormatSettings.{$EndIf}LongTimeFormat := Cm0LongTimeFormat; {$ifDef XE}FormatSettings.{$EndIf}ShortDateFormat := Cm0ShortDateFormat; {$ifDef XE}FormatSettings.{$EndIf}ShortTimeFormat := Cm0ShortTimeFormat; end; procedure m0DTFRest(); begin {$ifDef XE}FormatSettings.{$EndIf}ShortTimeFormat := GShortTimeFormat; {$ifDef XE}FormatSettings.{$EndIf}ShortDateFormat := GShortDateFormat; {$ifDef XE}FormatSettings.{$EndIf}LongTimeFormat := GLongTimeFormat; {$ifDef XE}FormatSettings.{$EndIf}LongDateFormat := GLongDateFormat; {$ifDef XE}FormatSettings.{$EndIf}TimeSeparator := GTimeSeparator; {$ifDef XE}FormatSettings.{$EndIf}DateSeparator := GDateSeparator; if IsMultiThread then begin LeaveCriticalSection(GThreadSafe); end; end; function m0DTFDateToStr(ADateTime: TDateTime): string; begin m0DTFSave(); try m0DTFLoad(); Result := DateToStr(ADateTime); finally m0DTFRest(); end; end; function m0DTFTimeToStr(ADateTime: TDateTime): string; begin m0DTFSave(); try m0DTFLoad(); Result := TimeToStr(ADateTime); finally m0DTFRest(); end; end; function m0DTFDateTimeToStr(ADateTime: TDateTime): string; begin m0DTFSave(); try m0DTFLoad(); Result := DateTimeToStr(ADateTime); finally m0DTFRest(); end; end; function m0IsValidStrDate(const AString: string): Boolean; var l_D: TDateTime; begin m0DTFSave; try m0DTFLoad; l_D:= 0; Result:= StrToDateDef(AString, l_D) <> l_D; finally m0DTFRest(); end; end; function m0DTFStrToDate(const AString: string): TDateTime; begin m0DTFSave(); try m0DTFLoad(); Result := StrToDate(AString); finally m0DTFRest(); end; end; function m0DTFStrToTime(const AString: string): TDateTime; begin m0DTFSave(); try m0DTFLoad(); Result := StrToTime(AString); finally m0DTFRest(); end; end; function m0DTFStrToDateTime(const AString: string): TDateTime; begin m0DTFSave(); try m0DTFLoad(); Result := StrToDateTime(AString); finally m0DTFRest(); end; end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\m0\pas\m0dtflib.pas initialization enter'); {$EndIf} _Initialization(); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\m0\pas\m0dtflib.pas initialization leave'); {$EndIf} finalization _Finalization(); end.
unit helpers.indy; interface uses idglobal, types, classes, sysutils, typex, idiohandlersocket; function TBytesToIDBytes(b: TBytes): TIDBytes; function AnsiStringToIDBytes(a: ansistring): TIDBytes; function idsocket_GuaranteeRead(idsocket: TIdIOHandlerSocket; iCount: ni): TidBytes; implementation function TBytesToIDBytes(b: TBytes): TIDBytes; var t: ni; begin setlength(result, length(b)); for t := low(b) to high(b) do result[t] := b[t]; end; function AnsiStringToIDBytes(a: ansistring): TIDBytes; {$IFNDEF NEEDFAKEANSISTRING} var t: ni; begin setlength(result, length(a)); for t := 0 to length(a)-1 do result[t] := ord(a[STRZ+t]); end; {$ELSE} var t: ni; begin setlength(result, length(a)); for t := 0 to length(a)-1 do result[t] := a.bytes[STRZ+t]; end; {$ENDIF} function idsocket_GuaranteeRead(idsocket: TIdIOHandlerSocket; iCount: ni): TidBytes; var iToGo: ni; begin setlength(result, 0); iToGo := iCount; while iToGo > 0 do begin idsocket.ReadBytes(result, iToGo); iTogo := length(result) - iCount; end; end; end.
unit linked_list_btree_compatible; interface uses typex, debug, sysutils, betterobject, unittest; type TLinkage<T> = class(TObject) public next: TLinkage<T>; prev: TLinkage<T>; obj: T; end; TLinkable = class(TObject) public NExt: TObject; Prev: TObject; Tree: TObject; list: TObject; constructor CReate;reintroduce;virtual; end; TDirectlyLinkedList<T: TLinkable> = class(TBetterObject) private FCount: nativeint; function GetItem(idx: nativeint): T; protected cached_index: nativeint; cached_link: T; procedure MoveCacheTo(idx: nativeint); procedure ManageFirstLast(objLink: T); PROCEDURE ClearCache; public FirstItem: T; LastItem: T; procedure Add(obj: T); procedure AddFirst(obj: T); procedure Remove(obj: T; bDontFree: boolean); procedure Replace(old, new: T); property Items[idx: nativeint]: T read GetItem;default; procedure Delete(idx: nativeint); function Has(obj: T): boolean; property Count: nativeint read FCount; procedure Clear; procedure ClearBruteForce; end; implementation procedure TDirectlyLinkedList<T>.Add(obj: T); begin if FirstItem = nil then begin FirstItem := obj; LAstItem := obj; obj.next := nil; obj.prev := nil; end else begin if assigned(LAstItem) then LAstItem.Next := obj; obj.prev := LastItem; LAstItem := obj; obj.next := nil; end; if obj.list = nil then begin inc(FCount); obj.list := self; end; end; procedure TDirectlyLinkedList<T>.AddFirst(obj: T); begin if LAstItem = nil then begin FirstItem := obj; LAstItem := obj; obj.Next := nil; obj.Prev := nil; end else begin if assigned(FirstItem) then FirstItem.Prev := obj; obj.Next := FirstItem; FirstItem := obj; obj.Prev := nil; end; if obj.list = nil then begin inc(FCount); obj.list := self; end; end; procedure TDirectlyLinkedList<T>.Clear; begin FirstItem := nil; LastItem := nil; cached_link := nil; cached_index := -1; FCount := 0; end; procedure TDirectlyLinkedList<T>.ClearBruteForce; begin Clear; end; procedure TDirectlyLinkedList<T>.ClearCache; begin cached_index := -1; cached_link := nil; end; procedure TDirectlyLinkedList<T>.Delete(idx: nativeint); begin MoveCacheTo(idx); Remove(cached_link,true); end; function TDirectlyLinkedList<T>.GetItem(idx: nativeint): T; begin MoveCacheTo(idx); result := (cached_link); end; function TDirectlyLinkedList<T>.Has(obj: T): boolean; var i: ni; begin result := false; for i := 0 to count-1 do begin if self.Items[i] = obj then begin result := true; break; end; end; end; procedure TDirectlyLinkedList<T>.ManageFirstLast(objLink: T); begin if FirstItem = nil then FirstItem := objlink; if LastItem = nil then LastItem := objlink; end; procedure TDirectlyLinkedList<T>.MoveCacheTo(idx: nativeint); begin if (idx = 0) then begin cached_index := 0; cached_link := FirstItem; exit; end; if (idx = (FCount-1)) then begin cached_index := FCount-1; cached_link := lastItem; exit; end; if cached_link = nil then cached_index := -1; if cached_index < 0 then begin cached_link := firstItem; cached_index := 0; end; while cached_index < idx do begin // Debug.Log(inttostr(cached_index)); inc(cached_index); cached_link := T(cached_link.next); if cached_link = nil then raise ECritical.create('seek past end of linked list @'+inttostr(cached_index)+' count='+inttostr(count)); end; while cached_index > idx do begin // Debug.Log(inttostr(cached_index)); dec(cached_index); cached_link := T(cached_link.prev); if cached_link = nil then raise ECritical.create('seek past end of linked list @'+inttostr(cached_index)+' count='+inttostr(count)); end; end; procedure TDirectlyLinkedList<T>.Remove(obj: T; bDontFree: boolean); begin if obj = lastItem then begin if lastitem.prev <> nil then begin lastitem := T(lastitem.prev); lastitem.next := nil; end else begin lastitem := nil; firstitem := nil; end; end else if obj = firstitem then begin if firstitem.next <> nil then begin firstitem := T(firstitem.next); firstitem.Prev := nil; end else begin lastitem := nil; firstitem := nil; end; end else begin if obj.next<>nil then T(obj.next).prev := obj.prev; if obj.prev<>nil then T(obj.prev).next := obj.next; end; obj.Next := nil; obj.prev := nil; ClearCache; ClearCache; if not bDontFree then obj.free; if obj.list = self then begin dec(FCount); obj.list := nil; end; end; procedure TDirectlyLinkedList<T>.Replace(old, new: T); begin if cached_link = old then cached_link := new; new.Prev := old.Prev; new.next := old.next; if new.next <> nil then T(new.next).prev := new; if new.prev <> nil then T(new.Prev).Next := new; if old = firstitem then firstitem := new; if old = lastitem then lastitem := new; if old <> nil then begin old.next := nil; old.Prev := nil; end; new.list := old.list; old.list := nil; end; { TLinkable } constructor TLinkable.CReate; begin // end; end.
unit LanderTypes; interface uses Graphics, GameTypes; const idNone = -1; type TLandOption = (loGrated, loGlassed, loShaded, loRedShaded, loBlackShaded, loUpProjected); TLandOptions = set of TLandOption; TLandState = (lsFocusable, lsGrounded, lsOverlayedGround, lsOverlayed); TLandStates = set of TLandState; type TObjInfo = object id : integer; Options : TLandOptions; Caption : string; Frame : integer; Height : integer; end; type THeightInfo = record lnx, lny, lnz, ld : integer; rnx, rny, rnz, rd : integer; end; type TLuminanceInfo = record lluma, llumb, llumc, llumd : single; rluma, rlumb, rlumc, rlumd : single; end; type TExtraLandInfo = record heightinfo : THeightInfo; luminfo : TLuminanceInfo; end; type ICoordinateConverter = interface function ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; function ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; function MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean; end; type IImager = interface function GetLandImage(id : integer) : TGameImage; function GetSpareImage : TGameImage; function GetShadeImage : TGameImage; function GetRedShadeImage : TGameImage; function GetBlackShadeImage : TGameImage; end; type IWorldMap = interface procedure InitMap; function GetRows : integer; function GetColumns : integer; function GetGroundInfo(i, j : integer; const focus : IGameFocus; out which : TObjInfo) : boolean; function GetExtraLandInfo(i, j : integer; out which : TExtraLandInfo) : boolean; function CreateFocus(const view : IGameView) : IGameFocus; function GetImager(const focus : IGameFocus) : IImager; end; implementation end.
unit MFichas.Controller.Venda.Interfaces; interface uses MFichas.Controller.Types; type iControllerVenda = interface; iControllerVendaMetodos = interface; iControllerVendaMetodosPagar = interface; iControllerVendaMetodosVenderItem = interface; iControllerVendaMetodosCancelarItem = interface; iControllerVendaMetodosDevolverItem = interface; iControllerVenda = interface ['{8F4E8184-D2AD-433B-A544-8A9F33E4C61C}'] function Metodos: iControllerVendaMetodos; end; iControllerVendaMetodos = interface ['{DC1C71F9-34FB-4184-B68F-B0C3CF99CD07}'] function AbrirVenda : iControllerVendaMetodos; function Pagar : iControllerVendaMetodos; function FinalizarVenda : iControllerVendaMetodos; function VenderItem : iControllerVendaMetodosVenderItem; function CancelarItem : iControllerVendaMetodosCancelarItem; function DevolverItem : iControllerVendaMetodosDevolverItem; function EfetuarPagamento: iControllerVendaMetodosPagar; end; iControllerVendaMetodosPagar = interface ['{CBCDE655-62AB-44F5-95A3-1BEADB5E72AE}'] function TipoDePagamento(ATipo: TTypeTipoPagamento): iControllerVendaMetodosPagar; function TipoDaVenda(ATipo: TTypeTipoVenda) : iControllerVendaMetodosPagar; function ValorTotalDaCompra(AValue: Currency) : iControllerVendaMetodosPagar; function Executar : iControllerVendaMetodosPagar; function &End : iControllerVendaMetodos; end; iControllerVendaMetodosVenderItem = interface ['{DEE9CD69-25BA-4298-AFA3-8A4B322FBDFF}'] function Codigo(ACodigo: String) : iControllerVendaMetodosVenderItem; function Quantidade(AQuantidade: Double): iControllerVendaMetodosVenderItem; function Valor(AValor: Currency) : iControllerVendaMetodosVenderItem; function Executar : iControllerVendaMetodosVenderItem; function &End : iControllerVendaMetodos; end; iControllerVendaMetodosCancelarItem = interface ['{7DAC8169-40CB-44A1-82F3-B1CB1E9A553B}'] function Index(AIndex: Integer): iControllerVendaMetodosCancelarItem; function Executar : iControllerVendaMetodosCancelarItem; function &End : iControllerVendaMetodos; end; iControllerVendaMetodosDevolverItem = interface ['{A85C3F96-4285-4130-97DA-256E07091F6C}'] function Codigo(ACodigo: String) : iControllerVendaMetodosDevolverItem; function Quantidade(AQuantidade: Double): iControllerVendaMetodosDevolverItem; function Valor(AValor: Currency) : iControllerVendaMetodosDevolverItem; function Executar : iControllerVendaMetodosDevolverItem; function &End : iControllerVendaMetodos; end; implementation end.
{ Subroutine SST_OPCODE_POS_PUSH (OPC_P) * * Push the current opcode chain position onto the stack, and set a new * position. OPC_P will be the new start of chain pointer. The new chain * will be initialized to empty. Subsequent calls to SST_OPCODE_NEW will * automatically cause new opcodes to be appended onto the new chain. } module sst_OPCODE_POS_PUSH; define sst_opcode_pos_push; %include 'sst2.ins.pas'; procedure sst_opcode_pos_push ( {push curr opc position, start new chain} in out opc_p: sst_opc_p_t); {pointer to new chain, will be set to NIL} var frame_p: sst_frame_opc_pos_p_t; {points to new stack frame} begin util_stack_push ( {create opcode position stack frame} sst_stack, {handle to the stack} sizeof(frame_p^), {size of stack frame} frame_p); {returned pointer to new stack frame} frame_p^.opc_p := sst_opc_p; {save pointer to current opcode} frame_p^.opc_pp := sst_opc_next_pp; {save old next chain start pointer} sst_opc_next_pp := addr(opc_p); {set new chain start pointer} opc_p := nil; {init new chain to empty} end;
unit Controller.Sistema; interface uses System.SysUtils, VCL.Forms, System.Classes, DAO.Conexao, Common.Utils, Global.Parametros; type TSistemaControl = class private FConexao: TConexao; FStart: Boolean; class var FInstante : TSistemaControl; public constructor Create; destructor Destroy; override; class function GetInstance: TSistemaControl; property Conexao: TConexao read FConexao write FConexao; property Start: Boolean read FStart write FStart; function StartGlobal(): Boolean; function SaveParamINI(sSection: String; sKey: String; sValue: String): Boolean; function ReturSkin(iIndex: Integer): String; function LoadSkinsINI(): TStringList; end; const INIFILE = 'database.ini'; implementation { TSistemaControl } constructor TSistemaControl.Create; begin FStart := StartGlobal; if FStart then FConexao := TConexao.Create; end; destructor TSistemaControl.Destroy; begin FConexao.Free; inherited; end; class function TSistemaControl.GetInstance: TSistemaControl; begin if not Assigned(Self.FInstante) then begin Self.FInstante := TSistemaControl.Create(); end; Result := Self.FInstante; end; function TSistemaControl.LoadSkinsINI: TStringList; var sSkinIni : String; lLista: TStringList; iIndex : Integer; sSkin: String; begin sSkinINI := ExtractFilePath(Application.ExeName) + '\skins.ini'; if not FileExists(sSkinINI) then Exit; iIndex := 0; lLista := TStringlist.Create(); sSkin := 'NONE'; while not sSKin.IsEmpty do begin sSkin := Common.Utils.TUtils.LeIni(sSkinINI,'Skin',iIndex.ToString); if not sSkin.IsEmpty then begin lLista.Add(sSkin); end; iIndex := iIndex + 1; end; Result := lLista; end; function TSistemaControl.ReturSkin(iIndex: Integer): String; var sSkinIni : String; sSkin: String; begin sSkin := ''; sSkinINI := ExtractFilePath(Application.ExeName) + '\skins.ini'; if not FileExists(sSkinINI) then Exit; Result := Common.Utils.TUtils.LeIni(sSkinINI,'Skin',iIndex.ToString); end; function TSistemaControl.SaveParamINI(sSection, sKey, sValue: String): Boolean; begin Result := False; Common.Utils.TUtils.GravaIni(Global.Parametros.pFileIni,sSection,sKey,sValue); Result := True; end; function TSistemaControl.StartGlobal: Boolean; begin Result := False; Global.Parametros.pFileIni := ExtractFilePath(Application.ExeName) + '\' + INIFILE; if not FileExists(Global.Parametros.pFileIni) then Exit; Global.Parametros.pDriverID := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','DriverID'); Global.Parametros.pServer := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','HostName'); Global.Parametros.pDatabase := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','Database'); Global.Parametros.pPort := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','Port'); Global.Parametros.pKBD := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','KBD'); Global.Parametros.pUBD := Common.Utils.TUtils.DesCriptografa(Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','UBD'),StrToIntDef(Global.Parametros.pKBD,0)); Global.Parametros.pPBD := Common.Utils.TUtils.DesCriptografa(Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','PBD'),StrToIntDef(Global.Parametros.pKBD,0)); Global.Parametros.pSkin := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','Skin'); Global.Parametros.pLastUser := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Login','LastUser'); Result := True; end; end.
program pl0 ; { version 1.0 oct.1989 } { PL/0 compiler with code generation } { comment by Song Lu Department of Computer Science&Engineering BUAA,Nov.2016 } {常量定义} const norw = 13; { no. of reserved words } {保留字的数目} txmax = 100; { length of identifier table } {符号表长度} nmax = 14; { max. no. of digits in numbers } {数字的最大长度} al = 10; { length of identifiers } {标识符的最大长度} amax = 2047; { maximum address } {相对地址最大值} levmax = 3; { maximum depth of block nesting } {最大嵌套层数} cxmax = 200; { size of code array } {生成目标代码数组最大长度} {类型变量定义} type symbol = ( nul,ident,number,plus,minus,times,slash,oddsym,eql,neq,lss, leq,gtr,geq,lparen,rparen,comma,semicolon,period,becomes, beginsym,endsym,ifsym,thensym,whilesym,dosym,callsym,constsym, varsym,procsym,readsym,writesym ); {symbol的宏定义为一个枚举} alfa = packed array[1..al] of char; {alfa宏定义为含有a1个元素的合并数组,为标识符的类型} objecttyp = (constant,variable,prosedure); {objecttyp的宏定义为一个枚举} symset = set of symbol; {symset为symbol的集合} fct = ( lit,opr,lod,sto,cal,int,jmp,jpc,red,wrt ); { functions } {fct为一个枚举,其实是PCODE的各条指令} instruction = packed record {instruction声明为一个记录类型} f : fct; { function code } {函数代码} l : 0..levmax; { level } {嵌套层次} a : 0..amax; { displacement address } {相对位移地址} end; { lit 0, a : load constant a 读取常量a到数据栈栈顶 opr 0, a : execute operation a 执行a运算 lod l, a : load variable l,a 读取变量放到数据栈栈顶,变量的相对地址为a,层次差为l sto l, a : store variable l,a 将数据栈栈顶内容存入变量,变量的相对地址为a,层次差为l cal l, a : call procedure a at level l 调用过程,过程入口指令为a,层次差为l int 0, a : increment t-register by a 数据栈栈顶指针增加a jmp 0, a : jump to a 无条件跳转到指令地址a jpc 0, a : jump conditional to a 条件转移到指令地址a red l, a : read variable l,a 读数据并存入变量, wrt 0, 0 : write stack-top 将栈顶内容输出 } {全局变量定义} var ch : char; { last character read } {最后读出的字符} sym: symbol; { last symbol read } {最近识别出来符号类型} id : alfa; { last identifier read } {最后读出来的识别符} num: integer; { last number read } {最后读出来的数字} cc : integer; { character count } {行缓冲区指针} ll : integer; { line length } {行缓冲区长度} kk,err: integer; cx : integer; { code allocation index } {代码分配指针} line: array[1..81] of char; {缓冲一行代码} a : alfa; {用来存储symbol的变量} code : array[0..cxmax] of instruction; {用来保存编译后的PCODE代码,最大容量为cxmax} word : array[1..norw] of alfa; {保留字表} wsym : array[1..norw] of symbol; {保留字表中每个保留字对应的symbol类型} ssym : array[char] of symbol; {符号对应的symbol类型} mnemonic : array[fct] of {助记符} packed array[1..5] of char; declbegsys, statbegsys, facbegsys : symset; {声明开始,表达式开始、项开始的符号集合} table : array[0..txmax] of {定义符号表} record {表中的元素类型是记录类型} name : alfa; {元素名} case kind: objecttyp of {根据符号的类型保存相应的信息} constant : (val:integer ); {如果是常量,val中保存常量的值} variable,prosedure: (level,adr: integer ) {如果是变量或过程,保存存放层数和偏移地址} end; fin : text; { source program file } {源代码文件} sfile: string; { source program file name } {源程序文件名} procedure error( n : integer ); {错误处理程序} begin writeln( '****', ' ':cc-1, '^', n:2 ); {报错提示信息,'^'指向出错位置,并提示错误类型} err := err+1 {错误次数+1} end; { error } procedure getsym; {词法分析程序} var i,j,k : integer; {声明计数变量} procedure getch; begin if cc = ll { get character to end of line } {如果读完了一行(行指针与该行长度相等)} then begin { read next line } {开始读取下一行} if eof(fin) {如果到达文件末尾} then begin writeln('program incomplete'); {报错} close(fin); {关闭文件} exit; {退出} end; ll := 0; {将行长度重置} cc := 0; {将行指针重置} write(cx:4,' '); { print code address } {输出代码地址,宽度为4} while not eoln(fin) do {当没有到行末时} begin ll := ll+1; {将行缓冲区的长度+1} read(fin,ch); {从文件中读取一个字符到ch中} write(ch); {控制台输出ch} line[ll] := ch {把这个字符放到当前行末尾} end; writeln; {换行} readln(fin); {源文件读取从下一行开始} ll := ll+1; {行长度计数加一} line[ll] := ' ' { process end-line } {行数组最后一个元素为空格} end; cc := cc+1; {行指针+1} ch := line[cc] {读取下一个字符,将字符放进全局变量ch} end; { getch } begin { procedure getsym; } {标识符识别开始} while ch = ' ' do {去除空字符} getch; {调用上面的getch过程} if ch in ['a'..'z'] {如果识别到字母,那么有可能是保留字或标识符} then begin { identifier of reserved word } {开始识别} k := 0; {标识符指针置零,这个量用来统计标识符长度} repeat {循环} if k < al {如果k的大小小于标识符的最大长度} then begin k := k+1; {k++} a[k] := ch {将ch写入标识符暂存变量a} end; getch {获取下一个字符} until not( ch in ['a'..'z','0'..'9']); {直到读出的不是数字或字母的时候,标识符结束} if k >= kk { kk : last identifier length } {若k比kk大} then kk := k {kk记录当前标识符的长度k} else repeat {循环} a[kk] := ' '; {标识符最后一位为空格} kk := kk-1 {k--} until kk = k; {直到kk等于当前标识符的长度,这样做的意义是防止上一个标识符存在a中的内容影响到当前标识符,比如上一个标识符为“qwerty”,现在的标识符为“abcd”,如果不清后几位则a中会保存"abcdty",这显然是错误的} id := a; {id保存标识符名} i := 1; {i指向第一个保留字} j := norw; { binary search reserved word table } {二分查找保留字表,将j设为保留字的最大数目} repeat k := (i+j) div 2; {再次用到k,但这里只是作为二分查找的中间变量} if id <= word[k] {若当前标识符小于或等于保留字表中的第k个,这里的判断依据的是字典序,那么我们可以推测符号表是按照字典序保存的} then j := k-1; {j = k-1} if id >= word[k] {若当前标识符大于或等于保留字表中的第k个} then i := k+1 {i = k+1} until i > j; {查找结束条件} if i-1 > j {找到了} then sym := wsym[k] {将找到的保留字类型赋给sym} else sym := ident {未找到则把sym置为ident类型,表示是标识符} end else if ch in ['0'..'9'] {如果字符是数字} then begin { number } k := 0; {这里的k用来记录数字的位数} num := 0; {num保存数字} sym := number; {将标识符设置为数字} repeat {循环开始} num := 10*num+(ord(ch)-ord('0')); {将数字字符转换为数字并拼接起来赋给num} k := k+1; {k++} getch {继续读字符} until not( ch in ['0'..'9']); {直到输入的不再是数字} if k > nmax {如果数字的位数超过了数字允许的最大长度} then error(30) {报错} end else if ch = ':' {当字符不是数字或字母,而是':'时} then begin getch; {读下一个字符} if ch = '=' {如果下一个字符是'='} then begin sym := becomes; {将标识符sym设置为becomes,表示复制} getch {读下一个字符} end else sym := nul {否则,将标识符设置为nul,表示非法} end else if ch = '<' {当读到的字符是'<'时} then begin getch; {读下一个字符} if ch = '=' {若读到的字符是'='} then begin sym := leq; {则sym为leq,表示小于等于} getch {读下一个字符} end else if ch = '>' {若读到的字符是'>'} then begin sym := neq; {则sym为neq,表示不等于} getch {读下一个字符} end else sym := lss {否则,sym设为lss,表示小于} end else if ch = '>' {若读到的是'>'} then begin getch; {读下一个字符} if ch = '=' {若读到的是'='} then begin sym := geq; {sym设为geq,表示大于等于} getch {读下一个字符} end else sym := gtr {否则,sym设为gtr,表示大于} end else begin {若非上述几种符号} sym := ssym[ch]; {从ssym表中查到此字符对应的类型,赋给sym} getch {读下一个字符} end end; { getsym } procedure gen( x: fct; y,z : integer ); {目标代码生成过程,x表示PCODE指令,y,z是指令的两个操作数} begin if cx > cxmax {如果当前生成代码的行数cx大于允许的最大长度cxmax} then begin writeln('program too long'); {输出报错信息} close(fin); {关闭文件} exit {退出程序} end; with code[cx] do {如果没有超出,对目标代码cx} begin f := x; {令其f为x} l := y; {令其l为y} a := z {令其a为z} {这三句对应着code身为instruction类型的三个属性} end; cx := cx+1 {将当前代码行数之计数加一} end; { gen } procedure test( s1,s2 :symset; n: integer ); {测试当前字符合法性过程,用于错误语法处理,若不合法则跳过单词值只读到合法单词为止} begin if not ( sym in s1 ) {如果当前符号不在s1中} then begin error(n); {报n号错误} s1 := s1+s2; {将s1赋值为s1和s2的集合} while not( sym in s1) do {这个while的本质是pass掉所有不合法的符号,以恢复语法分析工作} getsym {获得下一个标识符} end end; { test } procedure block( lev,tx : integer; fsys : symset ); {进行语法分析的主程序,lev表示语法分析所在层次,tx是当前符号表指针,fsys是用来恢复错误的单词集合} var dx : integer; { data allocation index } {数据地址索引} tx0: integer; { initial table index } {符号表初始索引} cx0: integer; { initial code index } {初始代码索引} procedure enter( k : objecttyp ); {将对象插入到符号表中} begin { enter object into table } tx := tx+1; {符号表序号加一,指向一个空表项} with table[tx] do {改变tx序号对应表的内容} begin name := id; {name记录object k的id,从getsym获得} kind := k; {kind记录k的类型,为传入参数} case k of {根据类型不同会进行不同的操作} constant : begin {对常量} if num > amax {如果常量的数值大于约定的最大值} then begin error(30); {报30号错误} num := 0 {将常量置零} end; val := num {val保存该常量的值,结合上句可以看出,如果超过限制则保存0} end; variable : begin {对变量} level := lev; {记录所属层次} adr := dx; {记录变量在当前层中的偏移量} dx := dx+1 {偏移量+1,位下一次插入做准备} end; prosedure: level := lev; {对过程,记录所属层次} end end end; { enter } function position ( id : alfa ): integer; {查找符号表的函数,输入id为需要寻找的符号,} var i : integer; {声明记录变量} begin table[0].name := id; {把id放到符号表0号位置} i := tx; {将i设置为符号表的最后一个位置,因为符号表是栈式结构,因此按层次逆序查找} while table[i].name <> id do {如果当前表项的name和id不同} i := i-1; {再向前找} position := i {找到了,把位置赋值给position返回} end; { position } procedure constdeclaration; {处理常量声明的过程} begin if sym = ident {如果sym是ident说明是标识符} then begin getsym; {获取下一个sym类型} if sym in [eql,becomes] {如果sym是等号或者赋值符号} then begin if sym = becomes {若是赋值符号} then error(1); {报一号错误,因为声明应该使用等号} getsym; {获取下一个sym类型} if sym = number {如果读到的是数字} then begin enter(constant); {将该常量入表} getsym {获取下一个sym类型} end else error(2) {如果等号后面不是数字,报2号错误} end else error(3) {如果常量标识符后面接的不是等号或赋值符号,报三号错误} end else error(4) {如果常量声明第一个符号不是标识符,报4号错误} end; { constdeclaration } {常量声明结束} procedure vardeclaration; {变量声明过程} begin if sym = ident {变量声明要求第一个sym为标识符} then begin enter(variable); {将该变量入表} getsym {获取下一个sym类型} end else error(4) {如果第一个sym不是标识符,抛出4号错误} end; { vardeclaration } procedure listcode; {列出PCODE的过程} var i : integer; {声明计数变量} begin for i := cx0 to cx-1 do {所有生成的代码} with code[i] do {对于每一行代码} writeln( i:4, mnemonic[f]:7,l:3, a:5) {格式化输出,分别输出序号,指令的助记符,层次,地址.实际的输出效果和我们实际的PCODE相同} end; { listcode } procedure statement( fsys : symset ); {语句处理的过程} var i,cx1,cx2: integer; {定义参数} procedure expression( fsys: symset); {处理表达式的过程} var addop : symbol; {定义参数} procedure term( fsys : symset); {处理项的过程} var mulop: symbol ; {定义参数} procedure factor( fsys : symset ); {处理因子的处理程序} var i : integer; {定义参数} begin test( facbegsys, fsys, 24 ); {测试单词的合法性,判别当前sym是否在facbegsys中,后者在main中定义,如果不在报24号错误} while sym in facbegsys do {循环处理因子} begin if sym = ident {如果识别到标识符} then begin i := position(id); {查表,记录其在符号表中的位置,保存至i} if i= 0 {如果i为0,表示没查到} then error(11) {报11号错误} else with table[i] do {对第i个表项的内容} case kind of {按照表项的类型执行不同的操作} constant : gen(lit,0,val); {如果是常量类型,生成lit指令,操作数为0,val} variable : gen(lod,lev-level,adr); {如果是变量类型,生成lod指令,操作数为lev-level,adr} prosedure: error(21) {如果因子处理中识别到了过程标识符,报21号错误} end; getsym {获取下一个sym类型} end else if sym = number {如果识别到数字} then begin if num > amax {判别数字是否超过规定上限} then begin error(30); {超过上限,报30号错误} num := 0 {将数字重置为0} end; gen(lit,0,num); {生成lit指令,将num的值放到栈顶} getsym {获取下一个sym类型} end else if sym = lparen {如果识别到左括号} then begin getsym; {获取下一个sym类型} expression([rparen]+fsys); {调用表达式的过程来处理,递归下降子程序方法} if sym = rparen {如果识别到右括号} then getsym {获取下一个sym类型} else error(22) {报22号错误} end; test(fsys,[lparen],23) {测试结合是否在fsys中,若不是,抛出23号错误} end end; { factor } begin { procedure term( fsys : symset); var mulop: symbol ; } {项的分析过程开始} factor( fsys+[times,slash]); {项的第一个符号应该是因子,调用因子分析程序} while sym in [times,slash] do {如果因子后面是乘/除号} begin mulop := sym; {使用mulop保存当前的运算符} getsym; {获取下一个sym类型} factor( fsys+[times,slash] ); {调用因子分析程序分析运算符后的因子} if mulop = times {如果运算符是称号} then gen( opr,0,4 ) {生成opr指令,乘法指令} else gen( opr,0,5) {生成opr指令,除法指令} end end; { term } begin { procedure expression( fsys: symset); var addop : symbol; } {表达式的分析过程开始} if sym in [plus, minus] {如果表达式的第一个符号是+/-符号} then begin addop := sym; {保存当前符号} getsym; {获取下一个sym类型} term( fsys+[plus,minus]); {正负号后面接项,调用项的分析过程} if addop = minus {如果符号开头} then gen(opr,0,1) {生成opr指令,完成取反运算} end else term( fsys+[plus,minus]); {如果不是符号开头,直接调用项的分析过程} while sym in [plus,minus] do {向后面可以接若干个term,使用操作符+-相连,因此此处用while} begin addop := sym; {记录运算符类型} getsym; {获取下一个sym类型} term( fsys+[plus,minus] ); {调用项的分析过程} if addop = plus {如果是加号} then gen( opr,0,2) {生成opr指令,完成加法运算} else gen( opr,0,3) {否则生成减法指令} end end; { expression } procedure condition( fsys : symset ); {条件处理过程} var relop : symbol; {临时变量} begin if sym = oddsym {如果当天符号是odd运算符} then begin getsym; {获取下一个sym类型} expression(fsys); {调用表达式分析过程} gen(opr,0,6) {生成opr6号指令,完成奇偶判断运算} end else begin expression( [eql,neq,lss,gtr,leq,geq]+fsys); {调用表达式分析过程对表达式进行计算} if not( sym in [eql,neq,lss,leq,gtr,geq]) {如果存在集合之外的符号} then error(20) {报20号错误} else begin relop := sym; {记录当前符号类型} getsym; {获取下一个sym类型} expression(fsys); {调用表达式分析过程对表达式进行分析} case relop of {根据当前符号类型不同完成不同的操作} eql : gen(opr,0,8); {如果是等号,生成opr8号指令,判断是否相等} neq : gen(opr,0,9); {如果是不等号,生成opr9号指令,判断是否不等} lss : gen(opr,0,10); {如果是小于号,生成opr10号指令,判断是否小于} geq : gen(opr,0,11); {如果是大于等于号,生成opr11号指令,判断是否大于等于} gtr : gen(opr,0,12); {如果是大于号,生成opr12号指令,判断是否大于} leq : gen(opr,0,13); {如果是小于等于号,生成opr13号指令,判断是否小于等于} end end end end; { condition } begin { procedure statement( fsys : symset ); var i,cx1,cx2: integer; } {声明处理过程} if sym = ident {如果以标识符开始} then begin i := position(id); {i记录该标识符在符号表中的位置} if i= 0 {如果返回0则是没找到} then error(11) {抛出11号错误} else if table[i].kind <> variable {如果在符号表中找到了该符号,但该符号的类型不是变量} then begin { giving value to non-variation } {那么现在的操作属于给非变量赋值} error(12); {报12号错误} i := 0 {将符号表标号置零} end; getsym; {获取下一个sym类型} if sym = becomes {如果读到的是赋值符号} then getsym {获取下一个sym类型} else error(13); {如果读到的不是赋值符号,报13号错误} expression(fsys); {赋值符号的后面可以跟表达式,因此调用表达式处理子程序} if i <> 0 {如果符号表中找到了合法的符号} then with table[i] do {使用该表项的内容来进行操作} gen(sto,lev-level,adr) {生成一条sto指令用来将表达式的值写入到相应变量的地址} end else if sym = callsym {如果读到的符号是call关键字} then begin getsym; {获取下一个sym类型} if sym <> ident {如果call后面跟的不是标识符} then error(14) {报14号错误} else begin {如果没有报错} i := position(id); {记录当前符号在符号表中的位置} if i = 0 {如果没有找到} then error(11) {报11号错误} else {如果找到了} with table[i] do {对第i个表项做如下操作} if kind = prosedure {如果该表项的种类为过程} then gen(cal,lev-level,adr) {生成cal代码用来实现call操作} else error(15); {如果种类不为过程类型,报15号错误} getsym {获取下一个sym类型} end end else if sym = ifsym {如果读到的符号是if关键字} then begin getsym; {获取下一个sym类型} condition([thensym,dosym]+fsys); {if后面跟的应该是条件语句,调用条件分析过程} if sym = thensym {如果条件语句后面跟的是then关键字的话} then getsym {获取下一个sym类型} else error(16); {如果条件后面接的不是then,报16号错误} cx1 := cx; {记录当前的生成代码位置} gen(jpc,0,0); {生成条件跳转指令,跳转位置暂填0} statement(fsys); {分析then语句后面的语句} code[cx1].a := cx {将之前记录的代码的位移地址改写到现在的生成代码位置(参考instruction类型的结构)} end else if sym = beginsym {如果读到了begin关键字} then begin getsym; {获取下一个sym类型} statement([semicolon,endsym]+fsys); {begin后面默认接语句,递归下降分析} while sym in ([semicolon]+statbegsys) do {在分析的过程中} begin if sym = semicolon {如果当前的符号是分好} then getsym {获取下一个sym类型} else error(10); {否则报10号错误} statement([semicolon,endsym]+fsys) {继续分析} end; if sym = endsym {如果读到了end关键字} then getsym {获取下一个sym类型} else error(17) {报17号错误} end else if sym = whilesym {如果读到了while关键字} then begin cx1 := cx; {记录当前生成代码的行数指针} getsym; {获取下一个sym类型} condition([dosym]+fsys); {因为while后需要添加循环条件,因此调用条件语句的分析过程} cx2 := cx; {记录在分析完条件之后的生成代码的位置,也是do开始的位置} gen(jpc,0,0); {生成一个条件跳转指令,但是跳转位置(a)置零} if sym = dosym {条件后应该接do关键字} then getsym {获取下一个sym类型} else error(18); {如果没接do,报18号错误} statement(fsys); {分析处理循环节中的语句} gen(jmp,0,cx1); {生成跳转到cx1的地址,既是重新判断一遍当前条件是否满足} code[cx2].a := cx {给之前生成的跳转指令设定跳转的位置为当前位置} end else if sym = readsym {如果读到的符号是read关键字} then begin getsym; {获取下一个sym类型} if sym = lparen {read的后面应该接左括号} then repeat {循环开始} getsym; {获取下一个sym类型} if sym = ident {如果第一个sym标识符} then begin i := position(id); {记录当前符号在符号表中的位置} if i = 0 {如果i为0,说明符号表中没有找到id对应的符号} then error(11) {报11号错误} else if table[i].kind <> variable {如果找到了,但该符号的类型不是变量} then begin error(12); {报12号错误,不能像常量和过程赋值} i := 0 {将i置零} end else with table[i] do {如果是变量类型} gen(red,lev-level,adr) {生成一条red指令,读取数据} end else error(4); {如果左括号后面跟的不是标识符,报4号错误} getsym; {获取下一个sym类型} until sym <> comma {知道现在的符号不是都好,循环结束} else error(40); {如果read后面跟的不是左括号,报40号错误} if sym <> rparen {如果上述内容之后接的不是右括号} then error(22); {报22号错误} getsym {获取下一个sym类型} end else if sym = writesym {如果读到的符号是write关键字} then begin getsym; {获取下一个sym类型} if sym = lparen {默认write右边应该加一个左括号} then begin repeat {循环开始} getsym; {获取下一个sym类型} expression([rparen,comma]+fsys); {分析括号中的表达式} gen(wrt,0,0); {生成一个wrt海曙,用来输出内容} until sym <> comma; {知道读取到的sym不是逗号} if sym <> rparen {如果内容结束没有右括号} then error(22); {报22号错误} getsym {获取下一个sym类型} end else error(40) {如果write后面没有跟左括号} end; test(fsys,[],19) {测试当前字符是否合法,如果没有出现在fsys中,报19号错} end; { statement } begin { procedure block( lev,tx : integer; fsys : symset ); var dx : integer; /* data allocation index */ tx0: integer; /*initial table index */ cx0: integer; /* initial code index */ } {分程序处理过程开始} dx := 3; {记录运行栈空间的栈顶位置,设置为3是因为需要预留SL,DL,RA的空间} tx0 := tx; {记录当前符号表的栈顶位置} table[tx].adr := cx; {符号表当前位置的偏移地址记录下一条生成代码开始的位置} gen(jmp,0,0); { jump from declaration part to statement part } {产生一条jmp类型的无条件跳转指令,跳转位置未知} if lev > levmax {当前过程所处的层次大于允许的最大嵌套层次} then error(32); {报32号错误} repeat {循环开始} if sym = constsym {如果符号类型是const保留字} then begin getsym; {获取下一个sym类型} repeat {循环开始} constdeclaration; {处理常量声明} while sym = comma do {如果声明常量后接的是逗号,说明常量声明没有结束,进入下一循环} begin getsym; {获取下一个sym类型} constdeclaration {处理常量声明} end; if sym = semicolon {如果读到了分号,说明常量声明已经结束了} then getsym {获取下一个sym类型} else error(5) {如果没有分号,报5号错误} until sym <> ident {循环直到遇到下一个标志符} end; if sym = varsym {如果读到的是var保留字} then begin getsym; {获取下一个sym类型} repeat {循环开始} vardeclaration; {处理变量声明} while sym = comma do {如果读到了逗号,说明声明未结束,进入循环} begin getsym; {获取下一个sym类型} vardeclaration {处理变量声明} end; if sym = semicolon {如果读到了分号,说明所有声明已经结束} then getsym {获取下一个sym类型} else error(5) {如果未读到分号,则报5号错误} until sym <> ident; {循环直到读到下一个标识符为止} end; while sym = procsym do {如果读到proc关键字} begin getsym; {获取下一个sym类型} if sym = ident {第一个符号应该是标识符类型} then begin enter(prosedure); {将该符号录入符号表,类型为过程,因为跟在proc后面的一定是过程名} getsym {获取下一个sym类型} end else error(4); {如果第一个符号不是标识符类型,报4号错误} if sym = semicolon {如果读到了分号,说明proc声明结束} then getsym {获取下一个sym类型} else error(5); {如果声明过程之后没有跟分号,报5号错误} block(lev+1,tx,[semicolon]+fsys); {执行分程序的分析过程} if sym = semicolon {递归调用返回后应该接分号} then begin {如果接的是分号} getsym; {获取下一个sym类型} test( statbegsys+[ident,procsym],fsys,6) {测试当前的sym是否合法} end else error(5) {如果接的不是分号,报5号错误} end; test( statbegsys+[ident],declbegsys,7) {测试当前的sym是否合法} until not ( sym in declbegsys ); {一直循环到sym不在声明符号集中为止} code[table[tx0].adr].a := cx; { back enter statement code's start adr. } {将之前生成无条件跳转指令的目标地址指向当前位置} with table[tx0] do {对符号表新加记录} begin adr := cx; { code's start address } {记录当前代码的分配为止} end; cx0 := cx; {记录当前代码分配的地址} gen(int,0,dx); { topstack point to operation area } {生成int指令,分配dx个空间} statement( [semicolon,endsym]+fsys); {调用语法分析程序} gen(opr,0,0); { return } {生成0号gen程序,完成返回操作} test( fsys, [],8 ); {测试当前状态是否合法,有问题报8号错误} listcode; {列出该block所生成的PCODE} end { block }; procedure interpret; {解释执行程序} const stacksize = 500; {设置栈大小为常量500} var p,b,t: integer; { program-,base-,topstack-register } {设置三个寄存器,分别记录下一条指令,基址地址和栈顶指针} i : instruction;{ instruction register } {指令寄存器,类型为instruction,显然是为了存放当前指令} s : array[1..stacksize] of integer; { data store } {数据栈,大小为stacksize=500个integer} function base( l : integer ): integer; {声明计算基地址的函数} var b1 : integer; {声明计数变量} begin { find base l levels down } {目标是找到相对于现在层次之差为l的层次基址} b1 := b; {记录当前层的基地址} while l > 0 do {如果层数大于0,即寻找的不是本层} begin b1 := s[b1]; {记录当前层数据基址的内容} l := l-1 {层数--} end; base := b1 {将找到的基地址保存起来} end; { base } begin writeln( 'START PL/0' ); {输出程序开始运行的提示语句} t := 0; {将栈顶指针置零} b := 1; {将基址地址置为1} p := 0; {将指令寄存器置零} s[1] := 0; {将数据栈的第一层置零,对应SL} s[2] := 0; {将数据栈的第二层置零,对应DL} s[3] := 0; {将数据栈的第三层置零,对应RA} repeat {循环开始} i := code[p]; {获取当前需要执行的代码} p := p+1; {将指令寄存器+1,以指向下一条置零} with i do {针对当前指令} case f of {不同类型的指令执行不同操作} lit : begin {对lit类型} t := t+1; {栈顶指针加1} s[t]:= a; {将a操作数的值放入栈顶} end; opr : case a of { operator } {针对opr类型的指令} 0 : begin { return } {0对应return操作} t := b-1; {t取到该层数据栈SL-1的位置,意味着将该层的数据栈全部清空(因为要返回了嘛)} p := s[t+3]; {将指令指针指向RA的值,即获得return address} b := s[t+2]; {将基址指针指向DL的值,即获得了return之后的基址,因为被调用层次的DL指向调用层次的基址} end; 1 : s[t] := -s[t]; {1对应取反操作} 2 : begin {2对应求和操作} t := t-1; {栈顶指针退一格} s[t] := s[t]+s[t+1] {将栈顶和次栈顶中的数值求和放入新的栈顶,注意运算后的栈顶是下降一格的,下面的运算亦如此} end; 3 : begin {3对应做差操作} t := t-1; {栈顶指针退格} s[t] := s[t]-s[t+1] {次栈顶减栈顶,结果放入新的栈顶} end; 4 : begin {4对应乘积操作} t := t-1; {栈顶退格} s[t] := s[t]*s[t+1] {栈顶和次栈顶相乘,结果放入新的栈顶} end; 5 : begin {5对应相除} t := t-1; {栈顶退格} s[t] := s[t]div s[t+1] {次栈顶除以栈顶,结果放入新的栈顶} end; 6 : s[t] := ord(odd(s[t])); {6对应判断是否栈顶数值为奇数} 8 : begin {8号对应等值判断} t := t-1; {栈顶退格} s[t] := ord(s[t]=s[t+1]) {如果栈顶和次栈顶数值相同,栈顶置一,否则置零} end; 9 : begin {9号对应不等判断} t := t-1; {栈顶退格} s[t] := ord(s[t]<>s[t+1]) {如果栈顶和次栈顶数值不同,栈顶置一,否则置零} end; 10: begin {10号对应小于判断} t := t-1; {栈顶退格} s[t] := ord(s[t]< s[t+1]) {如果次栈顶的数值小于栈顶的数值,栈顶置一,否则置零} end; 11: begin {11号对应大于等于判断} t := t-1; {栈顶退格} s[t] := ord(s[t] >= s[t+1]) {如果次栈顶的数值大于等于栈顶的数值,栈顶置一,否则置零} end; 12: begin {12号对应着大于判断} t := t-1; {栈顶退格} s[t] := ord(s[t] > s[t+1]) {如果次栈顶的数值大于栈顶的数值,栈顶置一,否则置零} end; 13: begin {13号对应着小于等于判断} t := t-1; {栈顶退格} s[t] := ord(s[t] <= s[t+1]) {如果次栈顶的数值小于等于栈顶的数值,栈顶置一,否则置零} end; end; lod : begin {如果是lod指令} t := t+1; {栈顶指针指向新栈} s[t] := s[base(l)+a] {将与当前数据层层次差为l,层内偏移为a的栈中的数据存到栈顶} end; sto : begin {对于sto指令} s[base(l)+a] := s[t]; { writeln(s[t]); } {将当前栈顶的数据保存到与当前层层差为l,层内偏移为a的数据栈中} t := t-1 {栈顶退栈} end; cal : begin { generate new block mark } {对于指令} s[t+1] := base(l); {由于要生成新的block,因此栈顶压入SL的值} s[t+2] := b; {在SL之上压入当前数据区的基址,作为DL} s[t+3] := p; {在DL之上压入指令指针,即是指令的断点,作为RA} b := t+1; {把当前的数据区基址指向新的SL} p := a; {从a的位置继续执行程序,a来自instruction结构体} end; int : t := t+a; {对int指令,将栈顶指针上移a个位置} jmp : p := a; {对jmp指令,将指令指针指向a} jpc : begin {对于jpc指令} if s[t] = 0 {如果栈顶数据为零} then p := a; {则将指令指针指向a} t := t-1; {栈顶向下移动} end; red : begin {对red指令} writeln('??:'); {输出提示信息} readln(s[base(l)+a]); {读一行数据,读入到相差l层,层内偏移为a的数据栈中的数据的信息} end; wrt : begin {对wrt指令} writeln(s[t]); {输出栈顶的信息} t := t+1 {栈顶上移} end end { with,case } until p = 0; {直到当前指令的指针为0,这意味着主程序返回了,即整个程序已经结束运行了} writeln('END PL/0'); {PL/0执行结束} end; { interpret } begin { main } { 主函数 } writeln('please input source program file name : '); {提示信息,要求用户输入源码的地址} readln(sfile); {读入一行保存至sfile} assign(fin,sfile); {将文件名字符串变量str付给文件变量fin} reset(fin); {打开fin} for ch := 'A' to ';' do ssym[ch] := nul; {将从'A'到';'的符号的ssym都设置为nul,表示不合法} word[1] := 'begin '; word[2] := 'call '; word[3] := 'const '; word[4] := 'do '; word[5] := 'end '; word[6] := 'if '; word[7] := 'odd '; word[8] := 'procedure '; word[9] := 'read '; word[10]:= 'then '; word[11]:= 'var '; word[12]:= 'while '; word[13]:= 'write '; {填写保留字表,注意这里所有字符都预留的相同的长度} wsym[1] := beginsym; wsym[2] := callsym; wsym[3] := constsym; wsym[4] := dosym; wsym[5] := endsym; wsym[6] := ifsym; wsym[7] := oddsym; wsym[8] := procsym; wsym[9] := readsym; wsym[10]:= thensym; wsym[11]:= varsym; wsym[12]:= whilesym; wsym[13]:= writesym; {填写保留字对应的标识符sym的值} ssym['+'] := plus; ssym['-'] := minus; ssym['*'] := times; ssym['/'] := slash; ssym['('] := lparen; ssym[')'] := rparen; ssym['='] := eql; ssym[','] := comma; ssym['.'] := period; ssym['<'] := lss; ssym['>'] := gtr; ssym[';'] := semicolon; {填写对应符号对应的标识符sym的值} mnemonic[lit] := 'LIT '; mnemonic[opr] := 'OPR '; mnemonic[lod] := 'LOD '; mnemonic[sto] := 'STO '; mnemonic[cal] := 'CAL '; mnemonic[int] := 'INT '; mnemonic[jmp] := 'JMP '; mnemonic[jpc] := 'JPC '; mnemonic[red] := 'RED '; mnemonic[wrt] := 'WRT '; {填写助记符表,与PCODE指令一一对应} declbegsys := [ constsym, varsym, procsym ]; {表达式开始的符号集合} statbegsys := [ beginsym, callsym, ifsym, whilesym]; {语句开始的符号集合} facbegsys := [ ident, number, lparen ]; {项开始的符号集合} err := 0; {将出错的标识符置零} cc := 0; {行缓冲指针置零} cx := 0; {生成代码行数计数置零} ll := 0; {词法分析行缓冲区长度置零} ch := ' '; {当前字符设为' '} kk := al; {kk的值初始化为0} getsym; {获取第一个词的标识符} block( 0,0,[period]+declbegsys+statbegsys ); {执行主程序block} if sym <> period {如果符号不是句号} then error(9); {报⑨号错误} if err = 0 {如果err为0表示没有错误} then interpret {开始解释执行生成的PCODE代码} else write('ERRORS IN PL/0 PROGRAM'); {否则出现了错误,报错} writeln; {换行} close(fin); {关闭源文件程序} readln(sfile); {读取PL/0源程序} end.
unit fmuMasterPayK; interface uses // VCL Windows, Forms, ComCtrls, StdCtrls, Controls, Classes, SysUtils, Messages, Buttons, Dialogs, // This untPages, untUtil, untDriver; type { TfmMasterPayK } TfmMasterPayK = class(TPage) Memo: TMemo; btnReadLastReceipt: TButton; btnReadLastReceiptLine: TButton; btnReadLastReceiptMac: TButton; btnReadReceipt: TButton; btnSave: TBitBtn; SaveDialog: TSaveDialog; chbSaveReceipt: TCheckBox; Label1: TLabel; procedure btnReadLastReceiptClick(Sender: TObject); procedure btnReadLastReceiptLineClick(Sender: TObject); procedure btnReadLastReceiptMacClick(Sender: TObject); procedure btnReadReceiptClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private function GetReceiptFileName: string; procedure SaveReceipt(const Text: string); end; implementation {$R *.DFM} { TfmMasterPayK } procedure TfmMasterPayK.btnReadLastReceiptClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; if Driver.ReadLastReceipt = 0 then begin Memo.Lines.Add(Format(' Íîìåð îïåðàòîðà: %d', [Driver.OperatorNumber])); end; finally EnableButtons(True); end; end; procedure TfmMasterPayK.btnReadLastReceiptLineClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; if Driver.ReadLastReceiptLine = 0 then begin Memo.Lines.Add(Format(' Íîìåð îïåðàòîðà: %d', [Driver.OperatorNumber])); Memo.Lines.Add(Format(' Äàííûå: %s', [Driver.LineData])); end; finally EnableButtons(True); end; end; procedure TfmMasterPayK.btnReadLastReceiptMacClick(Sender: TObject); begin EnableButtons(False); try Memo.Clear; if Driver.ReadLastReceiptMac = 0 then begin Memo.Lines.Add(Format(' Íîìåð îïåðàòîðà: %d', [Driver.OperatorNumber])); Memo.Lines.Add(Format(' ÊÏÊ: %d', [Driver.KPKNumber])); end; finally EnableButtons(True); end; end; function TfmMasterPayK.GetReceiptFileName: string; begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'Receipt.txt'; end; procedure TfmMasterPayK.SaveReceipt(const Text: string); var Mode: Integer; Stream: TFileStream; begin if Length(Text) = 0 then Exit; Mode := fmCreate; if FileExists(GetReceiptFileName) then Mode := fmOpenReadWrite; Mode := Mode + fmShareDenyWrite; Stream := TFileStream.Create(GetReceiptFileName, Mode); try Stream.Seek(0, soFromEnd); Stream.Write(Text[1], Length(Text)); finally Stream.Free; end; end; procedure TfmMasterPayK.btnReadReceiptClick(Sender: TObject); const CRLF = #13#10; TestReceipt = ' ÊÊÌ 1' + CRLF + 'ÊÊÌ 001234567890 ÈÍÍ 000000123456 ' + CRLF + 'ÝÊËÇ 0000000007 ' + CRLF + 'ÊÎÍÒÐÎËÜÍÀß ËÅÍÒÀ. ÑÌÅÍÀ 0001 ' + CRLF + 'ÏÐÎÄÀÆÀ 16/04/10 19:24 ÎÏÅÐÀÒÎÐ00 ' + CRLF + 'ÎÒÄÅË001 1.000 *1.23' + CRLF + 'ÑÊÈÄÊÀ *1.23' + CRLF + 'ÍÀÖÅÍÊÀ *1.23' + CRLF + 'ÈÒÎÃ *1.23' + CRLF + '00000005 #002163 '; begin EnableButtons(False); try Memo.Clear; if Driver.ReadLastReceipt = 0 then begin while True do begin if Driver.ReadLastReceiptLine <> 0 then Break; Memo.Lines.Add(Driver.LineData); end; end; //Memo.Lines.Text := TestReceipt; if chbSaveReceipt.Checked then SaveReceipt(Memo.Lines.Text); finally EnableButtons(True); end; end; procedure TfmMasterPayK.btnSaveClick(Sender: TObject); begin if SaveDialog.Execute then Memo.Lines.SaveToFile(SaveDialog.FileName); end; end.
unit CircTstWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Circuits, ExtCtrls, StdCtrls, Collection; type TTstWin = class(TForm) Image: TImage; Panel1: TPanel; Label1: TLabel; CircCount: TLabel; x1: TEdit; Label2: TLabel; Label3: TLabel; y1: TEdit; Label4: TLabel; x2: TEdit; Label5: TLabel; y2: TEdit; Go: TButton; ListBox: TListBox; Nodes: TLabel; Circs: TButton; OwnerId: TEdit; Label6: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GoClick(Sender: TObject); procedure CircsClick(Sender: TObject); private fMap : TCircuitMap; fDrawingSeg : TPoint; fInDrawingSeg : boolean; private procedure DrawMap; end; var TstWin: TTstWin; implementation const Scale = 10; {$R *.DFM} procedure TTstWin.FormCreate(Sender: TObject); begin fMap := TCircuitMap.Create( 1, TNode, TSegment, TCircuit ); Image.Picture.Bitmap := TBitmap.Create; Image.Picture.Bitmap.Width := Image.Width; Image.Picture.Bitmap.Height := Image.Height; end; procedure TTstWin.FormShow(Sender: TObject); begin DrawMap; end; procedure TTstWin.DrawMap; procedure DrawNode( Node : TNode ); const DotSize = 2; begin Image.Canvas.Pen.Color := clBlack; if Node.Segments[segNorth] <> nil then begin Image.Canvas.MoveTo( Scale*Node.x, Scale*Node.y ); Image.Canvas.LineTo( Scale*Node.x, Scale*Node.y - Scale div 2 ); end; if Node.Segments[segEast] <> nil then begin Image.Canvas.MoveTo( Scale*Node.x, Scale*Node.y ); Image.Canvas.LineTo( Scale*Node.x + Scale div 2, Scale*Node.y ); end; if Node.Segments[segSouth] <> nil then begin Image.Canvas.MoveTo( Scale*Node.x, Scale*Node.y ); Image.Canvas.LineTo( Scale*Node.x, Scale*Node.y + Scale div 2 ); end; if Node.Segments[segWest] <> nil then begin Image.Canvas.MoveTo( Scale*Node.x, Scale*Node.y ); Image.Canvas.LineTo( Scale*Node.x - Scale div 2, Scale*Node.y ); end; Image.Canvas.Ellipse( Scale*Node.x - DotSize, Scale*Node.y - DotSize, Scale*Node.x + DotSize, Scale*Node.y + DotSize + 1 ); end; var i, j : integer; begin Image.Canvas.Pen.Color := clWhite; Image.Canvas.Rectangle( 0, 0, Width, Height ); Image.Canvas.Pen.Color := $00EEEEEE; for i := 0 to Width div Scale do begin Image.Canvas.MoveTo( Scale*i - Scale div 2, 0 ); Image.Canvas.LineTo( Scale*i - Scale div 2, Height ); end; for i := 0 to Height div Scale do begin Image.Canvas.MoveTo( 0, Scale*i - Scale div 2 ); Image.Canvas.LineTo( Width, Scale*i - Scale div 2 ); end; for i := 0 to pred(fMap.Circuits.Count) do with TCircuit(fMap.Circuits[i]) do begin for j := 0 to pred(Segments.Count) do with TSegment(Segments[j]) do if (NodeA <> nil) and (NodeB <> nil) then begin Image.Canvas.Pen.Color := clSilver; Image.Canvas.MoveTo( Scale*NodeA.x, Scale*NodeA.y ); Image.Canvas.LineTo( Scale*NodeB.x, Scale*NodeB.y ); DrawNode( NodeA ); DrawNode( NodeB ); end; end; CircCount.Caption := IntToStr(fMap.Circuits.Count); if fMap.Circuits.Count > 0 then begin Nodes.Caption := IntToStr(TCircuit(fMap.Circuits[0]).Nodes.Count) + ', ' + IntToStr(TCircuit(fMap.Circuits[0]).Segments.Count); end; end; procedure TTstWin.ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ErrorCode : TCircuitErrorCode; begin if Button = mbLeft then if not fInDrawingSeg then begin fDrawingSeg.x := x; fDrawingSeg.y := y; fInDrawingSeg := true; Image.Cursor := crCross; end else begin if abs(fDrawingSeg.x - x) > abs(fDrawingSeg.y - y) then y := fDrawingSeg.y else x := fDrawingSeg.x; fMap.CreateSegment( round(fDrawingSeg.x/Scale), round(fDrawingSeg.y/Scale), round(x/Scale), round(y/Scale), StrToInt(OwnerId.Text), ErrorCode ); if ErrorCode = CIRCUIT_NOERROR then DrawMap; fInDrawingSeg := false; Image.Cursor := crArrow; end else begin fMap.BreakSegmentInPoint( round(x/Scale), round(y/Scale), StrToInt(OwnerId.Text), ErrorCode ); if ErrorCode = CIRCUIT_NOERROR then DrawMap; end; end; procedure TTstWin.GoClick(Sender: TObject); begin try ListBox.Items.Text := fMap.SegsInArea( StrToInt(x1.Text), StrToInt(y1.Text), StrToInt(x2.Text), StrToInt(y2.Text) ); except ListBox.Items.Text := 'ERROR'; end; end; procedure TTstWin.CircsClick(Sender: TObject); var Circs : TCollection; Area : TRect; ErrorCode : integer; i : integer; begin Circs := TCollection.Create( 0, rkUse ); try Area := Rect( StrToInt(x1.Text), StrToInt(y1.Text), StrToInt(x2.Text), StrToInt(y2.Text) ); fMap.NearestCircuitsToArea( Area, 0, Circs, ErrorCode ); ListBox.Items.Clear; for i := 0 to pred(Circs.Count) do ListBox.Items.Add( IntToStr(integer(Circs[i])) ); finally Circs.Free; end; end; end.
unit HopfieldNetwork; interface uses GBMatrixOperations; type HopfieldNet = class(TObject) private weights : Matrix2DRec; public function GetMatrix():Matrix2DRec; procedure TrainMatrix(pattern:T2DBoolean); function MatchMatrix(pattern:T2DBoolean):T2DBoolean; procedure EraseMatrix(); constructor Create( size : integer); end; implementation constructor HopfieldNet.Create( size : integer); begin (*size corresponed to the number of neurons*) (*A weighted matrix is created with NXN neurons, which defines the connection between each neuron pair*) weights.init(size,size, 0); end; (*return weighted matrix*) function HopfieldNet.GetMatrix():Matrix2DRec; begin result := weights; end; (*training procedure->given an input pattern the weighted matrix will change*) procedure HopfieldNet.TrainMatrix(pattern:T2DBoolean); var identity, transpose, inputMatrix, mult, sb : Matrix2DRec; inputBools : Matrix1DRec; r,c,index : integer; begin (*convert boolean 2D array into a single array*) inputBools.init(length(weights.data),0); index := 0; for r := 0 to length(pattern)-1 do for c := 0 to length(pattern)-1 do begin if pattern[r,c] then inputBools.data[index] := 1 else inputBools.data[index] := -1; inc(index); end; (*take that single array and copy to n rows of the input matrix*) inputMatrix.init(length(weights.data), length(weights.data),0); for r := 0 to length(weights.data)-1 do for c := 0 to length(weights.data)-1 do inputMatrix.data[r,c] := inputBools.data[c]; (*transpose previous matrix, then multiply the two matrices*) transpose := inputMatrix.Transpose; mult := transpose*inputMatrix; (*subtract the previous matrix by the identity*) (*the reason is that neurons don't connect to themselves*) identity := inputMatrix.Identity; sb := mult-identity; (*add prev matrix to the weighted matrix*) weights := weights+sb; end; function HopfieldNet.MatchMatrix(pattern:T2DBoolean):T2DBoolean; var inputMatrix, transpose, colMatrix : Matrix2DRec; inputBools : Matrix1DRec; r,r2,c, index, xpos,ypos : integer; begin (*convert boolean pattern into a matrix*) inputBools.init(length(weights.data),0); index := 0; for r := 0 to length(pattern)-1 do for c := 0 to length(pattern)-1 do begin if pattern[r,c] then inputBools.data[index] := 1 else inputBools.data[index] := -1; inc(index); end; inputMatrix.init(length(weights.data), length(weights.data),0); for r := 0 to length(weights.data)-1 do for c := 0 to length(weights.data)-1 do inputMatrix.data[r,c] := inputBools.data[c]; setlength(result, length(pattern), length(pattern)); colMatrix.init(length(weights.data),length(weights.data),0); (*dot product of the input matrix and the transpose matrix*) for index := 0 to length(weights.data)-1 do begin for r2 := 0 to length(weights.data)-1 do for c := 0 to length(weights.data)-1 do colMatrix.data[r2,c] := weights.data[index,c]; ypos := trunc(index/length(pattern)); xpos := index mod length(pattern); if inputMatrix.DotProduct(inputMatrix,colMatrix)>0 then result[ypos, xpos] := true else result[ypos, xpos] := false; end; end; (*set all weights to zero*) procedure HopfieldNet.EraseMatrix(); begin weights.SetDefaultValues(0); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerBmpString; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpCryptoLibTypes, ClpAsn1Object, ClpAsn1Tags, ClpAsn1OctetString, ClpDerOutputStream, ClpIProxiedInterface, ClpIDerBmpString, ClpIAsn1TaggedObject, ClpDerStringBase; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SEmptyInput = 'Input Cannot be Empty "astr"'; type TDerBmpString = class(TDerStringBase, IDerBmpString) strict private var FStr: String; function GetStr: String; inline; strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public property Str: String read GetStr; /// <summary> /// basic constructor - byte encoded string. /// </summary> constructor Create(const astr: TCryptoLibByteArray); overload; /// <summary> /// basic constructor /// </summary> constructor Create(const astr: String); overload; function GetString(): String; override; procedure Encode(const derOut: TStream); override; /// <summary> /// return a BMP string from the given object. /// </summary> /// <param name="obj"> /// the object we want converted. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerBmpString; overload; static; inline; /// <summary> /// return a BMP string from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// true if the object is meant to be explicitly tagged false otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerBmpString; overload; static; inline; end; implementation { TDerBmpString } function TDerBmpString.GetStr: String; begin result := FStr; end; function TDerBmpString.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerBmpString; begin if (not Supports(asn1Object, IDerBmpString, other)) then begin result := false; Exit; end; result := Str = other.Str; end; constructor TDerBmpString.Create(const astr: TCryptoLibByteArray); var cs: TCryptoLibCharArray; i: Int32; begin Inherited Create(); if (astr = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SEmptyInput); end; System.SetLength(cs, System.Length(astr) shr 1); i := 0; while i <> System.Length(cs) do begin cs[i] := Char((astr[2 * i] shl 8) or (astr[2 * i + 1] and $FF)); System.Inc(i); end; System.SetString(FStr, PChar(@cs[0]), System.Length(cs)); end; constructor TDerBmpString.Create(const astr: String); begin Inherited Create(); if (astr = '') then begin raise EArgumentNilCryptoLibException.CreateRes(@SEmptyInput); end; FStr := astr; end; procedure TDerBmpString.Encode(const derOut: TStream); var c: TCryptoLibCharArray; b: TCryptoLibByteArray; i, LowPoint, HighPoint: Int32; begin System.SetLength(c, System.Length(Str)); // had to use this loop because somehow, StrPLCopy causes memory leak in FPC v3.0.5 {$IFDEF DELPHIXE3_UP} LowPoint := System.Low(Str); HighPoint := System.High(Str); {$ELSE} LowPoint := 1; HighPoint := System.Length(Str); {$ENDIF DELPHIXE3_UP} for i := LowPoint to HighPoint do begin c[i - 1] := Str[i]; end; System.SetLength(b, System.Length(c) * 2); i := 0; while i <> System.Length(c) do begin b[2 * i] := Byte(Ord(c[i]) shr 8); b[2 * i + 1] := Byte(c[i]); System.Inc(i); end; (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.BmpString, b); end; class function TDerBmpString.GetInstance(const obj: TObject): IDerBmpString; begin if ((obj = Nil) or (obj is TDerBmpString)) then begin result := obj as TDerBmpString; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerBmpString.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerBmpString; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerBmpString))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := TDerBmpString.Create(TAsn1OctetString.GetInstance(o as TAsn1Object) .GetOctets()); end; function TDerBmpString.GetString: String; begin result := FStr; end; end.
unit uDMPlanoBackup; interface uses System.SysUtils, System.Classes, uDM, Data.DB, Datasnap.DBClient; type TdmPlanoBackup = class(TDataModule) CDSCadastro: TClientDataSet; CDSItens: TClientDataSet; CDSItensPlbIte_Id: TAutoIncField; CDSItensPlbIte_Hora: TTimeField; CDSItensPlbIte_PlanoBackup: TIntegerField; CDSItensPlbIte_Status: TBooleanField; CDSCadastroPlb_Id: TAutoIncField; CDSCadastroPlb_Destino: TStringField; CDSCadastroPlb_Domingo: TBooleanField; CDSCadastroPlb_Segunda: TBooleanField; CDSCadastroPlb_Terca: TBooleanField; CDSCadastroPlb_Quarta: TBooleanField; CDSCadastroPlb_Quinta: TBooleanField; CDSCadastroPlb_Sexta: TBooleanField; CDSCadastroPlb_Sabado: TBooleanField; CDSCadastroPlb_Ativo: TBooleanField; CDSCadastroPlb_DataUltimoBackup: TDateField; procedure DataModuleCreate(Sender: TObject); procedure CDSCadastroNewRecord(DataSet: TDataSet); procedure CDSItensBeforePost(DataSet: TDataSet); private { Private declarations } FIdItem: Integer; public { Public declarations } end; var dmPlanoBackup: TdmPlanoBackup; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TdmPlanoBackup.CDSCadastroNewRecord(DataSet: TDataSet); begin // CDSCadastroPlb_Id.AsInteger := 0; CDSCadastroPlb_Domingo.AsBoolean := False; CDSCadastroPlb_Segunda.AsBoolean := True; CDSCadastroPlb_Terca.AsBoolean := True; CDSCadastroPlb_Quarta.AsBoolean := True; CDSCadastroPlb_Quinta.AsBoolean := True; CDSCadastroPlb_Sexta.AsBoolean := True; CDSCadastroPlb_Sabado.AsBoolean := False; CDSCadastroPlb_Ativo.AsBoolean := True; end; procedure TdmPlanoBackup.CDSItensBeforePost(DataSet: TDataSet); begin if CDSItens.State = dsInsert then begin CDSItensPlbIte_PlanoBackup.AsInteger := 0; CDSItensPlbIte_Status.AsBoolean := False; CDSItensPlbIte_Id.AsInteger := FIdItem; Dec(FIdItem); end; end; procedure TdmPlanoBackup.DataModuleCreate(Sender: TObject); var i: Integer; begin for I := 0 to Self.ComponentCount -1 do begin if Self.Components[i] is TClientDataSet then TClientDataSet(Components[i]).RemoteServer := dm.DSPConexao2; end; FIdItem := -1; end; end.
unit vCardBase64; interface function Decode64(const S: ANSIString): ANSIString; function Encode64(const Input: string): string; implementation const Codes64:ANSIString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function Decode64(const S: ANSIString): ANSIString; var i: Integer; a: Integer; x: Integer; b: Integer; begin Result := ''; a := 0; b := 0; for i := 1 to Length(s) do begin x := Pos(s[i], codes64) - 1; if x >= 0 then begin b := b * 64 + x; a := a + 6; if a >= 8 then begin a := a - 8; x := b shr a; b := b AND ((1 SHL a)-1); Result := Result + ANSIChar(chr(x)); end; end else Exit; end; end; var EncodeTable: array[0..63] of Char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789+/'; DecodeTable: array[#0..#127] of Integer = ( Byte('='), 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64); type PPacket = ^TPacket; TPacket = packed record case Integer of 0: (b0, b1, b2, b3: Byte); 1: (i: Integer); 2: (a: array[0..3] of Byte); 3: (c: array[0..3] of Char); end; procedure EncodePacket(const Packet: TPacket; NumChars: Integer; OutBuf: PChar); begin OutBuf[0] := EnCodeTable[Packet.a[0] shr 2]; OutBuf[1] := EnCodeTable[((Packet.a[0] shl 4) or (Packet.a[1] shr 4)) and $0000003f]; if NumChars < 2 then OutBuf[2] := '=' else OutBuf[2] := EnCodeTable[((Packet.a[1] shl 2) or (Packet.a[2] shr 6)) and $0000003f]; if NumChars < 3 then OutBuf[3] := '=' else OutBuf[3] := EnCodeTable[Packet.a[2] and $0000003f]; end; function Encode64(const Input: string): string; var I, K, J: Integer; Packet: TPacket; begin Result := ''; I := (Length(Input) div 3) * 4; if Length(Input) mod 3 > 0 then Inc(I, 4); SetLength(Result, I); J := 1; for I := 1 to Length(Input) div 3 do begin Packet.i := 0; Packet.a[0] := Byte(Input[(I - 1) * 3 + 1]); Packet.a[1] := Byte(Input[(I - 1) * 3 + 2]); Packet.a[2] := Byte(Input[(I - 1) * 3 + 3]); EncodePacket(Packet, 3, PChar(@Result[J])); Inc(J, 4); end; K := 0; Packet.i := 0; for I := Length(Input) - (Length(Input) mod 3) + 1 to Length(Input) do begin Packet.a[K] := Byte(Input[I]); Inc(K); if I = Length(Input) then EncodePacket(Packet, Length(Input) mod 3, PChar(@Result[J])); end; end; end.
unit uBaseConhDetalhe; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, uBaseConhController; const COR_ABERTURA: Integer = clRed; COR_OCORR_GERAL: Integer = clPurple; COR_STATUS: Integer = clOlive; COR_PADRAO: Integer = clBlack; COR_TITULO: Integer = clRed; TAMANHO_DIVISAO: Integer = 164; TRACO: Char = '_'; type TfrmBaseConhDetalhe = class(TForm) redtGeral: TRichEdit; procedure redtGeralKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure FormatarLinha(var AMemo: TRichEdit; ACor: Integer; ATexto: string; ANegrito: Boolean = False); overload; procedure PreencherDados(AObj: TBaseConhController); public { Public declarations } constructor create(AIdBase: integer); end; var frmBaseConhDetalhe: TfrmBaseConhDetalhe; implementation {$R *.dfm} { TfrmBaseConhDetalhe } constructor TfrmBaseConhDetalhe.create(AIdBase: integer); var Controller: TBaseConhController; begin inherited create(nil); Controller := TBaseConhController.Create; try Controller.LocalizarId(AIdBase); PreencherDados(Controller); finally FreeAndNil(Controller); end; end; procedure TfrmBaseConhDetalhe.FormatarLinha(var AMemo: TRichEdit; ACor: Integer; ATexto: string; ANegrito: Boolean); begin AMemo.SelAttributes.Color := ACor; if ANegrito then AMemo.SelAttributes.Style:=[fsBold]; AMemo.Lines.Add(ATexto); AMemo.SelAttributes.Color:=Color; end; procedure TfrmBaseConhDetalhe.PreencherDados(AObj: TBaseConhController); begin redtGeral.Lines.Add(''); FormatarLinha(redtGeral,COR_TITULO, 'ABERTURA', True); FormatarLinha(redtGeral,COR_PADRAO, 'ID: ' + AObj.Model.CDSCadastroBas_Id.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Data: ' + AObj.Model.CDSCadastroBas_Data.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Nome: ' + AObj.Model.CDSCadastroBas_Nome.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Usuário: ' + AObj.Model.CDSCadastroUsu_Nome.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Módulo: ' + AObj.Model.CDSCadastroMod_Nome.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Produto: ' + AObj.Model.CDSCadastroProd_Nome.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Tipo: ' + AObj.Model.CDSCadastroTip_Nome.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Status: ' + AObj.Model.CDSCadastroSta_Nome.AsString); FormatarLinha(redtGeral,COR_PADRAO, 'Anexo: ' + AObj.Model.CDSCadastroBas_Anexo.AsString); FormatarLinha(redtGeral,COR_PADRAO, StringOfChar(TRACO, TAMANHO_DIVISAO)); redtGeral.Lines.Add(''); FormatarLinha(redtGeral,COR_TITULO, 'DESCRIÇÃO', True); FormatarLinha(redtGeral,COR_PADRAO, AObj.Model.CDSCadastroBas_Descricao.AsString); redtGeral.SelStart := Perform(EM_LINEINDEX, 0, 0); end; procedure TfrmBaseConhDetalhe.redtGeralKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; end.
{******************************************************************************* Animation Splash Form (ASF) Автор: Andy BitOff, asf@bitoff.ru, http://bitoff.ru/asf-main ICQ:95044580, Санкт-Петербург, Россия Copyright: Andy BitOff Дата: 27.08.2009 Версия: 2.3.0 Зависимость: GDI+ (GDIPAPI, GDIPOBJ, GDIPUTIL) ******************************************************************************** ================================================================================ ASFMain unit TAnimationSplashForm Создает анимированное окно в дополнительном потоке со своей очередью сообщений. Позволяет сделать информативное сплэш окно любой сложности. ================================================================================ История изменений ------------------------------------------------------------------------------ 2.3.0 + onDblClick - Сообщения приходящие от мыши + onMouseDown --| + onMouseUp --| + onMouseMove --| * Переименовано ProgressBarPercent -> ProgressBarPercentSection * ProgressBarPercentSection теперь Double + ProgressBarPercentFull (ReadOnly) - количество выполненного в процентах относительно всего прогрессбара + Свойство Visible для анимации + WaitModeStart - Метод вводящий прогрессбар и иконки в режим ожидания с соответстующей индикацией + WaitModeEnd - Выход из режима ожидания + isWaitMode - Находимся ли мы в режиме ожидания + onWaitModeCustomDraw - Событие позволяющее самому рисовать в прогрессбаре режим ожидания, если не устраивает дефолтная прорисовка. * Изменен порядок прорисовки, теперь сначала рисуется анимация, затем иконки, потом прогрессбар и наконец текст. 2.2.4 + свойство Cursor - Позволяет назначить свой курсор для сплэша 2.2.3 + onEndFade - Событие возникает когда сплэш полностью проявился + Исправлена 100% загрузка процессора на некоторых машинах 2.2.2 + AttemptedClosure - признак попытки закрытия сплэша 2.2.0 + onKeyPress + onKeyDown + onKeyUp + ClosingAllow - разрешить закрытие сплэша (Default - True) * небольшие переделки 2.0.0 * Исправлена ошибка использования нескольких экземпляров класса * Исправлена ошибка, при которой возникали проблемы при использовании класса с именем отличным от заданного в модуле ASFMain * Исправлена ситуация, при которой неверно отображался прогресс в прогрессбаре из-за не установки количества секций + Сохранение ВСЕХ данных сплэша в один внешний файл. + Загрузка ранее сохраненного сплэша из файла, ресурсов, потока одной строчкой кода + Добавлена функция GetGPColor, позволяющая вводить цвета в более удобном виде + Добавлены: onStartSplash - Событие возникает перед стартом сплэша onDestroySplash - Событие возникает перед уничтожением сплэша onBeforeDraw - Событие возникает перед началом прорисовки в обработчик передается чистая канва onAfterDraw - Событие возникает после прорисовки в обработчик передается канва с полным изображением сплэша в текущей итерации Следующие три свойства позволяют использовать прогрессбар по своему усмотрению ProgressBarTotalParts - число определяющее 100% части ProgressBarPartComplite - число определяющее выполненное количество ProgressBarPercent - количество выполненного в процентах ProgressBarSectionColor - возможность задать для каждой секции свой цвет BarDrawOnTime - Изменение ProgressBar'а по времени или вручную * Переименованы: ProgressBarCurrentPart -> ProgressBarCurrentSection ProgressBarPatrs -> ProgressBarSectionsCount IncCurrentPart -> IncCurrentSection LoadingPartTime -> LoadingSectionTime * Мелкие исправления 1.3.1 * Исправил загрузку бэкграунда из ресурсов (забыл мелочь ;)) 1.3.0 + Добавлена загрузка бэкграунда, анимации и иконок из ресурсов. + Добавлено свойство анимации DelayBetweenPassage - пауза между циклами анимации, что позволяет создать, например, анимацию блика ! Изменен формат сохранения анимации и иконок. Придется пересохранить уже созданные ресурсы в новом формате * Мелкие доработки 1.2.0 * Исправлены все мелкие и крупные утечки памяти, которые не показывал EurekaLog, но показал FastMM 4.92. * Переделан доступ к некоторым объектам ASF 1.1.1 * Исправлены недочеты в коде 1.1.0 * Устранена утечка памяти (defecator меня все-таки доканал) * Мелкие исправления 1.0.0 * Решен глюк с отображением эффекта фэйда для иконок * Работают все эффекты для иконок 0.94.0 + Добавлен эффект анимации, но пока не используется * Изменен приоритет потока (забыл исправить перед релизом. Спасибо Сергей М., что напомнил ;)) * Исправлена ошибка Access violation появлявшаяся в редких случаях при запуске Demo * Мелкие исправления 0.93.0 Тестовая версия ------------------------------------------------------------------------------ ===============================================================================} unit ASFMain; interface uses Windows, Messages, Classes, Graphics, SysUtils, Contnrs, Forms, GDIPAPI, GDIPOBJ, GDIPUTIL, ASFLists, Controls; resourcestring eFileNotFound = 'File %s not found'; eFileNotSupported = 'Unknown format.' + #13#10 + 'Stream: %s'; eIndexOutOfBounds = 'Index out of bounds (%d)'; type TIconInfo = record IconIndex: Integer; IconPos: Integer; IconWidth: Integer; IconHeight: Integer; end; PProgressBarInfo = ^TProgressBarInfo; TProgressBarInfo = record BarVisible: Boolean; BarBorderVisible: Boolean; BarBox: TGPRect; BarColor: Cardinal; BarBorderColor: Cardinal; BarDrawOnTime: Boolean; end; TIconAnimation = (iaNone, iaFade, iaFadeColor, iaSlideTop, iaSlideLeft, iaSlideCorner); TKeyEventType = (etKeyDown, etKeyUp, etKeyPress); TasfSplashEvent = procedure(Sender: TObject) of object; TasfStartSplashEvent = TasfSplashEvent; TasfDestroySplashEvent = TasfSplashEvent; TasfBeforeDrawEvent = procedure(Sender: TObject; GPGraphics: TGPGraphics) of object; TasfAfterDrawEvent = procedure(Sender: TObject; GPGraphics: TGPGraphics) of object; TasfKeyPressEvent = procedure(Sender: TObject; var Key: Char) of object; TasfKeyDownEvent = procedure(Sender: TObject; var Key: Word; Shift: TShiftState) of object; TasfKeyUpEvent = TasfKeyDownEvent; TasfEndFade = TasfSplashEvent; TasfMouseMoveEvent = procedure(Sender: TObject; Shift: TShiftState; X, Y: Integer) of object; TasfMouseEvent = procedure(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of object; TasfWaitModeCustomDrawEvent = procedure(Sender: TObject; GPGraphics: TGPGraphics; GPRegion: TGPRegion; var DefaultDraw:Boolean) of object; // TasfProgressPartCompliteEvent = procedure(Sender: TObject; Part: integer) of object; TAnimationSplashForm = class(TThread) private FAnimations: TObjectList; FBMPBackground: TGPBitmap; FClose: Boolean; FCritSec: TRTLCriticalSection; FAttemptedClosure: Boolean; FBarSectionsColor: array of cardinal; FClosingAllow: Boolean; FCurrentIconPosition: Integer; FDC: HDC; FDestroy: Boolean; FFadeSpeed: Integer; FGuid: string; FIconAnimation: TIconAnimation; FIconFullPaintPercent: Integer; FIconPosArray: array of TIconInfo; FIconPosLeft: Integer; FIconPosTop: Integer; FIcons: TImagesList; FIconSpace: Integer; FIconStep: Integer; FLoadingSectionTime: Integer; FonAfterDraw: TasfAfterDrawEvent; FonBeforeDraw: TasfBeforeDrawEvent; FonDestroySplash: TasfDestroySplashEvent; FOneSectionProgressSize: Integer; FonKeyDown: TasfKeyDownEvent; FonKeyPress: TasfKeyPressEvent; FonKeyUp: TasfKeyUpEvent; FonStartSplash: TasfStartSplashEvent; FOnEndFade: TasfEndFade; FProgressBar: PProgressBarInfo; FProgressBarCurrentSection: Integer; FProgressBarPartComplite: Integer; FProgressBarPercentSection: Double; FProgressBarSectionsCount: Integer; FProgressBarTotalParts: Integer; FProgressIconCurrentItem: Integer; FProgressIconsVisible: Boolean; FrameNumber: integer; FSelfClose: Boolean; FSetedSectColor: Boolean; FShowTaskbarButton: Boolean; FSplashFormCaption: String; FSplashFormTopMost: Boolean; FStartCurrentSection: Integer; FTestSpeed: Boolean; FTextData: TTextItemList; FTickCountAll: Integer; FTickCountOld: Integer; FTickZero: Cardinal; FTimerInterval: Integer; FTransparent: integer; FTransparentOld: integer; FWaitClose: Integer; FEndFadeHasOperated: Boolean; FCursor: TCursor; FonMouseMove: TasfMouseMoveEvent; FonMouseDown: TasfMouseEvent; FonMouseUp: TasfMouseEvent; FonDblClick: TasfSplashEvent; FHandle: HWND; FProgressBarPercentFull: Double; FWaitMode: Boolean; FWaitModeStepPR: Integer; FSlowWaitMode: Integer; FSlowWaitModeCount: Integer; FTempIconAnimation: TIconAnimation; FWaitModeStepICO: Real; FWaitModeICOinc: Boolean; FonWaitModeCustomDraw: TasfWaitModeCustomDrawEvent; function CreateMyWnd(): hWnd; procedure InitData; procedure TimerProc(); procedure RenderForm(TransparentValue: byte; SourceImage: TGPBitmap); procedure TextOut(TextInfo: TTextItem; TextColor: Cardinal; GPGraphics: TGPGraphics; GPRect: TGPRectF); procedure SetProgressBarSectionsCount(const Value: Integer); procedure SetProgressBarCurrentSection(const Value: Integer); procedure SetLoadingSectionTime(const Value: Integer); function GetMyTickCount: Integer; procedure PaintIcons(GPGraphics: TGPGraphics); procedure SetProgressIconCurrentItem(const Value: Integer); procedure SetProgressIconsVisible(const Value: Boolean); procedure SetIconFullPaintPercent(Value: Integer); procedure SetIconAnimation(const Value: TIconAnimation); procedure DrawSplash; procedure PaintProgressBar(GPGraphics: TGPGraphics); function GetAnimationRect(ItemIndex: Integer; GPImageAttributes: TGPImageAttributes): TGPRectF; function CalcCurrentIconPos(IconItem: Integer): Integer; function GetAnimations(Index: Integer): TAnimationFrames; procedure SetAnimations(Index: Integer; const Value: TAnimationFrames); function AnimationValidIndex(Index: integer): Boolean; procedure PaintAnimations(GPGraphics: TGPGraphics); procedure SetFadeSpeed(Value: Integer); function GetProgressBarSectionColor: cardinal; function GetProgressBarPartComplite: Integer; function GetProgressBarPercentSection: Double; function GetProgressBarTotalParts: Integer; procedure PaintText(GPGraphics: TGPGraphics); procedure SetIconPosLeft(const Value: Integer); procedure SetIconPosTop(const Value: Integer); procedure SetIconSpace(const Value: Integer); procedure SetIconStep(const Value: Integer); function SetLengthIconArray: Boolean; procedure SaveTextData(Stream: TStream); procedure SaveRectData(Stream: TStream; GPRect: TGPRect); procedure SaveStringData(Stream: TStream; Str: String); procedure SaveIconsData(Stream: TStream); procedure SaveAnimationsData(Stream: TStream); procedure LoadStringData(Stream: TStream; var Str: String); procedure LoadRectData(Stream: TStream; var GPRect: TGPRect); procedure LoadFromFile(FileName: string); procedure LoadFromStream(Stream: TStream); procedure Resume; procedure LoadAnimationsData(Stream: TStream); procedure LoadIconsData(Stream: TStream); procedure LoadTextData(Stream: TStream); procedure SetProgressBarSectionColor(const Value: cardinal); procedure SetProgressBarPartComplite(const Value: Integer); procedure SetProgressBarPercentSection(const Value: Double); procedure SetProgressBarTotalParts(const Value: Integer); function GetTimerInterval: Integer; procedure PressKey(var aMsg: TMsg; EventType: TKeyEventType); procedure WMSetCursor; procedure WMMouseMove(Shift: TShiftState; X, Y: Integer); procedure DoDblClick; procedure DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DrawWaitModeProgress(GPGraphics: TGPGraphics); protected procedure Execute; override; published public constructor Create(Width, Height, ResolutionX, ResolutionY: Integer); constructor CreateFrom(BackGroundFileName: string); overload; constructor CreateFrom(Stream: TStream); overload; constructor CreateFrom(ResourceName: string; ResourceType: PChar); overload; constructor CreateFullFrom(FileName: string; Start: Boolean = True); overload; constructor CreateFullFrom(Stream: TStream; Start: Boolean = True); overload; constructor CreateFullFrom(ResourceName: string; ResourceType: PChar; Start: Boolean = True); overload; destructor Destroy; override; procedure StartSplash; procedure CloseSplash(CloseDelay: Integer; Destroy: Boolean = True); property ClosingAllow: Boolean read FClosingAllow write FClosingAllow; property AttemptedClosure: Boolean read FAttemptedClosure; procedure SaveToFile(FileName: string); procedure SaveToStream(Stream: TStream); procedure SetTimerInterval(Interval: Integer); function TestSpeedDrawSplash: Integer; procedure IncCurrentSection; procedure IncCurrentItemIcon; function AnimationsAdd(Value: TAnimationFrames): Integer; function AnimationsAddFromFile(FileName: string): Integer; function AnimationsAddFromResource(ResourceName: string; ResourceType: PChar): Integer; function AnimationsAddFromStream(Stream: TStream): Integer; function AnimationsCount: Integer; procedure WaitModeStart(SlowWaitMode: Integer = 0); procedure WaitModeEnd; function isWaitMode: Boolean; property Animations[Index: Integer]: TAnimationFrames read GetAnimations write SetAnimations; property Cursor: TCursor read FCursor write FCursor; property FadeSpeed: Integer read FFadeSpeed write SetFadeSpeed; property IconAnimation: TIconAnimation read FIconAnimation write SetIconAnimation; property IconFullPaintPercent: Integer read FIconFullPaintPercent write SetIconFullPaintPercent; property IconPosLeft: Integer read FIconPosLeft write SetIconPosLeft; property IconPosTop: Integer read FIconPosTop write SetIconPosTop; property Icons: TImagesList read FIcons write FIcons; property IconSpace: Integer read FIconSpace write SetIconSpace; property IconStep: Integer read FIconStep write SetIconStep; property LoadingSectionTime: Integer read FLoadingSectionTime write SetLoadingSectionTime; property ProgressBar: PProgressBarInfo read FProgressBar write FProgressBar; property ProgressBarCurrentSection: Integer read FProgressBarCurrentSection write SetProgressBarCurrentSection; property ProgressBarSectionsCount: Integer read FProgressBarSectionsCount write SetProgressBarSectionsCount; property ProgressBarTotalParts: Integer read GetProgressBarTotalParts write SetProgressBarTotalParts; property ProgressBarPartComplite: Integer read GetProgressBarPartComplite write SetProgressBarPartComplite; property ProgressBarPercentSection: Double read GetProgressBarPercentSection write SetProgressBarPercentSection; property ProgressBarPercentFull: Double read FProgressBarPercentFull; property ProgressBarSectionColor: cardinal read GetProgressBarSectionColor write SetProgressBarSectionColor; property ProgressIconCurrentItem: Integer read FProgressIconCurrentItem write SetProgressIconCurrentItem; property ProgressIconsVisible: Boolean read FProgressIconsVisible write SetProgressIconsVisible; property ShowTaskbarButton: Boolean read FShowTaskbarButton write FShowTaskbarButton; property SplashFormCaption: String read FSplashFormCaption write FSplashFormCaption; property SplashFormTopMost: Boolean read FSplashFormTopMost write FSplashFormTopMost; property TextData: TTextItemList read FTextData write FTextData; property TimerInterval: Integer read GetTimerInterval write SetTimerInterval; property onStartSplash: TasfStartSplashEvent read FonStartSplash write FonStartSplash; property onEndFade: TasfEndFade read FOnEndFade write FOnEndFade; property onDestroySplash: TasfDestroySplashEvent read FonDestroySplash write FonDestroySplash; property onBeforeDraw: TasfBeforeDrawEvent read FonBeforeDraw write FonBeforeDraw; property onAfterDraw: TasfAfterDrawEvent read FonAfterDraw write FonAfterDraw; property onKeyPress: TasfKeyPressEvent read FonKeyPress write FonKeyPress; property onKeyDown: TasfKeyDownEvent read FonKeyDown write FonKeyDown; property onKeyUp: TasfKeyUpEvent read FonKeyUp write FonKeyUp; property onDblClick: TasfSplashEvent read FonDblClick write FonDblClick; property onMouseDown: TasfMouseEvent read FonMouseDown write FonMouseDown; property onMouseUp: TasfMouseEvent read FonMouseUp write FonMouseUp; property onMouseMove: TasfMouseMoveEvent read FonMouseMove write FonMouseMove; property onWaitModeCustomDraw: TasfWaitModeCustomDrawEvent read FonWaitModeCustomDraw write FonWaitModeCustomDraw; property Handle: HWND read FHandle; end; function WndProc(Wnd: HWND; message: UINT; wParam: Integer; lParam: Integer) : Integer; stdcall; function GetGPColor(Color: TColor; Alpha: byte): cardinal; var AnimationSplashForm: TAnimationSplashForm; implementation uses ActiveX; const RsSystemIdleProcess = 'System Idle Process'; RsSystemProcess = 'System Process'; InitProcessClassName = 'SplashWindow'; type TFixedStreamAdapter = class(TStreamAdapter) public function Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; override; stdcall; end; var { SplashHandle: HWND;} Msg: TMsg; FadeColorMatrix: TColorMatrix = // Для фэйда иконок ((1.0, 0.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 0.0, 1.0)); FadeColorColorMatrix: TColorMatrix = // Для фэйда цвета иконок ((0.299, 0.299, 0.299, 0.0, 0.0), (0.587, 0.587, 0.587, 0.0, 0.0), (0.114, 0.114, 0.114, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 0.0, 1.0)); function GetGPColor(Color: TColor; Alpha: byte): cardinal; begin Result := (Color and $FF) shl 16 + Color and $FF00 + (Color and $FF0000) shr 16 + Alpha shl 24; end; function WndProc(Wnd: HWND; message: UINT; wParam: Integer; lParam: Integer) : Integer; stdcall; var ASF: TAnimationSplashForm; begin ASF := TAnimationSplashForm(GetWindowLong(Wnd, GWL_USERDATA)); case message of WM_KEYDOWN: begin ASF.PressKey(msg, etKeyDown); end; WM_KEYUP: begin ASF.PressKey(msg, etKeyUp); end; WM_CHAR: begin ASF.PressKey(msg, etKeyPress); end; WM_TIMER: begin ASF.TimerProc(); result := 0; Exit; end; WM_SETCURSOR: begin ASF.WMSetCursor(); end; WM_MOUSEMOVE: begin ASF.WMMouseMove(KeysToShiftState(wParam), LOWORD(lParam), HIWORD(lParam)); end; WM_LBUTTONDBLCLK, WM_RBUTTONDBLCLK: begin ASF.DoDblClick; end; WM_LBUTTONDOWN: begin ASF.DoMouseDown(mbLeft, KeysToShiftState(wParam), LOWORD(lParam), HIWORD(lParam)); end; WM_RBUTTONDOWN: begin ASF.DoMouseDown(mbRight, KeysToShiftState(wParam), LOWORD(lParam), HIWORD(lParam)); end; WM_LBUTTONUP: begin ASF.DoMouseUp(mbLeft, KeysToShiftState(wParam), LOWORD(lParam), HIWORD(lParam)); end; WM_RBUTTONUP: begin ASF.DoMouseUp(mbRight, KeysToShiftState(wParam), LOWORD(lParam), HIWORD(lParam)); end; WM_SYSCOMMAND: begin if (wParam and $FFF0) = SC_CLOSE then begin with ASF do begin if not (FSelfClose or ClosingAllow) then begin FAttemptedClosure := True; result := 0; Exit; end; end; end; end; WM_DESTROY: begin PostQuitMessage(0); result := 0; Exit; end; end; result := DefWindowProc(Wnd, message, wParam, lParam); end; { TFixedStreamAdapter } function TFixedStreamAdapter.Stat(out statstg: TStatStg; grfStatFlag: Integer): HResult; begin Result := inherited Stat(statstg, grfStatFlag); statstg.pwcsName := nil; end; { TAnimationSplashForm } constructor TAnimationSplashForm.CreateFrom(BackGroundFileName: string); var st: TFileStream; begin st := TFileStream.Create(BackGroundFileName, fmOpenRead); try FBMPBackground := TGPBitmap.Create(TFixedStreamAdapter.Create(st)); InitData(); inherited Create(True); finally st.Free; end; end; constructor TAnimationSplashForm.Create(Width, Height, ResolutionX, ResolutionY: Integer); begin FBMPBackground := TGPBitmap.Create(Width, Height); FBMPBackground.SetResolution(ResolutionX, ResolutionY); InitData(); inherited Create(True); end; constructor TAnimationSplashForm.CreateFrom(Stream: TStream); begin FBMPBackground := TGPBitmap.Create(TFixedStreamAdapter.Create(Stream)); InitData(); inherited Create(True); end; constructor TAnimationSplashForm.CreateFrom(ResourceName: string; ResourceType: PChar); var st: TResourceStream; begin st := TResourceStream.Create(Hinstance, ResourceName, ResourceType); try FBMPBackground := TGPBitmap.Create(TFixedStreamAdapter.Create(st)); InitData(); inherited Create(True); finally st.Free; end; end; constructor TAnimationSplashForm.CreateFullFrom(FileName: string; Start: Boolean = True); begin InitData(); LoadFromFile(FileName); inherited Create(True); if Start then StartSplash; end; constructor TAnimationSplashForm.CreateFullFrom(Stream: TStream; Start: Boolean = True); begin InitData(); LoadFromStream(Stream); inherited Create(True); if Start then StartSplash; end; constructor TAnimationSplashForm.CreateFullFrom(ResourceName: string; ResourceType: PChar; Start: Boolean = True); var st: TResourceStream; begin st := TResourceStream.Create(Hinstance, ResourceName, ResourceType); try InitData(); LoadFromStream(St); inherited Create(True); if Start then StartSplash; finally st.Free; end; end; destructor TAnimationSplashForm.Destroy; begin if Assigned(FOnDestroySplash) then FOnDestroySplash(Self); KillTimer(Handle, 0); FAnimations.Free; FIcons.Free; TextData.Free; Dispose(FProgressBar); FBarSectionsColor := nil; FBMPBackground.Free; DeleteCriticalSection(FCritSec); SetForegroundWindow(Application.Handle); inherited; DestroyWindow(Handle); Windows.UnregisterClass(PChar(InitProcessClassName + FGuid), hInstance); end; procedure TAnimationSplashForm.Execute; {var PrevMask: DWord;} begin SetLengthIconArray(); FreeOnTerminate := True; FHandle := CreateMyWnd; if Handle = 0 then Exit; { PrevMask := SetThreadAffinityMask(GetCurrentThread, 1); Sleep(10);} SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_NORMAL); SetWindowLong(Handle, GWL_USERDATA, Integer(Self)); SetTimer(Handle, 0, FTimerInterval, nil); while GetMessage(Msg, 0, 0, 0) do begin TranslateMessage(Msg); DispatchMessage(Msg); SwitchToThread; { Sleep(0);} end; { SetThreadAffinityMask(GetCurrentThread, PrevMask);} end; function TAnimationSplashForm.CreateMyWnd(): hWnd; var wc: WndClass; f: Integer; Guid: TGuid; begin wc.style := CS_HREDRAW or CS_VREDRAW; wc.lpfnWndProc := @WndProc; wc.cbClsExtra := 0; wc.cbWndExtra := 0; wc.hInstance := hInstance; wc.hIcon := 0; wc.hCursor := 0; wc.hbrBackground := COLOR_INACTIVECAPTION; wc.lpszMenuName := nil; CreateGuid(Guid); FGuid := StringReplace(GuidToString(Guid), '-', '', [rfReplaceAll]); wc.lpszClassName := PChar(InitProcessClassName + FGuid); result := 0; if Windows.RegisterClass(wc) = 0 then Exit; f := WS_EX_APPWINDOW; if not ShowTaskbarButton then f := WS_EX_TOOLWINDOW; if SplashFormTopMost then f := f or WS_EX_TOPMOST; result := CreateWindowEx(f, PChar(InitProcessClassName + FGuid), PChar(SplashFormCaption), WS_POPUP, GetSystemMetrics(SM_CXFULLSCREEN) div 2 - Integer(FBMPBackground.GetWidth) div 2, GetSystemMetrics(SM_CYFULLSCREEN) div 2 - Integer(FBMPBackground.GetHeight) div 2, FBMPBackground.GetWidth, FBMPBackground.GetHeight, 0, 0, hInstance, nil); end; procedure TAnimationSplashForm.InitData; begin InitializeCriticalSection(FCritSec); Cursor := Screen.Cursors[crDefault]; FSelfClose := False; ClosingAllow := True; FAttemptedClosure := False; FTimerInterval := 100; FAnimations := TObjectList.Create(True); FIcons := TImagesList.Create; FClose := False; New(FProgressBar); with ProgressBar^ do begin BarVisible := False; BarBorderVisible := True; BarBox := MakeRect(0, 0, 100, 20); BarColor := $FFFFFFFF; BarBorderColor := $FFFFFFFF; BarDrawOnTime := True; end; ProgressBarTotalParts := 100; ProgressBarPartComplite := 0; ProgressBarSectionsCount := 1; TextData := TTextItemList.Create; FCurrentIconPosition := 0; FFadeSpeed := 7; FProgressIconCurrentItem := 0; FrameNumber := 0; FStartCurrentSection := 0; FTickCountAll := 0; FTickCountOld := 0; FTickZero := 0; FTransparent := 0; FTransparentOld := 255; IconFullPaintPercent := 100; LoadingSectionTime := 0; ProgressIconsVisible := True; ProgressBarSectionsCount := 1; FSetedSectColor := False; FEndFadeHasOperated := False; FWaitMode := False; FWaitModeStepPR := 0; end; procedure TAnimationSplashForm.CloseSplash(CloseDelay: Integer; Destroy: Boolean = True); begin FWaitClose := CloseDelay; FClose := True; FDestroy := Destroy; end; procedure TAnimationSplashForm.StartSplash; begin FClose := False; FOneSectionProgressSize := FProgressBar.BarBox.Width div FProgressBarSectionsCount; if not FSetedSectColor then FBarSectionsColor[0] := ProgressBar^.BarColor; if Assigned(FOnStartSplash) then FonStartSplash(Self); Resume; end; procedure TAnimationSplashForm.Resume; begin inherited; end; procedure TAnimationSplashForm.SetTimerInterval(Interval: Integer); begin FTimerInterval := Interval; end; function TAnimationSplashForm.GetTimerInterval: Integer; begin Result := FTimerInterval; end; procedure TAnimationSplashForm.SetFadeSpeed(Value: Integer); begin EnterCriticalSection(FCritSec); try if Value < 1 then Value := 1 else if Value > 255 then Value := 255; FFadeSpeed := Value; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressBarSectionsCount(const Value: Integer); var I: Integer; begin EnterCriticalSection(FCritSec); try if Value > 0 then FProgressBarSectionsCount := Value else FProgressBarSectionsCount := 1; FProgressBarCurrentSection := 1; FOneSectionProgressSize := FProgressBar.BarBox.Width div FProgressBarSectionsCount; SetLength(FBarSectionsColor, FProgressBarSectionsCount); for I := 0 to Length(FBarSectionsColor) - 1 do begin FBarSectionsColor[i] := ProgressBar^.BarColor; end; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressBarCurrentSection(const Value: Integer); begin EnterCriticalSection(FCritSec); try if Value <= 0 then FProgressBarCurrentSection := 1; if Value <= FProgressBarSectionsCount then FProgressBarCurrentSection := Value else FProgressBarCurrentSection := FProgressBarSectionsCount; FStartCurrentSection := FOneSectionProgressSize * (FProgressBarCurrentSection - 1); FTickCountAll := 0; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.IncCurrentSection; begin EnterCriticalSection(FCritSec); try if FProgressBarCurrentSection < FProgressBarSectionsCount then ProgressBarCurrentSection := ProgressBarCurrentSection + 1 else ProgressBarCurrentSection := FProgressBarSectionsCount; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetLoadingSectionTime(const Value: Integer); begin EnterCriticalSection(FCritSec); try if Value > 0 then FLoadingSectionTime := Value else FLoadingSectionTime := 1; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressIconsVisible(const Value: Boolean); begin FProgressIconsVisible := Value; end; procedure TAnimationSplashForm.SetIconPosLeft(const Value: Integer); begin EnterCriticalSection(FCritSec); try FIconPosLeft := Value; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetIconPosTop(const Value: Integer); begin EnterCriticalSection(FCritSec); try FIconPosTop := Value; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetIconSpace(const Value: Integer); begin EnterCriticalSection(FCritSec); try FIconSpace := Value; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetIconStep(const Value: Integer); begin EnterCriticalSection(FCritSec); try FIconStep := Value; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.CalcCurrentIconPos(IconItem: Integer): Integer; var I: Integer; a: Integer; begin Result := IconPosLeft; for I := 0 to Length(FIconPosArray) - 1 do begin if FIconPosArray[i].IconIndex = -1 then Continue; a := IconStep; if i = 0 then a := 0 else if a = 0 then a := FIconPosArray[i - 1].IconWidth; Result := Result + a; if i <> 0 then Result := Result + IconSpace; end; end; procedure TAnimationSplashForm.SetProgressIconCurrentItem(const Value: Integer); var nf: Integer; function NextFree: Integer; var I: Integer; begin Result := Length(FIconPosArray) - 1; for I := 0 to Result do begin if FIconPosArray[i].IconIndex = -1 then begin Result := I; Break; end; end; end; begin EnterCriticalSection(FCritSec); try if Icons <> nil then begin if FProgressIconCurrentItem <= Icons.Count - 1 then FProgressIconCurrentItem := Value else FProgressIconCurrentItem := Icons.Count - 1; nf := NextFree; if SetLengthIconArray() then begin FIconPosArray[nf].IconIndex := ProgressIconCurrentItem; FIconPosArray[nf].IconPos := CalcCurrentIconPos(ProgressIconCurrentItem); FIconPosArray[nf].IconWidth := Icons.Items[FProgressIconCurrentItem].GetWidth; FIconPosArray[nf].IconHeight := Icons.Items[FProgressIconCurrentItem].GetHeight; end; end; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.SetLengthIconArray: Boolean; var i: Integer; begin Result := False; if (Icons <> nil) and (Icons.Count <> 0) and (Length(FIconPosArray) <> Icons.Count) then begin SetLength(FIconPosArray, Icons.Count); for I := 0 to Length(FIconPosArray) - 1 do begin FIconPosArray[i].IconIndex := -1; FIconPosArray[i].IconPos := 0; FIconPosArray[i].IconWidth := 0; FIconPosArray[i].IconHeight := 0; end; end; if Length(FIconPosArray) <> 0 then Result := True; end; procedure TAnimationSplashForm.IncCurrentItemIcon; begin EnterCriticalSection(FCritSec); try if Icons <> nil then begin if FProgressIconCurrentItem < Icons.Count - 1 then ProgressIconCurrentItem := ProgressIconCurrentItem + 1 else ProgressIconCurrentItem := Icons.Count - 1; end; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetIconFullPaintPercent(Value: Integer); begin EnterCriticalSection(FCritSec); try if Value > 100 then Value := 100; if Value < 0 then Value := 0; FIconFullPaintPercent := Value; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetIconAnimation(const Value: TIconAnimation); begin EnterCriticalSection(FCritSec); try FIconAnimation := Value; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.GetMyTickCount: Integer; begin Result := GetTickCount() - FTickZero; end; function TAnimationSplashForm.TestSpeedDrawSplash: Integer; var TickCount: Integer; begin TickCount := GetTickCount(); FTestSpeed := True; DrawSplash(); FTestSpeed := False; Result := GetMyTickCount() - TickCount; end; function TAnimationSplashForm.GetAnimations(Index: Integer): TAnimationFrames; begin EnterCriticalSection(FCritSec); Result := nil; try if AnimationValidIndex(Index) then begin Result := TAnimationFrames(FAnimations.Items[index]); end else raise Exception.Create(Format(eIndexOutOfBounds, [Index])); finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetAnimations(Index: Integer; const Value: TAnimationFrames); begin EnterCriticalSection(FCritSec); try if (AnimationValidIndex(Index)) and (Value <> nil) then begin FAnimations.Items[index].Free; FAnimations.Items[index] := Value; end else raise Exception.Create(Format(eIndexOutOfBounds, [Index])); finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.AnimationsCount: Integer; begin EnterCriticalSection(FCritSec); try Result := FAnimations.Count; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.AnimationsAdd(Value: TAnimationFrames): Integer; var TmpVal: TAnimationFrames; begin EnterCriticalSection(FCritSec); try Result := -1; if Value <> nil then begin TmpVal := TAnimationFrames.Create; TmpVal.Assign(Value); Result := FAnimations.Add(TmpVal); end; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.AnimationsAddFromFile(FileName: string): Integer; var tmpAnim: TAnimationFrames; begin Result := -1; if not FileExists(FileName) then raise Exception.Create(Format(eFileNotFound , [FileName])); EnterCriticalSection(FCritSec); try tmpAnim := TAnimationFrames.CreateFrom(FileName); try Result := AnimationSplashForm.AnimationsAdd(tmpAnim); finally tmpAnim.Free; end; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.AnimationsAddFromStream(Stream: TStream): Integer; var tmpAnim: TAnimationFrames; begin Result := -1; EnterCriticalSection(FCritSec); try tmpAnim := TAnimationFrames.CreateFrom(Stream); try Result := AnimationSplashForm.AnimationsAdd(tmpAnim); finally tmpAnim.Free; end; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.AnimationsAddFromResource(ResourceName: string; ResourceType: PChar): Integer; var tmpAnim: TResourceStream; begin EnterCriticalSection(FCritSec); try tmpAnim := TResourceStream.Create(Hinstance, ResourceName, ResourceType); try Result := AnimationsAddFromStream(tmpAnim); finally tmpAnim.Free; end; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.GetProgressBarTotalParts: Integer; begin EnterCriticalSection(FCritSec); try Result := FProgressBarTotalParts; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressBarTotalParts(const Value: Integer); begin EnterCriticalSection(FCritSec); try FProgressBarTotalParts := Value; ProgressBarPartComplite := 0; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.GetProgressBarPartComplite: Integer; begin EnterCriticalSection(FCritSec); try Result := FProgressBarPartComplite; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressBarPartComplite(const Value: Integer); begin EnterCriticalSection(FCritSec); try if Value > FProgressBarTotalParts then FProgressBarPartComplite := FProgressBarTotalParts else FProgressBarPartComplite := Value; ProgressBarPercentSection := Value div (FProgressBarTotalParts div 100); finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.GetProgressBarPercentSection: Double; begin EnterCriticalSection(FCritSec); try Result := FProgressBarPercentSection; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressBarPercentSection(const Value: Double); begin EnterCriticalSection(FCritSec); try FProgressBarPercentSection := Value; if Value > 100 then FProgressBarPercentSection := 100; finally LeaveCriticalSection(FCritSec); end; end; function TAnimationSplashForm.GetProgressBarSectionColor: cardinal; begin EnterCriticalSection(FCritSec); try Result := FBarSectionsColor[FProgressBarCurrentSection - 1]; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SetProgressBarSectionColor(const Value: cardinal); begin EnterCriticalSection(FCritSec); try FBarSectionsColor[FProgressBarCurrentSection - 1] := Value; FSetedSectColor := True; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.WaitModeStart(SlowWaitMode: Integer = 0); begin FWaitMode := True; FSlowWaitModeCount := 0; if SlowWaitMode < 0 then SlowWaitMode := 0; FSlowWaitMode := SlowWaitMode; FTempIconAnimation := IconAnimation; FWaitModeStepICO := 0; FWaitModeICOinc := True; end; procedure TAnimationSplashForm.WaitModeEnd; begin IconAnimation := FTempIconAnimation; FWaitMode := False; end; function TAnimationSplashForm.isWaitMode: Boolean; begin Result := FWaitMode; end; procedure TAnimationSplashForm.SaveToFile(FileName: string); var st: TFileStream; begin EnterCriticalSection(FCritSec); try st := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite); try SaveToStream(st); finally st.Free; end; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.LoadFromFile(FileName: string); var st: TFileStream; begin EnterCriticalSection(FCritSec); try if not FileExists(FileName) then raise Exception.Create(Format(eFileNotFound , [FileName])); st := TFileStream.Create(FileName, fmOpenRead); try LoadFromStream(st); finally st.Free; end; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.LoadFromStream(Stream: TStream); var i: integer; aSize: Int64; s: AnsiString; tmpStream: TMemoryStream; begin EnterCriticalSection(FCritSec); try tmpStream := TMemoryStream.Create; try s := '12345678901'; Stream.Read(s[1], 11); if s = 'ASFFullData' then begin Stream.Read(aSize, SizeOf(aSize)); tmpStream.CopyFrom(Stream, aSize); FBMPBackground := TGPBitmap.Create(TFixedStreamAdapter.Create(tmpStream)); Stream.Read(FShowTaskbarButton, SizeOf(FShowTaskbarButton)); LoadStringData(Stream, FSplashFormCaption); Stream.Read(FSplashFormTopMost, SizeOf(FSplashFormTopMost)); Stream.Read(FFadeSpeed, SizeOf(FFadeSpeed)); Stream.Read(FTimerInterval, SizeOf(FTimerInterval)); Stream.Read(s[1], 11); if s = 'ClosingAllo' then begin Stream.Read(FClosingAllow, SizeOf(FClosingAllow)); end else begin Stream.Seek(-11, soCurrent); end; with ProgressBar^ do begin Stream.Read(BarVisible, SizeOf(BarVisible)); Stream.Read(BarBorderVisible, SizeOf(BarBorderVisible)); LoadRectData(Stream, BarBox); Stream.Read(BarColor, SizeOf(BarColor)); Stream.Read(BarBorderColor, SizeOf(BarBorderColor)); Stream.Read(BarDrawOnTime, SizeOf(BarDrawOnTime)); end; Stream.Read(i, SizeOf(FProgressBarSectionsCount)); ProgressBarSectionsCount := i; Stream.Read(s[1], 11); while s <> 'ASF_EndData' do begin if s = 'ASFTextData' then begin LoadTextData(Stream); end; if s = 'ASFIconData' then begin LoadIconsData(Stream); end; if s = 'ASFAnimData' then begin LoadAnimationsData(Stream); end; Stream.Read(s[1], 11); end; end else begin raise Exception.Create(Format(eFileNotSupported , ['ASFFullData'])); end; finally tmpStream.Free; end; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.LoadRectData(Stream: TStream; var GPRect: TGPRect); var i: Integer; begin i := SizeOf(integer); Stream.Read(GPRect.X, i); Stream.Read(GPRect.Y, i); Stream.Read(GPRect.Width, i); Stream.Read(GPRect.Height, i); end; procedure TAnimationSplashForm.LoadStringData(Stream: TStream; var Str: String); var i: Integer; begin Stream.Read(i, SizeOf(i)); SetLength(Str, i{ div 2}); Stream.Read(Str[1], i); end; procedure TAnimationSplashForm.LoadTextData(Stream: TStream); var I, a, NewIt, ti: Integer; tc: Cardinal; tb: Boolean; ts: String; tr: TGPRect; begin Stream.Read(a, SizeOf(a)); for I := 0 to a - 1 do begin NewIt := TextData.AddNewItem; with TextData.Items[NewIt] do begin Stream.Read(tb, SizeOf(tb)); Visible := tb; Stream.Read(tb, SizeOf(tb)); VisibleShadow := tb; LoadStringData(Stream, ts); Text := ts; LoadRectData(Stream, tr); TextBox := tr; Stream.Read(tc, SizeOf(tc)); Color := tc; Stream.Read(tc, SizeOf(tc)); ShadowColor := tc; LoadStringData(Stream, ts); FontName := ts; Stream.Read(ti, SizeOf(ti)); FontSize := ti; Stream.Read(ti, SizeOf(ti)); FontStyle := ti; Stream.Read(ti, SizeOf(ti)); PositionH := TStringAlignment(ti); Stream.Read(ti, SizeOf(ti)); PositionV := TStringAlignment(ti); Stream.Read(ti, SizeOf(ti)); RenderingHint := TTextRenderingHint(ti); end; end; end; procedure TAnimationSplashForm.LoadIconsData(Stream: TStream); var i: Integer; tb: Boolean; tmpStream: TMemoryStream; begin tmpStream := TMemoryStream.Create; try Stream.Read(tb, SizeOf(tb)); ProgressIconsVisible := tb; Stream.Read(i, SizeOf(i)); IconFullPaintPercent := i; Stream.Read(i, SizeOf(IconAnimation)); IconAnimation := TIconAnimation(i); Stream.Read(i, SizeOf(i)); IconPosLeft := i; Stream.Read(i, SizeOf(i)); IconPosTop := i; Stream.Read(i, SizeOf(i)); IconSpace := i; Stream.Read(i, SizeOf(i)); IconStep := i; Stream.Read(i, SizeOf(i)); tmpStream.CopyFrom(Stream, i); tmpStream.Position := 0; Icons.LoadFromStream(tmpStream); finally tmpStream.Free; end; end; procedure TAnimationSplashForm.LoadAnimationsData(Stream: TStream); var i, a: Integer; tmpStream: TMemoryStream; tmpAnim: TAnimationFrames; begin tmpStream := TMemoryStream.Create; try Stream.Read(a, SizeOf(a)); // размер всего блока анимаций Stream.Read(a, SizeOf(a)); for i := 0 to a - 1 do begin Stream.Read(a, SizeOf(a)); tmpStream.Clear; tmpStream.CopyFrom(Stream, a); tmpStream.Position := 0; tmpAnim := TAnimationFrames.CreateFrom(tmpStream); try AnimationsAdd(tmpAnim); finally tmpAnim.Free; end; end; finally tmpStream.Free; end; end; procedure TAnimationSplashForm.SaveToStream(Stream: TStream); var aSize: Int64; tmpStream: TMemoryStream; FencoderClsid: TGUID; begin EnterCriticalSection(FCritSec); try tmpStream := TMemoryStream.Create; try GetEncoderClsid('image/png', FencoderClsid); Stream.Write(AnsiString('ASFFullData'), 11); FBMPBackground.Save(TFixedStreamAdapter.Create(tmpStream), FencoderClsid); aSize := tmpStream.Size; Stream.Write(aSize, SizeOf(aSize)); tmpStream.Position := 0; Stream.CopyFrom(tmpStream, aSize); Stream.Write(FShowTaskbarButton, SizeOf(FShowTaskbarButton)); SaveStringData(Stream, FSplashFormCaption); Stream.Write(FSplashFormTopMost, SizeOf(FSplashFormTopMost)); Stream.Write(FFadeSpeed, SizeOf(FFadeSpeed)); Stream.Write(FTimerInterval, SizeOf(FTimerInterval)); Stream.Write(AnsiString('ClosingAllo'), 11); Stream.Write(FClosingAllow, SizeOf(FClosingAllow)); with ProgressBar^ do begin Stream.Write(BarVisible, SizeOf(BarVisible)); Stream.Write(BarBorderVisible, SizeOf(BarBorderVisible)); SaveRectData(Stream, BarBox); Stream.Write(BarColor, SizeOf(BarColor)); Stream.Write(BarBorderColor, SizeOf(BarBorderColor)); Stream.Write(BarDrawOnTime, SizeOf(BarDrawOnTime)); end; Stream.Write(FProgressBarSectionsCount, SizeOf(FProgressBarSectionsCount)); if TextData.Count <> 0 then begin SaveTextData(Stream); end; if Icons.Count <> 0 then begin SaveIconsData(Stream); end; if FAnimations.Count <> 0 then begin SaveAnimationsData(Stream); end; Stream.Write(AnsiString('ASF_EndData'), 11); finally tmpStream.Free; end; finally LeaveCriticalSection(FCritSec); end; end; procedure TAnimationSplashForm.SaveRectData(Stream: TStream; GPRect: TGPRect); var i: Integer; begin i := SizeOf(integer); Stream.Write(GPRect.X, i); Stream.Write(GPRect.Y, i); Stream.Write(GPRect.Width, i); Stream.Write(GPRect.Height, i); end; procedure TAnimationSplashForm.SaveStringData(Stream: TStream; Str: String); var i: Integer; begin i := Length(Str){ * 2}; Stream.Write(i, SizeOf(i)); Stream.Write(Str[1], i); end; procedure TAnimationSplashForm.SaveTextData(Stream: TStream); var I: Integer; begin Stream.Write(AnsiString('ASFTextData'), 11); i := TextData.Count; Stream.Write(i, SizeOf(i)); for I := 0 to TextData.Count - 1 do begin with TextData.Items[i] do begin Stream.Write(Visible, SizeOf(Visible)); Stream.Write(VisibleShadow, SizeOf(VisibleShadow)); SaveStringData(Stream, Text); SaveRectData(Stream, TextBox); Stream.Write(Color, SizeOf(Color)); Stream.Write(ShadowColor, SizeOf(ShadowColor)); SaveStringData(Stream, FontName); Stream.Write(FontSize, SizeOf(FontSize)); Stream.Write(FontStyle, SizeOf(FontStyle)); Stream.Write(PositionH, SizeOf(PositionH)); Stream.Write(PositionV, SizeOf(PositionV)); Stream.Write(RenderingHint, SizeOf(RenderingHint)); end; end; end; procedure TAnimationSplashForm.SaveIconsData(Stream: TStream); var i: Integer; tmpStream: TMemoryStream; begin tmpStream := TMemoryStream.Create; try Stream.Write(AnsiString('ASFIconData'), 11); Stream.Write(ProgressIconsVisible, SizeOf(ProgressIconsVisible)); Stream.Write(IconFullPaintPercent, SizeOf(IconFullPaintPercent)); Stream.Write(IconAnimation, SizeOf(IconAnimation)); Stream.Write(IconPosLeft, SizeOf(IconPosLeft)); Stream.Write(IconPosTop, SizeOf(IconPosTop)); Stream.Write(IconSpace, SizeOf(IconSpace)); Stream.Write(IconStep, SizeOf(IconStep)); Icons.SaveToStream(tmpStream); i := tmpStream.Size; Stream.Write(i, SizeOf(i)); tmpStream.Position := 0; Stream.CopyFrom(tmpStream, i); finally tmpStream.Free; end; end; procedure TAnimationSplashForm.SaveAnimationsData(Stream: TStream); var i, a: Integer; tmpStream, imgStream: TMemoryStream; begin tmpStream := TMemoryStream.Create; imgStream := TMemoryStream.Create; try Stream.Write(AnsiString('ASFAnimData'), 11); i := FAnimations.Count; tmpStream.Write(i, SizeOf(i)); for i := 0 to FAnimations.Count - 1 do begin imgStream.Clear; TAnimationFrames(FAnimations.Items[i]).SaveToStream(imgStream); a := imgStream.Size; tmpStream.Write(a, SizeOf(a)); imgStream.Position := 0; tmpStream.CopyFrom(imgStream, imgStream.Size); end; i := tmpStream.Size; Stream.Write(i, SizeOf(i)); tmpStream.Position := 0; Stream.CopyFrom(tmpStream, tmpStream.Size); finally imgStream.Free; tmpStream.Free; end; end; function TAnimationSplashForm.AnimationValidIndex(Index: integer): Boolean; begin Result := (Index >= 0) and (Index < AnimationsCount); end; procedure TAnimationSplashForm.TimerProc(); var TickCount: Integer; begin if FTickZero = 0 then FTickZero := GetTickCount(); TickCount := GetMyTickCount() - FTickCountOld; FTickCountOld := GetMyTickCount(); if FClose then begin if FTransparent >= 0 then begin if FWaitClose >= 0 then begin Dec(FWaitClose); end else begin FTransparent := FTransparent - FFadeSpeed; if FTransparent < 0 then begin FTransparent := 0; if FDestroy then begin { DestroyWindow(SplashHandle);} // при дестрое (DestroyWindow) происходит моргание во время // уничтожения сплэша и активации основной формы FSelfClose := True; PostMessage(Handle, WM_DESTROY, 0, 0); end; Exit; end; end; end; end else begin if FTransparent < 255 then begin if FTransparent < FTransparentOld then begin FTransparent := FTransparent + FFadeSpeed; if FTransparent > FTransparentOld then FTransparent := FTransparentOld; end else begin FTransparent := FTransparentOld; end; end else begin if (not FEndFadeHasOperated) and (Assigned(FOnEndFade)) then FOnEndFade(Self); FEndFadeHasOperated := True; end; end; DrawSplash(); if FrameNumber = 0 then ShowWindow(Handle, SW_SHOW); Inc(FrameNumber); FTickCountAll := FTickCountAll + TickCount; end; procedure TAnimationSplashForm.DrawSplash; var GPGraph: TGPGraphics; tmpImage: TGPBitmap; w, h: Integer; begin w := FBMPBackground.GetWidth; h := FBMPBackground.GetHeight; tmpImage := TGPBitmap.Create(w, h,PixelFormat32bppARGB); tmpImage.SetResolution(FBMPBackground.GetHorizontalResolution, FBMPBackground.GetVerticalResolution); GPGraph := TGPGraphics.Create(tmpImage); if Assigned(FOnBeforeDraw) then FOnBeforeDraw(Self, GPGraph); GPGraph.DrawImage(FBMPBackground, MakeRect(0, 0, w, h), 0, 0, w, h, UnitPixel); try if FAnimations.Count <> 0 then begin PaintAnimations(GPGraph); end; if ProgressIconsVisible then begin PaintIcons(GPGraph); end; if ProgressBar.BarVisible then begin PaintProgressBar(GPGraph); end; if TextData.Count <> 0 then begin PaintText(GPGraph); end; if Assigned(FOnAfterDraw) then FOnAfterDraw(Self, GPGraph); RenderForm(FTransparent, tmpImage); finally tmpImage.Free; GPGraph.Free; end; end; procedure TAnimationSplashForm.RenderForm(TransparentValue: byte; SourceImage: TGPBitmap); var zsize: TSize; zpoint: TPoint; zbf: TBlendFunction; TopLeft: TPoint; WR: TRect; GPGraph: TGPGraphics; m_hdcMemory: HDC; hdcScreen: HDC; hBMP: HBITMAP; begin hdcScreen := GetDC(0); m_hdcMemory := CreateCompatibleDC(hdcScreen); hBMP := CreateCompatibleBitmap(hdcScreen, SourceImage.GetWidth(), SourceImage.GetHeight()); SelectObject(m_hdcMemory, hBMP); GPGraph := TGPGraphics.Create(m_hdcMemory); try { GPGraph.SetInterpolationMode(InterpolationModeHighQualityBicubic);} GPGraph.DrawImage(SourceImage, 0, 0, SourceImage.GetWidth(), SourceImage.GetHeight()); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED); zsize.cx := SourceImage.GetWidth; zsize.cy := SourceImage.GetHeight; zpoint := Point(0, 0); with zbf do begin BlendOp := AC_SRC_OVER; BlendFlags := 0; AlphaFormat := AC_SRC_ALPHA; SourceConstantAlpha := TransparentValue; end; GetWindowRect(Handle, WR); TopLeft := Wr.TopLeft; if not FTestSpeed then begin UpdateLayeredWindow(Handle, FDC, @TopLeft, @zsize, GPGraph.GetHDC, @zpoint, 0, @zbf, ULW_ALPHA); end; finally GPGraph.ReleaseHDC(m_hdcMemory); ReleaseDC(0, hdcScreen); DeleteObject(hBMP); DeleteDC(m_hdcMemory); GPGraph.Free; end; end; procedure TAnimationSplashForm.PaintText(GPGraphics: TGPGraphics); var i: Integer; GPRect: TGPRectF; begin for I := 0 to TextData.Count - 1 do begin with TextData.Items[i] do begin if Visible then begin if VisibleShadow then begin GPRect := MakeRect(TextBox.X + 1, TextBox.Y + 1, TextBox.Width + 1, Int(TextBox.Height + 1)); TextOut(TextData.Items[i], TextData.Items[i].ShadowColor, GPGraphics, GPRect); end; GPRect := MakeRect(TextBox.X, TextBox.Y, TextBox.Width, Int(TextBox.Height)); TextOut(TextData.Items[i], TextData.Items[i].Color, GPGraphics, GPRect); end; end; end; end; procedure TAnimationSplashForm.TextOut(TextInfo: TTextItem; TextColor: Cardinal; GPGraphics: TGPGraphics; GPRect: TGPRectF); var GPStrForm: TGPStringFormat; GPBrush: TGPBrush; GPFont: TGPFont; begin with TextInfo do begin GPFont := TGPFont.Create(FontName, FontSize, FontStyle); GPBrush := TGPSolidBrush.Create(MakeColor(GetAlpha(TextColor), GetRValue(TextColor), GetGValue(TextColor), GetBValue(TextColor))); GPStrForm := TGPStringFormat.Create; try GPStrForm.SetAlignment(PositionH); GPStrForm.SetLineAlignment(PositionV); GPGraphics.SetTextRenderingHint(RenderingHint); GPGraphics.DrawString(Text, length(Text), GPFont, GPRect, GPStrForm, GPBrush); finally GPStrForm.Free; GPBrush.Free; GPFont.Free; end; end; end; procedure TAnimationSplashForm.PaintProgressBar(GPGraphics: TGPGraphics); var I: Integer; GPPen: TGPPen; W: Integer; a: integer; /////////////////// procedure DrawProgress(const GPRect: TGPRect; SectionNumber: Integer); var GPBrush: TGPBrush; begin if SectionNumber <= 0 then Exit; GPBrush := TGPSolidBrush.Create(FBarSectionsColor[SectionNumber - 1]); try with ProgressBar^ do begin if ProgressBar.BarBorderVisible then begin GPGraphics.DrawRectangle(GPPen, BarBox.X, BarBox.Y, BarBox.Width, BarBox.Height); GPGraphics.FillRectangle(GPBrush, GPRect.X + 2, GPRect.Y + 2, GPRect.Width, GPRect.Height - 3); end else begin GPGraphics.FillRectangle(GPBrush, GPRect.X, GPRect.Y, GPRect.Width, GPRect.Height); end; end; finally GPBrush.Free; end; end; //////////////////// begin GPPen := TGPPen.Create(ProgressBar.BarBorderColor); try if ProgressBar^.BarDrawOnTime then w := Round(FTickCountAll / (LoadingSectionTime / FOneSectionProgressSize)) + FStartCurrentSection else begin w := Round(FOneSectionProgressSize / 100 * ProgressBarPercentSection) + FStartCurrentSection; end; if w > FOneSectionProgressSize * ProgressBarCurrentSection then begin w := FOneSectionProgressSize * ProgressBarCurrentSection; end; if not FWaitMode then begin if ProgressBar^.BarDrawOnTime then begin FProgressBarPercentSection := (w - FStartCurrentSection) / (FOneSectionProgressSize / 100); end; FProgressBarPercentFull := w / (FOneSectionProgressSize * ProgressBarSectionsCount / 100); end; with ProgressBar^ do begin i := 0; while i <> FProgressBarCurrentSection do begin DrawProgress(MakeRect((I - 1) * FOneSectionProgressSize + BarBox.X, BarBox.Y, FOneSectionProgressSize, BarBox.Height), i); inc(i); end; if not FWaitMode then begin a := w - FStartCurrentSection; if ProgressBarCurrentSection = ProgressBarSectionsCount then a := w - FStartCurrentSection - 3; DrawProgress(MakeRect(FStartCurrentSection + BarBox.X, BarBox.Y, a, BarBox.Height), ProgressBarCurrentSection); end else begin FProgressBarPercentSection := 0; DrawWaitModeProgress(GPGraphics); end; end; finally GPPen.Free; end; end; procedure TAnimationSplashForm.DrawWaitModeProgress(GPGraphics: TGPGraphics); const LineSpace = 2.5; // Расстояние мешду линиями var I, BeginSectX: Integer; StartLineX: Single; GPRegion: TGPRegion; GPPen: TGPPen; DefDraw: Boolean; begin with ProgressBar^ do begin BeginSectX := FStartCurrentSection + BarBox.X; GPPen := TGPPen.Create(ProgressBar.BarColor, BarBox.Height div 3); if ProgressBar.BarBorderVisible then begin GPRegion := TGPRegion.Create(MakeRect(BeginSectX + 2, BarBox.Y + 2, FOneSectionProgressSize, BarBox.Height - 3)); end else begin GPRegion := TGPRegion.Create(MakeRect(BeginSectX, BarBox.Y, FOneSectionProgressSize, BarBox.Height)); end; try GPGraphics.SetClip(GPRegion); DefDraw := True; if Assigned(onWaitModeCustomDraw) then FonWaitModeCustomDraw(Self, GPGraphics, GPRegion, DefDraw); if DefDraw then begin inc(FSlowWaitModeCount); if (FSlowWaitMode = 0) or ((FSlowWaitModeCount mod FSlowWaitMode) = 0) then begin FSlowWaitModeCount := 0; inc(FWaitModeStepPR); if FWaitModeStepPR >= GPPen.GetWidth * LineSpace then FWaitModeStepPR := 0; end; for I := 0 to FOneSectionProgressSize div (BarBox.Height div 3) + 2 do begin StartLineX := BarBox.X + (GPPen.GetWidth * i * LineSpace) + FWaitModeStepPR; GPGraphics.DrawLine(GPPen, StartLineX + BarBox.Height, BarBox.Y - BarBox.Height, StartLineX - FOneSectionProgressSize - BarBox.Height, BarBox.Y + FOneSectionProgressSize + BarBox.Height) end; end; finally GPGraphics.ResetClip; GPPen.Free; GPRegion.Free; end; end; end; procedure TAnimationSplashForm.PaintIcons(GPGraphics: TGPGraphics); var I, it, w, h: Integer; GPImageAttributes: TGPImageAttributes; tmpImage: TGPBitmap; aRect: TGPRectF; GPGraph: TGPGraphics; begin if Assigned(Icons) then begin GPImageAttributes := TGPImageAttributes.Create; try for i := 0 to Length(FIconPosArray) - 1 do begin if FIconPosArray[i].IconIndex = -1 then begin it := i - 1; Break; end; it := i; end; if (it <> -1) and (Length(FIconPosArray) <> 0) then begin for I := 0 to it - 1 do begin if FIconPosArray[i].IconIndex <> -1 then GPGraphics.DrawImage(Icons.Items[FIconPosArray[i].IconIndex], FIconPosArray[i].IconPos, IconPosTop); end; aRect := GetAnimationRect(it, GPImageAttributes); w := Icons.Items[FIconPosArray[it].IconIndex].GetWidth; h := Icons.Items[FIconPosArray[it].IconIndex].GetHeight; tmpImage := TGPBitmap.Create(w, h, PixelFormat32bppARGB); // tmpImage.SetResolution(GPGraphics.GetDpiX, GPGraphics.GetDpiY); // Правилнее будет всё-таки ставить разрешение копируемой картинки. Мне так кажется tmpImage.SetResolution(Icons.Items[FIconPosArray[it].IconIndex].GetHorizontalResolution, Icons.Items[FIconPosArray[it].IconIndex].GetVerticalResolution); GPGraph := TGPGraphics.Create(tmpImage); GPGraph.DrawImage(Icons.Items[FIconPosArray[it].IconIndex], MakeRect(0, 0, w, h), 0, 0, w, h, UnitPixel); GPGraphics.DrawImage(tmpImage, aRect, 0, 0, aRect.Width, aRect.Height, UnitPixel, GPImageAttributes); tmpImage.Free; GPGraph.Free; end; finally GPImageAttributes.Free; end; end; end; function TAnimationSplashForm.GetAnimationRect(ItemIndex: Integer; GPImageAttributes: TGPImageAttributes): TGPRectF; const c299 = 1 - 0.299; c587 = 1 - 0.587; c114 = 1 - 0.114; var a, tc: Real; begin tc := FTickCountAll / (LoadingSectionTime * (IconFullPaintPercent / 100)); if FWaitMode then begin inc(FSlowWaitModeCount); if (FSlowWaitMode = 0) or ((FSlowWaitModeCount mod FSlowWaitMode) = 0) then begin FSlowWaitModeCount := 0; if FWaitModeICOinc then FWaitModeStepICO := FWaitModeStepICO + 0.1 else FWaitModeStepICO := FWaitModeStepICO - 0.1; if (FWaitModeStepICO >= 0.9) or (FWaitModeStepICO <= 0.1) then FWaitModeICOinc := not FWaitModeICOinc; end; tc := FWaitModeStepICO; end; case IconAnimation of iaNone: begin Result := MakeRect(CalcCurrentIconPos(ItemIndex), IconPosTop, Int(FIconPosArray[ItemIndex].IconWidth), Int(FIconPosArray[ItemIndex].IconHeight)); end; iaFade: begin a := tc; if a > 1 then a := 1; FadeColorMatrix[3, 3] := a; GPImageAttributes.SetColorMatrix(FadeColorMatrix); Result := MakeRect(CalcCurrentIconPos(ItemIndex), IconPosTop, Int(FIconPosArray[ItemIndex].IconWidth), Int(FIconPosArray[ItemIndex].IconHeight)); end; iaFadeColor: begin a := c299 + (c299 * tc); if a > 1 then a := 1; FadeColorColorMatrix[0, 0] := a; a := 0.299 - (0.299 * tc); if a < 0 then a := 0; FadeColorColorMatrix[0, 1] := a; FadeColorColorMatrix[0, 2] := a; a := c587 + (c587 * tc); if a > 1 then a := 1; FadeColorColorMatrix[1, 1] := a; a := 0.587 - (0.587 * tc); if a < 0 then a := 0; FadeColorColorMatrix[1, 0] := a; FadeColorColorMatrix[1, 2] := a; a := c114 + (c114 * tc); if a > 1 then a := 1; FadeColorColorMatrix[2, 2] := a; a := 0.114 - (0.114 * tc); if a < 0 then a := 0; FadeColorColorMatrix[2, 0] := a; FadeColorColorMatrix[2, 1] := a; GPImageAttributes.SetColorMatrix(FadeColorColorMatrix); Result := MakeRect(CalcCurrentIconPos(ItemIndex), IconPosTop, Int(FIconPosArray[ItemIndex].IconWidth), Int(FIconPosArray[ItemIndex].IconHeight)); end; iaSlideTop: begin Result := MakeRect(CalcCurrentIconPos(ItemIndex), IconPosTop, Int(FIconPosArray[ItemIndex].IconWidth), Round(FIconPosArray[ItemIndex].IconHeight * tc)); end; iaSlideLeft: begin Result := MakeRect(CalcCurrentIconPos(ItemIndex), IconPosTop, Round(FIconPosArray[ItemIndex].IconWidth * tc), Int(FIconPosArray[ItemIndex].IconHeight)); end; iaSlideCorner: begin Result := MakeRect(CalcCurrentIconPos(ItemIndex), IconPosTop, Int(FIconPosArray[ItemIndex].IconWidth * tc), Int(FIconPosArray[ItemIndex].IconHeight * tc)); end; end; end; procedure TAnimationSplashForm.PaintAnimations(GPGraphics: TGPGraphics); var i: Integer; begin for i := 0 to FAnimations.Count - 1 do begin with TAnimationFrames(FAnimations.Items[i]) do begin if (Count <> 0) and Visible then begin GPGraphics.DrawImage(Items[NumCurrentLoadingImage], PositionLeft, PositionTop); CalculateDelay; end; end; end; end; procedure TAnimationSplashForm.PressKey(var aMsg: TMsg; EventType: TKeyEventType); var a: Word; c: Char; begin case EventType of etKeyDown: begin if Assigned(FonKeyDown) then begin a := aMsg.wParam; FonKeyDown(Self, a, KeyDataToShiftState(aMsg.lParam)); aMsg.wParam := a; end; end; etKeyUp: begin if Assigned(FonKeyUp) then begin a := aMsg.wParam; FonKeyUp(Self, a, KeyDataToShiftState(aMsg.lParam)); aMsg.wParam := a; end; end; etKeyPress: begin if Assigned(FonKeyPress) then begin c := Char(aMsg.wParam); FonKeyPress(Self, c); aMsg.wParam := Ord(c); end; end; end; end; procedure TAnimationSplashForm.WMSetCursor; begin Windows.SetCursor(FCursor); end; procedure TAnimationSplashForm.WMMouseMove(Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseMove) then FOnMouseMove(Self, Shift, X, Y); end; procedure TAnimationSplashForm.DoDblClick; begin if Assigned(FOnDblClick) then FOnDblClick(Self); end; procedure TAnimationSplashForm.DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FonMouseDown) then FonMouseDown(Self, Button, Shift, X, Y); end; procedure TAnimationSplashForm.DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FonMouseUp) then FonMouseUp(Self, Button, Shift, X, Y); end; end.
unit MFichas.View.Configuracoes; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, System.Messaging, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.StdCtrls, FMX.ListView, FMX.Controls.Presentation, FMX.Objects, FMX.TabControl, FMX.Layouts, FMX.Platform, FMX.VirtualKeyboard, FMX.Gestures, FMX.Effects, FMX.ListBox, FMX.Edit, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.MediaLibrary, 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, MultiDetailAppearanceU, Data.DB, MFichas.Model.Conexao.Interfaces, MFichas.Model.Permissoes.Interfaces, MFichas.Model.Empresa.Interfaces, MFichas.Model.Configuracao.Interfaces, MFichas.View.Dialog.PedirSenha, MFichas.Model.Usuario.Interfaces; type TConfiguracoesView = class(TForm) LayoutPrincipal: TLayout; TabControlPrincipal: TTabControl; TabItemListarConfiguracoes: TTabItem; RectangleListar: TRectangle; ToolBarListar: TToolBar; LabelToolBarListar: TLabel; ButtonBackListar: TButton; ListBox1: TListBox; ListBoxGroupHeaderEmpresa: TListBoxGroupHeader; ListBoxGroupHeaderPermissoes: TListBoxGroupHeader; ListBoxGroupHeaderImpressora: TListBoxGroupHeader; ListBoxGroupHeaderTermino: TListBoxGroupHeader; ListBoxItemEmpresa: TListBoxItem; ListBoxItemPermissoes: TListBoxItem; ListBoxItemImpressora: TListBoxItem; ListBoxItemTermino: TListBoxItem; Layout1: TLayout; Layout2: TLayout; Label1: TLabel; Layout4: TLayout; Layout5: TLayout; Label2: TLabel; Layout6: TLayout; ImageEmpresa: TImage; EditNomeDaEmpresa: TEdit; CheckBoxAbrirCaixa: TCheckBox; CheckBoxExcluirProdutos: TCheckBox; CheckBoxAcessarConfiguracoes: TCheckBox; CheckBoxAcessarRelatorios: TCheckBox; CheckBoxCadastrarUsuarios: TCheckBox; CheckBoxCadastrarGrupos: TCheckBox; CheckBoxCadastrarProdutos: TCheckBox; CheckBoxSangriaCaixa: TCheckBox; CheckBoxSuprimentoCaixa: TCheckBox; CheckBoxFecharCaixa: TCheckBox; Label3: TLabel; RoundRectEncerrarSessao: TRoundRect; ComboBoxImpressora: TComboBox; LabelBotaoEncerrarSessao: TLabel; LayoutPagamentoBottom: TLayout; RoundRectSalvarAlteracoes: TRoundRect; LabelBotaoSalvarAlteracoes: TLabel; ActionList: TActionList; TakePhotoFromLibraryAction: TTakePhotoFromLibraryAction; Button1: TButton; FDMemTableEmpresa: TFDMemTable; FDMemTableConfiguracao: TFDMemTable; procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure ButtonBackListarClick(Sender: TObject); procedure TakePhotoFromLibraryActionDidFinishTaking(Image: TBitmap); procedure ComboBoxImpressoraClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure RoundRectSalvarAlteracoesClick(Sender: TObject); procedure EditNomeDaEmpresaChangeTracking(Sender: TObject); procedure RoundRectEncerrarSessaoClick(Sender: TObject); private { Private declarations } FPermissoes : iModelPermissoes; FEmpresa : iModelEmpresa; FConfiguracao : iModelConfiguracao; FUsuario : iModelUsuario; FConexao : iModelConexaoSQL; FConexaoBluetooth : iModelConexaoBluetooth; FListaDispositivos: TList<String>; FFrameSenha : TFrameViewPedirSenha; procedure VoltarAbas; procedure AtribuirPermissoesAosCheckBox; procedure FecharForm; procedure PreencherDadosDaEmpresa; procedure PreencherConfiguracoes; procedure AtualizarPermissoes; procedure AtualizarDadosEmpresa; procedure AtualizarConfiguracao; procedure CriarFramePedirSenha; procedure LimparBancoDeDados; procedure DoClickSenha(Sender: TObject); procedure DoClickSenhaCancel(Sender: TObject); procedure FecharFramePedirSenha; procedure LimparCampos; public { Public declarations } end; var ConfiguracoesView: TConfiguracoesView; implementation {$R *.fmx} uses MFichas.Model.Conexao.Factory, MFichas.Model.Permissoes, MFichas.Model.Empresa, MFichas.Model.Configuracao, MFichas.Model.Usuario, MaykoFichas.View.Principal; procedure TConfiguracoesView.AtribuirPermissoesAosCheckBox; begin CheckBoxAbrirCaixa.IsChecked := Boolean(FPermissoes.ListaDePermissoes.AbrirCaixa); CheckBoxFecharCaixa.IsChecked := Boolean(FPermissoes.ListaDePermissoes.FecharCaixa); CheckBoxSuprimentoCaixa.IsChecked := Boolean(FPermissoes.ListaDePermissoes.Suprimento); CheckBoxSangriaCaixa.IsChecked := Boolean(FPermissoes.ListaDePermissoes.Sangria); CheckBoxCadastrarProdutos.IsChecked := Boolean(FPermissoes.ListaDePermissoes.CadastrarProdutos); CheckBoxCadastrarGrupos.IsChecked := Boolean(FPermissoes.ListaDePermissoes.CadastrarGrupos); CheckBoxCadastrarUsuarios.IsChecked := Boolean(FPermissoes.ListaDePermissoes.CadastrarUsuarios); CheckBoxAcessarRelatorios.IsChecked := Boolean(FPermissoes.ListaDePermissoes.AcessarRelatorios); CheckBoxAcessarConfiguracoes.IsChecked := Boolean(FPermissoes.ListaDePermissoes.AcessarConfiguracoes); CheckBoxExcluirProdutos.IsChecked := Boolean(FPermissoes.ListaDePermissoes.ExcluirProdutosPosImpressao); end; procedure TConfiguracoesView.ButtonBackListarClick(Sender: TObject); begin VoltarAbas; end; procedure TConfiguracoesView.ComboBoxImpressoraClick(Sender: TObject); var LDeviceName: String; LSelected : String; LDropDown : Boolean; begin FConexaoBluetooth.ListarDispositivos(FListaDispositivos); if (ComboBoxImpressora.Items.Count > 0) and (ComboBoxImpressora.ItemIndex >= 0) then LSelected := ComboBoxImpressora.Items.Strings[ComboBoxImpressora.ItemIndex]; if ComboBoxImpressora.Items.Count = 0 then LDropDown := True; ComboBoxImpressora.Clear; ComboBoxImpressora.Items.BeginUpdate; for LDeviceName in FListaDispositivos do begin ComboBoxImpressora.Items.Add(LDeviceName); end; ComboBoxImpressora.Items.EndUpdate; if not LSelected.IsNullOrWhiteSpace(LSelected) then ComboBoxImpressora.ItemIndex := ComboBoxImpressora.Items.IndexOf(LSelected); if LDropDown then ComboBoxImpressora.DropDown; end; procedure TConfiguracoesView.CriarFramePedirSenha; begin FFrameSenha := TFrameViewPedirSenha.Create(nil); FFrameSenha.Parent := Self; FFrameSenha.ConfigurarTamanhoDoModal(Self); end; procedure TConfiguracoesView.DoClickSenha(Sender: TObject); begin if FFrameSenha.ComboBoxUsuario.ItemIndex < 0 then raise Exception.Create('Selecione um usuário.'); FUsuario .Funcoes .ValidarUsuarioESenha .NomeDoUsuario(FFrameSenha.ComboBoxUsuario.Items.Strings[FFrameSenha.ComboBoxUsuario.ItemIndex]) .Senha(FFrameSenha.EditSenha.Text) .&End .&End; LimparBancoDeDados; LimparCampos; FecharFramePedirSenha; FecharForm; end; procedure TConfiguracoesView.DoClickSenhaCancel(Sender: TObject); begin FecharFramePedirSenha; end; procedure TConfiguracoesView.EditNomeDaEmpresaChangeTracking(Sender: TObject); begin EditNomeDaEmpresa.Text := AnsiUpperCase(EditNomeDaEmpresa.Text); end; procedure TConfiguracoesView.FecharForm; begin ConfiguracoesView.Close; {$IFDEF ANDROID OR IOS} if Assigned(ConfiguracoesView) then begin ConfiguracoesView.DisposeOf; ConfiguracoesView.Free; end; {$ENDIF} end; procedure TConfiguracoesView.FecharFramePedirSenha; begin {$IFDEF MSWINDOWS} if Assigned(FFrameSenha) then begin FFrameSenha.Visible := False; FreeAndNil(FFrameSenha); end; {$ELSE} if Assigned(FFrameSenha) then begin FFrameSenha.Visible := False; FFrameSenha.Free; FFrameSenha.DisposeOf; end; {$ENDIF} end; procedure TConfiguracoesView.LimparCampos; begin EditNomeDaEmpresa.Text := ''; Form3.ComboBoxUsuario.Clear; ComboBoxImpressora.Clear; end; procedure TConfiguracoesView.FormCreate(Sender: TObject); begin TabControlPrincipal.TabPosition := TTabPosition.None; TabControlPrincipal.ActiveTab := TabItemListarConfiguracoes; FPermissoes := TModelPermissoes.New; FEmpresa := TModelEmpresa.New; FConfiguracao := TModelConfiguracao.New; FConexao := TModelConexaoFactory.New.ConexaoSQL; FUsuario := TModelUsuario.New; FConexaoBluetooth := TModelConexaoFactory.New.ConexaoBluetooth; FListaDispositivos := TList<String>.Create; AtribuirPermissoesAosCheckBox; PreencherDadosDaEmpresa; PreencherConfiguracoes; end; procedure TConfiguracoesView.FormDestroy(Sender: TObject); begin {$IFDEF MSWINDOWS} FreeAndNil(FListaDispositivos); {$ELSE} FListaDispositivos.Free; FListaDispositivos.DisposeOf; {$ENDIF} end; procedure TConfiguracoesView.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var LTeclado: IFMXVirtualKeyboardService; begin if (Key = vkHardwareBack) then begin TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(LTeclado)); if (LTeclado <> nil) and (TVirtualKeyboardState.Visible in LTeclado.VirtualKeyboardState) then begin end else begin Key := 0; VoltarAbas; end; end; end; procedure TConfiguracoesView.LimparBancoDeDados; begin FConexao.Query.SQL.Text := ''; FConexao.Query.SQL.Text := 'DELETE FROM CAIXA'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM CAIXAOPERACOES'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM CONFIGURACOES'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM EMPRESA'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM GRUPOPRODUTO'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM PRODUTO'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM USUARIO WHERE TIPO < 2'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM VENDA'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM VENDAITENS'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'DELETE FROM VENDAPAGAMENTOS'; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := '' + 'INSERT INTO EMPRESA ('+ ' DATAALTERACAO, '+ ' DATACADASTRO, '+ ' LOGOTIPO, '+ ' DESCRICAO, '+ ' GUUID '+ ') '+ 'VALUES ( '+ ' :DATAALTERACAO, '+ ' :DATACADASTRO, '+ ' :LOGOTIPO, '+ ' :DESCRICAO, '+ ' :GUUID '+ '); '; FConexao.Query.ParamByName('DATAALTERACAO').AsDateTime := Now; FConexao.Query.ParamByName('DATACADASTRO').AsDateTime := Now; FConexao.Query.ParamByName('LOGOTIPO').AsString := ''; FConexao.Query.ParamByName('DESCRICAO').AsString := ''; FConexao.Query.ParamByName('GUUID').AsString := TGUID.NewGuid.ToString; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := '' + 'INSERT INTO CONFIGURACOES ( '+ ' DATALIBERACAO, '+ ' DATAALTERACAO, '+ ' DATACADASTRO, '+ ' GUUIDDISPOSITIVO, '+ ' NOMEDISPOSITIVO, '+ ' IMPRESSORA, '+ ' GUUID '+ ') '+ 'VALUES ( '+ ' :DATALIBERACAO, '+ ' :DATAALTERACAO, '+ ' :DATACADASTRO, '+ ' :GUUIDDISPOSITIVO, '+ ' :NOMEDISPOSITIVO, '+ ' :IMPRESSORA, '+ ' :GUUID '+ '); '; FConexao.Query.ParamByName('DATALIBERACAO').AsDateTime := Now; FConexao.Query.ParamByName('DATAALTERACAO').AsDateTime := Now; FConexao.Query.ParamByName('DATACADASTRO').AsDateTime := Now; FConexao.Query.ParamByName('GUUIDDISPOSITIVO').AsString := ''; FConexao.Query.ParamByName('NOMEDISPOSITIVO').AsString := ''; FConexao.Query.ParamByName('IMPRESSORA').AsString := ''; FConexao.Query.ParamByName('GUUID').AsString := TGUID.NewGuid.ToString; FConexao.Query.ExecSQL; FConexao.Query.SQL.Text := 'UPDATE USUARIOPERMISSOES SET PERMISSAO = 0'; end; procedure TConfiguracoesView.PreencherConfiguracoes; var LDeviceName: String; LImpressora: String; begin FConfiguracao .Metodos .BuscarView .FDMemTable(FDMemTableConfiguracao) .BuscarConfiguracao .&End .&End; FDMemTableConfiguracao.First; LImpressora := FDMemTableConfiguracao.FieldByName('IMPRESSORA').AsString; if not LImpressora.IsNullOrWhiteSpace(LImpressora) then begin FConexaoBluetooth.ListarDispositivos(FListaDispositivos); ComboBoxImpressora.Clear; ComboBoxImpressora.Items.BeginUpdate; for LDeviceName in FListaDispositivos do begin ComboBoxImpressora.Items.Add(LDeviceName); end; ComboBoxImpressora.Items.EndUpdate; if not LImpressora.IsNullOrWhiteSpace(LImpressora) then ComboBoxImpressora.ItemIndex := ComboBoxImpressora.Items.IndexOf(LImpressora); end; end; procedure TConfiguracoesView.PreencherDadosDaEmpresa; var LNomeEmpresa: String; begin FEmpresa .Metodos .BuscarView .FDMemTable(FDMemTableEmpresa) .BuscarEmpresa .&End .&End; FDMemTableEmpresa.First; LNomeEmpresa := FDMemTableEmpresa.FieldByName('DESCRICAO').AsString; EditNomeDaEmpresa.Text := LNomeEmpresa; end; procedure TConfiguracoesView.AtualizarPermissoes; begin FPermissoes .EditarPermissoes .AbrirCaixa(Integer(CheckBoxAbrirCaixa.IsChecked)) .FecharCaixa(Integer(CheckBoxFecharCaixa.IsChecked)) .Suprimento(Integer(CheckBoxSuprimentoCaixa.IsChecked)) .Sangria(Integer(CheckBoxSangriaCaixa.IsChecked)) .CadastrarProdutos(Integer(CheckBoxCadastrarProdutos.IsChecked)) .CadastrarGrupos(Integer(CheckBoxCadastrarGrupos.IsChecked)) .CadastrarUsuarios(Integer(CheckBoxCadastrarUsuarios.IsChecked)) .AcessarRelatorios(Integer(CheckBoxAcessarRelatorios.IsChecked)) .AcessarConfiguracoes(Integer(CheckBoxAcessarConfiguracoes.IsChecked)) .ExcluirProdutosPosImpressao(Integer(CheckBoxExcluirProdutos.IsChecked)) .Executar .&End; end; procedure TConfiguracoesView.AtualizarDadosEmpresa; begin FEmpresa .Metodos .EditarView .Descricao(EditNomeDaEmpresa.Text) .&End .&End; end; procedure TConfiguracoesView.AtualizarConfiguracao; var LImpressoraAtual: String; LImpressoraNova: String; begin LImpressoraAtual := FDMemTableConfiguracao.FieldByName('IMPRESSORA').AsString; if (ComboBoxImpressora.ItemIndex >= 0) then LImpressoraNova := ComboBoxImpressora.Items.Strings[ComboBoxImpressora.ItemIndex]; if LImpressoraAtual <> LImpressoraNova then begin FConfiguracao .Metodos .EditarView .Impressora(ComboBoxImpressora.Items.Strings[ComboBoxImpressora.ItemIndex]) .&End .&End; end; end; procedure TConfiguracoesView.RoundRectEncerrarSessaoClick(Sender: TObject); begin if (Form3.TabControlPrincipal.ActiveTab <> Form3.TabItemLogin) then raise Exception.Create( 'Para encerrar esta sessão, você precisa estar na tela de LOGIN.' ); CriarFramePedirSenha; FFrameSenha.LabelTitulo.Text := 'Digite a senha de PROPRIETÁRIO'; FFrameSenha.LabelBotaoConfirmar.Text := 'Confirmar'; FFrameSenha.LabelBotaoCancelar.Text := 'Cancelar'; FFrameSenha.PreencherUsuariosGerentesNoComboBox; FFrameSenha.RoundRectBotaoConfirmar.OnClick := DoClickSenha; FFrameSenha.RoundRectBotaoCancelar.OnClick := DoClickSenhaCancel; end; procedure TConfiguracoesView.RoundRectSalvarAlteracoesClick(Sender: TObject); begin AtualizarPermissoes; AtualizarDadosEmpresa; AtualizarConfiguracao; FecharForm; end; procedure TConfiguracoesView.TakePhotoFromLibraryActionDidFinishTaking( Image: TBitmap); begin if (Image.Width > 50) or (Image.Height > 50) then raise Exception.Create( 'O tamanho desta imagem é maior do que o permitido.' + sLineBreak + 'Por favor selecione uma imagem com as dimensões de 50x50.' ); ImageEmpresa.Bitmap.Assign(Image); end; procedure TConfiguracoesView.VoltarAbas; begin FecharForm; end; end.
{!DOCTOPIC}{ Type » TExtArray } {!DOCREF} { @method: function TExtArray.Len(): Int32; @desc: Returns the length of the array. Same as 'Length(arr)' } function TExtArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TExtArray.IsEmpty(): Boolean; @desc: Returns True if the array is empty. Same as 'Length(arr) = 0' } function TExtArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure TExtArray.Append(const Value:Extended); @desc: Add another item to the array } procedure TExtArray.Append(const Value:Extended); var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := Value; end; {!DOCREF} { @method: procedure TExtArray.Insert(idx:Int32; Value:Extended); @desc: Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length, it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br] `Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`. } procedure TExtArray.Insert(idx:Int32; Value:Extended); var l:Int32; begin l := Length(Self); if (idx < 0) then idx := math.modulo(idx,l); if (l <= idx) then begin self.append(value); Exit(); end; SetLength(Self, l+1); MemMove(Self[idx], self[idx+1], (L-Idx)*SizeOf(Extended)); Self[idx] := value; end; {!DOCREF} { @method: procedure TExtArray.Del(idx:Int32); @desc: Removes the element at the given index c'idx' } procedure TExtArray.Del(idx:Int32); var i,l:Int32; begin l := Length(Self); if (l <= idx) or (idx < 0) then Exit(); if (L-1 <> idx) then MemMove(Self[idx+1], self[idx], (L-Idx)*SizeOf(Extended)); SetLength(Self, l-1); end; {!DOCREF} { @method: procedure TExtArray.Remove(Value:Extended); @desc: Removes the first element from left which is equal to c'Value' } procedure TExtArray.Remove(Value:Extended); begin Self.Del( Self.Find(Value) ); end; {!DOCREF} { @method: function TExtArray.Pop(): Extended; @desc: Removes and returns the last item in the array } function TExtArray.Pop(): Extended; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function TExtArray.PopLeft(): Extended; @desc: Removes and returns the first item in the array } function TExtArray.PopLeft(): Extended; begin Result := Self[0]; MemMove(Self[1], Self[0], SizeOf(Extended)*Length(Self)); SetLength(Self, High(self)); end; {!DOCREF} { @method: function TExtArray.Slice(Start,Stop: Int32; Step:Int32=1): TExtArray; @desc: Slicing similar to slice in Python, tho goes from 'start to and including stop' Can be used to eg reverse an array, and at the same time allows you to c'step' past items. You can give it negative start, and stop, then it will wrap around based on length(..) If c'Start >= Stop', and c'Step <= -1' it will result in reversed output. [note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note] } function TExtArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TExtArray; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 0; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 0; if Step = 0 then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result,0) end; end; {!DOCREF} { @method: procedure TExtArray.Extend(Arr:TExtArray); @desc: Extends the array with an array } procedure TExtArray.Extend(Arr:TExtArray); var L:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(Extended)); end; {!DOCREF} { @method: function TExtArray.Find(Value:Extended): Int32; @desc: Searces for the given value and returns the first position from the left. } function TExtArray.Find(Value:Extended): Int32; begin Result := exp_Find(Self,[Value]); end; {!DOCREF} { @method: function TExtArray.Find(Sequence:TExtArray): Int32; overload; @desc: Searces for the given sequence and returns the first position from the left. } function TExtArray.Find(Sequence:TExtArray): Int32; overload; begin Result := exp_Find(Self,Sequence); end; {!DOCREF} { @method: function TExtArray.FindAll(Value:Extended): TIntArray; @desc: Searces for the given value and returns all the position where it was found. } function TExtArray.FindAll(Value:Extended): TIntArray; begin Result := exp_FindAll(Self,[value]); end; {!DOCREF} { @method: function TExtArray.FindAll(Sequence:TExtArray): TIntArray; overload; @desc: Searces for the given sequence and returns all the position where it was found. } function TExtArray.FindAll(Sequence:TExtArray): TIntArray; overload; begin Result := exp_FindAll(Self,sequence); end; {!DOCREF} { @method: function TExtArray.Contains(val:Extended): Boolean; @desc: Checks if the arr contains the given value c'val' } function TExtArray.Contains(val:Extended): Boolean; begin Result := Self.Find(val) <> -1; end; {!DOCREF} { @method: function TExtArray.Count(val:Extended): Int32; @desc: Counts all the occurances of the given value c'val' } function TExtArray.Count(val:Extended): Int32; begin Result := Length(Self.FindAll(val)); end; {!DOCREF} { @method: procedure TExtArray.Sort(key:TSortKey=sort_Default); @desc: Sorts the array Supported keys: c'sort_Default' } procedure TExtArray.Sort(key:TSortKey=sort_Default); begin case key of sort_default: se.SortTEA(Self); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TExtArray.Sorted(key:TSortKey=sort_Default): TExtArray; @desc: Sorts and returns a copy of the array. Supported keys: c'sort_Default' } function TExtArray.Sorted(Key:TSortKey=sort_Default): TExtArray; begin Result := Copy(Self); case key of sort_default: se.SortTEA(Result); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TExtArray.Reversed(): TExtArray; @desc: Creates a reversed copy of the array } function TExtArray.Reversed(): TExtArray; begin Result := Self.Slice(-1,0,-1); end; {!DOCREF} { @method: procedure TExtArray.Reverse(); @desc: Reverses the array } procedure TExtArray.Reverse(); begin Self := Self.Slice(-1,0,-1); end; {=============================================================================} // The functions below this line is not in the standard array functionality // // By "standard array functionality" I mean, functions that all standard // array types should have. {=============================================================================} {!DOCREF} { @method: function TExtArray.Sum(): Extended; @desc: Adds up the TEA and returns the sum } function TExtArray.Sum(): Extended; begin Result := exp_SumFPtr(PChar(Self),SizeOf(Extended),Length(Self)); end; {!DOCREF} { @method: function TExtArray.Mean(): Extended; @desc:Returns the mean value of the array } function TExtArray.Mean(): Extended; begin Result := Self.Sum() / Length(Self); end; {!DOCREF} { @method: function TExtArray.Stdev(): Extended; @desc: Returns the standard deviation of the array } function TExtArray.Stdev(): Extended; var i:Int32; avg:Extended; square:TExtArray; begin avg := Self.Mean(); SetLength(square,Length(Self)); for i:=0 to High(self) do Square[i] := Sqr(Self[i] - avg); Result := sqrt(square.Mean()); end; {!DOCREF} { @method: function TExtArray.Variance(): Extended; @desc: Return the sample variance. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the array. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. } function TExtArray.Variance(): Extended; var avg:Extended; i:Int32; begin avg := Self.Mean(); for i:=0 to High(Self) do Result := Result + Sqr(Self[i] - avg); Result := Result / length(self); end; {!DOCREF} { @method: function TExtArray.Mode(Eps:Extended=0.000001): Extended; @desc: Returns the sample mode of the array, which is the [u]most frequently occurring value[/u] in the array. When there are multiple values occurring equally frequently, mode returns the smallest of those values. Takes an extra parameter c'Eps', can be used to allow some tolerance in the floating point comparison. } function TExtArray.Mode(Eps:Extended=0.0000001): Extended; var arr:TExtArray; i,hits,best: Int32; cur:Extended; begin arr := self.sorted(); cur := arr[0]; hits := 1; best := 0; for i:=1 to High(Arr) do begin if (arr[i]-cur > eps) then //arr[i] <> cur begin if (hits > best) then begin best := hits; Result := (Cur+Arr[i-1]) / 2; //Eps fix end; hits := 0; cur := Arr[I]; end; Inc(hits); end; if (hits > best) then Result := cur; end; {!DOCREF} { @method: function TExtArray.VarMin(): Extended; @desc: Returns the minimum value in the array } function TExtArray.VarMin(): Extended; var _:Extended; begin se.MinMaxTEA(Self,Result,_); end; {!DOCREF} { @method: function TExtArray.VarMax(): Extended; @desc: Returns the maximum value in the array } function TExtArray.VarMax(): Extended; var _:Extended; begin se.MinMaxTEA(Self,_,Result); end; {!DOCREF} { @method: function TExtArray.ArgMin(): Int32; @desc: Returns the index containing the smallest element in the array. } function TExtArray.ArgMin(): Int32; var mat:T2DExtArray; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMin(mat).x; end; {!DOCREF} { @method: function TExtArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the smallest element in the array. } function TExtArray.ArgMin(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TExtMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMin(n), Result, _); end; {!DOCREF} { @method: function TExtArray.ArgMin(Lo,Hi:int32): Int32; overload; @desc: Returns the index containing the smallest element in the array within the lower and upper bounds c'lo, hi'. } function TExtArray.ArgMin(lo,hi:Int32): Int32; overload; var B: TBox; mat:T2DExtArray; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMin(mat,B).x; end; {!DOCREF} { @method: function TExtArray.ArgMax(): Int32; @desc: Returns the index containing the largest element in the array. } function TExtArray.ArgMax(): Int32; var mat:T2DExtArray; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMax(mat).x; end; {!DOCREF} { @method: function TExtArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the largest element in the array. } function TExtArray.ArgMax(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TExtMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMax(n), Result, _); end; {!DOCREF} { @method: function TExtArray.ArgMax(Lo,Hi:int32): Int32; overload; @desc: Returns the index containing the largest element in the array within the lower and upper bounds c'lo, hi'. } function TExtArray.ArgMax(lo,hi:Int32): Int32; overload; var B: TBox; mat:T2DExtArray; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMax(mat,B).x; end;
unit dmDataAccess; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, IPPeerClient, Datasnap.DSClientRest, ClientclassesUnit1, Data.FireDACJSONReflect; type TDataModule1 = class(TDataModule) FDMemTableCustomer: TFDMemTable; FDStanStorageBinLink1: TFDStanStorageBinLink; DSRestConnection1: TDSRestConnection; private FClient: TServermethods1Client; function GetServerMethods: TServerMethods1Client; { Private declarations } public { Public declarations } procedure GetCustomers; procedure ApplyCustomers; property ServerMethods: TServerMethods1Client read GetServerMethods; end; var DataModule1: TDataModule1; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} { TDataModule1 } procedure TDataModule1.ApplyCustomers; var DeltaList: TFDJSONDeltas; begin DeltaList := TFDJSONDeltas.Create; if FDMemTableCustomer.State in dsEditModes then FDMemTableCustomer.Post; TFDJSONDeltasWriter.ListAdd(DeltaList, 'CUSTOMER', FDMemTableCustomer); ServerMethods.UpdateCustomers(DeltaList); end; procedure TDataModule1.GetCustomers; var DataSetLists: TFDJSONDataSets; begin DataSetLists := ServerMethods.GetCustomers; FDMemTableCustomer.Active := False; FDMemTableCustomer.AppendData( TFDJSONDataSetsReader.GetListValue(DataSetLists, 0)); end; function TDataModule1.GetServerMethods: TServerMethods1Client; begin if FClient = nil then FClient := TServerMethods1Client.Create(DSRestConnection1); Result := FClient; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clCryptMac; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clCryptAPI, clUtils, clWUtils, clConfig; type TclMac = class(TclConfigObject) public procedure Init(const AKey: TclByteArray; AStart, ALen: Integer); overload; virtual; abstract; procedure Init(const AKey: TclByteArray); overload; virtual; abstract; function GetBlockSize: Integer; virtual; abstract; procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); overload; virtual; abstract; procedure Update(const AValue: Integer); overload; virtual; abstract; function Digest: TclByteArray; virtual; abstract; end; TclCryptApiHmac = class(TclMac) private FContext: HCRYPTPROV; FHash: HCRYPTHASH; FCSPPtr: PclChar; FIPad: TclByteArray; FOPad: TclByteArray; procedure CreateHash; procedure DestroyHash; function GetHashValue: TclByteArray; procedure Clear; function GetCSPPtr: PclChar; protected function GetHashAlgorithm: ALG_ID; virtual; abstract; function GetCSP: string; virtual; abstract; function GetProviderType: Integer; virtual; abstract; public constructor Create; override; destructor Destroy; override; procedure Init(const AKey: TclByteArray; AStart, ALen: Integer); overload; override; procedure Init(const AKey: TclByteArray); overload; override; procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); overload; override; procedure Update(const AValue: Integer); overload; override; function Digest: TclByteArray; override; end; TclHmacMd5 = class(TclCryptApiHmac) protected function GetHashAlgorithm: ALG_ID; override; function GetCSP: string; override; function GetProviderType: Integer; override; public function GetBlockSize: Integer; override; end; TclHmacSha1 = class(TclCryptApiHmac) protected function GetHashAlgorithm: ALG_ID; override; function GetCSP: string; override; function GetProviderType: Integer; override; public function GetBlockSize: Integer; override; end; TclHmacSha256 = class(TclCryptApiHmac) protected function GetHashAlgorithm: ALG_ID; override; function GetCSP: string; override; function GetProviderType: Integer; override; public function GetBlockSize: Integer; override; end; function HMAC_MD5(const Text, Key: string): string; implementation uses clCryptUtils, clTranslator; function HMAC_MD5(const Text, Key: string): string; var mac: TclMac; k, b: TclByteArray; begin {$IFNDEF DELPHI2005}k := nil; b := nil;{$ENDIF} if (Text = '') or (Key = '') then begin Result := ''; Exit; end; mac := TclHmacMd5.Create(); try k := TclTranslator.GetBytes(Key); b := TclTranslator.GetBytes(Text); mac.Init(k); mac.Update(b, 0, Length(b)); Result := LowerCase(BytesToHex(mac.Digest())); finally mac.Free(); end; end; { TclCryptApiHmac } procedure TclCryptApiHmac.Clear; begin DestroyHash(); if (FContext <> nil) then begin CryptReleaseContext(FContext, 0); FContext := nil; end; FreeMem(FCSPPtr); FCSPPtr := nil; FIPad := nil; FOPad := nil; end; constructor TclCryptApiHmac.Create; begin inherited Create(); FContext := nil; FHash := nil; FIPad := nil; FOPad := nil; end; procedure TclCryptApiHmac.CreateHash; begin Assert(FHash = nil); if not CryptCreateHash(FContext, GetHashAlgorithm(), nil, 0, @FHash) then begin RaiseCryptError('CryptCreateHash'); end; end; destructor TclCryptApiHmac.Destroy; begin Clear(); inherited Destroy(); end; procedure TclCryptApiHmac.DestroyHash; begin if (FHash <> nil) then begin CryptDestroyHash(FHash); FHash := nil; end; end; function TclCryptApiHmac.Digest: TclByteArray; begin Result := GetHashValue(); DestroyHash(); CreateHash(); Update(FOPad, 0, Length(FOPad)); Update(Result, 0, Length(Result)); Result := GetHashValue(); DestroyHash(); end; function TclCryptApiHmac.GetCSPPtr: PclChar; var s: TclString; len: Integer; begin Result := FCSPPtr; if (Result <> nil) then Exit; if (Trim(GetCSP()) <> '') then begin s := GetTclString(GetCSP()); len := Length(s); GetMem(FCSPPtr, len + SizeOf(TclChar)); system.Move(PclChar(s)^, FCSPPtr^, len); FCSPPtr[len] := #0; end; Result := FCSPPtr; end; function TclCryptApiHmac.GetHashValue: TclByteArray; var dig: TclCryptData; hashSize: DWORD; begin Assert(FHash <> nil); dig := TclCryptData.Create(GetBlockSize()); try hashSize := GetBlockSize(); if not CryptGetHashParam(FHash, HP_HASHVAL, dig.Data, @hashSize, 0) then begin RaiseCryptError('CryptGetHashParam'); end; dig.Reduce(hashSize); SetLength(Result, dig.DataSize); System.Move(dig.Data^, Result[0], dig.DataSize); finally dig.Free(); end; end; procedure TclCryptApiHmac.Init(const AKey: TclByteArray); begin Init(AKey, 0, Length(AKey)); end; procedure TclCryptApiHmac.Init(const AKey: TclByteArray; AStart, ALen: Integer); var encodedKey, buf: TclByteArray; i: Integer; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} Clear(); if not CryptAcquireContext(@FContext, nil, GetCSPPtr(), GetProviderType(), CRYPT_VERIFYCONTEXT) then begin RaiseCryptError('CryptAcquireContext'); end; SetLength(encodedKey, 64); for i := 0 to Length(encodedKey) - 1 do begin encodedKey[i] := 0; end; if (ALen > Length(AKey) - AStart) then begin ALen := Length(AKey) - AStart; end; if (ALen > 64) then begin CreateHash(); Update(AKey, AStart, ALen); buf := GetHashValue(); System.Move(buf[0], encodedKey[0], Length(buf)); DestroyHash(); end else begin System.Move(AKey[AStart], encodedKey[0], ALen); end; SetLength(FIPad, 64); for i := 0 to Length(FIPad) - 1 do begin FIPad[i] := encodedKey[i] xor $36; end; SetLength(FOPad, 64); for i := 0 to Length(FOPad) - 1 do begin FOPad[i] := encodedKey[i] xor $5c; end; end; procedure TclCryptApiHmac.Update(const AValue: Integer); var buf: TclByteArray; ind: Integer; begin SetLength(buf, 4); ind := 0; ByteArrayWriteDWord(AValue, buf, ind); Update(buf, 0, 4); end; procedure TclCryptApiHmac.Update(const ABuffer: TclByteArray; AStart, ALen: Integer); begin if (FHash = nil) then begin CreateHash(); Update(FIPad, 0, Length(FIPad)); end; if not CryptHashData(FHash, Pointer(TclIntPtr(ABuffer) + AStart), ALen, 0) then begin RaiseCryptError('CryptHashData'); end; end; { TclHmacMd5 } function TclHmacMd5.GetBlockSize: Integer; begin Result := 16; end; function TclHmacMd5.GetCSP: string; begin Result := MS_DEF_PROV; end; function TclHmacMd5.GetHashAlgorithm: ALG_ID; begin Result := CALG_MD5; end; function TclHmacMd5.GetProviderType: Integer; begin Result := PROV_RSA_FULL; end; { TclHmacSha1 } function TclHmacSha1.GetBlockSize: Integer; begin Result := 20; end; function TclHmacSha1.GetCSP: string; begin Result := MS_DEF_PROV; end; function TclHmacSha1.GetHashAlgorithm: ALG_ID; begin Result := CALG_SHA1; end; function TclHmacSha1.GetProviderType: Integer; begin Result := PROV_RSA_FULL; end; { TclHmacSha256 } function TclHmacSha256.GetBlockSize: Integer; begin Result := 32; end; function TclHmacSha256.GetCSP: string; begin Result := MS_ENH_RSA_AES_PROV; end; function TclHmacSha256.GetHashAlgorithm: ALG_ID; begin Result := CALG_SHA_256; end; function TclHmacSha256.GetProviderType: Integer; begin Result := PROV_RSA_AES; end; end.
{ Subroutine SST_ROUTINES_MATCH (PROC1, PROC2, STAT) * * Check whether two routine definitions are compatible. PROC1 must be the * descriptor for a routine template. If PROC2 also describes a routine, then * both must match exactly (argument names, data types, and any flags). * * If PROC2 describes a call to a procedure, then it must conform to the * template PROC1. * * STAT is returned with no error if the routines matched. } module sst_ROUTINES_MATCH; define sst_routines_match; %include 'sst2.ins.pas'; procedure sst_routines_match ( {check that two routine descriptions match} in proc1: sst_proc_t; {descriptor for first routine} in proc2: sst_proc_t; {descriptor for second routine} out stat: sys_err_t); {no error if routines match} var arg1_p: sst_proc_arg_p_t; {points to argument of routine 1} arg2_p: sst_proc_arg_p_t; {points to argument of routine 2} argn: sys_int_machine_t; {current argument number} dt1_p, dt2_p: sst_dtype_p_t; {resolved data type descriptors} label arg_dtype_ok, arg_err; begin if proc2.sym_p <> nil then begin {routine 2 also a template ?} if (sst_symflag_global_k in proc2.sym_p^.flags) <> (sst_symflag_global_k in proc1.sym_p^.flags) then begin sys_stat_set (sst_subsys_k, sst_stat_rout_glbl_nmatch_k, stat); return; end; if (sst_symflag_extern_k in proc2.sym_p^.flags) <> (sst_symflag_extern_k in proc1.sym_p^.flags) then begin sys_stat_set (sst_subsys_k, sst_stat_rout_ext_nmatch_k, stat); return; end; if (sst_procflag_noreturn_k in proc2.flags) <> (sst_procflag_noreturn_k in proc1.flags) then begin sys_stat_set (sst_subsys_k, sst_stat_rout_nret_nmatch_k, stat); return; end; end; {done with routine 2 is also a template} if (proc2.dtype_func_p = nil) or (proc1.dtype_func_p = nil) then begin {at least one is a non-function routine} if proc2.dtype_func_p <> proc1.dtype_func_p then begin {one is a function ?} sys_stat_set (sst_subsys_k, sst_stat_rout_dtypef_nmatch_k, stat); return; end; end else begin {both routines are functions} dt1_p := proc1.dtype_func_p; {resolve base data type for routine 1} while dt1_p^.dtype = sst_dtype_copy_k do begin dt1_p := dt1_p^.copy_dtype_p; end; dt2_p := proc2.dtype_func_p; {resolve base data type for routine 2} while dt2_p^.dtype = sst_dtype_copy_k do begin dt2_p := dt2_p^.copy_dtype_p; end; if dt1_p <> dt2_p then begin {function data types mismatched ?} sys_stat_set (sst_subsys_k, sst_stat_rout_dtypef_nmatch_k, stat); return; end; end ; if proc2.n_args <> proc1.n_args then begin sys_stat_set (sst_subsys_k, sst_stat_rout_nargs_nmatch_k, stat); return; end; arg1_p := proc1.first_arg_p; {init curr arg to first in list} arg2_p := proc2.first_arg_p; argn := 1; while arg1_p <> nil do begin {loop thru each call argument template} dt1_p := arg1_p^.dtype_p; {resolve base data type for arg template} while dt1_p^.dtype = sst_dtype_copy_k do dt1_p := dt1_p^.copy_dtype_p; dt2_p := arg2_p^.dtype_p; {resolve base data type for arg} while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p; if arg2_p^.name_p = nil then begin {routine 2 descriptor is for actual call} if arg1_p^.univ {any argument allowed to match template ?} then goto arg_dtype_ok; if sst_rwflag_write_k in arg1_p^.rwflag_ext then begin {value is being passed back to argument} if dt1_p = dt2_p then goto arg_dtype_ok; if {both data types are pointers ?} (dt1_p^.dtype = sst_dtype_pnt_k) and {template dtype is a pointer ?} (dt2_p^.dtype = sst_dtype_pnt_k) {argument dtype is any pointer ?} then begin if {either one is a UNIV pointer ?} (dt1_p^.pnt_dtype_p = nil) or (dt2_p^.pnt_dtype_p = nil) then goto arg_dtype_ok; end; {done with both dtypes were pointers} end else begin {argument is only passed in to routine} if sst_dtype_convertable(dt2_p^, dt1_p^) then goto arg_dtype_ok; end ; sys_stat_set (sst_subsys_k, sst_stat_rout_dtypea_nmatch_k, stat); goto arg_err; arg_dtype_ok: {argument data type has been typed checked} if (not (arg1_p^.rwflag_ext <= arg2_p^.rwflag_ext)) then begin sys_stat_set (sst_subsys_k, sst_stat_rout_dir_nmatch_k, stat); goto arg_err; end; end else begin {routine 2 descriptor is a routine template} if dt1_p <> dt2_p then begin sys_stat_set (sst_subsys_k, sst_stat_rout_dtypea_nmatch_k, stat); goto arg_err; end; if arg2_p^.rwflag_ext <> arg1_p^.rwflag_ext then begin sys_stat_set (sst_subsys_k, sst_stat_rout_dir_nmatch_k, stat); goto arg_err; end; end ; if arg2_p^.pass <> arg1_p^.pass then begin sys_stat_set (sst_subsys_k, sst_stat_rout_pass_nmatch_k, stat); goto arg_err; end; arg1_p := arg1_p^.next_p; {advance to next call argument descriptors} arg2_p := arg2_p^.next_p; argn := argn + 1; end; {back and check next call argument} sys_error_none (stat); {indicate no mismatches} return; {return and indicate routines matched} arg_err: {jump here if mismatch error on an argument} sys_stat_parm_int (argn, stat); {indicate argument number that had error} end;
unit kwEmitString; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwEmitString.pas" // Начат: 22.04.2011 19:32 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwEmitString // // Позволяет ввести строку. // Пример: // {code} // : "Ввести строку" STRING IN aString // aString emitstring // ; // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} TkwEmitString = class(_tfwAutoregisteringWord_) {* Позволяет ввести строку. Пример: [code] : "Ввести строку" STRING IN aString aString emitstring ; [code] } protected // realized methods procedure DoDoIt(const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwEmitString {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses l3String, Windows, Messages, l3Chars, l3Interfaces, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwEmitString; {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} // start class TkwEmitString procedure TkwEmitString.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4DB19F7802E3_var* var l_Index : Integer; (* l_Scan : Integer;*) l_C : Integer; l_H : THandle; l_S : Il3CString; //#UC END# *4DAEEDE10285_4DB19F7802E3_var* begin //#UC START# *4DAEEDE10285_4DB19F7802E3_impl* l_S := aCtx.rEngine.PopString; try with l3PCharLen(l_S) do begin if not l3IsANSI(SCodePage) then RunnerAssert(false, 'Странная кодировка строки', aCtx); l_H := GetFocus; for l_Index := 0 to Pred(SLen) do begin l_C := ORD(S[l_Index]); if (GetFocus <> l_H) then SetFocus(l_H); SendMessage(l_H, WM_CHAR, l_C, 0); (* l_Scan := MapVirtualKey(l_C, 0); keybd_event(l_C, l_Scan, 0, 0); { Key down } keybd_event(l_C, l_Scan, KEYEVENTF_KEYUP, 0);*) end;//for l_Index end;//with l3PCharLen(aCtx.rEngine.PopString) finally l_S := nil; end;//try..finally //#UC END# *4DAEEDE10285_4DB19F7802E3_impl* end;//TkwEmitString.DoDoIt class function TkwEmitString.GetWordNameForRegister: AnsiString; //#UC START# *4DB0614603C8_4DB19F7802E3_var* //#UC END# *4DB0614603C8_4DB19F7802E3_var* begin //#UC START# *4DB0614603C8_4DB19F7802E3_impl* Result := 'emitstring'; //#UC END# *4DB0614603C8_4DB19F7802E3_impl* end;//TkwEmitString.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} {$IfEnd} //not NoScripts end.
unit FindUnit.OTAUtils; interface uses ToolsAPI, FindUnit.Header, Classes; function GetVolumeLabel(const DriveChar: string): string; function BrowseURL(const URL: string): boolean; function GetEditView(var ASourceEditor: IOTASourceEditor; var AEditView: IOTAEditView): boolean; function EditorAsString(SourceEditor: IOTASourceEditor): string; function ActiveSourceEditor: IOTASourceEditor; function SourceEditor(Module: IOTAMOdule): IOTASourceEditor; // GeExperts function GxOtaGetCurrentModule: IOTAMOdule; function GxOtaGetFileEditorForModule(Module: IOTAMOdule; Index: Integer): IOTAEditor; function GxOtaGetSourceEditorFromModule(Module: IOTAMOdule; const FileName: string = ''): IOTASourceEditor; function GetCurrentProject: IOTAProject; function OtaGetCurrentSourceEditor: IOTASourceEditor; function GetSelectedTextFromContext(Context: IOTAKeyContext): TStringPosition; function GetErrorListFromActiveModule: TOTAErrors; function GetAllFilesFromProjectGroup: TStringList; function GetWordAtCursor: TStringPosition; var PathUserDir: string; implementation uses Windows, ShellAPI, ShlObj, ActiveX, SysUtils; function SourceEditor(Module: IOTAMOdule): IOTASourceEditor; var iFileCount: Integer; i: Integer; begin Result := nil; if Module = nil then Exit; with Module do begin iFileCount := GetModuleFileCount; for i := 0 To iFileCount - 1 do if GetModuleFileEditor(i).QueryInterface(IOTASourceEditor, Result) = S_OK then Break; end; end; function ActiveSourceEditor: IOTASourceEditor; var CM: IOTAMOdule; begin Result := Nil; if BorlandIDEServices = nil then Exit; CM := (BorlandIDEServices as IOTAModuleServices).CurrentModule; Result := SourceEditor(CM); end; function GetErrorListFromActiveModule: TOTAErrors; var ModuleErrors: IOTAModuleErrors; begin ModuleErrors := GxOtaGetCurrentModule as IOTAModuleErrors; Result := ModuleErrors.GetErrors(ActiveSourceEditor.FileName); end; function GetAllFilesFromProjectGroup: TStringList; var ModServices: IOTAModuleServices; Module: IOTAMOdule; ProjectGroup: IOTAProjectGroup; iMod: Integer; FileDesc: string; iProj: Integer; CurProject: IOTAProject; iFile: Integer; begin Result := TStringList.Create; Result.Sorted := True; Result.Duplicates := dupIgnore; ModServices := BorlandIDEServices as IOTAModuleServices; for iMod := 0 to ModServices.ModuleCount - 1 do begin Module := ModServices.Modules[iMod]; if Supports(Module, IOTAProjectGroup, ProjectGroup) then begin for iProj := 0 to ProjectGroup.ProjectCount -1 do begin CurProject := ProjectGroup.Projects[iProj]; for iFile := 0 to CurProject.GetModuleCount -1 do begin FileDesc := CurProject.GetModule(iFile).FileName; if FileDesc = '' then Continue; Result.Add(FileDesc); end; end; end; end; end; function GetWordAtCursor: TStringPosition; const strIdentChars = ['a' .. 'z', 'A' .. 'Z', '_', '0' .. '9']; var SourceEditor: IOTASourceEditor; EditPos: TOTAEditPos; iPosition: Integer; Content: TStringList; ContentTxt: string; begin ContentTxt := ''; SourceEditor := ActiveSourceEditor; EditPos := SourceEditor.EditViews[0].CursorPos; Content := TStringList.Create; try Content.Text := EditorAsString(SourceEditor); ContentTxt := Content[Pred(EditPos.Line)]; iPosition := EditPos.Col; if (iPosition > 0) And (Length(ContentTxt) >= iPosition) and CharInSet(ContentTxt[iPosition], strIdentChars) then begin while (iPosition > 1) And (CharInSet(ContentTxt[Pred(iPosition)], strIdentChars)) do Dec(iPosition); Delete(ContentTxt, 1, Pred(iPosition)); iPosition := 1; while CharInSet(ContentTxt[iPosition], strIdentChars) do Inc(iPosition); Delete(ContentTxt, iPosition, Length(ContentTxt) - iPosition + 1); if CharInSet(ContentTxt[1], ['0' .. '9']) then ContentTxt := ''; end else ContentTxt := ''; Result.Value := ContentTxt; Result.Line := EditPos.Line; finally Content.Free; end; End; function GetSelectedTextFromContext(Context: IOTAKeyContext): TStringPosition; var Editor: IOTAEditBuffer; EdtPosition: IOTAEditPosition; EditPos: TOTAEditPos; CurSourceEditor: IOTASourceEditor; begin CurSourceEditor := ActiveSourceEditor; Result.Line := CurSourceEditor.EditViews[0].CursorPos.Line; Result.Value := ''; if Context = nil then Exit; Editor := Context.EditBuffer; if Editor = nil then Exit; Result.Value := Trim(Editor.EditBlock.Text); end; function GetCurrentProject: IOTAProject; var ModServices: IOTAModuleServices; Module: IOTAMOdule; Project: IOTAProject; ProjectGroup: IOTAProjectGroup; i: Integer; begin Result := nil; ModServices := BorlandIDEServices as IOTAModuleServices; for i := 0 to ModServices.ModuleCount - 1 do begin Module := ModServices.Modules[i]; if Supports(Module, IOTAProjectGroup, ProjectGroup) then begin Result := ProjectGroup.ActiveProject; Exit; end else if Supports(Module, IOTAProject, Project) then begin // In the case of unbound packages, return the 1st if Result = nil then Result := Project; end; end; end; // Credits to GXExperts function GxOtaGetCurrentModule: IOTAMOdule; var ModuleServices: IOTAModuleServices; begin ModuleServices := BorlandIDEServices as IOTAModuleServices; Assert(Assigned(ModuleServices)); Result := ModuleServices.CurrentModule; end; // Credits to GXExperts function GxOtaGetFileEditorForModule(Module: IOTAMOdule; Index: Integer): IOTAEditor; begin Assert(Assigned(Module)); Result := Module.GetModuleFileEditor(Index); end; // Credits to GXExperts function GxOtaGetSourceEditorFromModule(Module: IOTAMOdule; const FileName: string = ''): IOTASourceEditor; var i: Integer; IEditor: IOTAEditor; ISourceEditor: IOTASourceEditor; begin Result := nil; if not Assigned(Module) then Exit; for i := 0 to Module.GetModuleFileCount - 1 do begin IEditor := GxOtaGetFileEditorForModule(Module, i); if Supports(IEditor, IOTASourceEditor, ISourceEditor) then begin if Assigned(ISourceEditor) then begin if (FileName = '') or SameFileName(ISourceEditor.FileName, FileName) then begin Result := ISourceEditor; Break; end; end; end; end; end; function OtaGetCurrentSourceEditor: IOTASourceEditor; var LEditorServices: IOTAEditorServices; LFileName: string; LEditBuffer: IOTAEditBuffer; begin Result := nil; LEditorServices := (BorlandIDEServices as IOTAEditorServices); LEditBuffer := LEditorServices.TopBuffer; if Assigned(LEditBuffer) and (LEditBuffer.FileName <> '') then Result := GxOtaGetSourceEditorFromModule(GxOtaGetCurrentModule, LEditBuffer.FileName); if Result = nil then Result := GxOtaGetSourceEditorFromModule(GxOtaGetCurrentModule); end; function GetEditView(var ASourceEditor: IOTASourceEditor; var AEditView: IOTAEditView): boolean; begin Result := False; ASourceEditor := OtaGetCurrentSourceEditor; if not Assigned(ASourceEditor) then Exit; AEditView := ASourceEditor.GetEditView(0); Result := Assigned(AEditView); end; type TBrowserInformation = record Name: String; Path: String; Version: String; end; function GetDefaultBrowser: TBrowserInformation; var tmp: PChar; res: PChar; begin tmp := StrAlloc(255); res := StrAlloc(255); try GetTempPath(255, tmp); FileCreate(tmp + 'htmpl.htm'); FindExecutable('htmpl.htm', tmp, res); Result.Name := ExtractFileName(res); Result.Path := ExtractFilePath(res); SysUtils.DeleteFile(tmp + 'htmpl.htm'); finally StrDispose(tmp); StrDispose(res); end; end; function EditorAsString(SourceEditor: IOTASourceEditor): string; const iBufferSize: Integer = 1024; Var Reader: IOTAEditReader; iRead: Integer; iPosition: Integer; strBuffer: AnsiString; begin Result := ''; Reader := SourceEditor.CreateReader; try iPosition := 0; repeat SetLength(strBuffer, iBufferSize); iRead := Reader.GetText(iPosition, PAnsiChar(strBuffer), iBufferSize); SetLength(strBuffer, iRead); Result := Result + String(strBuffer); Inc(iPosition, iRead); until iRead < iBufferSize; finally Reader := Nil; end; end; function LongPathName(const ShortPathName: string): string; var PIDL: PItemIDList; Desktop: IShellFolder; WidePathName: WideString; AnsiPathName: AnsiString; begin Result := ShortPathName; if Succeeded(SHGetDesktopFolder(Desktop)) then begin WidePathName := ShortPathName; if Succeeded(Desktop.ParseDisplayName(0, nil, PWideChar(WidePathName), ULONG(nil^), PIDL, ULONG(nil^))) then try SetLength(AnsiPathName, MAX_PATH); SHGetPathFromIDList(PIDL, PChar(AnsiPathName)); Result := PChar(AnsiPathName); finally CoTaskMemFree(PIDL); end; end; end; function GetEnvVarValue(const AVarName: string): string; var LBufSize: Integer; begin LBufSize := GetEnvironmentVariable(PChar(AVarName), nil, 0); if LBufSize > 0 then begin SetLength(Result, LBufSize - 1); GetEnvironmentVariable(PChar(AVarName), PChar(Result), LBufSize); end else Result := ''; end; function GetVolumeLabel(const DriveChar: string): string; var NotUsed: DWORD; VolumeFlags: DWORD; VolumeInfo: array [0 .. MAX_PATH] of Char; VolumeSerialNumber: DWORD; Buf: array [0 .. MAX_PATH] of Char; begin GetVolumeInformation(PChar(DriveChar), Buf, SizeOf(VolumeInfo), @VolumeSerialNumber, NotUsed, VolumeFlags, nil, 0); SetString(Result, Buf, StrLen(Buf)); { Set return result } Result := AnsiUpperCase(Result); end; function BrowseURL(const URL: string): boolean; var LBrowserInformation: TBrowserInformation; begin Result := False; LBrowserInformation := GetDefaultBrowser; Result := ShellExecute(0, 'open', PChar(LBrowserInformation.Path + LBrowserInformation.Name), PChar(URL), nil, SW_SHOW) > 32; end; initialization PathUserDir := GetEnvVarValue('APPDATA') + '\RfUtils'; CreateDir(PathUserDir); end.
unit MaleFemale; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls; type TMaleFemale = class(TGroupBox) private FFeminino: TRadioButton; FMasculino: TRadioButton; { Private declarations } protected { Protected declarations } procedure CreateWnd; override; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property Masculino : TRadioButton read FMasculino; property Feminino : TRadioButton read FFeminino; end; procedure Register; implementation procedure Register; begin RegisterComponents('componenteOW', [TMaleFemale]); end; { TMaleFemale } constructor TMaleFemale.Create(AOwner: TComponent); begin inherited; Width := 100; Height := 60; FMasculino := TRadioButton.Create(Self); FMasculino.Parent := Self; FMasculino.Caption := '&Masculino'; FMasculino.Left := 20; FMasculino.Top := 18; FMasculino.Width := 75; FFeminino := TRadioButton.Create(Self); FFeminino.Parent := Self; FFeminino.Caption := '&Feminino'; FFeminino.Left := 20; FFeminino.Top := 35; FFeminino.Width := 75; FMasculino.SetSubComponent(True); end; procedure TMaleFemale.CreateWnd; begin inherited; Caption := ''; end; end.
{ Mark Sattolo 428500 CSI-1100A DGD-1 TA: Chris Lankester Assignment 7, Question 3 } program LookForIt_recursive (input,output); { Recursive program to find if a certain number occurs in an array. } { Data Dictionary Givens: X, N - X is an array of N numbers. Num - a number to search for in X. Intermediates: (none) Results: Found - a boolean which is true if Num is in X, and false otherwise. } type MarkArray = array[1..27] of integer; var N, Num : integer; X : MarkArray; Found : boolean; { ************************************************************************ } procedure LookForIt(X : MarkArray; N, Num : integer; var Found : boolean); begin Found := false; if N > 0 then if X[N] = Num then Found := true else LookForIt(X, N-1, Num, Found); { end if N > 0 } end; { procedure LookForIt } { ************************************************************************ } procedure FillArray(var ArrayName : MarkArray; var ArraySize : integer); var K : integer; { K - an index in the prompt for values. } begin { FillArray } write('Please enter the size of the array? '); readln(ArraySize); for K := 1 to ArraySize do begin write('Please enter array value #', K, '? '); read(ArrayName[K]) end { for } end; { procedure FillArray } {*************************************************************************************} begin { program } { Get the input values } writeln('For the array to be searched,'); FillArray(X, N); writeln; write('Please enter the value for Num: '); Readln(Num); { body } LookForIt(X, N, Num, Found); { write out the results } writeln; writeln('*******************************************************'); writeln('Mark Sattolo 428500'); writeln('CSI-1100A DGD-1 TA: Chris Lankester'); writeln('Assignment 7, Question 3'); writeln('*******************************************************'); writeln; if Found then writeln('"',Num, '" was found in the array.') else writeln('"',Num, '" was not found in the array.'); end. { program }
unit wayland_shared_buffer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseUnix, ctypes, wayland_protocol; type TFPWL_display = class Display: Pwl_display; Registry: Pwl_registry; Compositor: Pwl_compositor; Shell: Pwl_shell; Shm: Pwl_shm; end; function Create_shm_pool(shm: TWlShm; size: Integer; outdata: PPointer; outfd: Pcuint): TWlShmPool; function Create_shm_buffer(shm: TWlShm; AWidth, AHeight: Integer; AFormat: cuint32; out data: Pointer; out fd: cint): TWlBuffer; implementation const FD_CLOEXEC = 1; function mkstemp(filename: PChar):longint;cdecl;external 'libc' name 'mkstemp'; function mkostemp(filename: PChar; flags: cint):longint;cdecl;external 'libc' name 'mkostemp'; function CreateAnonymousFile(ASize: PtrUint): cint; {fd} forward; function Create_shm_pool(shm: TWlShm; size: Integer; outData: PPointer; outfd: Pcuint): TWlShmPool; var fd: cint; data: Pointer; begin Result := nil; fd := CreateAnonymousFile(size); if fd < 0 then Exit; data := Fpmmap(nil, size, PROT_READ or PROT_WRITE, MAP_SHARED, fd, 0); if Assigned(outData) then outData^ := data;; if data = MAP_FAILED then begin fpclose(fd); Exit; end; Result := shm.CreatePool(fd, size); if outfd = nil then FpClose(fd) else outfd^ := fd; end; function Create_shm_buffer(shm: TWlShm; AWidth, AHeight: Integer; AFormat: cuint32; out data: Pointer; out fd: cint): TWlBuffer; var pool: TWlShmPool; size, stride: cint; begin Result := nil; stride := AWidth *4; size := stride * Aheight; pool := Create_shm_pool(shm, size, @Data, @fd); Result := pool.CreateBuffer(0, AWidth, AHeight, stride, AFormat); pool.Free // proxy will be destroyed after the buffer is destroyed end; function CreateAnonymousFile(ASize: PtrUint): cint; {fd} const O_CLOEXEC = $80000; var lName: String; flags: cint; begin lName := GetEnvironmentVariable('XDG_RUNTIME_DIR') + '/weston-shared-XXXXXX'; Result := mkostemp(PChar(lName), O_CLOEXEC); FpUnlink(lName); if (FpFtruncate(Result, ASize) < 0) then begin FpClose(Result); Result := -1; end; end; end.
// **************************************************************************** // * An Outlook style sidebar component for Delphi. // **************************************************************************** // * Copyright 2001-2005, Bitvadász Kft. All Rights Reserved. // **************************************************************************** // * This component can be freely used and distributed in commercial and // * private environments, provied this notice is not modified in any way. // **************************************************************************** // * Feel free to contact me if you have any questions, comments or suggestions // * at support@maxcomponents.net // **************************************************************************** // * Description: // * // * The TmxOutlookBar 100% native VCL component with many added features to // * support the look, feel, and behavior introduced in Microsoft Office 97, // * 2000, and new Internet Explorer. It has got many features including // * scrolling headers, icon highlighting and positioning, small and large // * icons,gradient and bitmap Backgrounds. The header sections and buttons // * can be added, deleted and moved at design time. The header tabs can // * have individual font, alignment, tabcolor, glyph, tiled Background // * images. And many many more posibilities. // **************************************************************************** Unit mxOutlookBarAbout; Interface // ************************************************************************************* // ** List of used units // ************************************************************************************* Uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ShellAPI, ExtCtrls; Type Tfrm_AboutBox = Class( TForm ) lbl_Copyright: TLabel; Lbl_Delphi: TLabel; Lbl_ComponentName: TLabel; Label1: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label3: TLabel; Panel1: TPanel; btn_WebSite: TSpeedButton; btn_Close: TSpeedButton; Panel2: TPanel; SpeedButton1: TSpeedButton; Label2: TLabel; Label7: TLabel; Procedure Panel2MouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); Procedure btn_CloseClick( Sender: TObject ); Procedure btn_WebSiteClick( Sender: TObject ); Procedure SpeedButton1Click( Sender: TObject ); Private End; Procedure ShowAboutBox( Const ComponentName: String ); // ************************************************************************************* // ** End of Interface section // ************************************************************************************* Implementation {$R *.DFM} // ************************************************************************************* // ** ShowAboutBox, 4/11/01 10:13:27 AM // ************************************************************************************* Procedure ShowAboutBox( Const ComponentName: String ); Begin With Tfrm_AboutBox.Create( Application ) Do Try Lbl_ComponentName.Caption := ComponentName; Lbl_Delphi.Caption := 'Compiled in ' + {$IFDEF VER80} 'Delphi 1.0'{$ENDIF} {$IFDEF VER90} 'Delphi 2.0'{$ENDIF} {$IFDEF VER100} 'Delphi 3.0'{$ENDIF} {$IFDEF VER120} 'Delphi 4.0'{$ENDIF} {$IFDEF VER130} 'Delphi 5.0'{$ENDIF} {$IFDEF VER140} 'Delphi 6.0'{$ENDIF} {$IFDEF VER150} 'Delphi 7.0'{$ENDIF} {$IFDEF VER170} 'Delphi 2005'{$ENDIF} {$IFDEF VER93} 'C++Builder 1.0'{$ENDIF} {$IFDEF VER110} 'C++Builder 3.0'{$ENDIF} {$IFDEF VER125} 'C++Builder 4.0'{$ENDIF}; ShowModal; Finally Free; End; End; Procedure Tfrm_AboutBox.Panel2MouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); Begin ReleaseCapture; Perform( WM_SYSCOMMAND, $F012, 0 ); End; Procedure Tfrm_AboutBox.btn_CloseClick( Sender: TObject ); Begin Close; End; Procedure Tfrm_AboutBox.btn_WebSiteClick( Sender: TObject ); Begin ShellExecute( Application.Handle, Nil, 'www.maxcomponents.net', Nil, Nil, SW_SHOWNOACTIVATE ); End; Procedure Tfrm_AboutBox.SpeedButton1Click( Sender: TObject ); Begin ShellExecute( Application.Handle, Nil, 'mailto:support@maxcomponents.net', Nil, Nil, SW_SHOWNOACTIVATE ); End; End.
{ File: PEFBinaryFormat.p Contains: PEF Types and Macros Version: Technology: Master Interfaces Release: Universal Interfaces 3.4.2 Copyright: © 1993-2002 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit PEFBinaryFormat; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes; {$ALIGN MAC68K} { -------------------------------------------------------------------------------------------- } { Almost all types are padded for natural alignment. However the PEFExportedSymbol type is } { 10 bytes long, containing two 32 bit fields and one 16 bit field. Arrays of it must be } { packed, so it requires "68K" alignment. Setting this globally to 68K should also help } { ensure consistent treatment across compilers. } { ======================================================================================== } { Overall Structure } { ================= } { -------------------------------------------------------------------------------------------- } { This header contains a complete set of types and macros for dealing with the PEF executable } { format. While some description is provided, this header is not meant as a primary source } { of documentation on PEF. An excellent specification of PEF can be found in the Macintosh } { Runtime Architectures book. This header is primarily a physical format description. Thus } { it depends on as few other headers as possible and structure fields have obvious sizes. } { } { The physical storage for a PEF executable is known as a "container". This refers to just } { the executable itself, not the file etc. E.g. if five DLLs are packaged in a single file's } { data fork, that one data fork has five containers within it. } { } { A PEF container consists of an overall header, followed by one or more section headers, } { followed by the section name table, followed by the contents for the sections. Some kinds } { of sections have specific internal representation. The "loader" section is the most common } { of these special sections. It contains information on the exports, imports, and runtime } { relocations required to prepare the executable. PEF containers are self contained, all } { portions are located via relative offsets. } { } { } { +-------------------------------+ } { | Container Header | 40 bytes } { +-------------------------------+ } { | Section 0 header | 28 bytes each } { |...............................| } { | - - - - | } { |...............................| } { | Section n-1 header | } { +-------------------------------+ } { | Section Name Table | } { +-------------------------------+ } { | Section x raw data | } { +-------------------------------+ } { | - - - - | } { +-------------------------------+ } { | Section y raw data | } { +-------------------------------+ } { } { } { The sections are implicitly numbered from 0 to n according to the order of their headers. } { The headers of the instantiated sections must precede those of the non-instantiated } { sections. The ordering of the raw data is independent of the section header ordering. } { Each section header contains the offset for that section's raw data. } { =========================================================================================== } { Container Header } { ================ } type PEFContainerHeaderPtr = ^PEFContainerHeader; PEFContainerHeader = record tag1: OSType; { Must contain 'Joy!'. } tag2: OSType; { Must contain 'peff'. (Yes, with two 'f's.) } architecture: OSType; { The ISA for code sections. Constants in CodeFragments.h. } formatVersion: UInt32; { The physical format version. } dateTimeStamp: UInt32; { Macintosh format creation/modification stamp. } oldDefVersion: UInt32; { Old definition version number for the code fragment. } oldImpVersion: UInt32; { Old implementation version number for the code fragment. } currentVersion: UInt32; { Current version number for the code fragment. } sectionCount: UInt16; { Total number of section headers that follow. } instSectionCount: UInt16; { Number of instantiated sections. } reservedA: UInt32; { Reserved, must be written as zero. } end; const kPEFTag1 = FourCharCode('Joy!'); { For non-Apple compilers: 0x4A6F7921. } kPEFTag2 = FourCharCode('peff'); { For non-Apple compilers: 0x70656666. } kPEFVersion = $00000001; kPEFFirstSectionHeaderOffset = 40; { =========================================================================================== } { Section Headers } { =============== } type PEFSectionHeaderPtr = ^PEFSectionHeader; PEFSectionHeader = record nameOffset: SInt32; { Offset of name within the section name table, -1 => none. } defaultAddress: UInt32; { Default address, affects relocations. } totalLength: UInt32; { Fully expanded size in bytes of the section contents. } unpackedLength: UInt32; { Size in bytes of the "initialized" part of the contents. } containerLength: UInt32; { Size in bytes of the raw data in the container. } containerOffset: UInt32; { Offset of section's raw data. } sectionKind: SInt8; { Kind of section contents/usage. } shareKind: SInt8; { Sharing level, if a writeable section. } alignment: SInt8; { Preferred alignment, expressed as log 2. } reservedA: SInt8; { Reserved, must be zero. } end; const { Values for the sectionKind field. } { Section kind values for instantiated sections. } kPEFCodeSection = 0; { Code, presumed pure & position independent. } kPEFUnpackedDataSection = 1; { Unpacked writeable data. } kPEFPackedDataSection = 2; { Packed writeable data. } kPEFConstantSection = 3; { Read-only data. } kPEFExecDataSection = 6; { Intermixed code and writeable data. } { Section kind values for non-instantiated sections. } kPEFLoaderSection = 4; { Loader tables. } kPEFDebugSection = 5; { Reserved for future use. } kPEFExceptionSection = 7; { Reserved for future use. } kPEFTracebackSection = 8; { Reserved for future use. } { Values for the shareKind field. } kPEFProcessShare = 1; { Shared within a single process. } kPEFGlobalShare = 4; { Shared across the entire system. } kPEFProtectedShare = 5; { Readable across the entire system, writeable only to privileged code. } { =========================================================================================== } { Packed Data Contents } { ==================== } { -------------------------------------------------------------------------------------------- } { The raw contents of a packed data section are a sequence of byte codes. The basic format } { has a 3 bit opcode followed by a 5 bit count. Additional bytes might be used to contain } { counts larger than 31, and to contain a second or third count. Further additional bytes } { contain actual data values to transfer. } { } { All counts are represented in a variable length manner. A zero in the initial 5 bit count } { indicates the actual value follows. In this case, and for the second and third counts, the } { count is represented as a variable length sequence of bytes. The bytes are stored in big } { endian manner, most significant part first. The high order bit is set in all but the last } { byte. The value is accumulated by shifting the current value up 7 bits and adding in the } { low order 7 bits of the next byte. } { The packed data opcodes. } kPEFPkDataZero = 0; { Zero fill "count" bytes. } kPEFPkDataBlock = 1; { Block copy "count" bytes. } kPEFPkDataRepeat = 2; { Repeat "count" bytes "count2"+1 times. } kPEFPkDataRepeatBlock = 3; { Interleaved repeated and unique data. } kPEFPkDataRepeatZero = 4; { Interleaved zero and unique data. } kPEFPkDataOpcodeShift = 5; kPEFPkDataCount5Mask = $1F; kPEFPkDataMaxCount5 = 31; kPEFPkDataVCountShift = 7; kPEFPkDataVCountMask = $7F; kPEFPkDataVCountEndMask = $80; { -------------------------------------------------------------------------------------------- } { The following code snippet can be used to input a variable length count. } { } { count = 0; } { do ( } { byte = *bytePtr++; } { count = (count << kPEFPkDataVCountShift) | (byte & kPEFPkDataVCountMask); } { ) while ( (byte & kPEFPkDataVCountEndMask) != 0 ); } { } { The following code snippet can be used to output a variable length count to a byte array. } { This is more complex than the input code because the chunks are output in big endian order. } { Think about handling values like 0 or 0x030000. } { } { count = 1;. } { tempValue = value >> kPEFPkDataCountShift; } { while ( tempValue != 0 ) ( } { count += 1; } { tempValue = tempValue >> kPEFPkDataCountShift; } { ) } { } { bytePtr += count; } { tempPtr = bytePtr - 1; } { *tempPtr-- = value; // ! No need to mask, only the low order byte is stored. } { for ( count -= 1; count != 0; count -= 1 ) ( } { value = value >> kPEFPkDataCountShift; } { *tempPtr-- = value | kPEFPkDataCountEndMask; } { ) } { =========================================================================================== } { Loader Section } { ============== } { -------------------------------------------------------------------------------------------- } { The loader section contains information needed to prepare the code fragment for execution. } { This includes this fragment's exports, the import libraries and the imported symbols from } { each library, and the relocations for the writeable sections. } { } { +-----------------------------------+ <-- containerOffset --------+ } { | Loader Info Header | 56 bytes | } { |-----------------------------------| | } { | Imported Library 0 | 24 bytes each | } { |...................................| | } { | - - - | | } { |...................................| | } { | Imported Library l-1 | | } { |-----------------------------------| | } { | Imported Symbol 0 | 4 bytes each | } { |...................................| | } { | - - - | | } { |...................................| | } { | Imported Symbol i-1 | | } { |-----------------------------------| | } { | Relocation Header 0 | 12 bytes each | } { |...................................| | } { | - - - | | } { |...................................| | } { | Relocation Header r-1 | | } { |-----------------------------------| <-- + relocInstrOffset -----| } { | Relocation Instructions | | } { |-----------------------------------| <-- + loaderStringsOffset --| } { | Loader String Table | | } { |-----------------------------------| <-- + exportHashOffset -----+ } { | Export Hash Slot 0 | 4 bytes each } { |...................................| } { | - - - | } { |...................................| } { | Export Hash Slot h-1 | } { |-----------------------------------| } { | Export Symbol Key 0 | 4 bytes each } { |...................................| } { | - - - | } { |...................................| } { | Export Symbol Key e-1 | } { |-----------------------------------| } { | Export Symbol 0 | 10 bytes each } { |...................................| } { | - - - | } { |...................................| } { | Export Symbol e-1 | } { +-----------------------------------+ } type PEFLoaderInfoHeaderPtr = ^PEFLoaderInfoHeader; PEFLoaderInfoHeader = record mainSection: SInt32; { Section containing the main symbol, -1 => none. } mainOffset: UInt32; { Offset of main symbol. } initSection: SInt32; { Section containing the init routine's TVector, -1 => none. } initOffset: UInt32; { Offset of the init routine's TVector. } termSection: SInt32; { Section containing the term routine's TVector, -1 => none. } termOffset: UInt32; { Offset of the term routine's TVector. } importedLibraryCount: UInt32; { Number of imported libraries. ('l') } totalImportedSymbolCount: UInt32; { Total number of imported symbols. ('i') } relocSectionCount: UInt32; { Number of sections with relocations. ('r') } relocInstrOffset: UInt32; { Offset of the relocation instructions. } loaderStringsOffset: UInt32; { Offset of the loader string table. } exportHashOffset: UInt32; { Offset of the export hash table. } exportHashTablePower: UInt32; { Export hash table size as log 2. (Log2('h')) } exportedSymbolCount: UInt32; { Number of exported symbols. ('e') } end; { =========================================================================================== } { Imported Libraries } { ------------------ } PEFImportedLibraryPtr = ^PEFImportedLibrary; PEFImportedLibrary = record nameOffset: UInt32; { Loader string table offset of library's name. } oldImpVersion: UInt32; { Oldest compatible implementation version. } currentVersion: UInt32; { Current version at build time. } importedSymbolCount: UInt32; { Imported symbol count for this library. } firstImportedSymbol: UInt32; { Index of first imported symbol from this library. } options: SInt8; { Option bits for this library. } reservedA: SInt8; { Reserved, must be zero. } reservedB: UInt16; { Reserved, must be zero. } end; const { Bits for the PEFImportedLibrary options field. } kPEFWeakImportLibMask = $40; { The imported library is allowed to be missing. } kPEFInitLibBeforeMask = $80; { The imported library must be initialized first. } { =========================================================================================== } { Imported Symbols } { ---------------- } { -------------------------------------------------------------------------------------------- } { The PEFImportedSymbol type has the following bit field layout. } { } { 3 } { 0 7 8 1 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { | symbol class | offset of symbol name in loader string table | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 8 bits --->|<-- 24 bits ---------------------------------->| } type PEFImportedSymbolPtr = ^PEFImportedSymbol; PEFImportedSymbol = record classAndName: UInt32; end; const kPEFImpSymClassShift = 24; kPEFImpSymNameOffsetMask = $00FFFFFF; kPEFImpSymMaxNameOffset = $00FFFFFF; { 16,777,215 } { Imported and exported symbol classes. } kPEFCodeSymbol = $00; kPEFDataSymbol = $01; kPEFTVectorSymbol = $02; kPEFTOCSymbol = $03; kPEFGlueSymbol = $04; kPEFUndefinedSymbol = $0F; kPEFWeakImportSymMask = $80; { =========================================================================================== } { Exported Symbol Hash Table } { -------------------------- } { -------------------------------------------------------------------------------------------- } { Exported symbols are described in four parts, optimized for speed of lookup. These parts } { are the "export hash table", the "export key table", the "export symbol table", and the } { "export name table". Overall they contain a flattened representation of a fairly normal } { hashed symbol table. } { } { The export hash table is an array of small fixed size elements. The number of elements is } { a power of 2. A 32 bit hash word for a symbol is converted into an index into this array. } { Each hash slot contains a count of the number of exported symbols that map to this slot and } { the index of the first of those symbols in the key and symbol tables. Of course some hash } { slots will have a zero count. } { } { The key and symbol tables are also arrays of fixed size elements, one for each exported } { symbol. Their entries are grouped by hash slot, those elements mapping to the same hash } { slot are contiguous. The key table contains just the full 32 bit hash word for each } { exported symbol. The symbol table contains the offset of the symbol's name in the string } { table and other information about the exported symbol. } { } { To look up an export you take the hashword and compute the hash slot index. You then scan } { the indicated portion of the key table for matching hashwords. If a hashword matches, you } { look at the corresponding symbol table entry to find the full symbol name. If the names } { match the symbol is found. } { -------------------------------------------------------------------------------------------- } { The following function may be used to compute the hash table size. Signed values are used } { just to avoid potential code generation overhead for unsigned division. } { } { UInt8 PEFComputeHashTableExponent ( SInt32 exportCount ) } { ( } { SInt32 exponent; } { } { const SInt32 kExponentLimit = 16; // Arbitrary, but must not exceed 30. } { const SInt32 kAverageChainLimit = 10; // Arbitrary, for space/time tradeoff. } { } { for ( exponent = 0; exponent < kExponentLimit; exponent += 1 ) ( } { if ( (exportCount / (1 << exponent)) < kAverageChainLimit ) break; } { ) } { } { return exponent; } { } { ) // PEFComputeHashTableExponent () } { -------------------------------------------------------------------------------------------- } { The PEFExportedSymbolHashSlot type has the following bit field layout. } { } { 1 1 3 } { 0 3 4 1 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { | symbol count | index of first export key | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 14 bits -------------->|<-- 18 bits ---------------------->| } type PEFExportedSymbolHashSlotPtr = ^PEFExportedSymbolHashSlot; PEFExportedSymbolHashSlot = record countAndStart: UInt32; end; const kPEFHashSlotSymCountShift = 18; kPEFHashSlotFirstKeyMask = $0003FFFF; kPEFHashSlotMaxSymbolCount = $00003FFF; { 16,383 } kPEFHashSlotMaxKeyIndex = $0003FFFF; { 262,143 } { =========================================================================================== } { Exported Symbol Hash Key } { ------------------------ } type PEFSplitHashWordPtr = ^PEFSplitHashWord; PEFSplitHashWord = record nameLength: UInt16; hashValue: UInt16; end; PEFExportedSymbolKeyPtr = ^PEFExportedSymbolKey; PEFExportedSymbolKey = record case SInt16 of 0: ( fullHashWord: UInt32; ); 1: ( splitHashWord: PEFSplitHashWord; ); end; const kPEFHashLengthShift = 16; kPEFHashValueMask = $0000FFFF; kPEFHashMaxLength = $0000FFFF; { 65,535 } { ---------------------------------------------------------------------------------------------------- } { The following function computes the full 32 bit hash word. } { } { UInt32 PEFComputeHashWord ( BytePtr nameText, // ! First "letter", not length byte. } { UInt32 nameLength ) // ! The text may be zero terminated. } { ( } { BytePtr charPtr = nameText; } { SInt32 hashValue = 0; // ! Signed to match old published algorithm. } { UInt32 length = 0; } { UInt32 limit; } { UInt32 result; } { UInt8 currChar; } { } { #define PseudoRotate(x) ( ( (x) << 1 ) - ( (x) >> 16 ) ) } { } { for ( limit = nameLength; limit > 0; limit -= 1 ) ( } { currChar = *charPtr++; } { if ( currChar == NULL ) break; } { length += 1; } { hashValue = PseudoRotate ( hashValue ) ^ currChar; } { ) } { } { result = (length << kPEFHashLengthShift) | } { ((UInt16) ((hashValue ^ (hashValue >> 16)) & kPEFHashValueMask)); } { } { return result; } { } { ) // PEFComputeHashWord () } { =========================================================================================== } { Exported Symbols } { ---------------- } type PEFExportedSymbolPtr = ^PEFExportedSymbol; PEFExportedSymbol = record { ! This structure is 10 bytes long and arrays are packed. } classAndName: UInt32; { A combination of class and name offset. } symbolValue: UInt32; { Typically the symbol's offset within a section. } sectionIndex: SInt16; { The index of the section, or pseudo-section, for the symbol. } end; { -------------------------------------------------------------------------------------------- } { The classAndName field of the PEFExportedSymbol type has the following bit field layout. } { } { 3 } { 0 7 8 1 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { | symbol class | offset of symbol name in loader string table | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 8 bits --->|<-- 24 bits ---------------------------------->| } const kPEFExpSymClassShift = 24; kPEFExpSymNameOffsetMask = $00FFFFFF; kPEFExpSymMaxNameOffset = $00FFFFFF; { 16,777,215 } { Negative section indices indicate pseudo-sections. } kPEFAbsoluteExport = -2; { The symbol value is an absolute address. } kPEFReexportedImport = -3; { The symbol value is the index of a reexported import. } { =========================================================================================== } { Loader Relocations } { ================== } { -------------------------------------------------------------------------------------------- } { The relocations for a section are defined by a sequence of instructions for an abstract } { machine that is specifically geared to performing relocations commonly needed for the "CFM" } { code generation model. These instructions occur in 16 bit chunks. Most instructions have } { just a single chunk. Instructions that are larger than 16 bits have an opcode and some of } { the operands in the first chunk, with other operands in following chunks. } { } { ! Note that the multi-chunk relocations have separate "Compose" macros for each chunk. The } { ! macros have the same basic name with a positional suffix of "_1st", "_2nd", etc. } type PEFRelocChunk = UInt16; PEFLoaderRelocationHeaderPtr = ^PEFLoaderRelocationHeader; PEFLoaderRelocationHeader = record sectionIndex: UInt16; { Index of the section to be fixed up. } reservedA: UInt16; { Reserved, must be zero. } relocCount: UInt32; { Number of 16 bit relocation chunks. } firstRelocOffset: UInt32; { Offset of first relocation instruction. } end; { -------------------------------------------------------------------------------------------- } { ! Note that the relocCount field is the number of 16 bit relocation chunks, i.e. 1/2 the } { ! total number of bytes of relocation instructions. While most relocation instructions are } { ! 16 bits long, some are longer so the number of complete relocation instructions may be } { ! less than the relocCount value. } { ------------------------------------------------------------------------------------ } { The PEFRelocField macro is a utility for extracting relocation instruction fields. } { =========================================================================================== } { Basic Relocation Opcodes } { ------------------------ } { -------------------------------------------------------------------------------------------- } { The number of opcode bits varies from 2 to 7. The enumeration and switch table given here } { are defined in terms of the most significant 7 bits of the first instruction chunk. An } { instruction is decoded by using the most significant 7 bits as an index into the opcode } { table, which in turn contains appropriately masked forms of the most significant 7 bits. } { The macro PEFRelocBasicOpcode assumes a declaration of the form. } { } { UInt8 kPEFRelocBasicOpcodes [kPEFRelocBasicOpcodeRange] = ( PEFMaskedBasicOpcodes ); } const kPEFRelocBasicOpcodeRange = 128; { -------------------------------------------------------------------------------------------- } { The relocation opcodes, clustered by major and minor groups. The instructions within a } { cluster all have the same bit field layout. The enumeration values use the high order 7 } { bits of the relocation instruction. Unused low order bits are set to zero. } kPEFRelocBySectDWithSkip = $00; { Binary: 00x_xxxx } kPEFRelocBySectC = $20; { Binary: 010_0000, group is "RelocRun" } kPEFRelocBySectD = $21; { Binary: 010_0001 } kPEFRelocTVector12 = $22; { Binary: 010_0010 } kPEFRelocTVector8 = $23; { Binary: 010_0011 } kPEFRelocVTable8 = $24; { Binary: 010_0100 } kPEFRelocImportRun = $25; { Binary: 010_0101 } kPEFRelocSmByImport = $30; { Binary: 011_0000, group is "RelocSmIndex" } kPEFRelocSmSetSectC = $31; { Binary: 011_0001 } kPEFRelocSmSetSectD = $32; { Binary: 011_0010 } kPEFRelocSmBySection = $33; { Binary: 011_0011 } kPEFRelocIncrPosition = $40; { Binary: 100_0xxx } kPEFRelocSmRepeat = $48; { Binary: 100_1xxx } kPEFRelocSetPosition = $50; { Binary: 101_000x } kPEFRelocLgByImport = $52; { Binary: 101_001x } kPEFRelocLgRepeat = $58; { Binary: 101_100x } kPEFRelocLgSetOrBySection = $5A; { Binary: 101_101x } kPEFRelocUndefinedOpcode = $FF; { Used in masking table for all undefined values. } { ---------------------------------------------------------------------------- } { The RelocLgSetOrBySection instruction has an additional 4 bits of subopcode } { beyond the 7 used by the dispatch table. To be precise it has 6 plus 4 but } { the dispatch table ignores the 7th bit, so the subdispatch is on all 4 extra } { subopcode bits. } kPEFRelocLgBySectionSubopcode = $00; { Binary: 0000 } kPEFRelocLgSetSectCSubopcode = $01; { Binary: 0001 } kPEFRelocLgSetSectDSubopcode = $02; { Binary: 0010 } { -------------------------------------------------------------------------------------------- } { The initial values for the opcode "masking" table. This has the enumeration values from } { above with appropriate replications for "don't care" bits. It is almost certainly shorter } { and faster to look up the masked value in a table than to use a branch tree. } { =========================================================================================== } { RelocBySectDWithSkip Instruction (DDAT) } { --------------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocBySectDWithSkip" (DDAT) instruction has the following bit field layout. } { } { 1 1 } { 0 1 2 9 0 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |0 0| skip count | rel count | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { | 2 |<-- 8 bits --->|<-- 6 --->| } { } { ! Note that the stored skip count and reloc count are the actual values! } kPEFRelocWithSkipMaxSkipCount = 255; kPEFRelocWithSkipMaxRelocCount = 63; { =========================================================================================== } { RelocRun Group (CODE, DATA, DESC, DSC2, VTBL, SYMR) } { --------------------------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocRun" group includes the "RelocBySectC" (CODE), "RelocBySectD" (DATA), } { "RelocTVector12" (DESC), "RelocTVector8" (DSC2), "RelocVTable8" (VTBL), and } { "RelocImportRun" (SYMR) instructions. This group has the following bit field layout. } { } { 1 } { 0 2 3 6 7 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |0 1 0| subop.| run length | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { | 3 |<- 4 ->|<-- 9 bits ----->| } { } { ! Note that the stored run length is the actual value minus 1, but the macros deal with the } { ! actual value! } kPEFRelocRunMaxRunLength = 512; { =========================================================================================== } { RelocSmIndex Group (SYMB, CDIS, DTIS, SECN) } { ------------------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocSmIndex" group includes the "RelocSmByImport" (SYMB), "RelocSmSetSectC" (CDIS), } { "RelocSmSetSectD" (DTIS) and "RelocSmBySection" (SECN) instructions. This group has the } { following bit field layout. } { } { 1 } { 0 2 3 6 7 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |0 1 1| subop.| index | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { | 3 |<- 4 ->|<-- 9 bits ----->| } { } { ! Note that the stored index is the actual value! } kPEFRelocSmIndexMaxIndex = 511; { =========================================================================================== } { RelocIncrPosition Instruction (DELT) } { ------------------------------------ } { -------------------------------------------------------------------------------------------- } { The "RelocIncrPosition" (DELT) instruction has the following bit field layout. } { } { 1 } { 0 3 4 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |1 0 0 0| offset | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<- 4 ->|<-- 12 bits ---------->| } { } { ! Note that the stored offset is the actual value minus 1, but the macros deal with the } { ! actual value! } kPEFRelocIncrPositionMaxOffset = 4096; { =========================================================================================== } { RelocSmRepeat Instruction (RPT) } { ------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocSmRepeat" (RPT) instruction has the following bit field layout. } { } { 1 } { 0 3 4 7 8 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |1 0 0 1| chnks | repeat count | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<- 4 ->|<- 4 ->|<-- 8 bits --->| } { } { ! Note that the stored chunk count and repeat count are the actual values minus 1, but the } { ! macros deal with the actual values! } kPEFRelocSmRepeatMaxChunkCount = 16; kPEFRelocSmRepeatMaxRepeatCount = 256; { =========================================================================================== } { RelocSetPosition Instruction (LABS) } { ----------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocSetPosition" (LABS) instruction has the following bit field layout. } { } { 1 1 } { 0 5 6 5 0 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |1 0 1 0 0 0| offset (high) | | offset (low) | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 6 ---->|<-- 10 bits ------>| |<-- 16 bits ------------------>| } { } { ! Note that the stored offset is the actual value! } kPEFRelocSetPosMaxOffset = $03FFFFFF; { 67,108,863 } { =========================================================================================== } { RelocLgByImport Instruction (LSYM) } { ---------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocLgByImport" (LSYM) instruction has the following bit field layout. } { } { 1 1 } { 0 5 6 5 0 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |1 0 1 0 0 1| index (high) | | index (low) | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 6 ---->|<-- 10 bits ------>| |<-- 16 bits ------------------>| } { } { ! Note that the stored offset is the actual value! } kPEFRelocLgByImportMaxIndex = $03FFFFFF; { 67,108,863 } { =========================================================================================== } { RelocLgRepeat Instruction (LRPT) } { -------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocLgRepeat" (LRPT) instruction has the following bit field layout. } { } { 1 1 1 } { 0 5 6 9 0 5 0 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |1 0 1 1 0 0| chnks | rpt (high)| | repeat count (low) | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 6 --->|<- 4 ->|<-- 6 --->| |<-- 16 bits ------------------>| } { } { ! Note that the stored chunk count is the actual value minus 1, but the macros deal with } { ! the actual value! The stored repeat count is the actual value! } kPEFRelocLgRepeatMaxChunkCount = 16; kPEFRelocLgRepeatMaxRepeatCount = $003FFFFF; { 4,194,303 } { =========================================================================================== } { RelocLgSetOrBySection Group (LSEC) } { ---------------------------------- } { -------------------------------------------------------------------------------------------- } { The "RelocLgSetOrBySection" (LSEC) instruction is a group including the "RelocLgBySection", } { "RelocLgSetSectC" and "RelocLgSetSectD" instructions. This group has the following bit } { field layout. } { } { 1 1 1 } { 0 5 6 9 0 5 0 5 } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |1 0 1 1 0 1| subop | idx (high)| | index (low) | } { +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } { |<-- 6 --->|<- 4 ->|<-- 6 --->| |<-- 16 bits ------------------>| } { } { ! Note that the stored index is the actual value! } kPEFRelocLgSetOrBySectionMaxIndex = $003FFFFF; { 4,194,303 } {$ALIGN MAC68K} end.
unit ConfigValueRequestUnit; interface uses REST.Json.Types, GenericParametersUnit, NullableBasicTypesUnit, JSONNullableAttributeUnit; type TConfigValueRequest = class(TGenericParameters) private [JSONName('config_key')] FKey: String; [JSONName('config_value')] [Nullable] FValue: NullableString; public constructor Create(Key: String); overload; constructor Create(Key, Value: String); overload; property Key: String read FKey; property Value: NullableString read FValue; end; implementation { TConfigValueRequest } constructor TConfigValueRequest.Create(Key, Value: String); begin Create(Key); FValue := Value; end; constructor TConfigValueRequest.Create(Key: String); begin inherited Create; FKey := Key; FValue := NullableString.Null; end; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StNetMsg.pas 4.04 *} {*********************************************************} {* SysTools: Net Message Class *} {*********************************************************} {$I StDefine.inc} {$H+} {Huge strings} unit StNetMsg; interface uses Windows, Classes, StBase; type TStNetMessage = class(TStComponent) private { Private Methods/Properties } FAliasNames : TStringList; FMsgFrom : string; FMsgText : string; FMsgTo : string; FServerName : string; FOnMessageSent : TNotifyEvent; protected { Protected Methods/Properties } function GetServer: string; procedure SetServer(Value: string); public { Public Methods/Properties } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure AddAlias(AName: string); function AliasNames: TStringList; procedure RemoveAlias(AName: string); procedure Send; published { Published Methods/Properties } property MsgFrom: string read FMsgFrom write FMsgFrom; property MsgText: string read FMsgText write FMsgText; property MsgTo : string read FMsgTo write FMsgTo; property Server : string read GetServer write SetServer; property OnMessageSent: TNotifyEvent read FOnMessageSent write FOnMessageSent; end; implementation uses SysUtils, StStrL, StNetApi, Dialogs; constructor TStNetMessage.Create(AOwner: TComponent); begin inherited Create(AOwner); FAliasNames := TStringList.Create; end; destructor TStNetMessage.Destroy; begin FAliasNames.Free; inherited Destroy; end; procedure TStNetMessage.AddAlias(AName: string); var ErrorD : DWord; begin ErrorD := StNetMessageNameAdd(FServerName, AName); if ErrorD <> NERR_SUCCESS then RaiseStWin32Error(EStNetException, ErrorD); end; function TStNetMessage.AliasNames: TStringList; var ErrorD : DWord; Buffer : Pointer; TotalEntries : DWord; EntriesRead : DWord; I : Integer; begin ErrorD := StNetMessageNameEnum(FServerName, 0, Buffer, DWord(-1), EntriesRead, TotalEntries, nil); if ErrorD = NERR_SUCCESS then begin FAliasNames.Clear; for I := 0 to EntriesRead-1 do begin FAliasNames.Add(TMsgInfo0Array(Buffer^)[I].msgi0_name); end; StNetApiBufferFree(Buffer); end else begin RaiseStWin32Error(EStNetException, ErrorD); end; Result := FAliasNames; end; procedure TStNetMessage.RemoveAlias(AName: string); var ErrorD : DWord; begin ErrorD := StNetMessageNameDel(FServerName, AName); if ErrorD <> NERR_SUCCESS then RaiseStWin32Error(EStNetException, ErrorD); end; procedure TStNetMessage.Send; var ErrorD : DWord; Buffer : TLMWideChar; begin Buffer.Value := nil; try CvtToWideChar(FMsgText, Buffer); ErrorD := StNetMessageBufferSend(FServerName, FMsgTo, FMsgFrom, Buffer.Value, Buffer.Length); if ErrorD <> NERR_SUCCESS then RaiseStWin32Error(EStNetException, ErrorD) else if Assigned(FOnMessageSent) then FOnMessageSent(Self); finally FreeMem(Buffer.Value, Buffer.Length); end; end; function TStNetMessage.GetServer: string; begin { don't return any UNC notation } Result := FilterL(FServerName, '\'); end; procedure TStNetMessage.SetServer(Value: string); begin { get rid of any UNC notation or trailing marks } Value := FilterL(Value, '\'); { do we have a valid server name? } if (Length(Value) > 0) then if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) then FServerName := Value else FServerName := '\\' + Value else FServerName := Value; end; end.
unit udmItensPedido; interface uses System.SysUtils, System.Classes, udmPadrao, Data.DB, DBAccess, IBC, MemDS, udmPrincipal, LibGeral; type TdmItensPedido = class(TdmPadrao) qryManutencaoFIL_PEDIDO: TStringField; qryManutencaoNRO_PEDIDO: TIntegerField; qryManutencaoTIPO: TStringField; qryManutencaoITEM: TIntegerField; qryManutencaoCOD_PRODUTO: TStringField; qryManutencaoDESCRICAO: TBlobField; qryManutencaoUNID: TStringField; qryManutencaoQTD_ITEM: TFloatField; qryManutencaoVLR_PRODUTO: TFloatField; qryManutencaoVLR_SERVICO: TFloatField; qryManutencaoC_FISCAL: TStringField; qryManutencaoS_TRIBUTARIA: TStringField; qryManutencaoISS_BASE: TFloatField; qryManutencaoISS_ALIQUOTA: TFloatField; qryManutencaoISS_VALOR: TFloatField; qryManutencaoICMS_BASE: TFloatField; qryManutencaoICMS_ALIQUOTA: TFloatField; qryManutencaoICMS_VALOR: TFloatField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoVLR_MERCADO: TFloatField; qryLocalizacaoFIL_PEDIDO: TStringField; qryLocalizacaoNRO_PEDIDO: TIntegerField; qryLocalizacaoTIPO: TStringField; qryLocalizacaoITEM: TIntegerField; qryLocalizacaoCOD_PRODUTO: TStringField; qryLocalizacaoDESCRICAO: TBlobField; qryLocalizacaoUNID: TStringField; qryLocalizacaoQTD_ITEM: TFloatField; qryLocalizacaoVLR_PRODUTO: TFloatField; qryLocalizacaoVLR_SERVICO: TFloatField; qryLocalizacaoC_FISCAL: TStringField; qryLocalizacaoS_TRIBUTARIA: TStringField; qryLocalizacaoISS_BASE: TFloatField; qryLocalizacaoISS_ALIQUOTA: TFloatField; qryLocalizacaoISS_VALOR: TFloatField; qryLocalizacaoICMS_BASE: TFloatField; qryLocalizacaoICMS_ALIQUOTA: TFloatField; qryLocalizacaoICMS_VALOR: TFloatField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoVLR_MERCADO: TFloatField; protected procedure MontaSQLBusca(DataSet :TDataSet = Nil); override; procedure MontaSQLRefresh; override; private FEmissora: String; FItem: Integer; FPedido: Real; FTipo: String; function GetSqlDefault: string; { Private declarations } public property Emissora :String read FEmissora write FEmissora; property Nro_Pedido :Real read FPedido write FPedido; property Tipo :String read FTipo write FTipo; property Item :Integer read FItem write FItem; function LocalizarPorPedido(DataSet: TDataSet = Nil) :Boolean; procedure ApagaItensPedido(FechaTransacao: Boolean = True); property SqlDefault: string read GetSqlDefault; end; CONST SQL_DEFAULT = 'SELECT IPED.FIL_PEDIDO,' + ' IPED.NRO_PEDIDO, ' + ' IPED.TIPO, ' + ' IPED.ITEM, ' + ' IPED.COD_PRODUTO, ' + ' IPED.DESCRICAO, ' + ' IPED.UNID, ' + ' IPED.QTD_ITEM, ' + ' IPED.VLR_PRODUTO, ' + ' IPED.VLR_SERVICO, ' + ' IPED.C_FISCAL, ' + ' IPED.S_TRIBUTARIA, ' + ' IPED.ISS_BASE, ' + ' IPED.ISS_ALIQUOTA, ' + ' IPED.ISS_VALOR, ' + ' IPED.ICMS_BASE, ' + ' IPED.ICMS_ALIQUOTA, ' + ' IPED.ICMS_VALOR, ' + ' IPED.DT_ALTERACAO, ' + ' IPED.OPERADOR, ' + ' PROD.VLR_MERCADO ' + ' FROM STWARMTIPED IPED' + ' LEFT JOIN STWARMTPROD PROD ON PROD.CODIGO = IPED.COD_PRODUTO'; var dmItensPedido: TdmItensPedido; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmPadrao2 } procedure TdmItensPedido.ApagaItensPedido(FechaTransacao: Boolean); begin with qryManipulacao do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE ( IPED.FIL_PEDIDO = :FIL_PEDIDO ) AND ( IPED.NRO_PEDIDO = :NRO_PEDIDO )'); Params[0].AsString := FEmissora; Params[1].AsFloat := FPedido; try ExecSQL; if FechaTransacao then dmPrincipal.ConexaoBanco.Commit; except on Error: EDAError do begin dmPrincipal.ConexaoNumerador.RollbackRetaining; TrataErrosIB(Error); end; end; end; end; function TdmItensPedido.GetSqlDefault: string; begin Result := SQL_DEFAULT; end; function TdmItensPedido.LocalizarPorPedido(DataSet: TDataSet): Boolean; begin if DataSet = Nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE ( IPED.FIL_PEDIDO = :FIL_PEDIDO ) AND ( IPED.NRO_PEDIDO = :NRO_PEDIDO )'); SQL.Add('ORDER BY IPED.FIL_PEDIDO, IPED.NRO_PEDIDO, IPED.TIPO, IPED.ITEM'); Params[0].AsString := FEmissora; Params[1].AsFloat := FPedido; Open; First; Result := Not IsEmpty; end; end; procedure TdmItensPedido.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TibcQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE ( IPED.FIL_PEDIDO = :FIL_PEDIDO ) AND ( IPED.NRO_PEDIDO = :NRO_PEDIDO ) AND ( IPED.TIPO = :TIPO ) AND ( IPED.ITEM = :ITEM )'); SQL.Add(' ORDER BY IPED.FIL_PEDIDO, IPED.NRO_PEDIDO, IPED.TIPO, ITEM'); Params[0].AsString := FEmissora; Params[1].AsFloat := FPedido; Params[2].AsString := FTipo; Params[3].AsInteger := FItem; end; end; procedure TdmItensPedido.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' ORDER BY IPED.FIL_PEDIDO, IPED.NRO_PEDIDO, IPED.TIPO, ITEM'); end; end; end.
unit uEstoque; interface uses System.SysUtils, FireDAC.Comp.Client; type tMovimentoEstoque = (tMovimentoEstoqueENTRADA, tMovimentoEstoqueSAIDA); procedure adicionarMovimentacaoEstoque(movimentacao: tMovimentoEstoque; codProduto: string; quantidade: integer; codComanda: string = ''); function verificarProdutoEmEstoque(codProduto: string; var qtdEntrada, qtdSaida, qtdTotal: integer; qntMinima: integer = 1): Boolean; function verificarProdutoMovimentaEstoque(codProduto: string): Boolean; implementation uses dmPrincipal, uConstantes, uData, uHora, uUsuario, uConsulta; function getCodigoMovimentacao(mvmtc: tMovimentoEstoque): string; begin case mvmtc of tMovimentoEstoqueENTRADA: Result := '1'; tMovimentoEstoqueSAIDA: Result := '2'; end; end; function verificarProdutoMovimentaEstoque(codProduto: string): Boolean; begin Result := buscarDado(conexaoSistema, 'RADIUS_PRODUTO', 'ID_PRODUTO', 'LG_CONTROLE_ESTOQUE', codProduto) = '1'; end; procedure adicionarMovimentacaoEstoque(movimentacao: tMovimentoEstoque; codProduto: string; quantidade: integer; codComanda: string = ''); const LINHA_SQL = 'INSERT INTO RADIUS_ESTOQUE (ID_MOVIMENTO, DATA_ESTOQUE, HORA_ESTOQUE, ID_USUARIO, ID_PRODUTO, QTD_ESTOQUE, ID_COMANDA) VALUES (%s, ''%s'', ''%s'', %s, %s, %d, %s);'; var dataMovimentacao: string[10]; horaMovimentacao: string[8]; begin dataMovimentacao := FormatDateTime('dd.mm.yyyy', getDataHoje); horaMovimentacao := FormatDateTime('hh.MM.SS', getHoraAgora); dmPrincipal.frmDmPrincipal.FDConnexao.ExecSQL (Format(LINHA_SQL, [getCodigoMovimentacao(movimentacao), dataMovimentacao, horaMovimentacao, getCodigoUsuario, codProduto, quantidade, codComanda])) end; // qntMinima = Parametro para que se verifique no banco se a quantidade do produto que tem no estoque é maior ou igual a "qnt mínima" que deverá ter em estoque function verificarProdutoEmEstoque(codProduto: string; var qtdEntrada, qtdSaida, qtdTotal: integer; qntMinima: integer = 1): Boolean; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'WITH TMP_ENTRADA AS (' + #13 + 'SELECT' + #13 + 'P.ID_PRODUTO AS "PRODUTO_ENTRADA",' + #13 + 'SUM(P.QTD_ESTOQUE) AS QTD_ENTRADA' + #13 + 'FROM RADIUS_ESTOQUE P' + #13 + 'WHERE P.ID_MOVIMENTO = 1' + #13 + 'GROUP BY 1' + #13 + '), TMP_SAIDA AS (' + #13 + 'SELECT' + #13 + 'Q.ID_PRODUTO AS "PRODUTO_SAIDA",' + #13 + 'SUM(Q.QTD_ESTOQUE) AS QTD_SAIDA' + #13 + 'FROM RADIUS_ESTOQUE Q' + #13 + 'INNER JOIN RADIUS_COMANDA N ON (N.ID_COMANDA = Q.ID_COMANDA)' + #13 + 'WHERE' + #13 + 'Q.ID_PRODUTO = 16' + #13 + 'AND Q.ID_MOVIMENTO = 2' + #13 + 'AND ((N.ID_CNC_CMD <> 1) OR (N.ID_CNC_CMD IS NULL))' + #13 + 'GROUP BY 1' + #13 + ')' + #13 + 'SELECT DISTINCT' + #13 + 'IIF(E.QTD_ENTRADA IS NULL, ''0'', E.QTD_ENTRADA) AS ENTRADA,' + #13 + 'IIF(S.QTD_SAIDA IS NULL, ''0'', S.QTD_SAIDA) AS SAIDA' + #13 + 'FROM RADIUS_ESTOQUE T' + #13 + 'INNER JOIN TMP_ENTRADA E ON (T.ID_PRODUTO = E.PRODUTO_ENTRADA)' + #13 + 'INNER JOIN RADIUS_PRODUTO R ON (R.ID_PRODUTO = T.ID_PRODUTO)' + #13 + 'LEFT JOIN TMP_SAIDA S ON (T.ID_PRODUTO = S.PRODUTO_SAIDA)' + #13 + 'WHERE' + #13 + 'T.ID_PRODUTO = ' + codProduto + #13 + 'AND R.LG_CONTROLE_ESTOQUE = 1'; dsConsulta := TFDQuery.Create(dmPrincipal.frmDmPrincipal.FDConnexao); dsConsulta.Connection := dmPrincipal.frmDmPrincipal.FDConnexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try qtdEntrada := StrToIntDef(dsConsulta.FieldByName('ENTRADA').AsString, 0); qtdSaida := StrToIntDef(dsConsulta.FieldByName('SAIDA').AsString, 0); qtdTotal := qtdEntrada - qtdSaida; Result := (qtdEntrada - qtdSaida) >= qntMinima; finally FreeAndNil(dsConsulta) end; end; end.
unit vos_win32_hw_monitor; interface uses Windows, MultiMon; type TDefaultMonitor = ( dmDesktop, dmPrimary, dmMainForm, dmActiveForm); TMonitorDefaultTo = (mdNearest, mdNull, mdPrimary); PVOS_Win32_HW_Monitor_Rec = ^TVOS_Win32_HW_Monitor_Rec; TVOS_Win32_HW_Monitor_Rec = packed record Handle : MultiMon.HMONITOR; end; PVOS_Win32_HW_Monitors_Rec = ^TVOS_Win32_HW_Monitors_Rec; TVOS_Win32_HW_Monitors_Rec = record MonitorCount : integer; Monitors : array[0..3] of TVOS_Win32_HW_Monitor_Rec; end; const MonitorDefaultFlags: array[TMonitorDefaultTo] of DWORD = (MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY); function MonitorGetWorkareaRect(AMonitor: PVOS_Win32_HW_Monitor_Rec): TRect; function MonitorGetBoundsRect(AMonitor: PVOS_Win32_HW_Monitor_Rec): TRect; function MonitorIsPrimary(AMonitor: PVOS_Win32_HW_Monitor_Rec): Boolean; procedure EnumMonitors(AMonitors: PVOS_Win32_HW_Monitors_Rec); implementation function MonitorGetWorkareaRect(AMonitor: PVOS_Win32_HW_Monitor_Rec): TRect; var MonInfo: TMonitorInfo; begin MonInfo.cbSize := SizeOf(MonInfo); MultiMon.GetMonitorInfo(AMonitor.Handle, @MonInfo); Result := MonInfo.rcWork; end; function MonitorGetBoundsRect(AMonitor: PVOS_Win32_HW_Monitor_Rec): TRect; var MonInfo: TMonitorInfo; begin MonInfo.cbSize := SizeOf(MonInfo); GetMonitorInfo(AMonitor.Handle, @MonInfo); Result := MonInfo.rcMonitor; end; function MonitorIsPrimary(AMonitor: PVOS_Win32_HW_Monitor_Rec): Boolean; var MonInfo: TMonitorInfo; begin MonInfo.cbSize := SizeOf(MonInfo); GetMonitorInfo(AMonitor.Handle, @MonInfo); Result := (MonInfo.dwFlags and MONITORINFOF_PRIMARY) <> 0; end; function EnumMonitorsProc(hm: HMONITOR; dc: HDC; r: PRect; Data: Pointer): Boolean; stdcall; var tmpMonitors: PVOS_Win32_HW_Monitors_Rec; begin tmpMonitors := Data; if nil <> tmpMonitors then begin if 4 > tmpMonitors.MonitorCount then begin tmpMonitors := PVOS_Win32_HW_Monitors_Rec(Data); tmpMonitors.Monitors[tmpMonitors.MonitorCount].Handle := hm; tmpMonitors.MonitorCount := tmpMonitors.MonitorCount + 1; Result := True; end else begin Result := False; end; end else begin Result := False; end; end; procedure EnumMonitors(AMonitors: PVOS_Win32_HW_Monitors_Rec); begin EnumDisplayMonitors(0, nil, @EnumMonitorsProc, LongInt(AMonitors)); end; end.
unit MFichas.Model.GrupoProduto.Metodos.Cadastrar; interface uses System.SysUtils, MFichas.Model.GrupoProduto.Interfaces, MFichas.Controller.Types; type TModelGrupoProdutoMetodosCadastrar = class(TInterfacedObject, iModelGrupoProdutoMetodosCadastrar) private [weak] FParent : iModelGrupoProduto; FDescricao: String; constructor Create(AParent: iModelGrupoProduto); procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelGrupoProduto): iModelGrupoProdutoMetodosCadastrar; function Descricao(ADescricao: String): iModelGrupoProdutoMetodosCadastrar; function &End : iModelGrupoProdutoMetodos; end; implementation { TModelGrupoProdutoMetodosCadastrar } function TModelGrupoProdutoMetodosCadastrar.&End: iModelGrupoProdutoMetodos; begin //TODO: IMPLEMENTAR MÉTODO DE CADASTRO DE GRUPOS. Result := FParent.Metodos; Gravar; end; procedure TModelGrupoProdutoMetodosCadastrar.Gravar; begin FParent.Entidade.DESCRICAO := FDescricao; FParent.Entidade.STATUS := Integer(saiAtivo); FParent.DAO.Insert(FParent.Entidade); end; constructor TModelGrupoProdutoMetodosCadastrar.Create(AParent: iModelGrupoProduto); begin FParent := AParent; end; function TModelGrupoProdutoMetodosCadastrar.Descricao( ADescricao: String): iModelGrupoProdutoMetodosCadastrar; begin Result := Self; if ADescricao.IsNullOrWhiteSpace(ADescricao) then raise Exception.Create( 'Não é possível cadastrar um grupo sem adicioná-lo um Nome/Descrição.' ); FDescricao := ADescricao.ToUpper; end; destructor TModelGrupoProdutoMetodosCadastrar.Destroy; begin inherited; end; class function TModelGrupoProdutoMetodosCadastrar.New(AParent: iModelGrupoProduto): iModelGrupoProdutoMetodosCadastrar; begin Result := Self.Create(AParent); end; end.
unit uPrincipal; 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 TForm1 = class(TForm) nbPrincipal: TNotebook; edNumero: TEdit; btnIniciar: TButton; lbTitulo: TLabel; Button3: TButton; lbResultado: TLabel; Panel1: TPanel; btnSomaImpar: TButton; btnSomaPar: TButton; procedure FormResize(Sender: TObject); procedure btnIniciarClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSomaImparClick(Sender: TObject); procedure btnSomaParClick(Sender: TObject); private { Private declarations } procedure RecalculaPosicoes; procedure CalculaPosicoes; function Soma(Impar:Boolean) : Currency; public { Public declarations } FPosicoes : TArray<Currency>; FNumeroInformado : Integer; end; var Form1: TForm1; implementation {$R *.dfm} { TForm1 } procedure TForm1.btnIniciarClick(Sender: TObject); var Num : Integer; begin if (Trim(edNumero.Text)<>'') then begin Num := StrToInt(edNumero.Text); if ((Num<100) or (Num>1000)) then begin ShowMessage('O número deve ser entre 100 e 1000'); Exit; end; if (not (Num mod 10 = 0)) then begin ShowMessage('O número deve ser múltiplo de 10'); Exit; end; FNumeroInformado := Num; nbPrincipal.PageIndex := 1; CalculaPosicoes; end; end; procedure TForm1.btnSomaImparClick(Sender: TObject); begin lbResultado.Caption := 'Resultado: ' + CurrToStr(Soma(True)); end; procedure TForm1.btnSomaParClick(Sender: TObject); begin lbResultado.Caption := 'Resultado: ' + CurrToStr(Soma(False)); end; procedure TForm1.Button3Click(Sender: TObject); begin nbPrincipal.PageIndex := 0; lbResultado.Caption := ''; edNumero.Text := ''; end; procedure TForm1.CalculaPosicoes; var Loop: Integer; begin SetLength(FPosicoes,0); SetLength(FPosicoes,10); for Loop := Low(FPosicoes) to High(FPosicoes) do begin if ((Loop+1) mod 3 = 0) then FPosicoes[Loop] := (Loop+1) * 30/100 * FNumeroInformado else FPosicoes[Loop] := (Loop+1) * 10/100 * FNumeroInformado end; end; procedure TForm1.FormCreate(Sender: TObject); begin nbPrincipal.PageIndex := 0; Self.Left:=Trunc((Screen.Width-Width) / 2); Self.Top:=Trunc((Screen.Height-Height) / 2); end; procedure TForm1.FormResize(Sender: TObject); begin RecalculaPosicoes end; procedure TForm1.RecalculaPosicoes; begin edNumero.Left := Trunc(Self.Width/2 - edNumero.Width/2); btnIniciar.Left := Trunc(Self.Width/2 - btnIniciar.Width/2); lbTitulo.Left := Trunc(Self.Width/2 - lbTitulo.Width/2); end; function TForm1.Soma(Impar: Boolean): Currency; var Loop: Integer; begin Result := 0; for Loop := Low(FPosicoes) to High(FPosicoes) do begin if (Impar) then begin if (not ((Loop+1) mod 2 = 0)) then Result := Result + FPosicoes[Loop]; end else begin if ((Loop+1) mod 2 = 0) then Result := Result + FPosicoes[Loop]; end; end; end; end.
unit Project1_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // $Rev: 52393 $ // File generated on 10.07.2019 10:11:26 from Type Library described below. // ************************************************************************ // // Type Lib: C:\Users\hieut\OneDrive\Документы\Embarcadero\Studio\Projects\TryDelphiV2\MyAppServer\Project1 (1) // LIBID: {74143191-CC5D-49E4-B560-91ACFD3E485D} // LCID: 0 // Helpfile: // HelpString: // DepndLst: // (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb) // (2) v1.0 Midas, (midas.dll) // (3) v4.0 StdVCL, (stdvcl40.tlb) // SYS_KIND: SYS_WIN32 // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Winapi.Windows, Midas, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleServer, Winapi.ActiveX; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions Project1MajorVersion = 1; Project1MinorVersion = 0; LIBID_Project1: TGUID = '{74143191-CC5D-49E4-B560-91ACFD3E485D}'; IID_IMyServer: TGUID = '{8A9AD366-C9F5-4E6A-B386-4E48A7869EC2}'; CLASS_MyServer: TGUID = '{501BC8B9-C934-4038-8DB9-B04A850245BA}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IMyServer = interface; IMyServerDisp = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// MyServer = IMyServer; // *********************************************************************// // Interface: IMyServer // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {8A9AD366-C9F5-4E6A-B386-4E48A7869EC2} // *********************************************************************// IMyServer = interface(IAppServer) ['{8A9AD366-C9F5-4E6A-B386-4E48A7869EC2}'] procedure smUpdateClient(ID: Integer; const Name: WideString; const Adress: WideString); safecall; procedure smDeleteClient(ID: Integer); safecall; procedure smUpdateProduct(ID: Integer; const Name: WideString; const Mg: WideString; VAT: Double); safecall; procedure smDeleteProduct(ID: Integer); safecall; procedure smUpdateFutura(ID: Integer; ClientID: Integer; TotalSum: Double); safecall; procedure smDeleteFutura(ID: Integer); safecall; procedure smUpdateFuturaInfo(FuturaID: Integer; ProductID: Integer; Quantity: Double; Price: Double); safecall; procedure smDeleteFuturaInfo(FuturaID: Integer; ProductID: Integer); safecall; procedure smSQLClear; safecall; procedure smSQLAddString(const s: WideString); safecall; procedure smSQLExecute; safecall; end; // *********************************************************************// // DispIntf: IMyServerDisp // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {8A9AD366-C9F5-4E6A-B386-4E48A7869EC2} // *********************************************************************// IMyServerDisp = dispinterface ['{8A9AD366-C9F5-4E6A-B386-4E48A7869EC2}'] procedure smUpdateClient(ID: Integer; const Name: WideString; const Adress: WideString); dispid 301; procedure smDeleteClient(ID: Integer); dispid 302; procedure smUpdateProduct(ID: Integer; const Name: WideString; const Mg: WideString; VAT: Double); dispid 303; procedure smDeleteProduct(ID: Integer); dispid 304; procedure smUpdateFutura(ID: Integer; ClientID: Integer; TotalSum: Double); dispid 305; procedure smDeleteFutura(ID: Integer); dispid 306; procedure smUpdateFuturaInfo(FuturaID: Integer; ProductID: Integer; Quantity: Double; Price: Double); dispid 307; procedure smDeleteFuturaInfo(FuturaID: Integer; ProductID: Integer); dispid 308; procedure smSQLClear; dispid 309; procedure smSQLAddString(const s: WideString); dispid 310; procedure smSQLExecute; dispid 311; function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: SYSINT; out ErrorCount: SYSINT; var OwnerData: OleVariant): OleVariant; dispid 20000000; function AS_GetRecords(const ProviderName: WideString; Count: SYSINT; out RecsOut: SYSINT; Options: SYSINT; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant): OleVariant; dispid 20000001; function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; dispid 20000002; function AS_GetProviderNames: OleVariant; dispid 20000003; function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; dispid 20000004; function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: SYSINT; var OwnerData: OleVariant): OleVariant; dispid 20000005; procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant); dispid 20000006; end; // *********************************************************************// // The Class CoMyServer provides a Create and CreateRemote method to // create instances of the default interface IMyServer exposed by // the CoClass MyServer. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoMyServer = class class function Create: IMyServer; class function CreateRemote(const MachineName: string): IMyServer; end; implementation uses System.Win.ComObj; class function CoMyServer.Create: IMyServer; begin Result := CreateComObject(CLASS_MyServer) as IMyServer; end; class function CoMyServer.CreateRemote(const MachineName: string): IMyServer; begin Result := CreateRemoteComObject(MachineName, CLASS_MyServer) as IMyServer; end; end.
unit LinkHistoWin; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, daTypes, DT_Types, Dt_Const, dt_AttrSchema, DT_Dict, DT_LinkServ, l3DatLst, l3Tree_TLB, l3Nodes, vtForm, OvcBase, vtlister, Menus, AdvMenus, ComCtrls, vtStatusBar, afwControl, afwInputControl, afwControlPrim, afwBaseControl; type TLinkHistoForm = class(TvtForm) lstHisto : TvtDStringlister; ListPopUpMenu: TPopupMenu; miInsertClassToObjList: TMenuItem; ListFooter: TvtStatusBar; procedure lstHistoCurrentChanged(Sender: TObject; aNewCurrent: Integer; aOldCurrent: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure miInsertClassToObjListClick(Sender: TObject); private fFamily : TdaFamilyID; fDictID : TdaDictionaryType; fHistList : Tl3DataList; procedure LoadList; function evntOnCompareItems(I, J : Longint) : Longint; protected procedure SetSpeedButton(Enabled : Boolean); override; function Copy : boolean; override; public constructor Create(aOwner : TComponent; aFamily : TdaFamilyID; aDictID : TdaDictionaryType); reintroduce; procedure Cleanup; override; end; implementation {$R *.dfm} Uses l3Base, l3Clipboard, l3Parser, l3Filer, l3Types, l3Stream, ObjList, StrShop, Main; constructor TLinkHistoForm.Create(aOwner : TComponent; aFamily : TdaFamilyID; aDictID : TdaDictionaryType); begin inherited Create(aOwner); fFamily := aFamily; fDictID := aDictID; LoadList; end; procedure TLinkHistoForm.Cleanup; begin l3Free(fHistList); inherited; end; procedure TLinkHistoForm.SetSpeedButton(Enabled : Boolean); begin If Application.Terminated then Exit; MainForm.acCopy .Enabled := Enabled; inherited; end; function TLinkHistoForm.evntOnCompareItems(I, J : Longint) : Longint; begin with fHistList do Result := PDictHistogramRec(Data[J])^.Count - PDictHistogramRec(Data[I])^.Count; end; procedure TLinkHistoForm.LoadList; var I : Integer; lRootNode : Il3Node; lCNode : Il3Node; lHistRec : PDictHistogramRec; lCurIdx : Integer; begin fHistList := Tl3DataList.Create; LinkServer(fFamily).GetHistogramOfDictElementUsing(fDictID, fHistList, 500); fHistList.OnCompareItems := evntOnCompareItems; fHistList.Sort; lstHisto.Items.HostDataList := fHistList; lstHisto.Items.NeedAllocStr := True; lRootNode := DictServer(fFamily).DictRootNode[fDictID]; for I := 0 to pred(lstHisto.Items.Count) do begin lHistRec := PDictHistogramRec(fHistList.Data[I]); DictServer(ffamily).DictTbl[fDictID].ItemList.FindData(lHistRec^.ID,lCurIdx); lCNode := TDictItem(DictServer(fFamily).DictTbl[fDictID].ItemList.Items[lCurIdx]).LinkNode; lstHisto.Items.Strings[I] := PansiChar(Format('[%d] %s', [lHistRec^.Count, l3GetFullPathStr(lRootNode, lCNode, #13, ' ')])); end; end; procedure TLinkHistoForm.lstHistoCurrentChanged(Sender: TObject; aNewCurrent: Integer; aOldCurrent: Integer); begin If lstHisto.Total > 0 then begin ListFooter.Panels[0].Text:=Format(scFmtFuterCounter,[Succ(aNewCurrent),lstHisto.Total]); ListFooter.Panels[1].Text:=Format(scFmtFuterID,[PDictHistogramRec(lstHisto.Items.Data[aNewCurrent])^.ID]); end else begin ListFooter.Panels[0].Text:=''; ListFooter.Panels[1].Text:=''; end; end; procedure TLinkHistoForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TLinkHistoForm.miInsertClassToObjListClick(Sender: TObject); var ItDataRec : TDictItemAddr; begin if lstHisto.Current = -1 then Exit; with ItDataRec do begin FamID := fFamily; DictID := Ord(fDictID); ItemID := PDictHistogramRec(lstHisto.Items.Data[lstHisto.Current])^.ID; end; // with ItDataRec do ArchiObjectList.AddObjRec(lstHisto.Items.Strings[lstHisto.Current], ddDictItem, @ItDataRec); end; function TLinkHistoForm.Copy : boolean; var lStream : Tl3ClipboardStream; lTextStream : Tl3TextStream; I : Longint; lString : AnsiString; begin lStream := Tl3ClipboardStream.Create(l3_fmWrite); try lTextStream := Tl3TextStream.Create(lStream); try with lTextStream do begin for I := 0 to Pred(lstHisto.Total) do begin lString := lstHisto.Items.Strings[I]+#13#10; Write(lString[1], Length(lString)); end; lString := #0; Write(lString[1], Length(lString)); end; finally l3Free(lTextStream); end; finally l3Free(lStream); end; end; end.
{*********************************************************} {* VPCLOCK.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} unit VpClock; {-clock component} {$I vp.inc} interface uses {$IFDEF LCL} LMessages,LCLProc,LCLType,LCLIntf, {$ELSE} Windows, Messages, {$ENDIF} Classes, Controls, Dialogs, Forms, Graphics, Menus,Math, SysUtils, VpBase, VpMisc, VpLEDLabel, VpTimerPool; type TVpPercent = 0..100; TVpClockMode = (cmClock, cmTimer, cmCountdownTimer); TVpClockDisplayMode = (dmAnalog, dmDigital); TVpLEDClockDisplay = class(TVpCustomLEDLabel) public procedure PaintSelf; end; TVpDigitalOptions = class(TPersistent) protected{private} FOwner : TComponent; FOnColor : TColor; FOffColor : TColor; FBgColor : TColor; FSize : TSegmentSize; FShowSeconds : Boolean; FFlashColon : Boolean; FOnChange : TNotifyEvent; F24Hour : Boolean; procedure Set24Hour(Value: Boolean); procedure SetOnColor(Value: TColor); procedure SetOffColor(Value: TColor); procedure SetBgColor(Value: TColor); procedure SetSize(Value: TSegmentSize); procedure SetShowSeconds(Value: Boolean); procedure DoOnChange; public constructor Create; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property MilitaryTime : Boolean read F24Hour write Set24Hour; property OnColor: TColor read FOnColor write SetOnColor; property OffColor: TColor read FOffColor write SetOffColor; property BgColor: TColor read FBgColor write SetBgColor; property Size: TSegmentSize read FSize write SetSize; property ShowSeconds: Boolean read FShowSeconds write SetShowSeconds; end; TVpHandOptions = class(TPersistent) protected {private} {property variables} FClockFace : TBitmap; FDrawMarks : Boolean; FHourHandColor : TColor; FHourHandLength : TVpPercent; FHourHandWidth : Integer; FMinuteHandColor : TColor; FMinuteHandLength : TVpPercent; FMinuteHandWidth : Integer; FSecondHandColor : TColor; FSecondHandLength : TVpPercent; FSecondHandWidth : Integer; FShowSecondHand : Boolean; FSolidHands : Boolean; {events variables} FOnChange : TNotifyEvent; {property methods} procedure SetClockFace(Value : TBitMap); procedure SetDrawMarks(Value : Boolean); procedure SetHourHandColor(Value : TColor); procedure SetHourHandLength(Value : TVpPercent); procedure SetHourHandWidth(Value : Integer); procedure SetMinuteHandColor(Value : TColor); procedure SetMinuteHandLength(Value : TVpPercent); procedure SetMinuteHandWidth(Value : Integer); procedure SetSecondHandColor(Value : TColor); procedure SetSecondHandLength(Value : TVpPercent); procedure SetSecondHandWidth(Value : Integer); procedure SetShowSecondHand(Value : Boolean); procedure SetSolidHands(Value : Boolean); {internal methods} procedure DoOnChange; public constructor Create; destructor Destroy; override; procedure Assign(Source : TPersistent); override; property OnChange : TNotifyEvent read FOnChange write FOnChange; published property ClockFace : TBitMap read FClockFace write SetClockFace; property DrawMarks : Boolean read FDrawMarks write SetDrawMarks; property HourHandColor : TColor read FHourHandColor write SetHourHandColor; property HourHandLength : TVpPercent read FHourHandLength write SetHourHandLength; property HourHandWidth : Integer read FHourHandWidth write SetHourHandWidth; property MinuteHandColor : TColor read FMinuteHandColor write SetMinuteHandColor; property MinuteHandLength : TVpPercent read FMinuteHandLength write SetMinuteHandLength; property MinuteHandWidth : Integer read FMinuteHandWidth write SetMinuteHandWidth; property SecondHandColor : TColor read FSecondHandColor write SetSecondHandColor; property SecondHandLength : TVpPercent read FSecondHandLength write SetSecondHandLength; property SecondHandWidth : Integer read FSecondHandWidth write SetSecondHandWidth; property ShowSecondHand : Boolean read FShowSecondHand write SetShowSecondHand; property SolidHands : Boolean read FSolidHands write SetSolidHands; end; TVpCustomClock = class(TVpCustomControl) protected {private} FTimerPool : TVpTimerPool; FActive : Boolean; FClockMode : TVpClockMode; FDigitalOptions : TVpDigitalOptions; FDisplayMode : TVpClockDisplayMode; FElapsedDays : Integer; FElapsedHours : Integer; FElapsedMinutes : LongInt; FElapsedSeconds : LongInt; FHandOptions : TVpHandOptions; FTime : TDateTime; FMilitaryTime : Boolean; FStartTime : TDateTime; FHourOffset : Integer; {Hours} FMinuteOffset : Integer; {Minutes} FSecondOffset : Integer; {Seconds} {event variables} FOnHourChange : TNotifyEvent; FOnMinuteChange : TNotifyEvent; FOnSecondChange : TNotifyEvent; FOnCountdownDone: TNotifyEvent; {internal variables} ckAnalogHeight : Integer; ckAnalogWidth : Integer; ckLEDDisplay : TVpLEDClockDisplay; ckDraw : TBitMap; ckClockHandle : Integer; ckOldHour : Integer; ckOldMinute : Integer; ckOldSecond : Integer; ckTimerTime : TDateTime; ckDays : Integer; ckHours : Integer; ckMinutes : Integer; ckSeconds : Integer; ckTotalSeconds : Integer; {property methods} function GetElapsedDays : Integer; function GetElapsedHours : Integer; function GetElapsedMinutes : LongInt; function GetElapsedSeconds : LongInt; function GetElapsedSecondsTotal : LongInt; procedure SetActive(Value : Boolean); procedure SetClockMode(Value : TVpClockMode); procedure SetDisplayMode(Value: TVpClockDisplayMode); procedure SetMinuteOffset(Value : Integer); procedure SetHourOffset(Value : Integer); procedure SetSecondOffset(Value : Integer); {internal methods} function ckConvertMsToDateTime(Value : LongInt) : TDateTime; procedure ckHandOptionChange(Sender : TObject); procedure ckDigitalOptionChange(Sender : TObject); procedure SizeDigitalDisplay; procedure ckTimerEvent(Sender : TObject; Handle : Integer; Interval : Cardinal; ElapsedTime : LongInt); procedure DoOnHourChange; procedure DoOnMinuteChange; procedure DoOnSecondChange; procedure DoOnCountdownDone; procedure PaintHands(ACanvas : TCanvas); {windows message methods} {$IFDEF LCL} procedure WMResize (var Msg: TLMSize); message LM_SIZE; procedure WMEraseBkgnd (var Msg : TLMEraseBkgnd); message LM_ERASEBKGND; {$ELSE} procedure WMResize (var Msg: TWMSize); message WM_SIZE; procedure WMEraseBkgnd (var Msg : TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMGetDlgCode (var Msg : TWMGetDlgCode); message WM_GETDLGCODE; {$ENDIF} protected procedure Loaded; override; procedure Paint; override; procedure PaintAnalog; procedure PaintDigital; {virtual property methods} procedure SetTime(Value : TDateTime); virtual; property Active : Boolean read FActive write SetActive; property ClockMode : TVpClockMode read FClockMode write SetClockMode; property DigitalOptions: TVpDigitalOptions read FDigitalOptions write FDigitalOptions; property AnalogOptions : TVpHandOptions read FHandOptions write FHandOptions; property MinuteOffset : Integer read FMinuteOffset write SetMinuteOffset; property HourOffset : Integer read FHourOffset write SetHourOffset; property SecondOffset: Integer read FSecondOffset write SetSecondOffset; {events} property OnHourChange : TNotifyEvent read FOnHourChange write FOnHourChange; property OnMinuteChange : TNotifyEvent read FOnMinuteChange write FOnMinuteChange; property OnSecondChange : TNotifyEvent read FOnSecondChange write FOnSecondChange; property OnCountdownDone : TNotifyEvent read FOnCountdownDone write FOnCountdownDone; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight : Integer); override; property DisplayMode: TVpClockDisplayMode read FDisplayMode write SetDisplayMode; property ElapsedDays : Integer read GetElapsedDays; property ElapsedHours : Integer read GetElapsedHours; property ElapsedMinutes : LongInt read GetElapsedMinutes; property ElapsedSeconds : LongInt read GetElapsedSeconds; property ElapsedSecondsTotal : LongInt read GetElapsedSecondsTotal; property Time : TDateTime read FTime write SetTime; end; TVpClock = class(TVpCustomClock) published {properties} {$IFDEF VERSION4} property Anchors; property Constraints; {$ENDIF} property Active; property Align; property Color; property ClockMode; property DigitalOptions; property DisplayMode; property Hint; property AnalogOptions; property MinuteOffset; property ParentColor; property ParentShowHint; property PopupMenu; property SecondOffset; property ShowHint; property HourOffset; property Visible; {events} property OnClick; property OnCountdownDone; property OnDblClick; property OnHourChange; property OnMinuteChange; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnSecondChange; end; implementation uses VpConst; const ckDToR = (Pi / 180); ckInterval = 500; {===== TVpLEDClockDisplay ===========================================} procedure TVpLEDClockDisplay.PaintSelf; begin Paint; end; {===== TVpDigitalOptions ============================================} constructor TVpDigitalOptions.Create; begin inherited Create; FSize := 2; FOnColor := clLime; FOffColor := $000E3432; FBgColor := clBlack; FShowSeconds := True; MilitaryTime := True; end; {=====} procedure TVpDigitalOptions.DoOnChange; begin if Assigned(FOnChange) then FOnChange(Self); end; {=====} procedure TVpDigitalOptions.Set24Hour(Value: Boolean); begin if F24Hour <> Value then begin F24Hour := Value; DoOnChange; end; end; {=====} procedure TVpDigitalOptions.SetOnColor(Value: TColor); begin if FOnColor <> Value then begin FOnColor := Value; DoOnChange; end; end; {=====} procedure TVpDigitalOptions.SetOffColor(Value: TColor); begin if FOffColor <> Value then begin FOffColor := Value; DoOnChange; end; end; {=====} procedure TVpDigitalOptions.SetBgColor(Value: TColor); begin if FBgColor <> Value then begin FBgColor := Value; DoOnChange; end; end; {=====} procedure TVpDigitalOptions.SetSize(Value: TSegmentSize); begin if FSize <> Value then begin FSize := Value; DoOnChange; end; end; {=====} procedure TVpDigitalOptions.SetShowSeconds(Value: Boolean); begin if FShowSeconds <> Value then begin FShowSeconds := Value; DoOnChange; end; end; {=====} {===== TVpHandOptions ===============================================} constructor TVpHandOptions.Create; begin inherited; FClockFace := TBitMap.Create; FDrawMarks := True; end; {=====} destructor TVpHandOptions.Destroy; begin FClockFace.Free; FClockFace := nil; inherited; end; {=====} procedure TVpHandOptions.Assign(Source : TPersistent); begin if Source is TVpHandOptions then begin FHourHandColor := TVpHandOptions(Source).FHourHandColor; FHourHandLength := TVpHandOptions(Source).FHourHandLength; FHourHandWidth := TVpHandOptions(Source).FHourHandWidth; FMinuteHandColor := TVpHandOptions(Source).FMinuteHandColor; FMinuteHandLength := TVpHandOptions(Source).FMinuteHandLength; FMinuteHandWidth := TVpHandOptions(Source).FMinuteHandWidth; FSecondHandColor := TVpHandOptions(Source).FSecondHandColor; FSecondHandLength := TVpHandOptions(Source).FSecondHandLength; FSecondHandWidth := TVpHandOptions(Source).FSecondHandWidth; FShowSecondHand := TVpHandOptions(Source).FShowSecondHand; FSolidHands := TVpHandOptions(Source).FSolidHands; FOnChange := TVpHandOptions(Source).FOnChange; end else inherited Assign(Source); end; {=====} procedure TVpHandOptions.SetClockFace(Value : TBitMap); begin if Assigned(Value) then FClockFace.Assign(Value) else begin FClockFace.Free; FClockFace := TBitmap.Create; end; FOnChange(self); end; {=====} procedure TVpHandOptions.SetDrawMarks(Value : Boolean); begin if Value <> FDrawMarks then begin FDrawMarks := Value; FOnChange(Self); end; end; {=====} procedure TVpHandOptions.DoOnChange; begin if Assigned(FOnChange) then FOnChange(Self); end; {=====} procedure TVpHandOptions.SetHourHandColor(Value : TColor); begin if Value <> FHourHandColor then begin FHourHandColor := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetHourHandLength(Value : TVpPercent); begin if Value <> FHourHandLength then begin FHourHandLength := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetHourHandWidth(Value : Integer); begin if (Value <> FHourHandWidth) and (Value > 0) then begin FHourHandWidth := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetMinuteHandColor(Value : TColor); begin if Value <> FMinuteHandColor then begin FMinuteHandColor := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetMinuteHandLength(Value : TVpPercent); begin if Value <> FMinuteHandLength then begin FMinuteHandLength := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetMinuteHandWidth(Value : Integer); begin if (Value <> FMinuteHandWidth) and (Value > 0) then begin FMinuteHandWidth := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetSecondHandColor(Value : TColor); begin if Value <> FSecondHandColor then begin FSecondHandColor := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetSecondHandLength(Value : TVpPercent); begin if Value <> FSecondHandLength then begin FSecondHandLength := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetSecondHandWidth(Value : Integer); begin if (Value <> FSecondHandWidth) and (Value > 0) then begin FSecondHandWidth := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetShowSecondHand(Value : Boolean); begin if Value <> FShowSecondHand then begin FShowSecondHand := Value; DoOnChange; end; end; {=====} procedure TVpHandOptions.SetSolidHands(Value : Boolean); begin if Value <> FSolidHands then begin FSolidHands := Value; DoOnChange; end; end; {===== TOvcCustomClock ===============================================} constructor TVpCustomClock.Create(AOwner : TComponent); begin inherited Create(AOwner); Width := 136; Height := 136; FClockMode := cmClock; FTimerPool := TVpTimerPool.Create(self); FHandOptions := TVpHandOptions.Create; FHandOptions.OnChange := ckHandOptionChange; FHandOptions.HourHandColor := clBlack; FHandOptions.HourHandLength := 60; FHandOptions.HourHandWidth := 4; FHandOptions.MinuteHandColor := clBlack; FHandOptions.MinuteHandLength := 80; FHandOptions.MinuteHandWidth := 3; FHandOptions.SecondHandColor := clRed; FHandOptions.SecondHandLength := 90; FHandOptions.SecondHandWidth := 1; FHandOptions.ShowSecondHand := True; FHandOptions.FSolidHands := True; FDigitalOptions := TVpDigitalOptions.Create; FDigitalOptions.FOnChange := ckDigitalOptionChange; ckDraw := TBitMap.Create; ckDraw.Width := Width; ckDraw.Height := Height; ckClockHandle := -1; end; {=====} destructor TVpCustomClock.Destroy; begin Active := False; FHandOptions.Free; FHandOptions := nil; FDigitalOptions.Free; FDigitalOptions := nil; ckDraw.Free; ckDraw := nil; inherited Destroy; end; {=====} function TVpCustomClock.ckConvertMsToDateTime(Value : LongInt) : TDateTime; var S, Days : LongInt; Hour, Minute, Second : Word; begin S := Value div 1000; Days := S div SecondsInDay; S := S mod SecondsInDay; Hour := S div SecondsInHour; S := S mod SecondsInHour; Minute := S div SecondsInMinute; Second := S mod SecondsInMinute; Result := EncodeTime(Hour, Minute, Second, 0) + Days; end; {=====} procedure TVpCustomClock.ckHandOptionChange(Sender : TObject); begin if FDisplayMode = dmAnalog then Invalidate; end; {=====} procedure TVpCustomClock.ckDigitalOptionChange(Sender : TObject); begin if FDisplayMode = dmDigital then begin ckLEDDisplay.Size := FDigitalOptions.Size; ckLEDDisplay.BgColor := FDigitalOptions.BgColor; ckLEDDisplay.OnColor := FDigitalOptions.OnColor ; ckLEDDisplay.OffColor := FDigitalOptions.OffColor; FMilitaryTime := FDigitalOptions.MilitaryTime; if FDigitalOptions.ShowSeconds and FMilitaryTime then ckLEDDisplay.Columns := 8 else if FDigitalOptions.ShowSeconds and not FMilitaryTime then ckLEDDisplay.Columns := 11 else if not FDigitalOptions.ShowSeconds and FMilitaryTime then ckLEDDisplay.Columns := 5 else if not FDigitalOptions.ShowSeconds and not FMilitaryTime then ckLEDDisplay.Columns := 8; SizeDigitalDisplay; Invalidate; end; end; {=====} procedure TVpCustomClock.SizeDigitalDisplay; begin Width := ckLEDDisplay.Width; Height := ckLEDDisplay.Height; end; {=====} procedure TVpCustomClock.ckTimerEvent(Sender : TObject; Handle : Integer; Interval : Cardinal; ElapsedTime : LongInt); var Hour, Minute, Second, MSecond : Word; C, D : Integer; begin if FClockMode = cmClock then begin {Clock} DecodeTime(Now, Hour, Minute, Second, MSecond); D := Minute + FMinuteOffset; Minute := Abs(D mod 60); C := Hour + FHourOffset + (D div 60); if C > 23 then Dec(C, 24); if C < 0 then Inc(C, 24); Hour := C; SetTime(EncodeTime(Hour, Minute, Second, MSecond)); end else if FClockMode = cmTimer then begin {Count Up Timer} SetTime(ckConvertMsToDateTime(ElapsedTime)); end else begin {Countdown Timer} if (FStartTime - ckConvertMsToDateTime(ElapsedTime) <= 0) then begin SetTime(0); Active := false; DoOnCountdownDone; end else SetTime(FStartTime - ckConvertMsToDateTime(ElapsedTime)); end; end; {=====} procedure TVpCustomClock.DoOnHourChange; begin if Assigned(FOnHourChange) then FOnHourChange(Self); end; {=====} procedure TVpCustomClock.DoOnMinuteChange; begin if Assigned(FOnMinuteChange) then FOnMinuteChange(Self); end; {=====} procedure TVpCustomClock.DoOnSecondChange; begin if Assigned(FOnSecondChange) then FOnSecondChange(Self); end; {=====} procedure TVpCustomClock.DoOnCountdownDone; begin if Assigned (FOnCOuntdownDone) then FOnCountdownDone(self); end; {=====} function TVpCustomClock.GetElapsedDays: Integer; var ClockDate : TDateTime; begin if ckClockHandle > -1 then begin ClockDate := ckConvertMsToDateTime(FTimerPool.ElapsedTime[ckClockHandle]); ckDays := Trunc(ClockDate); end; Result := ckDays; end; {=====} function TVpCustomClock.GetElapsedHours: Integer; var Hour : Word; Min : Word; Sec : Word; MSec : Word; TempTime : TDateTime; begin if ckClockHandle > -1 then begin TempTime := ckConvertMsToDateTime(FTimerPool.ElapsedTime[ckClockHandle]); DecodeTime(TempTime, Hour, Min, Sec, MSec); ckHours := Hour end; Result := ckHours; end; {=====} function TVpCustomClock.GetElapsedMinutes: LongInt; var Hour : Word; Min : Word; Sec : Word; MSec : Word; TempTime : TDateTime; begin if ckClockHandle > -1 then begin TempTime := ckConvertMsToDateTime(FTimerPool.ElapsedTime[ckClockHandle]); DecodeTime(TempTime, Hour, Min, Sec, MSec); ckMinutes := Min; end; Result := ckMinutes; end; {=====} function TVpCustomClock.GetElapsedSeconds : LongInt; var Hour : Word; Min : Word; Sec : Word; MSec : Word; TempTime : TDateTime; begin if ckClockHandle > -1 then begin TempTime := ckConvertMsToDateTime(FTimerPool.ElapsedTime[ckClockHandle]); DecodeTime(TempTime, Hour, Min, Sec, MSec); ckSeconds := Sec; end; Result := ckSeconds; end; {=====} function TVpCustomClock.GetElapsedSecondsTotal : LongInt; begin if ckClockHandle > -1 then ckTotalSeconds := FTimerPool.ElapsedTime[ckClockHandle] div 1000; Result := ckTotalSeconds; end; {=====} procedure TVpCustomClock.Loaded; var HA : Boolean; begin inherited Loaded; ckHandOptionChange(self); ckDigitalOptionChange(self); HA := FActive; FActive := False; SetActive(HA); end; {=====} procedure TVpCustomClock.Paint; begin case FDisplayMode of dmDigital : PaintDigital; dmAnalog : PaintAnalog; end; end; {=====} procedure TVpCustomClock.PaintDigital; begin ckLEDDisplay.PaintSelf; end; {=====} procedure TVpCustomClock.PaintAnalog; var HalfWidth : Integer; HalfHeight : Integer; Lcv : Integer; MarkX : Integer; MarkY : Integer; MarkAngle : Double; ElRgn : HRgn; R : TRect; procedure DrawTickMark(MarkX, MarkY : Integer; LColor, MColor, RColor : TColor; FiveMinute : Boolean); begin with ckDraw.Canvas do begin Pixels[MarkX, MarkY] := MColor; Pixels[MarkX-1, MarkY-1] := LColor; Pixels[MarkX, MarkY-1] := LColor; Pixels[MarkX-1, MarkY] := LColor; Pixels[MarkX+1, MarkY+1] := RColor; Pixels[MarkX+1, MarkY] := RColor; Pixels[MarkX, MarkY+1] := RColor; if (FiveMinute) then begin Pixels[MarkX-1, MarkY+1] := LColor; Pixels[MarkX+1, MarkY-1] := RColor; end; end; end; begin with ckDraw.Canvas do begin Brush.Color := Color; Pen.Color := FHandOptions.HourHandColor; Pen.Width := 1; FillRect(ClientRect); if not (FHandOptions. ClockFace.Empty) then begin R := ClientRect; if FHandOptions.DrawMarks then InflateRect(R, -3, -3); ElRgn := CreateEllipticRgn(R.Left, R.Top, R.Right, R.Bottom); try SelectClipRgn(ckDraw.Canvas.Handle, ElRgn); StretchDraw(R, FHandOptions.ClockFace); finally DeleteObject(ElRgn); end; SelectClipRgn(ckDraw.Canvas.Handle, 0);{remove clipping region} end; {draw marks} if FHandOptions.DrawMarks then begin with ClientRect do begin HalfWidth := (Right - Left) shr 1; HalfHeight := (Bottom - Top) shr 1; end; if HalfWidth < 1 then HalfWidth := 1; if HalfHeight < 1 then HalfHeight := 1; for Lcv := 0 to 59 do begin MarkAngle := ckDToR * (((Round((Lcv / 60) * 360)) + 90) mod 360); MarkX := Round(HalfWidth * (1 - (((100 - 2) / 100) * Cos(MarkAngle)))); MarkY := Round(HalfHeight * (1 - (((100 - 2) / 100) * Sin(MarkAngle)))); MoveTo(MarkX, MarkY); if Lcv mod 5 = 0 then DrawTickMark(MarkX, MarkY, clBlue, clGray, clBlack, True) else DrawTickMark(MarkX, MarkY, clGray, clSilver, clWhite, False); end; end; end; PaintHands(ckDraw.Canvas); Canvas.CopyMode := cmSrcCopy; Canvas.CopyRect(ClientRect, ckDraw.Canvas, ClientRect); end; {=====} procedure TVpCustomClock.PaintHands(ACanvas : TCanvas); type HandType = (HourHand, MinuteHand, SecondHand); var X : Integer; Hour : Word; Minute : Word; Second : Word; MSecond : Word; HalfWidth : Integer; HalfHeight : Integer; HandBase : Integer; HandAngle : Double; HourHandLen : Integer; MinuteHandLen : Integer; SecondHandLen : Integer; procedure RotatePoint(OldPoint : TPoint; var NewPoint : TPoint); begin OldPoint.X := OldPoint.X - HalfWidth; OldPoint.Y := OldPoint.Y - HalfHeight; NewPoint.X := Round(OldPoint.X * Cos(HandAngle-Pi/2) - OldPoint.Y * Sin(HandAngle-Pi/2)); NewPoint.Y := Round(OldPoint.X * Sin(HandAngle-Pi/2) + OldPoint.Y * Cos(HandAngle-Pi/2)); if (HalfHeight < HalfWidth) then NewPoint.X := Round(NewPoint.X * (HalfWidth/HalfHeight)) else NewPoint.Y := Round(NewPoint.Y * (HalfHeight/HalfWidth)); NewPoint.X := NewPoint.X + HalfWidth; NewPoint.Y := NewPoint.Y + HalfHeight; end; procedure DrawNewHand(PenColor : TColor; Hand : HandType; HandLength : Integer; HipWidth : Integer); const MaxPoints = 7; var I : Integer; Hip : Integer; Points : array[1..MaxPoints] of TPoint; HandPoints : array[1..MaxPoints] of TPoint; procedure ShadeHand; Var CPoints : array[1..3] of TPoint; procedure LoadPoints(Pt1, Pt2, Pt3 : Integer); begin CPoints[1] := HandPoints[Pt1]; CPoints[2] := HandPoints[Pt2]; CPoints[3] := HandPoints[Pt3]; ACanvas.Polygon(CPoints); end; begin ACanvas.Brush.Color := clWhite; case Hand of HourHand : begin case Hour of 0..3, 12..15 : begin LoadPoints(2,3,4); LoadPoints(1,2,4); end; 4..5, 16..17 : begin LoadPoints(1,2,4); LoadPoints(1,2,6); end; 6..9, 18..21 : begin LoadPoints(1,2,6); LoadPoints(2,3,6); end; 10..11, 22..23 : begin LoadPoints(2,3,4); LoadPoints(2,3,6); end; end; end; MinuteHand: begin case Minute of 0..15 : begin LoadPoints(2,3,4); LoadPoints(1,2,4); end; 16..25: begin LoadPoints(1,2,4); LoadPoints(1,2,6); end; 26..50: begin LoadPoints(1,2,6); LoadPoints(2,3,6); end; 51..59: begin LoadPoints(2,3,4); LoadPoints(2,3,6); end; end; end; SecondHand: begin case Second of 0..15 : begin LoadPoints(2,3,4); LoadPoints(1,2,4); end; 16..25: begin LoadPoints(1,2,4); LoadPoints(1,2,6); end; 26..50: begin LoadPoints(1,2,6); LoadPoints(2,3,6); end; 51..59: begin LoadPoints(2,3,4); LoadPoints(2,3,6); end; end; end; end; ACanvas.Brush.Color := Color; end; begin {where to put Crossbar} if HipWidth > 1 then Hip := Trunc(HandLength * 0.25) else Hip := 0; {start at Center Point} Points[1].X := HalfWidth; Points[1].Y := HalfHeight; {up Center to Hip} Points[2].X := HalfWidth; Points[2].Y := HalfHeight-Hip; {up Center to Top} Points[3].X := HalfWidth; Points[3].Y := HalfHeight-HandLength; {angle Left} Points[4].X := HalfWidth-HipWidth; Points[4].Y := HalfHeight - Hip; {start at Center Point} Points[5].X := HalfWidth; Points[5].Y := HalfHeight; {angle Left} Points[6].X := HalfWidth+HipWidth; Points[6].Y := HalfHeight - Hip; {up Center to Top} Points[7].X := HalfWidth; Points[7].Y := HalfHeight-HandLength; for I :=1 to 7 do RotatePoint(Points[I], HandPoints[I]); ACanvas.Pen.Width := 1; ACanvas.Pen.Color := PenColor; if FHandOptions.SolidHands then ACanvas.Brush.Color := PenColor else ACanvas.Brush.Color := Color; ACanvas.MoveTo(HalfWidth, HalfHeight); ACanvas.Polygon(HandPoints); if not FHandOptions.SolidHands then ShadeHand; end; begin DecodeTime(FTime, Hour, Minute, Second, MSecond); HalfWidth := (ClientRect.Right - ClientRect.Left) shr 1; HalfHeight := (ClientRect.Bottom - ClientRect.Top) shr 1; if HalfWidth < 1 then HalfWidth := 1; if HalfHeight < 1 then HalfHeight := 1; {based on the Height or Width of the Clock, set the Hand Lengths} HandBase := Min(HalfWidth, HalfHeight); HourHandLen := Trunc(HandBase * FHandOptions.HourHandLength / 100); MinuteHandLen := Trunc(HandBase * FHandOptions.MinuteHandLength / 100); SecondHandLen := Trunc(HandBase * FHandOptions.SecondHandLength / 100); HandAngle := ckDToR * (((Round((((Hour * 5) + (Minute div 12)) / 60) * 360)) + 90) mod 360); DrawNewHand(FHandOptions.HourHandColor, HourHand, HourHandLen, FHandOptions.HourHandWidth); HandAngle := ckDToR * (((Round((Minute / 60) * 360)) + 90) mod 360); DrawNewHand(FHandOptions.MinuteHandColor, MinuteHand, MinuteHandLen, FHandOptions.MinuteHandWidth); if (FHandOptions.ShowSecondHand) then begin HandAngle := ckDToR * (((Round((Second / 60) * 360)) + 90) mod 360); DrawNewHand(FHandOptions.SecondHandColor, SecondHand, SecondHandLen, FHandOptions.SecondHandWidth); end; if FHandOptions.ShowSecondHand then ACanvas.Brush.Color := FHandOptions.SecondHandColor else ACanvas.Brush.Color := FHandOptions.MinuteHandColor; ACanvas.Pen.Color := clBlack; X := Round(HandBase * 0.04) + 1; ACanvas.Ellipse(HalfWidth-X, HalfHeight-X, HalfWidth+X, HalfHeight+X); end; {=====} procedure TVpCustomClock.SetActive(Value : Boolean); begin if csLoading in ComponentState then begin FActive := Value; Exit; end; if Value <> FActive then begin FActive := Value; if FActive then begin if FDisplayMode = dmDigital then FMilitaryTime := DigitalOptions.MilitaryTime; if ckClockHandle = -1 then ckClockHandle := FTimerPool.Add(ckTimerEvent, ckInterval); if FClockMode = cmClock then FTime := Now else if FClockMode = cmCountdownTimer then FStartTime := EncodeTime(FHourOffset, FMinuteOffset, FSecondOffset, 0) else FTime := 0; end else if ckClockHandle > -1 then begin FTimerPool.Remove(ckClockHandle); ckClockHandle := -1; end; Invalidate; end; end; {=====} procedure TVpCustomClock.SetBounds(ALeft, ATop, AWidth, AHeight : Integer); begin inherited SetBounds(ALeft, ATop, AWidth, AHeight); if Assigned(ckDraw) then begin ckDraw.Width := AWidth; ckDraw.Height := AHeight; end; Invalidate; end; {=====} procedure TVpCustomClock.SetClockMode(Value : TVpClockMode); begin if Value <> FClockMode then begin if FActive then Active := false; FClockMode := Value; if FClockMode = cmClock then DigitalOptions.MilitaryTime := false else DigitalOptions.MilitaryTime := true; if FClockMode <> cmCountdownTimer then FTime := 0 else SetTime(EncodeTime(FHourOffset, FMinuteOffset, 0, 0)); Invalidate; end; end; {=====} procedure TVpCustomClock.SetDisplayMode(Value: TVpClockDisplayMode); begin if Value <> FDisplayMode then begin FDisplayMode := Value; case FDisplayMode of dmDigital: begin {Save the analog height and width} ckAnalogHeight := Height; ckAnalogWidth := Width; {Create and initialize the LED display} ckLEDDisplay := TVpLEDClockDisplay.Create(self); ckLEDDisplay.Parent := self; ckLEDDisplay.OnColor := FDigitalOptions.OnColor; ckLEDDisplay.OffColor := FDigitalOptions.OffColor; ckLEDDisplay.BgColor := FDigitalOptions.BgColor; ckLEDDisplay.Size := FDigitalOptions.Size; if FDigitalOptions.ShowSeconds then begin ckLEDDisplay.Columns := 8; ckLEDDisplay.Caption := '00:00:00'; end else begin ckLEDDisplay.Columns := 5; ckLEDDisplay.Caption := '00:00'; end; {Set the height and width of the control} SizeDigitalDisplay; {Blank the control} Canvas.Brush.Color := FDigitalOptions.BgColor; Canvas.FillRect(GetClientRect); {Initialize the LED display} if FActive then begin if FClockMode = cmClock then {Clock} SetTime(Now) else if FClockMode = cmTimer then {Timer} SetTime(ckConvertMsToDateTime(FElapsedSeconds * 1000)) else {Countdown Timer} if (FStartTime - ckConvertMsToDateTime( FElapsedSeconds * 1000) <= 0) then begin SetTime(0); Active := false; DoOnCountdownDone; end else SetTime(FStartTime - ckConvertMsToDateTime(FElapsedSeconds * 1000)); end; end; dmAnalog: begin {Destroy the LED Display} if ckLEDDisplay <> nil then begin ckLEDDisplay.Free; ckLEDDisplay := nil; end; {Adjust the height and width} if (ckAnalogHeight < ckAnalogWidth) then begin {If the analog clock is shorted than it is wide then load default } {height and width } Height := 136; Width := 136; end else begin {Otherwise reload saved values} Height := ckAnalogHeight; Width := ckAnalogWidth; end; {Blank the canvas} with ckDraw.Canvas do begin Brush.Color := Color; FillRect(ClientRect); Canvas.CopyMode := cmSrcCopy; Canvas.CopyRect(ClientRect, ckDraw.Canvas, ClientRect); end; end; end; Invalidate; end; end; {=====} procedure TVpCustomClock.SetTime(Value : TDateTime); var Hour1, Minute1, Second1 : Word; Hour2, Minute2, Second2 : Word; MSecond : Word; TimeStr: string; begin DecodeTime(Value, Hour1, Minute1, Second1, MSecond); DecodeTime(FTime, Hour2, Minute2, Second2, MSecond); if (Hour1 <> Hour2) or (Minute1 <> Minute2) or (Second1 <> Second2) then begin FTime := Value; if (Hour1 <> ckOldHour) then DoOnHourChange; ckOldHour := Hour1; if (Minute1 <> ckOldMinute) then DoOnMinuteChange; ckOldMinute := Minute1; if (Second1 <> ckOldSecond) then DoOnSecondChange; ckOldSecond := Second1; if DisplayMode = dmDigital then begin if FDigitalOptions.ShowSeconds and FMilitaryTime then TimeStr := FormatDateTime('hh:mm:ss', FTime) else if FDigitalOptions.ShowSeconds and not FMilitaryTime then TimeStr := FormatDateTime('hh:mm:ss am/pm', FTime) else if not FDigitalOptions.ShowSeconds and FMilitaryTime then TimeStr := FormatDateTime('hh:mm', FTime) else if not FDigitalOptions.ShowSeconds and not FMilitaryTime then TimeStr := FormatDateTime('hh:mm am/pm', FTime); ckLEDDisplay.Caption := TimeStr; end; Invalidate; end; end; {=====} procedure TVpCustomClock.SetMinuteOffset(Value : Integer); begin if (Value <> FMinuteOffset) and (Abs(Value) <= 60) then begin FMinuteOffset := Value; if FClockMode = cmCountdownTimer then SetTime(EncodeTime(FHourOffset, FMinuteOffset, FSecondOffset, 0)); Invalidate; end; end; {=====} procedure TVpCustomClock.SetHourOffset(Value : Integer); begin if (Value <> FHourOffset) and (Abs(Value) <= 24) then begin FHourOffset := Value; if FClockMode = cmCountdownTimer then SetTime(EncodeTime(FHourOffset, FMinuteOffset, FSecondOffset, 0)); Invalidate; end; end; {=====} procedure TVpCustomClock.SetSecondOffset(Value : Integer); begin if (Value <> FSecondOffset) and (Abs(Value) <= 59) then begin FSecondOffset := Value; if FClockMode = cmCountdownTimer then SetTime(EncodeTime(FHourOffset, FMinuteOffset, FSecondOffset, 0)); Invalidate; end; end; {=====} {$IFNDEF LCL} procedure TVpCustomClock.WMResize(var Msg: TWMSize); {$ELSE} procedure TVpCustomClock.WMResize(var Msg: TLMSize); {$ENDIF} begin if DisplayMode = dmDigital then begin Width := ckLEDDisplay.Width; Height := ckLEDDisplay.Height; Invalidate; end; end; {$IFNDEF LCL} procedure TVpCustomClock.WMEraseBkgnd(var Msg : TWMEraseBkGnd); {$ELSE} procedure TVpCustomClock.WMEraseBkgnd(var Msg : TLMEraseBkGnd); {$ENDIF} begin Msg.Result := 1; end; {=====} {$IFNDEF LCL} procedure TVpCustomClock.WMGetDlgCode(var Msg : TWMGetDlgCode); begin {tell windows we are a static control to avoid receiving the focus} Msg.Result := DLGC_STATIC; end; {$ENDIF} {=====} end.
unit Atsargos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinOffice2007Black, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxButtonEdit, System.Actions, Vcl.ActnList, cxDropDownEdit, cxHyperLinkEdit, dxSkinsdxBarPainter, dxBar, Vcl.ImgList, dxBarExtItems, cxPCdxBarPopupMenu, cxPC, Vcl.Menus, dxLayoutControlAdapters, dxLayoutContainer, Vcl.StdCtrls, cxButtons, dxLayoutControl, dxLayoutcxEditAdapters, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, cxTextEdit, cxMaskEdit, cxCalendar, cxPropertiesStore; type TfrmAtsargos = class(TForm) cxgr_AtsargosFakt: TcxGrid; gtv_AtsargosFakt: TcxGridDBTableView; cxgr_AtsargosFaktLevel1: TcxGridLevel; gtv_AtsargosFaktVieta: TcxGridDBColumn; gtv_AtsargosFaktPrekesKodas: TcxGridDBColumn; gtv_AtsargosFaktPrekGrupeEN: TcxGridDBColumn; gtv_AtsargosFaktZaliavuFormaEN: TcxGridDBColumn; gtv_AtsargosFaktSpalvaEN: TcxGridDBColumn; gtv_AtsargosFaktIpakavimoFormaEN: TcxGridDBColumn; gtv_AtsargosFaktKiekis: TcxGridDBColumn; gtv_AtsargosFaktMatVienetasEN: TcxGridDBColumn; gtv_AtsargosFaktSvoris: TcxGridDBColumn; gtv_AtsargosFaktDoctype: TcxGridDBColumn; gtv_AtsargosFaktDokumentoNr: TcxGridDBColumn; gtv_AtsargosFaktPardavejoKodas: TcxGridDBColumn; gtv_AtsargosFaktPardavejoPavad: TcxGridDBColumn; ActionList1: TActionList; gtv_AtsargosFaktLOTnumber: TcxGridDBColumn; acrAtnaujinti: TAction; imglist_Operacijos: TcxImageList; sp_Atsargos_Fakt_by_Date: TFDStoredProc; sp_Atsargos_Fakt_by_DateVieta: TWideStringField; sp_Atsargos_Fakt_by_DatePrekesKodas: TIntegerField; sp_Atsargos_Fakt_by_DatePrekGrupeEN: TWideStringField; sp_Atsargos_Fakt_by_DateZaliavuFormaEN: TWideStringField; sp_Atsargos_Fakt_by_DateSpalvaEN: TWideStringField; sp_Atsargos_Fakt_by_DateIpakavimoFormaEN: TWideStringField; sp_Atsargos_Fakt_by_DateKiekis: TFloatField; sp_Atsargos_Fakt_by_DateMatVienetasEN: TWideStringField; sp_Atsargos_Fakt_by_DateSvoris: TFloatField; sp_Atsargos_Fakt_by_DateDoctype: TStringField; sp_Atsargos_Fakt_by_DateDokKeyFieldID: TIntegerField; sp_Atsargos_Fakt_by_DateDokumentoNr: TIntegerField; sp_Atsargos_Fakt_by_DatePardavejoID: TIntegerField; sp_Atsargos_Fakt_by_DatePardavejoKodas: TWideStringField; sp_Atsargos_Fakt_by_DatePardavejoPavad: TWideStringField; sp_Atsargos_Fakt_by_DateLOTnumber: TIntegerField; sp_Atsargos_Fakt_by_DateLotID: TIntegerField; sp_Atsargos_Fakt_by_DateVietosID: TIntegerField; sp_Atsargos_Fakt_by_DatePrekesID: TIntegerField; ds_sp_Atsargos_Fakt_by_Date: TDataSource; cxPageControl1: TcxPageControl; ts_Fakt: TcxTabSheet; ts_Plan: TcxTabSheet; cxgr_AtsargosPlan: TcxGrid; gtv_AtsargosPlan: TcxGridDBTableView; gtv_AtsargosPlan_Vieta: TcxGridDBColumn; gtv_AtsargosPlan_LOTnumber: TcxGridDBColumn; gtv_AtsargosPlan_PrekesKodas: TcxGridDBColumn; gtv_AtsargosPlan_PrekGrupeEN: TcxGridDBColumn; gtv_AtsargosPlan_ZaliavuFormaEN: TcxGridDBColumn; gtv_AtsargosPlan_SpalvaEN: TcxGridDBColumn; gtv_AtsargosPlan_IpakavimoFormaEN: TcxGridDBColumn; gtv_AtsargosPlan_PlanKiekis: TcxGridDBColumn; gtv_AtsargosPlan_MatVienetasEN: TcxGridDBColumn; gtv_AtsargosPlan_PlanSvoris: TcxGridDBColumn; gtv_AtsargosPlan_Doctype: TcxGridDBColumn; gtv_AtsargosPlan_DokumentoNr: TcxGridDBColumn; gtv_AtsargosPlan_PardavejoKodas: TcxGridDBColumn; gtv_AtsargosPlan_PardavejoPavad: TcxGridDBColumn; cxgr_AtsargosPlanLevel1: TcxGridLevel; sp_Atsargos_Plan_by_Date: TFDStoredProc; ds_sp_Atsargos_Plan_by_Date: TDataSource; sp_Atsargos_Plan_by_DateVieta: TWideStringField; sp_Atsargos_Plan_by_DatePrekesKodas: TIntegerField; sp_Atsargos_Plan_by_DatePrekGrupeEN: TWideStringField; sp_Atsargos_Plan_by_DateZaliavuFormaEN: TWideStringField; sp_Atsargos_Plan_by_DateSpalvaEN: TWideStringField; sp_Atsargos_Plan_by_DateIpakavimoFormaEN: TWideStringField; sp_Atsargos_Plan_by_DateMatVienetasEN: TWideStringField; sp_Atsargos_Plan_by_DateDoctype: TStringField; sp_Atsargos_Plan_by_DateDokKeyFieldID: TIntegerField; sp_Atsargos_Plan_by_DateDokumentoNr: TIntegerField; sp_Atsargos_Plan_by_DatePardavejoID: TIntegerField; sp_Atsargos_Plan_by_DatePardavejoKodas: TWideStringField; sp_Atsargos_Plan_by_DatePardavejoPavad: TWideStringField; sp_Atsargos_Plan_by_DateLOTnumber: TIntegerField; sp_Atsargos_Plan_by_DateLotID: TIntegerField; sp_Atsargos_Plan_by_DateVietosID: TIntegerField; sp_Atsargos_Plan_by_DatePrekesID: TIntegerField; sp_Atsargos_Plan_by_DateFaktKiekis: TFloatField; gtv_AtsargosPlan_FaktKiekis: TcxGridDBColumn; dxlc_Buttons: TdxLayoutControl; cxButton1: TcxButton; cxButton2: TcxButton; dxLayoutGroup1: TdxLayoutGroup; dxLayoutItem1: TdxLayoutItem; dxlc_ButtonsItem2: TdxLayoutItem; actAtsisakyti: TAction; actTesti: TAction; dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; btnAtnaujinti: TcxButton; dxLayoutControl1Item1: TdxLayoutItem; cb_Date: TcxDateEdit; dxLayoutControl1Item2: TdxLayoutItem; dxLayoutControl1Group1: TdxLayoutGroup; cxPropertiesStore: TcxPropertiesStore; sp_Atsargos_Plan_by_DateFaktSvoris: TFloatField; gtv_AtsargosPlan_FaktSvoris: TcxGridDBColumn; sp_Atsargos_Plan_by_DatePlanKiekis: TFloatField; sp_Atsargos_Plan_by_DatePlanSvoris: TFloatField; dxLayoutControl1Item3: TdxLayoutItem; btnPrekOperacijos: TcxButton; actParodOperacijos: TAction; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure acrAtnaujintiExecute(Sender: TObject); procedure gtv_AtsargosFaktPardavejoPavadPropertiesStartClick(Sender: TObject); procedure gtv_AtsargosFaktDokumentoNrPropertiesStartClick(Sender: TObject); procedure gtv_AtsargosPlan_DokumentoNrPropertiesStartClick(Sender: TObject); procedure gtv_AtsargosPlan_PardavejoPavadPropertiesStartClick(Sender: TObject); procedure gtv_AtsargosPlanStylesGetContentStyle(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle); procedure actAtsisakytiExecute(Sender: TObject); procedure actTestiExecute(Sender: TObject); procedure actParodOperacijosExecute(Sender: TObject); private ARedStyle: TcxStyle; public constructor Create(Owner: TComponent); override; procedure Prepare_as_form(Date: TDateTime); procedure Prepare_as_select_dialog(Date: TDateTime); procedure ReActivateTables; end; var frmAtsargos: TfrmAtsargos; implementation {$R *.dfm} uses DataModule, Organizacijos, Pirkimai, Sandelis, Gamyba, Main; // ------------------------------------------------------ // // ------------------------------------------------------ constructor TfrmAtsargos.Create(Owner: TComponent); begin if (dm.f_SecurAdmin = False) and (dm.f_PardVald = False) then begin ShowMessage('Operacija uždrausta. Vartotojo teisės apribotos!'); Abort; end; inherited; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.FormCreate(Sender: TObject); begin dm.RestoreFormProperties(Self); dm.Adjust_form_size(Self); // if dm.tfdt__workplace_settingsDeveloper.Value = False then // begin // btnPrekOperacijos.Visible := False; // end; ARedStyle := TcxStyle.Create(Self); ARedStyle.Color := $0080FFFF; ARedStyle.TextColor := clMaroon; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.gtv_AtsargosFaktDokumentoNrPropertiesStartClick(Sender: TObject); begin frmMain.GoToSelectedDocument(sp_Atsargos_Fakt_by_DateDoctype.Value, sp_Atsargos_Fakt_by_DateDokKeyFieldID.Value); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.gtv_AtsargosPlan_DokumentoNrPropertiesStartClick(Sender: TObject); begin frmMain.GoToSelectedDocument(sp_Atsargos_Plan_by_DateDoctype.Value, sp_Atsargos_Plan_by_DateDokKeyFieldID.Value); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.gtv_AtsargosFaktPardavejoPavadPropertiesStartClick(Sender: TObject); begin if frmOrganizacijos = Nil then begin frmOrganizacijos := TfrmOrganizacijos.Create(Self); frmOrganizacijos.Show; end else frmOrganizacijos.Show; frmOrganizacijos.Organizacijos.Locate('OrganizacijosID', sp_Atsargos_Fakt_by_DatePardavejoID.Value); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.gtv_AtsargosPlanStylesGetContentStyle(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle); begin if ARecord.Values[gtv_AtsargosPlan_FaktKiekis.Index] <> ARecord.Values[gtv_AtsargosPlan_PlanKiekis.Index] then begin AStyle := ARedStyle; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.gtv_AtsargosPlan_PardavejoPavadPropertiesStartClick(Sender: TObject); begin if frmOrganizacijos = Nil then begin frmOrganizacijos := TfrmOrganizacijos.Create(Self); frmOrganizacijos.Show; end else frmOrganizacijos.Show; frmOrganizacijos.Organizacijos.Locate('OrganizacijosID', sp_Atsargos_Plan_by_DatePardavejoID.Value); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.Prepare_as_form(Date: TDateTime); begin cb_Date.Date := Date; ReActivateTables; ts_Plan.Show; dxlc_Buttons.Visible := False; Self.FormStyle := fsNormal; Self.BorderStyle := bsSizeable; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.Prepare_as_select_dialog(Date: TDateTime); begin cb_Date.Date := Date; if dm.tfdt__workplace_settingsDeveloper.Value = False then cb_Date.Visible := False else cb_Date.Visible := True; ReActivateTables; dxlc_Buttons.Visible := True; ts_Plan.Caption := 'Atsargos faktinės ir planuojamos'; ts_Plan.Show; ts_Fakt.TabVisible := False; gtv_AtsargosPlan.OptionsSelection.MultiSelect := True; gtv_AtsargosPlan.OptionsSelection.CellSelect := False; Self.FormStyle := fsStayOnTop; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.acrAtnaujintiExecute(Sender: TObject); begin ReActivateTables; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.ReActivateTables; begin if sp_Atsargos_Fakt_by_Date.Active = True then sp_Atsargos_Fakt_by_Date.Active := False; sp_Atsargos_Fakt_by_Date.ParamByName('@Date').Value := cb_Date.Date; sp_Atsargos_Fakt_by_Date.Active := True; if sp_Atsargos_Plan_by_Date.Active = True then sp_Atsargos_Plan_by_Date.Active := False; sp_Atsargos_Plan_by_Date.ParamByName('@Date').Value := cb_Date.Date; sp_Atsargos_Plan_by_Date.Active := True; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.actAtsisakytiExecute(Sender: TObject); begin // end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.actParodOperacijosExecute(Sender: TObject); begin if dm.sp_VisiOperacijos_pagal_PrekesKodas.Active = True then dm.sp_VisiOperacijos_pagal_PrekesKodas.Active := False; if ts_Plan.Visible then begin dm.sp_VisiOperacijos_pagal_PrekesKodas.ParamByName('@PrekesKodas').Value := sp_Atsargos_Plan_by_DatePrekesKodas.Value; end; if ts_Fakt.Visible then begin dm.sp_VisiOperacijos_pagal_PrekesKodas.ParamByName('@PrekesKodas').Value := sp_Atsargos_Fakt_by_DatePrekesKodas.Value; end; dm.sp_VisiOperacijos_pagal_PrekesKodas.Active := True; frmMain.actOperacijosExecute(Self); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.actTestiExecute(Sender: TObject); begin // end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmAtsargos.FormClose(Sender: TObject; var Action: TCloseAction); begin dm.SaveFormProperties(Self); Action := caFree; frmAtsargos := Nil; end; end.
{$include lem_directives.inc} unit LemMetaAnimation; interface uses Classes, UTools, LemCore; const lat_Loop = 0; // always animate lat_Once = 1; // state change if finished type TMetaAnimationClass = class of TMetaAnimation; TMetaAnimation = class(TCollectionItem) private protected fDescription : string; // for fun, really fFrameCount : Integer; // number of frames fWidth : Integer; // width of a single frame picture fHeight : Integer; // height of a single frame fImageLocation : Integer; // dos only fBitsPerPixel : Integer; // dos only public procedure Assign(Source: TPersistent); override; published property Description : string read fDescription write fDescription; property FrameCount : Integer read fFrameCount write fFrameCount; property Width : Integer read fWidth write fWidth; property Height : Integer read fHeight write fHeight; property BitsPerPixel : Integer read fBitsPerPixel write fBitsPerPixel; property ImageLocation : Integer read fImageLocation write fImageLocation; end; { TMetaAnimationFrame = class(TCollectionItem) private fFootX : Integer; fFootY : Integer; protected public published property FootX : Integer read fFootX write fFootX; property FootY : Integer read fFootY write fFootY; end; } TMetaLemmingAnimationClass = class of TMetaLemmingAnimation; TMetaLemmingAnimation = class(TMetaAnimation) private fAnimationType : Integer; // at_xxxx fFootX : Integer; fFootY : Integer; protected public procedure Assign(Source: TPersistent); override; published { mechanics } property AnimationType : Integer read fAnimationType write fAnimationType; property FootX : Integer read fFootX write fFootX; property FootY : Integer read fFootY write fFootY; end; TMetaAnimations = class(TCollectionEx) private function GetItem(Index: Integer): TMetaAnimation; procedure SetItem(Index: Integer; const Value: TMetaAnimation); protected public constructor Create(aItemClass: TMetaAnimationClass); function Add: TMetaAnimation; function Insert(Index: Integer): TMetaAnimation; property Items[Index: Integer]: TMetaAnimation read GetItem write SetItem; default; published end; TMetaLemmingAnimations = class(TMetaAnimations) private function GetItem(Index: Integer): TMetaLemmingAnimation; procedure SetItem(Index: Integer; const Value: TMetaLemmingAnimation); protected public constructor Create(aItemClass: TMetaLemmingAnimationClass); function Add: TMetaLemmingAnimation; function Insert(Index: Integer): TMetaLemmingAnimation; property Items[Index: Integer]: TMetaLemmingAnimation read GetItem write SetItem; default; published end; implementation { TMetaAnimation } procedure TMetaAnimation.Assign(Source: TPersistent); var M: TMetaAnimation absolute Source; begin if Source is TMetaAnimation then begin Description := M.Description; FrameCount := M.FrameCount; Width := M.Width; Height := M.Height; BitsPerPixel := M.BitsPerPixel; ImageLocation := M.ImageLocation; end else inherited Assign(Source); end; { TMetaLemmingAnimation } procedure TMetaLemmingAnimation.Assign(Source: TPersistent); var A: TMetaLemmingAnimation absolute Source; begin if Source is TMetaLemmingAnimation then begin inherited Assign(Source); AnimationType := A.AnimationType; FootX := A.FootX; FootY := A.FootY; end else inherited Assign(Source); end; { TMetaAnimations } function TMetaAnimations.Add: TMetaAnimation; begin Result := TMetaAnimation(inherited Add); end; constructor TMetaAnimations.Create(aItemClass: TMetaAnimationClass); begin inherited Create(aItemClass); end; function TMetaAnimations.GetItem(Index: Integer): TMetaAnimation; begin Result := TMetaAnimation(inherited GetItem(Index)) end; function TMetaAnimations.Insert(Index: Integer): TMetaAnimation; begin Result := TMetaAnimation(inherited Insert(Index)) end; procedure TMetaAnimations.SetItem(Index: Integer; const Value: TMetaAnimation); begin inherited SetItem(Index, Value); end; { TMetaLemmingAnimations } function TMetaLemmingAnimations.Add: TMetaLemmingAnimation; begin Result := TMetaLemmingAnimation(inherited Add); end; constructor TMetaLemmingAnimations.Create(aItemClass: TMetaLemmingAnimationClass); begin inherited Create(aItemClass); end; function TMetaLemmingAnimations.GetItem(Index: Integer): TMetaLemmingAnimation; begin Result := TMetaLemmingAnimation(inherited GetItem(Index)) end; function TMetaLemmingAnimations.Insert(Index: Integer): TMetaLemmingAnimation; begin Result := TMetaLemmingAnimation(inherited Insert(Index)) end; procedure TMetaLemmingAnimations.SetItem(Index: Integer; const Value: TMetaLemmingAnimation); begin inherited SetItem(Index, Value); end; end.
unit ssCalcEdit; interface uses Windows, SysUtils, Classes, Controls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalc, Graphics, Variants; var ShowCalcOnKeyPress: Boolean = False; type TssCalculator = class(TcxPopupCalculator) published property Color; end; //---------------------------------------------------------------------- TssPopupCalculator = class(TcxPopupCalculator) protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; public procedure SetEditorValue(const Value: string); override; property AutoFontSize; property Edit; end; //---------------------------------------------------------------------- TssCalcEdit = class(TcxCalcEdit) private FDecimalPlaces: Cardinal; FOldValue: Extended; procedure SetCalcColor(const Value: TColor); function GetCalcColor: TColor; procedure SetDecimalPlaces(const Value: Cardinal); procedure CheckValue; protected procedure DoInitPopup; override; procedure PopupWindowClosed(Sender: TObject); override; procedure KeyPress(var Key: Char); override; procedure SetEditValue(const Value: TcxEditValue); override; procedure ResetValue; public constructor Create(AOwner: TComponent); override; published property CalcColor: TColor read GetCalcColor write SetCalcColor; property DecimalPlaces: Cardinal read FDecimalPlaces write SetDecimalPlaces; end; //======================================================================== implementation uses Math, ssStrUtil, Dialogs; procedure TssCalcEdit.CheckValue; begin if not DroppedDown and (EditText<>'') then EditValue:=RoundTo(StrToFloat(EditText), -FDecimalPlaces); end; constructor TssCalcEdit.Create(AOwner: TComponent); begin inherited; FDecimalPlaces := 2; EditValue := 0; {$IFNDEF NODESIGN_} FCalculator.Free; FCalculator := TssPopupCalculator.Create(Self); with TssPopupCalculator(FCalculator) do begin Parent := PopupWindow; Edit := Self; AutoFontSize := False; OnHidePopup := HideCalculator; end; {$ENDIF} end; procedure TssCalcEdit.DoInitPopup; begin inherited; FOldValue := Value; end; function TssCalcEdit.GetCalcColor: TColor; begin Result:=TssCalculator(Calculator).Color; end; procedure TssCalcEdit.KeyPress(var Key: Char); var s: string; begin if CharInSet(Key, [',', '.']) then Key := DecimalSeparator; if ShowCalcOnKeyPress and CharInSet(Key, ['0'..'9', '.', ',']) then begin {$IFNDEF NODESIGN_} TssPopupCalculator(FCalculator).FStatus := csValid; if not DroppedDown then DropDown; TssPopupCalculator(FCalculator).FStatus := csValid; {$ENDIF} end; if Key = ' ' then begin Key := #0; if not DroppedDown then DropDown; Exit; end; if (FDecimalPlaces=0) and CharInSet(Key, [',', '.']) then begin if Properties.BeepOnError then Beep; Key := #0; Exit; end; if IsValidChar(Key) and CharInSet(Key, ['0'..'9', #13, #8, '.', ',']) then begin s:=EditText; System.Insert(Key, s, CursorPos+1); if (WordCount(s, [DecimalSeparator])=2) and (Cardinal(Length(ExtractWord(2, s, [DecimalSeparator])))>FDecimalPlaces) and (SelText='') then begin if Properties.BeepOnError then Beep; Key:=#0; Exit; end; end; if key<>#0 then inherited KeyPress(Key); end; procedure TssCalcEdit.PopupWindowClosed(Sender: TObject); begin inherited; CheckValue; SelectAll; end; procedure TssCalcEdit.ResetValue; begin Value := FOldValue; end; procedure TssCalcEdit.SetCalcColor(const Value: TColor); begin TssCalculator(Calculator).Color:=Value; end; procedure TssCalcEdit.SetDecimalPlaces(const Value: Cardinal); begin FDecimalPlaces := Value; CheckValue; end; procedure TssCalcEdit.SetEditValue(const Value: TcxEditValue); begin inherited SetEditValue(RoundTo(Value, -FDecimalPlaces)); end; { TssPopupCalculator } procedure TssPopupCalculator.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Key := 0; TssCalcEdit(Edit).ResetValue; HidePopup; end; inherited KeyDown(Key, Shift);; end; procedure TssPopupCalculator.SetEditorValue(const Value: string); begin inherited; end; end.
unit MoabConst; interface uses Standards; const tidClusterName_Moab = 'Moab'; const tidInventionKind_Rulership = 'MoabRulership'; tidInventionKind_Industrial = 'MoabIndustrial'; tidInventionKind_Market = 'MoabMarket'; tidInventionKind_Residential = 'MoabResidential'; tidInventionKind_Public = 'MoabPublic'; const nidInvention_MoabLove = 1; nidInvention_MoabDynamics = 2; nidInvention_MoabLandLording = 3; nidInvention_MoabBasicIllusions = 4; nidInvention_MoabBasicCorrections = 5; nidInvention_MoabOffices = 10; const tidFacilityKind_MoabSacred = 'MoabSacred'; tidFacilityKind_MoabIndustrial = 'MoabIndustrial'; tidFacilityKind_MoabResidentials = 'MoabResidentials'; tidFacilityKind_MoabIllusions = 'MoabIllusions'; tidFacilityKind_MoabCorrectionals = 'MoabCorrectionals'; tidFacilityKind_MoabBusinessFacilities = tidClusterName_Moab + tidFacilityKind_BusinessFacilities; tidFacilityKind_MoabSpecial = tidClusterName_Moab + tidFacilityKind_Special; const tmeInvention_VeryShort = 10; // NOTE: Research time is in hours! tmeInvention_Short = 30; tmeInvention_Normal = 50; tmeInvention_Long = 90; tmeInvention_VeryLong = 120; const tidFacilityStage_Construction = 'Construction'; tidFacilityStage_Complete = 'Completed'; const tidBlock_MoabTownHall = 'MoabTownHall'; tidFacility_MoabTownHall = 'MoabTownHall'; vidFacility_MoabTownHall = 1500; const tidBlock_MoabTradeCenter = 'MoabTradeCenter'; tidFacility_MoabTradeCenter = 'MoabTradeCenter'; vidFacility_MoabTradeCenter = 1510; const tidBlock_LoCostKnightsConstr = 'KnightsLoCostConstr'; tidBlock_LoCostKnights = 'KnightsLoCost'; tidFacility_LoCostKnights = 'KnightsLoCost'; vidFacility_LoCostKnights = 1461; const tidBlock_LoCostNursesConstr = 'NursesLoCostConstr'; tidBlock_LoCostNurses = 'NursesLoCost'; tidFacility_LoCostNurses = 'NursesLoCost'; vidFacility_LoCostNurses = 1471; //1441; const tidBlock_LoCostBeingsConstr = 'BeingsLoCostConstr'; tidBlock_LoCostBeings = 'BeingsLoCost'; tidFacility_LoCostBeings = 'BeingsLoCost'; vidFacility_LoCostBeings = 1481;//1451; const tidBlock_KnightsBuildingConstrA = 'KnightsBuildingConstrA'; tidBlock_KnightsBuildingA = 'KnightsBuildingA'; tidFacility_KnightsBuildingA = 'KnightsBuildingA'; vidFacility_KnightsBuildingA = 1361; const tidBlock_KnightsBuildingConstrB = 'KnightsBuildingConstrB'; tidBlock_KnightsBuildingB = 'KnightsBuildingB'; tidFacility_KnightsBuildingB = 'KnightsBuildingB'; vidFacility_KnightsBuildingB = 1371; const tidBlock_KnightsBuildingConstrC = 'KnightsBuildingConstrC'; tidBlock_KnightsBuildingC = 'KnightsBuildingC'; tidFacility_KnightsBuildingC = 'KnightsBuildingC'; vidFacility_KnightsBuildingC = 1381; const tidBlock_KnightsBuildingConstrD = 'KnightsBuildingConstrD'; tidBlock_KnightsBuildingD = 'KnightsBuildingD'; tidFacility_KnightsBuildingD = 'KnightsBuildingD'; vidFacility_KnightsBuildingD = 1451; const tidBlock_KnightsBuildingConstrE = 'KnightsBuildingConstrE'; tidBlock_KnightsBuildingE = 'KnightsBuildingE'; tidFacility_KnightsBuildingE = 'KnightsBuildingE'; vidFacility_KnightsBuildingE = 1451; const tidBlock_NurseDomeConstrA = 'NurseDomeConstrA'; tidBlock_NurseDomeA = 'NurseDomeA'; tidFacility_NurseDomeA = 'NurseDomeA'; vidFacility_NurseDomeA = 1341; const tidBlock_NurseDomeConstrB = 'NurseDomeConstrB'; tidBlock_NurseDomeB = 'NurseDomeB'; tidFacility_NurseDomeB = 'NurseDomeB'; vidFacility_NurseDomeB = 1351; const tidBlock_NurseDomeConstrC = 'NurseDomeConstrC'; tidBlock_NurseDomeC = 'NurseDomeC'; tidFacility_NurseDomeC = 'NurseDomeC'; vidFacility_NurseDomeC = 1431; const tidBlock_NurseDomeConstrD = 'NurseDomeConstrD'; tidBlock_NurseDomeD = 'NurseDomeD'; tidFacility_NurseDomeD = 'NurseDomeD'; vidFacility_NurseDomeD = 1441; const tidBlock_BeingsDomeConstrA = 'BeingsDomeConstrA'; tidBlock_BeingsDomeA = 'BeingsDomeA'; tidFacility_BeingsDomeA = 'BeingsDomeA'; vidFacility_BeingsDomeA = 1301; const tidBlock_BeingsDomeConstrB = 'BeingsDomeConstrB'; tidBlock_BeingsDomeB = 'BeingsDomeB'; tidFacility_BeingsDomeB = 'BeingsDomeB'; vidFacility_BeingsDomeB = 1311; const tidBlock_BeingsDomeConstrC = 'BeingsDomeConstrC'; tidBlock_BeingsDomeC = 'BeingsDomeC'; tidFacility_BeingsDomeC = 'BeingsDomeC'; vidFacility_BeingsDomeC = 1321; const tidBlock_BeingsDomeConstrD = 'BeingsDomeConstrD'; tidBlock_BeingsDomeD = 'BeingsDomeD'; tidFacility_BeingsDomeD = 'BeingsDomeD'; vidFacility_BeingsDomeD = 1331; const tidBlock_MoabFarmConstr = 'MoabFarmConstr'; tidBlock_MoabFarm = 'MoabFarm'; tidFacility_MoabFarm = 'MoabFarm'; vidFacility_MoabFarm = 1111; const tidBlock_MoabChemicalConstr = 'MoabChemicalConstr'; tidBlock_MoabChemical = 'MoabChemical'; tidFacility_MoabChemical = 'MoabChemical'; vidFacility_MoabChemical = 1161; const tidBlock_MoabMineConstr = 'MoabMineConstr'; tidBlock_MoabMine = 'MoabMine'; tidFacility_MoabMine = 'MoabMine'; vidFacility_MoabMine = 1121; const tidBlock_MoabChemMineConstr = 'MoabChemMineConstr'; tidBlock_MoabChemMine = 'MoabChemMine'; tidFacility_MoabChemMine = 'MoabChemMine'; vidFacility_MoabChemMine = 7011; const tidBlock_MoabSiliconMineConstr = 'MoabSiliconMineConstr'; tidBlock_MoabSiliconMine = 'MoabSiliconMine'; tidFacility_MoabSiliconMine = 'MoabSiliconMine'; vidFacility_MoabSiliconMine = 7021; const tidBlock_MoabStoneMineConstr = 'MoabStoneMineConstr'; tidBlock_MoabStoneMine = 'MoabStoneMine'; tidFacility_MoabStoneMine = 'MoabStoneMine'; vidFacility_MoabStoneMine = 7031; const tidBlock_MoabCoalMineConstr = 'MoabCoalMineConstr'; tidBlock_MoabCoalMine = 'MoabCoalMine'; tidFacility_MoabCoalMine = 'MoabCoalMine'; vidFacility_MoabCoalMine = 7041; const tidBlock_MoabOilRigConstr = 'MoabOilRigConstr'; tidBlock_MoabOilRig = 'MoabOilRig'; tidFacility_MoabOilRig = 'MoabOilRig'; vidFacility_MoabOilRig = 1241; const tidBlock_MoabRefineryConstr = 'MoabRefineryConstr'; tidBlock_MoabRefinery = 'MoabRefinery'; tidFacility_MoabRefinery = 'MoabRefinery'; vidFacility_MoabRefinery = 1251; const tidBlock_MoabFoodDomeConstr = 'MoabFoodDomeConstr'; tidBlock_MoabFoodDome = 'MoabFoodDome'; tidFacility_MoabFoodDome = 'MoabFoodDome'; vidFacility_MoabFoodDome = 1141; const tidBlock_MoabMetalConstr = 'MoabMetalConstr'; tidBlock_MoabMetal = 'MoabMetal'; tidFacility_MoabMetal = 'MoabMetal'; vidFacility_MoabMetal = 1151; const tidBlock_MoabTextileConstr = 'MoabTextileConstr'; tidBlock_MoabTextile = 'MoabTextile'; tidFacility_MoabTextile = 'MoabTextile'; vidFacility_MoabTextile = 1171; const tidBlock_MoabClothingsConstr = 'MoabClothingsConstr'; tidBlock_MoabClothings = 'MoabClothings'; tidFacility_MoabClothings = 'MoabClothings'; vidFacility_MoabClothings = 1181; const tidBlock_MoabElectronicConstr = 'MoabElectronicConstr'; tidBlock_MoabElectronic = 'MoabElectronic'; tidFacility_MoabElectronic = 'MoabElectronic'; vidFacility_MoabElectronic = 1131; const tidBlock_MoabConstructionConstr = 'MoabConstructionConstr'; tidBlock_MoabConstruction = 'MoabConstruction'; tidFacility_MoabConstruction = 'MoabConstruction'; vidFacility_MoabConstruction = 1221; // >> change latter const tidBlock_MoabHeavyConstr = 'MoabHeavyConstr'; tidBlock_MoabHeavy = 'MoabHeavy'; tidFacility_MoabHeavy = 'MoabHeavy'; vidFacility_MoabHeavy = 1231; // >> change latter const tidBlock_MoabCarIndustryConstr = 'MoabCarIndustryConstr'; tidBlock_MoabCarIndustry = 'MoabCarIndustry'; tidFacility_MoabCarIndustry = 'MoabCarIndustry'; vidFacility_MoabCarIndustry = 1191; const tidBlock_MoabHHAIndustryConstr = 'MoabHHAIndustryConstr'; tidBlock_MoabHHAIndustry = 'MoabHHAIndustry'; tidFacility_MoabHHAIndustry = 'MoabHHAIndustry'; vidFacility_MoabHHAIndustry = 1201; const tidBlock_MoabBusinessMachineConstr = 'MoabBusinessMachineConstr'; tidBlock_MoabBusinessMachine = 'MoabBusinessMachine'; tidFacility_MoabBusinessMachine = 'MoabBusinessMachine'; vidFacility_MoabBusinessMachine = 1211; const tidBlock_MoabFoodStoreConstr = 'MoabFoodStoreConstr'; tidBlock_MoabFoodStore = 'MoabFoodStore'; tidFacility_MoabFoodStore = 'MoabFoodStore'; vidFacility_MoabFoodStore = 1711; const tidBlock_MoabCarStoreConstr = 'MoabCarStoreConstr'; tidBlock_MoabCarStore = 'MoabCarStore'; tidFacility_MoabCarStore = 'MoabCarStore'; vidFacility_MoabCarStore = 1721; const tidBlock_MoabGasStationConstr = 'MoabGasStationConstr'; tidBlock_MoabGasStation = 'MoabGasStation'; tidFacility_MoabGasStation = 'MoabGasStation'; vidFacility_MoabGasStation = 1781; const tidBlock_MoabClothesStoreConstr = 'MoabClothesStoreConstr'; tidBlock_MoabClothesStore = 'MoabClothesStore'; tidFacility_MoabClothesStore = 'MoabClothesStore'; vidFacility_MoabClothesStore = 1731; const tidBlock_MoabSupermarketConstr = 'MoabSupermarketConstr'; tidBlock_MoabSupermarket = 'MoabSupermarket'; tidFacility_MoabSupermarket = 'MoabSupermarket'; vidFacility_MoabSupermarket = 1741; const tidBlock_MoabBarConstr = 'MoabBarConstr'; tidBlock_MoabBar = 'MoabBar'; tidFacility_MoabBar = 'MoabBar'; vidFacility_MoabBar = 1751; const tidBlock_MoabFuneralConstr = 'MoabFuneralConstr'; tidBlock_MoabFuneral = 'MoabFuneral'; tidFacility_MoabFuneral = 'MoabFuneral'; vidFacility_MoabFuneral = 7301; const tidBlock_MoabHHAStoreConstr = 'MoabHHAsStoreConstr'; tidBlock_MoabHHAStore = 'MoabHHAsStore'; tidFacility_MoabHHAStore = 'MoabHHAsStore'; vidFacility_MoabHHAStore = 1761; const tidBlock_MoabRestaurantConstr = 'MoabRestaurantConstr'; tidBlock_MoabRestaurant = 'MoabRestaurant'; tidFacility_MoabRestaurant = 'MoabRestaurant'; vidFacility_MoabRestaurant = 1751; // >> const tidBlock_MoabMovieConstr = 'MoabMovieConstr'; tidBlock_MoabMovie = 'MoabMovie'; tidFacility_MoabMovie = 'MoabMovie'; vidFacility_MoabMovie = 1771; // >> const tidBlock_MoabGeneralHeadquarterConstr = 'MoabGeneralHeadquarterConstr'; tidBlock_MoabGeneralHeadquarter = 'MoabGeneralHeadquarter'; tidFacility_MoabGeneralHeadquarter = 'MoabGeneralHeadquarter'; vidFacility_MoabGeneralHeadquarter = 1901; const tidBlock_MoabIndHeadquarterConstr = 'MoabIndHeadquarterConstr'; tidBlock_MoabIndHeadquarter = 'MoabIndHeadquarter'; tidFacility_MoabIndHeadquarter = 'MoabIndHeadquarter'; vidFacility_MoabIndHeadquarter = 1911; const tidBlock_MoabIllusionHeadquarterConstr = 'MoabIllusionHeadquarterConstr'; tidBlock_MoabIllusionHeadquarter = 'MoabIllusionHeadquarter'; tidFacility_MoabIllusionHeadquarter = 'MoabIllusionHeadquarter'; vidFacility_MoabIllusionHeadquarter = 1921; const tidBlock_MoabResHeadquarterConstr = 'MoabResHeadquarterConstr'; tidBlock_MoabResHeadquarter = 'MoabResHeadquarter'; tidFacility_MoabResHeadquarter = 'MoabResHeadquarter'; vidFacility_MoabResHeadquarter = 1931; const tidBlock_MoabCorrectionHeadquarterConstr = 'MoabCorrectionHeadquarterConstr'; tidBlock_MoabCorrectionHeadquarter = 'MoabCorrectionHeadquarter'; tidFacility_MoabCorrectionHeadquarter = 'MoabCorrectionHeadquarter'; vidFacility_MoabCorrectionHeadquarter = 1941; const tidBlock_MoabBigCorrectionalConstr = 'MoabBigCorrectionalConstr'; tidBlock_MoabBigCorrectional = 'MoabBigCorrectional'; tidFacility_MoabBigCorrectional = 'MoabBigCorrectional'; vidFacility_MoabBigCorrectional = 1021; const tidBlock_MoabSmallParkConstr = 'MoabSmallParkConstr'; tidBlock_MoabSmallPark = 'MoabSmallPark'; tidFacility_MoabSmallPark = 'MoabSmallPark'; vidFacility_MoabSmallPark = 2831; const tidBlock_MoabMediumParkConstr = 'MoabMediumParkConstr'; tidBlock_MoabMediumPark = 'MoabMediumPark'; tidFacility_MoabMediumPark = 'MoabMediumPark'; vidFacility_MoabMediumPark = 2841; const tidBlock_MoabCentralParkConstr = 'MoabCentralParkConstr'; tidBlock_MoabCentralPark = 'MoabCentralPark'; tidFacility_MoabCentralPark = 'MoabCentralPark'; vidFacility_MoabCentralPark = 2851; const tidBlock_MoabComputingIndustryConstr = 'MoabComputingIndustryConstr'; tidBlock_MoabComputingIndustry = 'MoabComputingIndustry'; tidFacility_MoabComputingIndustry = 'MoabComputingIndustry'; vidFacility_MoabComputingIndustry = 1031; const tidBlock_MoabLegalServicesConstr = 'MoabLegalServicesConstr'; tidBlock_MoabLegalServices = 'MoabLegalServices'; tidFacility_MoabLegalServices = 'MoabLegalServices'; vidFacility_MoabLegalServices = 1041; const tidBlock_MoabOfficeBuildingConstrA = 'MoabOfficeBuildingConstrA'; tidBlock_MoabOfficeBuildingA = 'MoabOfficeBuildingA'; tidFacility_MoabOfficeBuildingA = 'MoabOfficeBuildingA'; vidFacility_MoabOfficeBuildingA = 1951; const tidBlock_MoabOfficeBuildingConstrB = 'MoabOfficeBuildingConstrB'; tidBlock_MoabOfficeBuildingB = 'MoabOfficeBuildingB'; tidFacility_MoabOfficeBuildingB = 'MoabOfficeBuildingB'; vidFacility_MoabOfficeBuildingB = 1961; const tidBlock_MoabTVStationConstr = 'MoabTVStationConstr'; tidBlock_MoabTVStation = 'MoabTVStation'; tidFacility_MoabTVStation = 'MoabTVStation'; vidFacility_MoabTVStation = 1981; const tidBlock_MoabTVAntennaConstr = 'MoabTVAntennaConstr'; tidBlock_MoabTVAntenna = 'MoabTVAntenna'; tidFacility_MoabTVAntenna = 'MoabTVAntenna'; vidFacility_MoabTVAntenna = 1991; const tidBlock_MoabLibertyConstr = 'MoabLibertyConstr'; tidBlock_MoabLiberty = 'MoabLiberty'; tidFacility_MoabLiberty = 'MoabLiberty'; vidFacility_MoabLiberty = 6011; const tidBlock_MoabTowerConstr = 'MoabTowerConstr'; tidBlock_MoabTower = 'MoabTower'; tidFacility_MoabTower = 'MoabTower'; vidFacility_MoabTower = 6021; implementation end.
{ \file DGLE_Base.pas \author Korotkov Andrey aka DRON \version 2:0.3.1 \date 17.11.2014 (c)Korotkov Andrey This header is a part of DGLE_SDK. } unit DGLE_Base; interface {$I include.inc} {$IFNDEF DGLE_CRENDERER} {$DEFINE DGLE_CRENDERER} {$ENDIF} uses DGLE_types; type E_ENGINE_OBJECT_TYPE = ( EOT_UNKNOWN = 0, EOT_TEXTURE = 1, EOT_MATERIAL = 2, EOT_LIGHT = 3, EOT_MESH = 4, EOT_MODEL = 5, EOT_BITMAP_FONT = 6, EOT_SOUND_SAMPLE = 7, EOT_MUSIC = 8, EOT_EMPTY = 9 ); {Engine SubSystem interface flags} E_ENGINE_SUB_SYSTEM = ( ESS_RENDER = 0, ESS_INPUT = 1, ESS_SOUND = 2, ESS_RESOURCE_MANAGER = 3, ESS_FILESYSTEM = 4, ESS_CORE_RENDERER = 5 ); E_TEXTURE_DATA_FORMAT = ( TDF_RGB8 = 0, TDF_RGBA8 = 1, TDF_ALPHA8 = 2, TDF_BGR8 = 3, TDF_BGRA8 = 4, TDF_DXT1 = 5, TDF_DXT5 = 6, TDF_DEPTH_COMPONENT24 = 7, TDF_DEPTH_COMPONENT32 = 8 ); E_LIGHT_TYPE = ( LT_DIRECTIONAL = 0, LT_POINT = 1, LT_SPOT = 2 ); DGLE_RESULT = HRESULT; IDGLE_Base = interface(IUnknown) ['{DFB1F52B-D906-4108-AD6F-3144E224688A}'] function GetGUID(out stGuid: TGUID): DGLE_RESULT; stdcall; function ExecuteCommand(uiCmd: Cardinal; out stVar: TVariant): DGLE_RESULT; stdcall; function ExecuteTextCommand(pcCommand: pAnsiChar; out stVar: TVariant): DGLE_RESULT; stdcall; function ExecuteTextCommandEx(const pcCommand: pAnsiChar; pcResult: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall; end; //Engine SubSystem interface// IEngineSubSystem = interface(IDGLE_Base) ['{C682F875-E0BD-4af9-B79C-E209850025F8}'] function GetType(out eSubSystemType :E_ENGINE_SUB_SYSTEM): DGLE_RESULT; stdcall; end; implementation end.
unit Model.CadastroHistorico; interface uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, Control.Sistema, System.SysUtils; type TCadastroHistorico = class private FAcao: Tacao; FHistorico: String; FSequencia: Integer; FID: Integer; FUsuario: Integer; FData: TDateTime; FConexao: TConexao; FQuery: TFDQuery; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public Constructor Create(); property ID: Integer read FID write FID; property Sequencia: Integer read FSequencia write FSequencia; property Data: TDateTime read FData write FData; property Historico: String read FHistorico write FHistorico; property Usuario: Integer read FUsuario write FUsuario; property Query: TFDQuery read FQuery write FQuery; property Acao: Tacao read FAcao write FAcao; function GetID(): Integer; function Localizar(aParam: array of variant): Boolean; function Gravar(): Boolean; function SetupClass(FDquery: TFDQuery): boolean; function ClearClass(): boolean; end; const TABLENAME = 'cadastro_historico'; SQLINSERT = 'insert into ' + TABLENAME + '(id_historico, id_cadastro, dat_log_cadastro, des_historico, id_usuario) ' + 'values ' + '(:id_historico, :id_cadastro, :dat_log_cadastro, :des_historico, :id_usuario);'; SQLUPDATE = 'update ' + TABLENAME + ' set ' + 'dat_log_cadastro = :dat_log_cadastro, des_historico = :des_historico, id_usuario = :id_usuario ' + 'where ' + 'id_historico = :id_historico and id_cadastro = :id_cadastro;'; SQLQUERY = 'select ' + 'id_historico, id_cadastro, dat_log_cadastro, des_historico, id_usuario ' + 'from ' + TABLENAME; implementation { TCadastroHistorico } function TCadastroHistorico.Alterar: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE, [Self.Data, Self.Historico, Self.Usuario, Self.Sequencia, Self.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroHistorico.ClearClass: boolean; begin Result := False; FHistorico := ''; FSequencia := 0; FID := 0; FUsuario := 0; FData := StrToDate('31/12/1899'); Result := True; end; constructor TCadastroHistorico.Create; begin FConexao := Tconexao.Create; end; function TCadastroHistorico.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_historico = :id_historico and id_cadastro = :id_cadastro;', [Self.Sequencia, Self.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TCadastroHistorico.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_historico),0) + 1 from ' + TABLENAME + ' where id_cadastro = :id_cadastro'); FDQuery.ParamByName('id_cadastro').AsInteger := Self.ID; Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroHistorico.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Self.Inserir(); tacAlterar: Result := Self.Alterar(); tacExcluir: Result := Self.Excluir(); end; end; function TCadastroHistorico.Inserir: Boolean; var FDQuery : TFDQuery; begin try Result := False; Self.Sequencia := GetID; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLINSERT, [Self.Sequencia, Self.ID, Self.Data, Self.Historico, Self.Usuario]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroHistorico.Localizar(aParam: array of variant): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add(SQLQUERY); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_cadastro = :id_cadastro'); FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FDQuery.SQL.Add('where id_historico = :id_historico and id_cadastro = :id_cadastro'); FDQuery.ParamByName('id_historico').AsString := aParam[1]; FDQuery.ParamByName('id_cadastro').AsString := aParam[2]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); if not FDQuery.IsEmpty then begin FQuery := FDQuery; end; Result := True; finally FDQuery.Close; FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroHistorico.SetupClass(FDquery: TFDQuery): boolean; begin Result := False; FHistorico := FDQuery.FieldByName('des_historico').AsString; FSequencia := FDquery.FieldByName('id_historico').AsInteger; FID := FDquery.FieldByName('id_cadastro').AsInteger; FUsuario := FDquery.FieldByName('id_usuario').AsInteger; FData := FDquery.FieldByName('dat_log_cadastro').AsDateTime; REsult := True; end; end.
unit tfwFile; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/tfwFile.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::FileProcessing::TtfwFile // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses l3Filer, l3CProtoObject, tfwScriptingInterfaces, l3Interfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type TtfwFile = class(Tl3CProtoObject, ItfwFile) private // private fields f_Filer : Tl3CustomDosFiler; protected // realized methods {iterator} function ReadLines(anAction: ItfwFile_ReadLines_Action): Integer; {iterator} function ReadLinesF(anAction: ItfwFile_ReadLines_Action): Integer; function ReadLn: Il3CString; procedure WriteLn(const aString: Il3CString); procedure WriteChar(aChar: AnsiChar); function ReadWStrLn: Tl3WString; procedure WriteWStrLn(const aStr: Tl3WString); procedure WriteWStr(const aStr: Tl3WString); function EOF: Boolean; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // public methods constructor CreateRead(const aFileName: AnsiString); constructor CreateWrite(const aFileName: AnsiString); class function MakeRead(const aFileName: AnsiString): ItfwFile; reintroduce; {* Сигнатура фабрики TtfwFile.MakeRead } class function MakeWrite(const aFileName: AnsiString): ItfwFile; reintroduce; {* Сигнатура фабрики TtfwFile.MakeWrite } end;//TtfwFile {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses l3Base, l3Types, SysUtils, l3String ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} // start class TtfwFile constructor TtfwFile.CreateRead(const aFileName: AnsiString); //#UC START# *4F4FD849026C_4F4FD77B03CC_var* //#UC END# *4F4FD849026C_4F4FD77B03CC_var* begin //#UC START# *4F4FD849026C_4F4FD77B03CC_impl* inherited Create; f_Filer := Tl3CustomDosFiler.Make(aFileName, l3_fmRead, false); f_Filer.Open; //#UC END# *4F4FD849026C_4F4FD77B03CC_impl* end;//TtfwFile.CreateRead constructor TtfwFile.CreateWrite(const aFileName: AnsiString); //#UC START# *4F4FD85F033A_4F4FD77B03CC_var* //#UC END# *4F4FD85F033A_4F4FD77B03CC_var* begin //#UC START# *4F4FD85F033A_4F4FD77B03CC_impl* inherited Create; f_Filer := Tl3CustomDosFiler.Make(aFileName, l3_fmWrite, false); f_Filer.Open; //#UC END# *4F4FD85F033A_4F4FD77B03CC_impl* end;//TtfwFile.CreateWrite class function TtfwFile.MakeRead(const aFileName: AnsiString): ItfwFile; var l_Inst : TtfwFile; begin l_Inst := CreateRead(aFileName); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; class function TtfwFile.MakeWrite(const aFileName: AnsiString): ItfwFile; var l_Inst : TtfwFile; begin l_Inst := CreateWrite(aFileName); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TtfwFile.ReadLn: Il3CString; //#UC START# *4F4E4E7E0350_4F4FD77B03CC_var* //#UC END# *4F4E4E7E0350_4F4FD77B03CC_var* begin //#UC START# *4F4E4E7E0350_4F4FD77B03CC_impl* Result := TtfwCStringFactory.C(f_Filer.ReadLn); //#UC END# *4F4E4E7E0350_4F4FD77B03CC_impl* end;//TtfwFile.ReadLn procedure TtfwFile.WriteLn(const aString: Il3CString); //#UC START# *4F4E4EA7007D_4F4FD77B03CC_var* //#UC END# *4F4E4EA7007D_4F4FD77B03CC_var* begin //#UC START# *4F4E4EA7007D_4F4FD77B03CC_impl* f_Filer.WriteLn(l3PCharLen(aString)); //#UC END# *4F4E4EA7007D_4F4FD77B03CC_impl* end;//TtfwFile.WriteLn procedure TtfwFile.WriteChar(aChar: AnsiChar); //#UC START# *4F4FDC540264_4F4FD77B03CC_var* //#UC END# *4F4FDC540264_4F4FD77B03CC_var* begin //#UC START# *4F4FDC540264_4F4FD77B03CC_impl* f_Filer.Write(aChar); //#UC END# *4F4FDC540264_4F4FD77B03CC_impl* end;//TtfwFile.WriteChar function TtfwFile.ReadWStrLn: Tl3WString; //#UC START# *4F4FE16A0269_4F4FD77B03CC_var* //#UC END# *4F4FE16A0269_4F4FD77B03CC_var* begin //#UC START# *4F4FE16A0269_4F4FD77B03CC_impl* Result := f_Filer.ReadLn; //#UC END# *4F4FE16A0269_4F4FD77B03CC_impl* end;//TtfwFile.ReadWStrLn procedure TtfwFile.WriteWStrLn(const aStr: Tl3WString); //#UC START# *4F4FE19301A1_4F4FD77B03CC_var* //#UC END# *4F4FE19301A1_4F4FD77B03CC_var* begin //#UC START# *4F4FE19301A1_4F4FD77B03CC_impl* f_Filer.WriteLn(aStr); //#UC END# *4F4FE19301A1_4F4FD77B03CC_impl* end;//TtfwFile.WriteWStrLn procedure TtfwFile.WriteWStr(const aStr: Tl3WString); //#UC START# *4F4FE1B40314_4F4FD77B03CC_var* //#UC END# *4F4FE1B40314_4F4FD77B03CC_var* begin //#UC START# *4F4FE1B40314_4F4FD77B03CC_impl* f_Filer.Write(aStr); //#UC END# *4F4FE1B40314_4F4FD77B03CC_impl* end;//TtfwFile.WriteWStr function TtfwFile.EOF: Boolean; //#UC START# *4F50821201E7_4F4FD77B03CC_var* //#UC END# *4F50821201E7_4F4FD77B03CC_var* begin //#UC START# *4F50821201E7_4F4FD77B03CC_impl* Result := f_Filer.EOF; //#UC END# *4F50821201E7_4F4FD77B03CC_impl* end;//TtfwFile.EOF procedure TtfwFile.Cleanup; //#UC START# *479731C50290_4F4FD77B03CC_var* //#UC END# *479731C50290_4F4FD77B03CC_var* begin //#UC START# *479731C50290_4F4FD77B03CC_impl* f_Filer.Close; FreeAndNil(f_Filer); inherited; //#UC END# *479731C50290_4F4FD77B03CC_impl* end;//TtfwFile.Cleanup {iterator} function TtfwFile.ReadLines(anAction: ItfwFile_ReadLines_Action): Integer; //#UC START# *4F4E4EC9027A_4F4FD77B03CC_var* var l_S : Tl3WString; //#UC END# *4F4E4EC9027A_4F4FD77B03CC_var* begin //#UC START# *4F4E4EC9027A_4F4FD77B03CC_impl* Result := 0; while not f_Filer.EOF do begin l_S := f_Filer.ReadLn; if not l3IsNil(l_S) OR not f_Filer.EOF then // - это чтобы не размножались пустые строки в конце файлов if not anAction(l_S) then break; end;//not f_Filer.EOF //#UC END# *4F4E4EC9027A_4F4FD77B03CC_impl* end;//TtfwFile.ReadLines {iterator} function TtfwFile.ReadLinesF(anAction: ItfwFile_ReadLines_Action): Integer; var Hack : Pointer absolute anAction; begin try Result := ReadLines(anAction); finally l3FreeLocalStub(Hack); end;//try..finally end; {$IfEnd} //not NoScripts end.
(* * iocp 服务端 SQL 管理器(可选) *) unit iocp_sqlMgr; interface uses Classes, SysUtils, iocp_lists; type // 一条 SQL 命令对象 TSQLObject = class(TObject) private FSQL: TStrings; // SQL 命令 FSQLText: String; // SQL 命令(运行时) FSQLName: String; // 名称 procedure ToStringEx; public constructor Create(const AName: String); destructor Destroy; override; property SQL: TStrings read FSQL; property SQLName: String read FSQLName; end; // 一组 SQL 命令的管理器 TInSQLManager = class(TComponent) private FNames: TInList; // SQL 命名列表 FSQLs: TStrings; // SQL 文本文件资源 function GetCount: Integer; function GetItems(Index: Integer): TSQLObject; procedure ClearNames; procedure OnSQLChange(Sender: TObject); procedure SetSQLs(const Value: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetSQL(Index: Integer): String; overload; function GetSQL(const AName: String): String; overload; public property Items[Index: Integer]: TSQLObject read GetItems; published property Count: Integer read GetCount; property SQLs: TStrings read FSQLs write SetSQLs; end; implementation { TSQLObject } constructor TSQLObject.Create(const AName: String); begin inherited Create; FSQLName := AName; FSQL := TStringList.Create; end; destructor TSQLObject.Destroy; begin if Assigned(FSQL) then FSQL.Free; inherited; end; procedure TSQLObject.ToStringEx; begin FSQLText := FSQL.Text; FSQL.Clear; // 也清空 end; { TInSQLManager } procedure TInSQLManager.OnSQLChange(Sender: TObject); var i: Integer; S: String; SQLObj: TSQLObject; begin // FSQLs 内容改变,提取各段内容 if (FSQLs.Count = 0) then Exit; // 提取 SQL 命令 // 每一 Section 为一条命令,Section 为命名 ClearNames; SQLObj := nil; for i := 0 to FSQLs.Count - 1 do begin S := Trim(FSQLs.Strings[i]); if (Length(S) >= 3) and (S[1] = '[') and (S[Length(S)] = ']') then // Section 开始 begin SQLObj := TSQLObject.Create(Copy(S, 2, Length(S) - 2)); // 区分大小写 FNames.Add(SQLObj); end else if Assigned(SQLObj) then begin if (csDestroying in ComponentState) then SQLObj.FSQL.Add(S) else if (Length(S) > 0) and (S[1] <> '/') then SQLObj.FSQL.Add(S); end; end; // 运行状态,把命令转为 String,清空 FSQLs if not (csDesigning in ComponentState) then begin for i := 0 to FNames.Count - 1 do TSQLObject(FNames.Items[i]).ToStringEx; FSQLs.Clear; end; end; procedure TInSQLManager.ClearNames; var i: Integer; begin // 清除 SQL 命名表 for i := 0 to FNames.Count - 1 do TSQLObject(FNames.Items[i]).Free; FNames.Clear; end; constructor TInSQLManager.Create(AOwner: TComponent); begin inherited; FNames := TInList.Create; FSQLs := TStringList.Create; TStringList(FSQLs).OnChange := OnSQLChange; end; destructor TInSQLManager.Destroy; begin ClearNames; FNames.Free; FSQLs.Free; inherited; end; function TInSQLManager.GetCount: Integer; begin Result := FNames.Count; end; function TInSQLManager.GetItems(Index: Integer): TSQLObject; begin Result := TSQLObject(FNames.Items[Index]); end; function TInSQLManager.GetSQL(Index: Integer): String; begin // 运行状态调用! Result := TSQLObject(FNames.Items[Index]).FSQLText; end; function TInSQLManager.GetSQL(const AName: String): String; var i: Integer; Obj: TSQLObject; begin // 运行状态调用! for i := 0 to FNames.Count - 1 do begin Obj := TSQLObject(FNames.Items[i]); if (AName = Obj.FSQLName) then // 区分大小写 begin Result := Obj.FSQLText; Exit; end; end;; end; procedure TInSQLManager.SetSQLs(const Value: TStrings); begin ClearNames; FSQLs.Clear; if Assigned(Value) then FSQLs.AddStrings(Value); end; end.
unit uProtoBufParserAbstractClasses; interface uses System.Classes, System.Generics.Collections; type TAbstractProtoBufParserItem = class(TObject) protected FName: string; FRoot: TAbstractProtoBufParserItem; FComments: TStringList; public constructor Create(ARoot: TAbstractProtoBufParserItem); virtual; destructor Destroy; override; procedure ParseFromProto(const Proto: string; var iPos: Integer); virtual; abstract; procedure AddCommentsToBeginning(AComments: TStringList); property Name: string read FName write FName; property Comments: TStringList read FComments; end; TAbstractProtoBufParserContainer<T: TAbstractProtoBufParserItem> = class(TObjectList<T>) private FExtendOf: string; FIsImported: Boolean; protected FName: string; FRoot: TAbstractProtoBufParserItem; FComments: TStringList; public constructor Create(ARoot: TAbstractProtoBufParserItem); virtual; destructor Destroy; override; procedure ParseFromProto(const Proto: string; var iPos: Integer); virtual; procedure AddCommentsToBeginning(AComments: TStringList); property Name: string read FName write FName; property Comments: TStringList read FComments; property IsImported: Boolean read FIsImported write FIsImported; property ExtendOf: string read FExtendOf write FExtendOf; end; implementation { TAbstractProtoBufParserItem } procedure TAbstractProtoBufParserItem.AddCommentsToBeginning( AComments: TStringList); begin if (AComments <> nil) and (AComments.Count > 0) then if FComments.Count > 0 then FComments.Text:= AComments.Text + FComments.LineBreak + FComments.Text else FComments.Text:= AComments.Text; end; constructor TAbstractProtoBufParserItem.Create(ARoot: TAbstractProtoBufParserItem); begin inherited Create; FRoot := ARoot; FComments:= TStringList.Create; FComments.TrailingLineBreak:= False; end; destructor TAbstractProtoBufParserItem.Destroy; begin FComments.Free; inherited; end; { TAbstractProtoBufParserContainer<T> } procedure TAbstractProtoBufParserContainer<T>.AddCommentsToBeginning(AComments: TStringList); begin if (AComments <> nil) and (AComments.Count > 0) then if FComments.Count > 0 then FComments.Text:= AComments.Text + FComments.LineBreak + FComments.Text else FComments.Text:= AComments.Text; end; constructor TAbstractProtoBufParserContainer<T>.Create(ARoot: TAbstractProtoBufParserItem); begin inherited Create(True); FRoot := ARoot; FComments := TStringList.Create; FComments.TrailingLineBreak:= False; end; destructor TAbstractProtoBufParserContainer<T>.Destroy; begin FComments.Free; inherited; end; procedure TAbstractProtoBufParserContainer<T>.ParseFromProto(const Proto: string; var iPos: Integer); begin FComments.Clear; Clear; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElPropTools; interface uses Classes, TypInfo, ElIni, ElTools, SysUtils; function HasProperty(Comp : TObject; PropertyName : string) : boolean; function GetPropertyRecord(Comp : TObject; PropertyName : string) : PPropInfo; procedure StoreSetProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure StoreFloatProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure StoreObject(Comp : TObject; Storage : TElIniFile); procedure StoreCollection(Collection : TCollection; Name : string; Storage : TElIniFile); procedure StoreIntegerProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure StoreEnumProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure StoreStringProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure StoreStringList(Strings : TStrings; Name : string; Storage : TElIniFile); procedure LoadSetProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure LoadFloatProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure LoadObject(Comp : TObject; Storage : TElIniFile); procedure LoadCollection(Collection : TCollection; Name : string; Storage : TElIniFile); procedure LoadIntegerProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure LoadEnumProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure LoadStringProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); procedure LoadStringList(Strings : TStrings; Name : string; Storage : TElIniFile); implementation procedure LoadSetProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); begin LoadIntegerProperty(Comp, Prop, Storage); end; procedure LoadFloatProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); var X : Extended; Stream : TDirectMemoryStream; var i : integer; begin Stream := TDirectMemoryStream.Create; i := sizeof(X); Stream.SetSize(i); Storage.ReadBinary('', Prop.Name, pchar(Stream.Memory)^, i); Stream.ReadBuffer(X, i); Stream.Free; SetFloatProp(Comp, Prop, X); end; function GetPropertyRecord(Comp : TObject; PropertyName : string) : PPropInfo; var i : integer; PropCount : Integer; PropList : PPropList; PPI : PPropInfo; begin PropCount := GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], nil); GetMem(PropList, PropCount * sizeof(pointer)); GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], PropList); for i := 0 to PropCount - 1 do // Iterate begin if Uppercase(PropList[i].Name) = Uppercase(PropertyName) then begin New(PPI); Move(PropList[i]^, PPI^, sizeof(PPI^)); result := PPI; FreeMem(PropList); exit; end; end; // for FreeMem(PropList); result := nil; end; function HasProperty(Comp : TObject; PropertyName : string) : boolean; var i : integer; PropCount : Integer; PropList : PPropList; begin PropCount := GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], nil); GetMem(PropList, PropCount * sizeof(pointer)); GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], PropList); for i := 0 to PropCount - 1 do // Iterate begin if Uppercase(PropList[i].Name) = Uppercase(PropertyName) then begin result := true; FreeMem(PropList); exit; end; end; // for FreeMem(PropList); result := false; end; procedure LoadObject(Comp : TObject; Storage : TElIniFile); var i : integer; PropCount : Integer; PropList : PPropList; Obj : TObject; FSaveKey : string; begin PropCount := GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], nil); GetMem(PropList, PropCount * sizeof(pointer)); GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], PropList); for i := 0 to PropCount - 1 do // Iterate begin case PropList[i]^.PropType^.Kind of // tkString, tkLString : LoadStringProperty(Comp, PropList[i], Storage); tkEnumeration, tkInteger : LoadIntegerProperty(Comp, PropList[i], Storage); tkSet : LoadSetProperty(Comp, PropList[i], Storage); tkFloat : LoadFloatProperty(Comp, PropList[i], Storage); tkClass : begin Obj := TObject(GetOrdProp(Comp, PropList[i])); if (Obj <> nil) then begin if Obj is TStrings then LoadStringList(Obj as TStrings, PropList[i].Name, Storage) else if Obj is TCollection then LoadCollection(Obj as TCollection, PropList[i].Name, Storage) else begin FSaveKey := Storage.CurrentKey; if Storage.OpenKey(PropList[i].Name, false) then LoadObject(Obj as TObject, Storage); Storage.OpenKey(FSaveKey, false); end; end; end; end; // case end; // for FreeMem(PropList); end; procedure LoadCollection(Collection : TCollection; Name : string; Storage : TElIniFile); var FSaveKey, FSaveKey1 : string; i : integer; begin FSaveKey := Storage.CurrentKey; if Storage.OpenKey(Name, false) then begin for i := 0 to Collection.Count - 1 do // Iterate begin FSaveKey1 := Storage.CurrentKey; if Storage.OpenKey('Item' + IntToStr(i), false) then LoadObject(Collection.Items[i], Storage); Storage.OpenKey(FSaveKey1, false); end; // for end; Storage.OpenKey(FSaveKey, false); end; procedure LoadIntegerProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); var i : integer; begin Storage.ReadInteger('', Prop.Name, GetOrdProp(Comp, Prop), i); SetOrdProp(Comp, Prop, i); end; procedure LoadEnumProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); begin LoadIntegerProperty(Comp, Prop, Storage); end; procedure LoadStringProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); var S : string; begin Storage.ReadString('', Prop.Name, GetStrProp(Comp, Prop), S); SetStrProp(Comp, Prop, S); end; procedure LoadStringList(Strings : TStrings; Name : string; Storage : TElIniFile); begin Storage.ReadMultiString('', Name, Strings); end; type TFakeSet = set of 0..31; procedure StoreStringList(Strings : TStrings; Name : string; Storage : TElIniFile); begin Storage.WriteMultiString('', Name, Strings); end; procedure StoreObject(Comp : TObject; Storage : TElIniFile); var i : integer; PropCount : Integer; PropList : PPropList; Obj : TObject; FSaveKey : string; begin PropCount := GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], nil); GetMem(PropList, PropCount * sizeof(pointer)); GetPropList(Comp.ClassInfo, [tkInteger, tkEnumeration, tkString, tkLString, tkSet, tkClass], PropList); for i := 0 to PropCount - 1 do // Iterate begin case PropList[i]^.PropType^.Kind of // tkString, tkLString : StoreStringProperty(Comp, PropList[i], Storage); tkEnumeration, tkInteger : StoreIntegerProperty(Comp, PropList[i], Storage); tkSet : StoreSetProperty(Comp, PropList[i], Storage); tkFloat : StoreFloatProperty(Comp, PropList[i], Storage); tkClass : begin Obj := TObject(GetOrdProp(Comp, PropList[i])); if (Obj <> nil) then begin if Obj is TStrings then StoreStringList(Obj as TStrings, PropList[i].Name, Storage) else if Obj is TCollection then StoreCollection(Obj as TCollection, PropList[i].Name, Storage) else begin FSaveKey := Storage.CurrentKey; if Storage.OpenKey(PropList[i].Name, true) then StoreObject(Obj as TObject, Storage); Storage.OpenKey(FSaveKey, false); end; end; end; end; // case end; // for FreeMem(PropList); end; procedure StoreCollection(Collection : TCollection; Name : string; Storage : TElIniFile); var FSaveKey, FSaveKey1 : string; i : integer; begin FSaveKey := Storage.CurrentKey; if Storage.OpenKey(Name, true) then begin for i := 0 to Collection.Count - 1 do // Iterate begin FSaveKey1 := Storage.CurrentKey; if Storage.OpenKey('Item' + IntToStr(i), true) then StoreObject(Collection.Items[i], Storage); Storage.OpenKey(FSaveKey1, false); end; // for end; Storage.OpenKey(FSaveKey, false); end; procedure StoreIntegerProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); var i : integer; begin i := GetOrdProp(Comp, Prop); Storage.WriteInteger('', Prop.Name, i); end; procedure StoreEnumProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); begin StoreIntegerProperty(Comp, Prop, Storage); end; procedure StoreStringProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); var S : string; begin S := GetStrProp(Comp, Prop); Storage.WriteString('', Prop.Name, S); end; procedure StoreSetProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); begin StoreIntegerProperty(Comp, Prop, Storage); end; procedure StoreFloatProperty(Comp : TObject; Prop : PPropInfo; Storage : TElIniFile); var X : Extended; Stream : TDirectMemoryStream; begin X := GetFloatProp(Comp, Prop); Stream := TDirectMemoryStream.Create; Stream.WriteBuffer(X, SizeOf(X)); Storage.WriteBinary('', Prop.Name, pchar(Stream.Memory)^, sizeof(X)); Stream.Free; end; end.
unit dcDataPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, DataController, Db, menus; type TdcDataPanel = class(tpanel) private Fclearing: boolean; procedure Setclearing(const Value: boolean); private { Private declarations } popup : TPopupmenu; property clearing:boolean read Fclearing write Setclearing; protected { Protected declarations } fTranData : String; fdcLink : TdcLink; function GetDatabufIndex: integer; function GetDataField: String; procedure SetDataBufIndex(const Value: integer); procedure SetDataField(const Value: String); function GetDataController:TDataController; procedure SetDataController(const value:TDataController); function GetDataSource:TDataSource; procedure SetDataSource(const value:TDataSource); procedure ReadData(sender:TObject); virtual; procedure ClearData(sender:TObject); procedure OnCopyClick(sender:TObject); public { Public declarations } constructor create(AOwner:TComponent);override; destructor destroy;override; published { Published declarations } property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDataSource; property DatabufIndex:integer read GetDatabufIndex write SetDataBufIndex; end; procedure Register; implementation uses clipbrd; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcDataPanel]); end; { TdcDataPanel } procedure TdcDataPanel.ClearData(sender: TObject); begin clearing := true; if assigned(fdclink.Field) then begin text := trim(fdclink.Field.DefaultExpression); end else text := ''; clearing := false; end; constructor TdcDataPanel.create(AOwner: TComponent); begin inherited; fdclink := tdclink.create(self); with fdcLink do begin OnReadData := ReadData; OnClearData := ClearData; end; BevelOuter := bvLowered; Color := clWindow; Alignment := taLeftJustify; height := 21; popup := TPopupMenu.Create(self); popup.Items.Add(TMenuItem.create(self)); popup.Items[0].Caption := 'Copy'; popup.Items[0].OnClick := OnCopyClick; PopupMenu := popup; BorderStyle := bsNone; BorderWidth := 2; end; destructor TdcDataPanel.destroy; begin fdclink.Free; inherited; end; function TdcDataPanel.GetDatabufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; function TdcDataPanel.GetDataController: TDataController; begin result := fdcLink.DataController; end; function TdcDataPanel.GetDataField: String; begin result := fdcLink.FieldName; end; function TdcDataPanel.getDataSource: TDataSource; begin result := fdclink.DataSource; end; procedure TdcDataPanel.OnCopyClick(sender: TObject); begin clipboard.AsText := text; end; procedure TdcDataPanel.ReadData(sender: TObject); begin if not assigned(fdclink.DataController) then exit; if assigned(fdclink.datacontroller.databuf) then text := fdclink.datacontroller.databuf.AsString[DataBufIndex]; end; procedure TdcDataPanel.Setclearing(const Value: boolean); begin Fclearing := Value; end; procedure TdcDataPanel.SetDataBufIndex(const Value: integer); begin end; procedure TdcDataPanel.setDataController(const Value: TDataController); begin fdcLink.datacontroller := value; end; procedure TdcDataPanel.SetDataField(const Value: String); begin fdcLink.FieldName := value; end; procedure TdcDataPanel.SetDataSource(const Value: TDataSource); begin end; end.
program Morpion (input, output); uses crt; type TCase=record //Enregistrement du type TCase pour la structure des cases CoordX:integer;//Coordonnee en x de la case CoordY:integer;//Coordonnee en y de la case Numero:integer;//Numero de la case Rempli:boolean;//Indique si la case est deja remplie ou non Signe:string;//Indique le caractere entre dans la case si elle est remplie end; type TPlateau=Array[1..9] of TCase; //Le plateau est compose de cases type TPlayer=record //Enregistrement du type TPlayer contenant les parametres qui definissent un joueur NumPlayer:integer;//Numero du joueur SignePlayer:string;//Signe du joueur end; //BUT : Creation des joueurs //ENTREE : Pas d'entree //SORTIE : Joueurs correctement definis procedure CreatPlayer(P1,P2:TPlayer); begin //Joueur 1 P1.NumPlayer:=1; P1.SignePlayer:='X'; //Joueur 2 P2.NumPlayer:=2; P2.SignePlayer:='O'; end; //BUT : Creation des cases du morpion //ENTREE : Pas d'entree //SORTIE : Cases creees et correctement structurees procedure CreatCases(var Plateau:TPlateau); begin //Case 1 Plateau[1].CoordX:=1; Plateau[1].CoordY:=1; Plateau[1].Numero:=1; Plateau[1].Rempli:=FALSE; //Case 2 Plateau[2].CoordX:=3; Plateau[2].CoordY:=1; Plateau[2].Numero:=2; Plateau[2].Rempli:=FALSE; //Case 3 Plateau[3].CoordX:=5; Plateau[3].CoordY:=1; Plateau[3].Numero:=3; Plateau[3].Rempli:=FALSE; //Case 4 Plateau[4].CoordX:=1; Plateau[4].CoordY:=3; Plateau[4].Numero:=4; Plateau[4].Rempli:=FALSE; //Case 5 Plateau[5].CoordX:=3; Plateau[5].CoordY:=3; Plateau[5].Numero:=5; Plateau[5].Rempli:=FALSE; //Case 6 Plateau[6].CoordX:=5; Plateau[6].CoordY:=3; Plateau[6].Numero:=6; Plateau[6].Rempli:=FALSE; //Case 7 Plateau[7].CoordX:=1; Plateau[7].CoordY:=5; Plateau[7].Numero:=7; Plateau[7].Rempli:=FALSE; //Case 8 Plateau[8].CoordX:=3; Plateau[8].CoordY:=5; Plateau[8].Numero:=8; Plateau[8].Rempli:=FALSE; //Case 9 Plateau[9].CoordX:=5; Plateau[9].CoordY:=5; Plateau[9].Numero:=9; Plateau[9].Rempli:=FALSE; end; //BUT : Affichage du plateau de jeu //ENTREE : Pas d'entree //SORTIE : Plateau de jeu correctement affiche procedure AffPlateau; var x,y:integer; compteur:integer; //Permet d'afficher le numero des cases begin //Initialisation du compteur a 1 compteur:=1; //Boucle d'affichage du tableau //Passage de lignes en lignes FOR y:=1 TO 5 DO begin //Passage de cases en cases FOR x:=1 TO 5 DO begin //Place le pointeur aux coordonnees definies par la boucle GoToXY(x,y); //Si les coordonnees sont paires on affiche le caractere de la grille IF ((x MOD 2 = 0) OR (y MOD 2=0)) THEN begin write('*'); end //Sinon affiche le numero de la case ELSE begin write(compteur); compteur:=compteur+1;//Incrementation du compteur end; end; end; end; //BUT : Proposer au joueur de choisir une case dans laquelle il veut mettre son signe //ENTREE : la case choisie du joueur //SORTIE : Le signe s'inscrit dans la case ou affiche un message en cas d'erreur procedure ChoixJoueur(var Plateau:TPlateau;var Tour:integer; P1,P2:TPlayer); var choix:integer; //Choix du joueur begin //Boucle de choix REPEAT //Boucle d'instruction REPEAT //Place le pointeur en dessous du plateau et vide la ligne si elle est deja remplie GoToXY(1,9); write(' '); //Instruction GoToXY(1,9); write('Veuillez entrer le numero de la case que vous souhaitez remplir : '); readln(choix); //Affichage du message d'erreur si le joueur entre un nombre non compris entre 1 et 9 IF ((choix<1)OR(choix>9)) THEN begin //Place le pointeur au dessus de la phrase et vide la ligne si elle est deja remplie GoToXY(1,8); write(' '); //Message d'erreur GoToXY(1,8); write('/!\ Vous n''avez pas mis un chiffre entre 1 et 9 /!\'); end; UNTIL ((choix>=1)AND(choix<=9)); //Jusqu'a ce que le joueur ait entre un chiffre entre 1 et 9 IF Plateau[choix].Rempli=TRUE THEN begin //Place le pointeur au dessus de la phrase et vide la ligne si elle est deja remplie GoToXY(1,8); write(' '); //Message d'erreur GoToXY(1,8); write('/!\ Vous n''avez pas mis un chiffre entre 1 et 9 /!\'); end; UNTIL (Plateau[choix].Rempli=FALSE); //Jusqu'a ce que le joueur ait choisi une case vide //On place le pointeur sur la case associee au choix GoToXY(Plateau[choix].CoordX,Plateau[choix].CoordY); //On insere le signe associe au joueur //Tour pair = Joueur 2 ( X ) IF (Tour MOD 2 = 0) THEN begin write(P2.SignePlayer); Plateau[choix].Signe:=P2.SignePlayer; end //Tour impair = Joueur 1 ( O ) ELSE begin write(P1.SignePlayer); Plateau[choix].Signe:=P1.SignePlayer; end; //On indique que la case est remplie desormais Plateau[choix].Rempli:=TRUE; //On vide la ligne ou sont marquees les erreurs GoToXY(1,8); write(' '); end; //BUT : Faire le tour de jeu //ENTREE : Pas d'entree //SORTIE : Changement de tour, insertion du signe dans la case que le joueur a choisi s'il en choisi une valide ou affiche un message d'erreur procedure TourDeJeu(var Plateau:TPlateau;var Tour:integer; P1,P2:TPlayer); begin //Initialisation du numero du tour a 1 Tour:=1; //Boucle de jeu REPEAT //Le joueur entre son choix ChoixJoueur(Plateau,Tour,P1,P2); //Incrementation du numero du tour Tour:=Tour+1; UNTIL(Tour=9); end; //PROGRAMME PRINCIPAL var Plateau:TPlateau; //Plateau compose de cases Tour:integer; //Numero du tour P1,P2:TPlayer; //Joueur 1 et 2 BEGIN //Message de depart clrscr; writeln('Programme : jeu du Morpion'); writeln('Appuyez sur ''entrer'' pour lancer la partie'); readln; clrscr; //Creation des joueurs CreatPlayer(P1,P2); //Creation des cases du plateau de jeu CreatCases(Plateau); //Affichage du plateau AffPlateau; //Tour de jeu TourDeJeu(Plateau,Tour,P1,P2); readln; END.
{!DOCTOPIC}{ Matrix » TExtMatrix } {!DOCREF} { @method: Extended percision floating point matrix @desc: [hr] } {!DOCREF} { @method: procedure TExtMatrix.SetSize(Height,Width:Int32); @desc: Sets the size (width and height) of the matrix. Same as SetLength(Matrix, H,W); } procedure TExtMatrix.SetSize(Height,Width:Int32); begin SetLength(Self, Height,Width); end; {!DOCREF} { @method: function TExtMatrix.Width(): Int32; @desc: Retruns the width of the matrix (safely) } function TExtMatrix.Width(): Int32; begin if Length(Self) > 0 then Result := Length(Self[0]) else Result := 0; end; {!DOCREF} { @method: function TExtMatrix.Height(): Int32; @desc: Retruns the height of the matrix } function TExtMatrix.Height(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TExtMatrix.Get(const Indices:TPointArray): TExtArray @desc: Gets all the values at the given indices. If any of the points goes out of bounds, it will simply be ignored. [code=pascal] var Matrix:TExtMatrix; begin Matrix.SetSize(100,100); Matrix[10][10] := 100; Matrix[10][13] := 29; WriteLn( Matrix.Get([Point(10,10),Point(13,10),Point(20,20)])); end; [/code] } function TExtMatrix.Get(const Indices:TPointArray): TExtArray; begin Result := exp_GetValues(Self, Indices); end; {!DOCREF} { @method: procedure TExtMatrix.Put(const TPA:TPointArray; Values:TExtArray); @desc: Adds the points to the matrix with the given values. } procedure TExtMatrix.Put(const TPA:TPointArray; Values:TExtArray); begin exp_PutValues(Self, TPA, Values); end; {!DOCREF} { @method: procedure TExtMatrix.Put(const TPA:TPointArray; Value:Extended); overload; @desc: Adds the points to the matrix with the given value. } procedure TExtMatrix.Put(const TPA:TPointArray; Value:Extended); overload; begin exp_PutValues(Self, TPA, TExtArray([Value])); end; {!DOCREF} { @method: function TExtMatrix.Merge(): TExtArray; @desc: Merges the matrix is to a flat array of the same type. } function TExtMatrix.Merge(): TExtArray; var i,s,wid: Int32; begin S := 0; SetLength(Result, Self.Width()*Self.Height()); Wid := Self.Width(); for i:=0 to High(Self) do begin MemMove(Self[i][0], Result[S], Wid*SizeOf(Extended)); S := S + Wid; end; end; {!DOCREF} { @method: function TExtMatrix.Sum(): Extended; @desc: Returns the sum of the matrix } function TExtMatrix.Sum(): Extended; var i: Integer; begin for i:=0 to High(Self) do Result := Result + Self[i].Sum(); end; {!DOCREF} { @method: function TExtMatrix.Mean(): Extended; @desc: Returns the mean of the matrix } function TExtMatrix.Mean(): Extended; var i: Integer; begin for i:=0 to High(Self) do Result := Result + Self[i].Mean(); Result := Result / Length(Self); end; {!DOCREF} { @method: function TExtMatrix.Stdev(): Extended; @desc: Returns the standard deviation of the matrix } function TExtMatrix.Stdev(): Extended; var x,y,i,W,H:Int32; avg:Extended; square:TExtArray; begin W := Self.Width() - 1; H := Self.Height() - 1; avg := Self.Mean(); SetLength(square,Self.Width()*Self.Height()); i := -1; for y:=0 to H do for x:=0 to W do Square[inc(i)] := Sqr(Self[y,x] - avg); Result := Sqrt(square.Mean()); end; {!DOCREF} { @method: function TExtMatrix.Variance(): Extended; @desc: Return the sample variance. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the matrix. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. } function TExtMatrix.Variance(): Extended; var avg:Extended; x,y,w,h:Int32; begin W := Self.Width() - 1; H := Self.Height() - 1; avg := Self.Mean(); for y:=0 to H do for x:=0 to W do Result := Result + Sqr(Self[y,x] - avg); Result := Result / ((W+1) * (H+1)); end; {!DOCREF} { @method: function TExtMatrix.Mode(Eps:Extended=0.0000001): Extended; @desc: Returns the sample mode of the matrix, which is the most frequently occurring value in the matrix. When there are multiple values occurring equally frequently, mode returns the smallest of those values. } function TExtMatrix.Mode(Eps:Extended=0.0000001): Extended; begin Result := Self.Merge().Mode(Eps); end; {------------| GetArea, GetCols, GetRows |------------} {!DOCREF} { @method: function TExtMatrix.Area(X1,Y1,X2,Y2:Int32): TExtMatrix; @desc: Crops the matrix to the given box and returns that area. } function TExtMatrix.Area(X1,Y1,X2,Y2:Int32): TExtMatrix; begin Result := exp_GetArea(Self, X1,Y1,X2,Y2); end; {!DOCREF} { @method: function TExtMatrix.Cols(FromCol, ToCol:Integer): TExtMatrix; @desc: Returns all the wanted columns as a new matrix. } function TExtMatrix.Cols(FromCol, ToCol:Integer): TExtMatrix; begin Result := exp_GetCols(Self, FromCol, ToCol); end; {!DOCREF} { @method: function TExtMatrix.Rows(FromRow, ToRow:Integer): TExtMatrix; @desc: Returns all the wanted rows as a new matrix. } function TExtMatrix.Rows(FromRow, ToRow:Integer): TExtMatrix; begin Result := exp_GetRows(Self, FromRow, ToRow); end; {------------| FlipMat |------------} {!DOCREF} { @method: function TExtMatrix.Rows(FromRow, ToRow:Integer): TExtMatrix; @desc: Order of the items in the array is flipped, meaning x becomes y, and y becomes x. Example: [code=pascal] var x:TExtMatrix; begin x := [[1,2,3],[1,2,3],[1,2,3]]; WriteLn(x.Flip()); end. [/code] >> `[[1, 1, 1], [2, 2, 2], [3, 3, 3]]` } function TExtMatrix.Flip(): TExtMatrix; begin Result := exp_Flip(Self); end; {------------| Indices |------------} {!DOCREF} { @method: function TExtMatrix.Indices(Value: Extended; const Comparator:TComparator): TPointArray; @desc: Returns all the indices which matches the given value, and comperator. EG: c'TPA := Matrix.Indices(10, __LT__)' would return where all the items which are less then 10 is. } function TExtMatrix.Indices(Value: Extended; const Comparator:TComparator): TPointArray; begin Result := exp_Indices(Self, Value, Comparator); end; {!DOCREF} { @method: function TExtMatrix.Indices(Value: Extended; B:TBox; const Comparator:TComparator): TPointArray; overload; @desc: Returns all the indices which matches the given value, and comperator. EG: c'Matrix.Indices(10, __LT__)' would return all the items which are less then 10. Takes an extra param to only check a cirtain area of the matrix. } function TExtMatrix.Indices(Value: Extended; B:TBox; const Comparator:TComparator): TPointArray; overload; begin Result := exp_Indices(Self, B, Value, Comparator); end; {------------| ArgMin/ArgMax |------------} {!DOCREF} { @method: function TExtMatrix.ArgMax(): TPoint; @desc: ... } function TExtMatrix.ArgMax(): TPoint; begin Result := exp_ArgMax(Self); end; {!DOCREF} { @method: function TExtMatrix.ArgMax(Count:Int32): TPointArray; overload; @desc: Returns the n-largest elements, by index } function TExtMatrix.ArgMax(Count:Int32): TPointArray; overload; begin Result := exp_ArgMulti(Self, Count, True); end; {!DOCREF} { @method: function TExtMatrix.ArgMax(B:TBox): TPoint; overload; @desc: ... } function TExtMatrix.ArgMax(B:TBox): TPoint; overload; begin Result := exp_ArgMax(Self, B); end; {!DOCREF} { @method: function TExtMatrix.ArgMin(): TPoint; @desc: ... } function TExtMatrix.ArgMin(): TPoint; begin Result := exp_ArgMin(Self); end; {!DOCREF} { @method: function TExtMatrix.ArgMin(Count:Int32): TPointArray; overload; @desc: Returns the n-smallest elements, by index } function TExtMatrix.ArgMin(Count:Int32): TPointArray; overload; begin Result := exp_ArgMulti(Self, Count, False); end; {!DOCREF} { @method: function TExtMatrix.ArgMin(B:TBox): TPoint; overload; @desc: ... } function TExtMatrix.ArgMin(B:TBox): TPoint; overload; begin Result := exp_ArgMin(Self, B); end; {------------| VarMin/VarMax |------------} {!DOCREF} { @method: function TExtMatrix.VarMax(): Extended; @desc: Returns the largest element } function TExtMatrix.VarMax(): Extended; var tmp:TPoint; begin tmp := exp_ArgMax(Self); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TExtMatrix.VarMax(Count:Int32): TExtArray; overload; @desc: Returns the n-largest elements } function TExtMatrix.VarMax(Count:Int32): TExtArray; overload; begin Result := exp_VarMulti(Self, Count, True); end; {!DOCREF} { @method: function TExtMatrix.VarMax(B:TBox): Extended; overload; @desc: Returns the largest element within the given bounds `B` } function TExtMatrix.VarMax(B:TBox): Extended; overload; var tmp:TPoint; begin tmp := exp_ArgMax(Self, B); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TExtMatrix.VarMin(): Extended; @desc: Returns the the smallest element } function TExtMatrix.VarMin(): Extended; var tmp:TPoint; begin tmp := exp_ArgMin(Self); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TExtMatrix.VarMax(Count:Int32): TExtArray; overload; @desc: Returns the n-smallest elements } function TExtMatrix.VarMin(Count:Int32): TExtArray; overload; begin Result := exp_VarMulti(Self, Count, False); end; {!DOCREF} { @method: function TExtMatrix.VarMin(B:TBox): Extended; overload; @desc: VarMin returns the smallest item within the given bounds `B` } function TExtMatrix.VarMin(B:TBox): Extended; overload; var tmp:TPoint; begin tmp := exp_ArgMin(Self, B); Result := Self[tmp.y, tmp.x]; end; {------------| MinMax |------------} {!DOCREF} { @method: procedure TExtMatrix.MinMax(var Min, Max:Extended); @desc: Returns the smallest, and the largest element in the matrix. } procedure TExtMatrix.MinMax(var Min, Max:Extended); begin exp_MinMax(Self, Min, Max); end; {------------| CombineMatrix |------------} {!DOCREF} { @method: function TExtMatrix.Combine(Other:TExtMatrix; OP:Char='+'): TExtMatrix; @desc: Merges the two matrices in to one matrix.. Supports different operatrions/methods for combining ['+','-','*','/']. [code=pascal] var Mat:TExtMatrix; begin SetLength(Mat, 3); Mat[0] := [1,1,1]; Mat[1] := [2,2,2]; Mat[2] := [3,3,3]; WriteLn( Mat.Combine(Mat, '*') ); end. [/code] Outputs: >>> `[[1, 1, 1], [4, 4, 4], [9, 9, 9]]` } function TExtMatrix.Combine(Other:TExtMatrix; OP:Char='+'): TExtMatrix; begin Result := exp_CombineMatrix(Self, Other, OP); end; {------------| Normalize (Matrix) |------------} {!DOCREF} { @method: function TExtMatrix.Normalize(Alpha, Beta:Extended): TExtMatrix; @desc: Fits each element of the matrix within the values of Alpha and Beta. } function TExtMatrix.Normalize(Alpha, Beta:Extended): TExtMatrix; begin Result := exp_Normalize(Self, Alpha, Beta); end;
{$MODE OBJFPC} unit camera; interface uses gl,glu,glut; type TCamera=class private x,y,z:extended; rd,ud:extended; public constructor Create; procedure Move(t:extended); procedure MoveY(t:extended); procedure Turn(drd,dud:extended); procedure Modify; end; implementation constructor TCamera.Create; begin x:=0; y:=0; z:=0; rd:=0; ud:=0; end; procedure TCamera.Move(t:extended); begin x:=x+sin(rd*PI/180)*t; z:=z+cos(rd*PI/180)*t; end; procedure TCamera.MoveY(t:extended); begin y:=y-t; end; procedure TCamera.Turn(drd,dud:extended); begin rd:=rd+drd; if(rd>359)then rd:=0; if(rd<-359)then rd:=0; ud:=ud+dud; if(ud>89)then ud:=89; if(ud<-89)then ud:=-89; end; procedure TCamera.Modify; begin glRotatef(ud,1,0,0); glRotatef(360-rd,0,1,0); glTranslatef(x,y,z); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ScktComp, IdBaseComponent, IdComponent, IdGlobal, IdUDPBase, IdUDPClient; type TByteArr = array of byte; TForm1 = class(TForm) Panel1: TPanel; Panel2: TPanel; Edit1: TEdit; Button1: TButton; Label1: TLabel; Label2: TLabel; Edit2: TEdit; Label3: TLabel; Edit3: TEdit; Memo1: TMemo; IdUDPClient1: TIdUDPClient; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin IdUDPClient1.Port := StrToInt(Edit1.Text); IdUDPClient1.Host := Edit2.Text; end; procedure TForm1.Button1Click(Sender: TObject); var ArByte : TByteArr; idx: integer; sl:TStringList; puerto:Word; sIp:String; begin try try puerto := 8040; sIp:= '127.0.0.1'; // sl := TStringList.Create; IdUDPClient1.Active := True; // sl.Delimiter := ','; // sl.DelimitedText := Edit3.Text; IdUDPClient1.Send(Edit3.Text); Memo1.Lines.Text := IdUDPClient1.ReceiveString(); // SetLength(ArByte, sl.Count); // for idx := 0 to sl.Count - 1 do // begin // ArByte[idx] := StrToInt(sl[idx]); // end; except on E:Exception do begin ShowMessage('Error de envío: ' + E.Message); end; end; finally // sl.Free; end; end; end.
unit MMO.ClientReadThread; interface uses Classes, IdTCPClient, MMO.PacketReader, IdIOHandler, IdGlobal, MMO.Types; type TClientReadThread = class; TSyncClientReadThreadReadEvent = procedure(const sender: TObject; const packetReader: TPacketReader) of object; TClientReadThread = class(TThread) private var m_client: TIdTCPClient; var m_onRead: TSyncClientReadThreadReadEvent; var m_name: string; procedure Execute; override; procedure TriggerReadEvent(const packetReader: TPacketReader); function TryReadBuffer(const ioHandler: TIdIOHandler; var buffer: TIdBytes; var packetHeader: TPacketHeader): Boolean; public constructor Create(const threadName: string; const client: TIdTCPClient); destructor Destroy; override; property OnRead: TSyncClientReadThreadReadEvent read m_onRead write m_onRead; end; implementation constructor TClientReadThread.Create(const threadName: string; const client: TIdTCPClient); begin inherited Create(True); m_name := threadName; m_client := client; end; destructor TClientReadThread.Destroy; begin inherited; end; procedure TClientReadThread.Execute; var ioHandler: TIdIOHandler; buffer: TIdBytes; bufferSize, dataSize: UInt32; packetReader: TPacketReader; packetHeader: TPacketHeader; begin inherited; NameThreadForDebugging(m_name + 'ReadThread', self.ThreadID); while not Terminated do begin if not m_client.Connected then begin Sleep(100); continue; end; ioHandler := m_client.IOHandler; SetLength(buffer, 0); if not TryReadBuffer(ioHandler, buffer, packetHeader) then begin break; end; dataSize := packetHeader.Size; bufferSize := Length(buffer); if not (dataSize = bufferSize) then begin m_client.Disconnect; Exit; end; packetReader := TPacketReader.CreateFromBytesArray(buffer); self.TriggerReadEvent(packetReader); packetReader.Free; end; end; function TClientReadThread.TryReadBuffer(const ioHandler: TIdIOHandler; var buffer: TIdBytes; var packetHeader: TPacketHeader): Boolean; begin try ioHandler.ReadBytes(buffer, SizeOfTPacketHeader, False); move(buffer[0], packetHeader, SizeOfTPacketHeader); ioHandler.ReadBytes(buffer, packetHeader.Size, False); except Exit(False); end; Exit(True); end; procedure TClientReadThread.TriggerReadEvent(const packetReader: TPacketReader); begin if Assigned(m_onRead) then begin m_onRead(self, packetReader); end; end; end.
unit Privacy; interface type IPrivacyHandler = interface procedure IgnoreUser( username : string ); procedure ClearIgnoredUser( username : string ); function UserIsIgnored( username : string ) : boolean; procedure GetDefaultChannelData( out name, password : string ); procedure SetDefaultChannelData( name, password : string ); end; const evnAnswerPrivacyHandler = 5700; implementation end.
unit FDAMSupp; {MPArith support routines for D/AMath test programs} interface {$i STD.INC} {$ifdef BIT16} {$N+} {$endif} uses BTypes, mp_types, mp_real; {$i mp_conf.inc} (************************************************************************* DESCRIPTION : MPArith support routines for D/AMath test programs} REQUIREMENTS : BP7, D1-D7/D9-D10/D12/D17-D18, FPC, VP REMARK : The routines should not be used as stand-alone functions! The precision handling is appropriate only for checking the AMath and DAMath functions! Many routines do not have error handling, argument and/or range checks. Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.0.01 30.06.14 W.Ehrhardt Separate unit forked from t_amathx 0.0.02 01.07.14 we mpf_rem_2pi from t_xdamat 0.0.03 06.10.14 we mpf_logistic 0.0.04 31.05.15 we mpf_versint 0.0.05 19.06.15 we mpf_sinhc 0.0.06 25.06.15 we mpf_sinhmx **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2007-2015 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. ----------------------------------------------------------------------------*) procedure mpf_arccosd(const a: mp_float; var b: mp_float); {-Calculate b = arccos(a), b in degrees} procedure mpf_arccotcd(const a: mp_float; var b: mp_float); {-Calculate b = arccotc(a), b in degrees} procedure mpf_arccotd(const a: mp_float; var b: mp_float); {-Calculate b = arccot(a), b in degrees} procedure mpf_arcsind(const a: mp_float; var b: mp_float); {-Calculate b = arcsin(a), b in degrees} procedure mpf_arctand(const a: mp_float; var b: mp_float); {-Calculate b = arctan(a), b in degrees} procedure mpf_cbrt(const a: mp_float; var b: mp_float); {-Calculate b = a^(1/3) } procedure mpf_cosd(const a: mp_float; var b: mp_float); {-Calculate b = cos(a), a in degrees} procedure mpf_cotd(const a: mp_float; var b: mp_float); {-Calculate b = cot(a), a in degrees} procedure mpf_covers(const a: mp_float; var b: mp_float); {-Calculate b = 1-sin(a)} procedure mpf_deg2rad(const a: mp_float; var b: mp_float); {-Convert a in degrees to b in radians} procedure mpf_exp3(const a: mp_float; var b: mp_float); {-Calculate b = 3^a} procedure mpf_exp5(const a: mp_float; var b: mp_float); {-Calculate b = 5^a} procedure mpf_exp7(const a: mp_float; var b: mp_float); {-Calculate b = 7^a} procedure mpf_expmx2h(const a: mp_float; var b: mp_float); {-Calculate b = exp(-0.5*x^2) } procedure mpf_exprel(const a: mp_float; var b: mp_float); {-Calculate b = (exp(a)-1)/a, 1 for a=0} procedure mpf_expt1p(const a,b: mp_float; var c: mp_float); {-Calculate c = (1+a)^b, a>-1} procedure mpf_expx2(const a: mp_float; var b: mp_float); {-Calculate b = exp(a*abs(a)) } procedure mpf_langevin(const a: mp_float; var b: mp_float); {-Calculate the Langevin function b = L(a) = coth(a) - 1/a, L(0) = 0} procedure mpf_ln1mexp(const a: mp_float; var b: mp_float); {-Calculate b := ln(1-exp(a)), a<0} procedure mpf_ln1pmx(const x: mp_float; var y: mp_float); {-Calculate y = ln(1+x)-x} procedure mpf_logistic(const a: mp_float; var b: mp_float); {-Calculate b = 1/(1+exp(-a))} procedure mpf_logit(const a: mp_float; var b: mp_float); {-Calculate b := ln(a/(1-a)), 0<a<1)} procedure mpf_rad2deg(const a: mp_float; var b: mp_float); {-Convert a in radians to b in degrees} procedure mpf_rem_2pi(const a: mp_float; var b: mp_float); {-Calculate b = a mod (2*Pi)} procedure mpf_sincPi(const a: mp_float; var b: mp_float); {-Calculate b = sin(Pi*a)/(Pi*a)} procedure mpf_sind(const a: mp_float; var b: mp_float); {-Calculate b = sin(a), a in degrees} procedure mpf_sinhc(const a: mp_float; var b: mp_float); {-Calculate b = sinh(a)/a} procedure mpf_sinhmx(const a: mp_float; var b: mp_float); {-Calculate b = sinh(a)-a} procedure mpf_tand(const a: mp_float; var b: mp_float); {-Calculate b = tan(a), a in degrees} procedure mpf_versint(const a: mp_float; var b: mp_float); {-Return b := versint(a) = int(vers(a),a) = a - sin(a)} implementation {---------------------------------------------------------------------------} procedure mpf_exp3(const a: mp_float; var b: mp_float); {-Calculate b = 3^a} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set_ext(t,3.0); mpf_expt(t,a,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_exp5(const a: mp_float; var b: mp_float); {-Calculate b = 5^a} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set_ext(t,5.0); mpf_expt(t,a,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_exp7(const a: mp_float; var b: mp_float); {-Calculate b = 7^a} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set_ext(t,7.0); mpf_expt(t,a,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_sincPi(const a: mp_float; var b: mp_float); {-Calculate b = sin(Pi*a)/(Pi*a)} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_trig_ex(a, true, nil, @t, nil); mpf_div(t,a,b); mpf_set_pi(t); mpf_div(b,t,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_ln1pmx(const x: mp_float; var y: mp_float); {-Calculate y = ln(1+x)-x} var c: mp_float; begin mpf_initp(c,y.bitprec+32); if mp_error<>MP_OKAY then exit; mpf_ln1p(x,c); mpf_sub(c,x,y); mpf_clear(c); end; {---------------------------------------------------------------------------} procedure mpf_expx2(const a: mp_float; var b: mp_float); {-Calculate b = exp(a*abs(a)) } begin mpf_abs(a,b); mpf_mul(a,b,b); mpf_exp(b,b); end; {---------------------------------------------------------------------------} procedure mpf_expmx2h(const a: mp_float; var b: mp_float); {-Calculate b = exp(-0.5*x^2) } begin mpf_mul(a,a,b); mpf_mul_ext(b,-0.5,b); mpf_exp(b,b); end; {---------------------------------------------------------------------------} procedure mpf_cbrt(const a: mp_float; var b: mp_float); {-Calculate b = a^(1/3) } var an: boolean; begin an := s_mpf_is_neg(a); mpf_abs(a,b); mpf_ln(b,b); mpf_div_ext(b,3.0,b); mpf_exp(b,b); if an then s_mpf_chs(b); end; {---------------------------------------------------------------------------} procedure mpf_exprel(const a: mp_float; var b: mp_float); {-Calculate b = (exp(a)-1)/a, 1 for a=0} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_expm1(a,t); mpf_div(t,a,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_covers(const a: mp_float; var b: mp_float); {-Calculate b = 1-sin(a)} var e,t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp2(e,t,b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set1(e); mpf_sin(a,t); mpf_sub(e,t,t); mpf_copyp(t,b); mpf_clear2(e,t); end; end; {---------------------------------------------------------------------------} procedure mpf_versint(const a: mp_float; var b: mp_float); {-Return b := versint(a) = int(vers(a),a) = a - sin(a)} var t: mp_float; begin if mp_error<>MP_OKAY then exit; {$ifdef MPC_ArgCheck} if mpf_not_init(a) or mpf_not_init(b) then begin {$ifdef MPC_HaltOnArgCheck} {$ifdef MPC_UseExceptions} raise MPXNotInit.Create('mpf_versint'); {$else} RunError(MP_RTE_NOTINIT); {$endif} {$else} set_mp_error(MP_NOTINIT); exit; {$endif} end; {$endif} if mpf_is0(a) then begin mpf_set0(b); exit; end; if s_mpf_ldx(a)>0 then mpf_initp(t, b.bitprec+32) else mpf_initp(t, 2*b.bitprec); if mp_error=MP_OKAY then begin mpf_sin(a,t); mpf_sub(a,t,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_deg2rad(const a: mp_float; var b: mp_float); {-Convert a in degrees to b in radians} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set0(b); exit; end; mpf_initp(t,b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set_pi(t); mpf_mul(t,a,t); mpf_div_d(t,180,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_rad2deg(const a: mp_float; var b: mp_float); {-Convert a in radians to b in degrees} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set0(b); exit; end; mpf_initp(t,b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set_pi(t); mpf_div(a,t,t); mpf_mul_d(t,180,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_rem_2pi(const a: mp_float; var b: mp_float); {-Calculate b = a mod (2*Pi)} var oddm: boolean; begin if mp_error<>MP_OKAY then exit; s_mpf_mod_pi2k(a,1,b,oddm); end; {---------------------------------------------------------------------------} procedure mpf_langevin(const a: mp_float; var b: mp_float); {-Calculate the Langevin function b = L(a) = coth(a) - 1/a, L(0) = 0} var s,t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set0(b); exit; end; mpf_initp2(s,t,b.bitprec+32); if mp_error=MP_OKAY then begin mpf_coth(a,s); mpf_inv(a,t); mpf_sub(s,t,t); mpf_copyp(t,b); mpf_clear2(s,t); end; end; {---------------------------------------------------------------------------} procedure mpf_ln1mexp(const a: mp_float; var b: mp_float); {-Calculate b := ln(1-exp(a)), a<0} var t: mp_float; begin if mp_error<>MP_OKAY then exit; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin if mpf_cmp_ext(a,-0.693147180559945309)>0 then begin {range -ln(2) < a < 0} mpf_expm1(a,t); s_mpf_chs(t); mpf_ln(t,b); end else begin mpf_exp(a,t); s_mpf_chs(t); mpf_ln1p(t,b); end; mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_logistic(const a: mp_float; var b: mp_float); {-Calculate b = 1/(1+exp(-a))} var t: mp_float; begin if mp_error<>MP_OKAY then exit; mpf_initp(t,b.bitprec+8); if mp_error=MP_OKAY then begin {check exp(-a) < 2^(-t.bitprec)} if s_mpf_ldx(a) > 1.45*ln(t.bitprec+2.0) then begin if s_mpf_is_ge0(a) then mpf_set0(b) else begin {a negative, 1/(1+exp(-a)) ~ 1/exp(-a) = exp(a)} mpf_exp(a,b); end; end else begin mpf_chs(a,t); mpf_exp(t,t); s_mpf_inc1(t); mpf_inv(t,b); end; mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_logit(const a: mp_float; var b: mp_float); {-Calculate b := ln(a/(1-a)), 0<a<1)} var t: mp_float; begin if mp_error<>MP_OKAY then exit; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_set1(t); mpf_sub(t,a,t); mpf_div(a,t,t); mpf_ln(t,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_expt1p(const a,b: mp_float; var c: mp_float); {-Calculate c = (1+a)^b, a>-1} var t: mp_float; p: longint; begin if mp_error<>MP_OKAY then exit; {$ifdef MPC_ArgCheck} if mpf_not_init(a) or mpf_not_init(b) or mpf_not_init(c) then begin {$ifdef MPC_HaltOnArgCheck} {$ifdef MPC_UseExceptions} raise MPXNotInit.Create('mpf_expt1p'); {$else} RunError(MP_RTE_NOTINIT); {$endif} {$else} set_mp_error(MP_NOTINIT); exit; {$endif} end; {$endif} if s_mpf_is_le0(a) then p:=0 else begin p := abs(s_mpf_ldx(a)); if p<32 then p := 32; end; mpf_initp(t, c.bitprec+p); if mp_error=MP_OKAY then begin mpf_ln1p(a,t); mpf_mul(t,b,t); mpf_exp(t,c); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_sind(const a: mp_float; var b: mp_float); {-Calculate b = sin(a), a in degrees} begin mpf_deg2rad(a,b); mpf_sin(b,b); end; {---------------------------------------------------------------------------} procedure mpf_sinhc(const a: mp_float; var b: mp_float); {-Calculate b = sinh(a)/a} var t: mp_float; begin if mp_error<>MP_OKAY then exit; if mpf_is0(a) then begin mpf_set1(b); exit; end; mpf_initp(t, b.bitprec+32); if mp_error=MP_OKAY then begin mpf_sinh(a,t); mpf_div(t,a,t); mpf_copyp(t,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_sinhmx(const a: mp_float; var b: mp_float); {-Calculate b = sinh(a)-a} var t: mp_float; p: longint; begin if mp_error<>MP_OKAY then exit; p := b.bitprec+16; if s_mpf_ldx(a)<=1 then p := 2*p; mpf_initp(t, p); if mp_error=MP_OKAY then begin mpf_sinh(a,t); mpf_sub(t,a,t); mpf_copyp(t,b); mpf_clear(t); end; end; {---------------------------------------------------------------------------} procedure mpf_cosd(const a: mp_float; var b: mp_float); {-Calculate b = cos(a), a in degrees} begin mpf_deg2rad(a,b); mpf_cos(b,b); end; {---------------------------------------------------------------------------} procedure mpf_tand(const a: mp_float; var b: mp_float); {-Calculate b = tan(a), a in degrees} begin mpf_deg2rad(a,b); mpf_tan(b,b); end; {---------------------------------------------------------------------------} procedure mpf_cotd(const a: mp_float; var b: mp_float); {-Calculate b = cot(a), a in degrees} begin mpf_deg2rad(a,b); mpf_cot(b,b); end; {---------------------------------------------------------------------------} procedure mpf_arctand(const a: mp_float; var b: mp_float); {-Calculate b = arctan(a), b in degrees} begin mpf_arctan(a,b); mpf_rad2deg(b,b); end; {---------------------------------------------------------------------------} procedure mpf_arccotd(const a: mp_float; var b: mp_float); {-Calculate b = arccot(a), b in degrees} begin mpf_arccot(a,b); mpf_rad2deg(b,b); end; {---------------------------------------------------------------------------} procedure mpf_arccotcd(const a: mp_float; var b: mp_float); {-Calculate b = arccotc(a), b in degrees} begin mpf_arccotc(a,b); mpf_rad2deg(b,b); end; {---------------------------------------------------------------------------} procedure mpf_arcsind(const a: mp_float; var b: mp_float); {-Calculate b = arcsin(a), b in degrees} begin mpf_arcsin(a,b); mpf_rad2deg(b,b); end; {---------------------------------------------------------------------------} procedure mpf_arccosd(const a: mp_float; var b: mp_float); {-Calculate b = arccos(a), b in degrees} begin mpf_arccos(a,b); mpf_rad2deg(b,b); end; end.
program xpatch(them); {This program is supplied as a simple example of interrupt handling. Actually I think it may have a slight timing problem, but it will give the idea. It crosspatches your terminal to another one, or to a PTY:. I.e. anything you type it gets and visa versa. E.g. if you dial out from your computer to another one, this could let you communicate with it. On Tops-10 this program would be symmetrical, driven by interrupts on the channels on which the two terminals are openned. However here it is only possible to get an interrupt for the controlling terminal, so the other is done in a loop. To get out of this, you type ^A. } label 1; const sibe=102B; priin=100B; ati=137B; rfmod=107B; sfmod=110B; stiw=174B; fhslf=400000B; epcap=151B; type byte=0..377B; var us,them:file of byte; procedure fromus; {FROMUS is activated whenever the input buffer from our terminal becomes non-empty (after having been empty). We must keep reading characters until it becomes empty, or we may hang.} var ret,count:integer; begin loop jsys(sibe,2,ret;0:us;count,count); {Any more char's waiting?} exit if (ret = 2) or (count = 0); {No} for count := count downto 1 do {SIBE returns how many char's} begin get(us); {Copy each one} if (us^ = 1) or (us^ = 201B) then goto 1; them^ := us^; put(them) end end; end; procedure psidefine(chan,level:integer;procedure p); extern; procedure psienable(chan:integer); extern; begin update(us,'TTY:',true,0,100000000000B,1); {open in 8-bit mode, BIN/BOUT} update(them,'',true,0,100000000000B,1); jsys(epcap;fhslf,0,400000B:0); {turn on ability to trap ^C} jsys(stiw;0:-5,20B); {turn off all char interrupts except 31} psidefine(35,1,fromus); {call fromus on chan 35 int., level 1} psienable(35); {turn on those interrupts} jsys(ati;31:35); {assign int 31 (incoming char) to chan 35} fromus; {prevent possible race} while true do {now do them to us, us to them at int. level} begin get(them); us^ := them^; put(us) end; 1: {here when type ^A} end.
program ejercicio1; const dimF = 5; type rangoGenreo = 1..5; str40 = String[40]; persona = record dni : Integer; apellido : str40; nombre : str40; edad : Integer; codGenero : rangoGenreo; end; lista = ^nodo; nodo = record datos : persona; sig : lista; end; vContador = array[rangoGenreo] of Integer; procedure leerDatos(var p: persona); begin with p do begin write('Ingres el DNI: '); readln(dni); write('Ingrese APELLIDO: '); readln(apellido); write('Ingres NOMBRE: '); readln(nombre); write('ingrese EDAD: '); readln(edad); write('Ingrese CODIGO DE GENERO: '); readln(codGenero); writeln('------------------------'); end; end; procedure inicializarVector(var vc:vContador); var i: Integer; begin for i := 1 to dimF do begin vc[i]:= 0; end; end; procedure agregarAdelante(var l:lista; p:persona); var nue: lista; begin new(nue); nue^.datos:= p; nue^.sig:= l; l:= nue; end; procedure cargarLista(var l:lista; var vc:vContador); var p: persona; begin repeat leerDatos(p); agregarAdelante(l,p); until (p.dni = 33555444); end; procedure codMax(vc: vContador; codigo: Integer; var max1,max2: Integer; var codMax1,codMax2: Integer); var i: Integer; begin for i := 1 to dimF do begin if (vc[i] > max1) then begin max2:= max1; codMax2:= codMax1; max1:= vc[i]; codMax1:= codigo; end else if (vc[i] > max2) then begin max2:= vc[i]; codMax2:= codigo; end; end; end; function cumple(dni:Integer): Boolean; var dig, par, imp: Integer; begin par:= 0; imp:= 0; while (dni <> 0) do begin dig:= dni mod 10; if ((dig mod 2) = 0 ) then par:= par + 1 else imp:= imp + 1; dni:= dni div 10; end; cumple:= par > imp; end; procedure procesarInfo(l:lista; vc:vContador); var max1, max2, codMax1, codMax2,conDni: Integer; begin max1:= -1; max2:= -2; codMax1:= 0; codMax2:= 0; conDni:= 0; while (l <> nil) do begin if (cumple(l^.datos.dni)) then conDni:= conDni + 1; vc[l^.datos.codGenero]:= vc[l^.datos.codGenero] + 1; l:= l^.sig; end; codMax(vc,l^.datos.codGenero, max1,max2, codMax1,codMax2); writeln('La cantidad de personas cuyo DNI contiene mas digitos pares que impares son: ', conDni); writeln('Los dos codigos de genero mas elegidos son: ', codMax1, ' y ', codMax2); end; procedure eliminarDni(var l:lista; dniE: Integer; var ok: Boolean); var act,ant: lista; begin ok:= false; act:= l; ant:= l; while (act <> nil) and (act^.datos.dni <> dniE) do begin ant:= act; act:= act^.sig; end; if (act <> nil) then begin ok:= true; if (act = l) then l:= l^.sig else ant^.sig:= act^.sig; dispose(act); end; end; var l: lista; vc: vContador; dniE: Integer; ok: Boolean; begin l:= nil; inicializarVector(vc); cargarLista(l, vc); procesarInfo(l,vc); writeln('Ingrese DNI a ELIMINAR: '); readln(dniE); eliminarDni(l,dniE,ok); if (ok) then writeln('El DNI ', dniE, ' SE ha ELIMINADO ') else writeln('El DNI ', dniE, ' NO se ha ELIMIANDO '); readln(); end.
unit uFiltroChamado; interface uses uRevendaVO, uModuloVO, System.SysUtils, uFiltroCliente; type TFiltroChamado = class private FIdStatus: string; FIdTipo: string; FIdCliente: string; FIdUsuarioAbertura: string; FDataFinal: string; FDataInicial: string; FRevenda: TRevendaVO; FModulo: TModuloVO; FCliente: TFiltroCliente; FTipoMovimento: Integer; FId: Integer; FOrigem: Integer; public constructor Create; destructor Destroy; override; property DataInicial: string read FDataInicial write FDataInicial; property DataFinal: string read FDataFinal write FDataFinal; property IdUsuarioAbertura: string read FIdUsuarioAbertura write FIdUsuarioAbertura; property IdCliente: string read FIdCliente write FIdCliente; property IdTipo: string read FIdTipo write FIdTipo; property IdStatus: string read FIdStatus write FIdStatus; property Revenda: TRevendaVO read FRevenda write FRevenda; property Modulo: TModuloVO read FModulo write FModulo; property Cliente: TFiltroCliente read FCliente write FCliente; property TipoMovimento: Integer read FTipoMovimento write FTipoMovimento; property Id: Integer read FId write FId; property Origem: Integer read FOrigem write FOrigem; end; implementation constructor TFiltroChamado.Create; begin inherited Create(); FRevenda := TRevendaVO.Create; FModulo := TModuloVO.Create; FCliente := TFiltroCliente.Create; end; destructor TFiltroChamado.Destroy; begin FreeAndNil(FRevenda); FreeAndNil(FModulo); FreeAndNil(FCliente); inherited; end; end.
Unit TERRA_ResourceLoader; {$I terra.inc} Interface Uses TERRA_Utils, TERRA_Application, TERRA_Resource; Type ResourceLoader = Class(ApplicationComponent) Protected _Resources:Array Of Resource; _ResourceCount:Integer; _Index:Integer; _FistTime:Boolean; _LastProgress:Single; Procedure Update; Override; Procedure Init; Override; Public Class Function Instance:ResourceLoader; Procedure Release; Override; Procedure Clear; Procedure AddResource(Res:Resource); Function GetCurrent:Resource; Function GetProgress:Single; Function IsReady:Boolean; End; Implementation Uses TERRA_ResourceManager, TERRA_Mesh, TERRA_Log; { LoaderManager } Var _LoaderManagerInstance:ApplicationObject; Procedure ResourceLoader.AddResource(Res: Resource); Var I:Integer; Begin If (Res= Nil) Then Begin IntToString(2); Exit; End; For I:=0 To Pred(_ResourceCount) Do If (_Resources[I] = Res) Then Exit; Inc(_ResourceCount); SetLength(_Resources, _ResourceCount); _Resources[Pred(_ResourceCount)] := Res; Log(logDebug, 'Loader', 'Adding resource: '+Res.Name); End; Procedure ResourceLoader.Clear; Begin _Index := 0; _ResourceCount :=0 ; _FistTime := True; _LastProgress := 0; End; Procedure ResourceLoader.Init; Begin Self.Clear; End; Procedure ResourceLoader.Release; Begin _LoaderManagerInstance := Nil; End; Function ResourceLoader.GetCurrent:Resource; Begin If _ResourceCount<=0 Then Result := Nil Else Result := _Resources[_Index]; End; Function ResourceLoader.GetProgress:Single; Var I, Count:Integer; Begin Count := 0; For I:=0 To Pred(_ResourceCount) Do If (_Resources[I].Status = rsReady) Then Inc(Count); If (_ResourceCount<=0) Then Result := 100 Else Result := (Count/_ResourceCount)*100; If (Result<_LastProgress) Then Result := _LastProgress; _LastProgress := Result; End; Class Function ResourceLoader.Instance:ResourceLoader; Begin If _LoaderManagerInstance = Nil Then _LoaderManagerInstance := InitializeApplicationComponent(ResourceLoader, Nil); Result := ResourceLoader(_LoaderManagerInstance.Instance); End; Function ResourceLoader.IsReady: Boolean; Begin Result := GetProgress>=100; End; Procedure ResourceLoader.Update; Var J:Integer; Group:MeshGroup; MyMesh:Mesh; Begin If (_ResourceCount<=0) Then Exit; If _FistTime Then Begin _FistTime := False; End; _Resources[_Index].IsReady(); If (_Resources[_Index].Status = rsReady) Then Begin If _Resources[_Index] Is Mesh Then Begin MyMesh := Mesh(_Resources[_Index]); For J:=0 To Pred(MyMesh.GroupCount) Do Begin Group := MyMesh.GetGroup(J); Self.AddResource(Group.DiffuseMap); Self.AddResource(Group.NormalMap); Self.AddResource(Group.SpecularMap); Self.AddResource(Group.GlowMap); Self.AddResource(Group.LightMap); Self.AddResource(Group.ToonRamp); End; End; If (_Index<Pred(_ResourceCount)) Then Inc(_Index); End; End; End.
unit MdiChilds.LatinCheck; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, GsDocument, ComObj, ActionHandler; type TFmLatinCheck = class(TFmProcess) lbFiles: TListBox; DragDrop: TJvDragDrop; procedure DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); private function isValidWord(Word: string): Boolean; function HasLatin(Word: string): Boolean; function HasCyr(Word: string): Boolean; protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public procedure Exec(D: TGsDocument); procedure CheckLatin(S: TStringList; Item: TGsAbstractItem); procedure CreateReportRow(WS: OleVariant; RecType: string; RecValue: string; Comment: string); function GetChapterInfo(Item: TGsAbstractItem): string; procedure GetRowInfo(S: TStringList; Item: TGsAbstractItem); procedure GetDetailInfo(S: TStringList; Item: TGsAbstractItem); procedure GetResourceInfo(S: TStringList; Item: TGsAbstractItem); procedure Analize(S: TStringList; WS: OleVariant); procedure AnalizeCell(Cell: OleVariant); function LatinExists(Value: string): Boolean; end; TLatinCheckActionHandler = class(TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmLatinCheck: TFmLatinCheck; implementation {$R *.dfm} procedure TFmLatinCheck.Analize(S: TStringList; WS: OleVariant); var I, J: Integer; v: TArray<String>; begin J := 1; for I := 0 to S.Count - 1 do begin v := S[I].Split(['#']); if LatinExists(v[3]) then begin WS.Cells[J, 1].Value := '''' + v[0]; WS.Cells[J, 2].Value := '''' + v[1]; WS.Cells[J, 3].Value := '''' + v[2]; WS.Cells[J, 4].Value := '''' + v[3] + ''''; AnalizeCell(WS.Cells[J, 4]); Inc(J); end; SetLength(v, 0); end; end; procedure TFmLatinCheck.AnalizeCell(Cell: OleVariant); var Value: string; I: Integer; NewWord: String; begin Value := Cell.Value; NewWord := ''; I := 1; // [' ', #9, '/', ',', ':', ';', '-', '=', '(', ')', '<', '>', '«', '»', '•', '·', '.', '–', '"', ''''] while (I <= Length(Value)) do begin if (I < Length(Value)) and not(CharInSet( Value[I] , [' ', #9, '/', ',', ':', ';', '-', '=', '(', ')', '<', '>', '«', '»', '•', '·', '.', '–', '"', ''''])) then NewWord := NewWord + Value[I] else begin if not isValidWord(NewWord) then begin Cell.Characters[I - Length(NewWord), Length(NewWord)].Font.ColorIndex := 5; end; NewWord := ''; end; Inc(I); end; for I := 1 to Length(Value) do if CharInSet(Value[I], ['A' .. 'Z', 'a' .. 'z']) then Cell.Characters[I, 1].Font.ColorIndex := 3; end; procedure TFmLatinCheck.CheckLatin(S: TStringList; Item: TGsAbstractItem); var I: Integer; begin if Item is TGsChapter then S.Add(GetChapterInfo(Item)) else if Item is TGsRow then GetRowInfo(S, Item) else if Item is TGsDetail then GetDetailInfo(S, Item) else if Item is TGsResource then GetResourceInfo(S, Item); for I := 0 to Item.Count - 1 do CheckLatin(S, Item.Items[I]); end; function TFmLatinCheck.HasCyr(Word: string): Boolean; const Rus = '¨ÉÖÓÊÅÍÃØÙÇÕÚÔÛÂÀÏÐÎËÄÆÝß×ÑÌÈÒÜÁÞàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ'; var I: Integer; begin Result := False; for I := 1 to Length(Word) do if Pos(Word[I], Rus) > 0 then begin Exit(True); end; end; function TFmLatinCheck.HasLatin(Word: string): Boolean; var I: Integer; begin Result := False; for I := 1 to Length(Word) do if CharInSet(Word[I], ['A' .. 'Z', 'a' .. 'z']) then begin Exit(True); end; end; function TFmLatinCheck.isValidWord(Word: string): Boolean; var A, B: Boolean; begin Result := True; if Word = '' then Exit; A := HasLatin(Word); B := HasCyr(Word); if A and B then Exit(False); end; function TFmLatinCheck.LatinExists(Value: string): Boolean; var A: TArray<String>; I: Integer; begin Result := False; A := Value.Split([' ', #9, '/', ',', ':', ';', '-', '=', '(', ')', '<', '>', '«', '»', '•', '·', '.', '–', '"']); for I := 0 to Length(A) - 1 do if HasLatin(A[I]) and HasCyr(A[I]) then begin Result := True; Break; end; SetLength(A, 0); end; procedure TFmLatinCheck.CreateReportRow(WS: OleVariant; RecType, RecValue, Comment: string); begin end; procedure TFmLatinCheck.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; D: TGsDocument; begin ProgressForm.InitPB(lbFiles.Count); ProgressForm.Show; for I := 0 to lbFiles.Count - 1 do begin if not ProgressForm.InProcess then Break; ProgressForm.StepIt(lbFiles.Items[I]); D := TGsDocument.Create; try D.LoadFromFile(lbFiles.Items[I]); try Exec(D); except on E: Exception do Self.MessageBoxError('Îøèáêà ïðè îáðàáîòêå äîêóìåíòà:' + lbFiles.Items[I]); end; finally D.Free; end; end; end; procedure TFmLatinCheck.DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin lbFiles.Items.Assign(Value); end; procedure TFmLatinCheck.Exec(D: TGsDocument); var I: Integer; ExlApp: OleVariant; WB: OleVariant; WS: OleVariant; S: TStringList; begin ExlApp := CreateOleObject('Excel.Application'); try ExlApp.Visible := False; ExlApp.DisplayAlerts := False; WB := ExlApp.Workbooks.Add; WS := WB.WorkSheets.Add; WS.Name := 'Ïðîòîêîë'; try S := TStringList.Create; S.Sorted := True; S.Duplicates := dupIgnore; try for I := 0 to D.Chapters.Count - 1 do CheckLatin(S, D.Chapters.Items[I]); Analize(S, WS); if S.Count > 0 then WB.SaveAs(ChangeFileExt(D.FileName, '_ÏÐÎÒÎÊÎË_ÍÀ_ËÀÒÈÍÈÖÓ.xlsx')); finally S.Free; end; finally WS := Unassigned; WB.Close; WB := Unassigned; end; finally ExlApp.Quit; ExlApp := Unassigned; end; end; function TFmLatinCheck.GetChapterInfo(Item: TGsAbstractItem): string; begin Result := EmptyStr; if Item is TGsChapter then begin Result := Format('%s#%s#%s#%s', [TGsChapter(Item).Number(True), 'ÐÀÇÄÅË', 'ÍÀÈÌÅÍÎÂÀÍÈÅ', TGsChapter(Item).Caption]); end; end; procedure TFmLatinCheck.GetDetailInfo(S: TStringList; Item: TGsAbstractItem); begin if Item is TGsDetail then begin S.Add(Format('%s#%s#%s#%s', [TGsDetail(Item).Attributes[Ord(dtaNumber)], 'ÄÎÏ.ÈÍÔÎ', 'ÍÀÈÌÅÍÎÂÀÍÈÅ', TGsDetail(Item).Attributes[Ord(dtaCaption)]])); end; end; procedure TFmLatinCheck.GetResourceInfo(S: TStringList; Item: TGsAbstractItem); begin if Item is TGsResource then begin S.Add(Format('%s#%s#%s#%s', [TGsResource(Item).Code, 'ÐÅÑÓÐÑ', 'ÍÀÈÌÅÍÎÂÀÍÈÅ', TGsResource(Item).Caption])); S.Add(Format('%s#%s#%s#%s', [TGsResource(Item).Code, 'ÐÅÑÓÐÑ', 'ÈÇÌÅÐÈÒÅËÜ', TGsResource(Item).Measure])); end; end; procedure TFmLatinCheck.GetRowInfo(S: TStringList; Item: TGsAbstractItem); begin if Item is TGsRow then begin S.Add(Format('%s#%s#%s#%s', [TGsRow(Item).Number(True), 'ÐÀÑÖÅÍÊÀ', 'ÍÀÈÌÅÍÎÂÀÍÈÅ', TGsRow(Item).Caption])); S.Add(Format('%s#%s#%s#%s', [TGsRow(Item).Number(True), 'ÐÀÑÖÅÍÊÀ', 'ÈÇÌÅÐÈÒÅËÜ', TGsRow(Item).Measure])); end; end; { TLatinCheckActionHandler } procedure TLatinCheckActionHandler.ExecuteAction(UserData: Pointer); begin TFmLatinCheck.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Ïðîâåðêà íà ëàòèíèöó', hkDefault, TLatinCheckActionHandler); end.
unit btree; interface const MAXESIZE = 1024; ESIZE = 512; type btarraytype = array[0..MAXESIZE - 1] of byte; bptrtype = ^node; node = record data:btarraytype; size:integer; next:bptrtype; prev:bptrtype end; btreetype = record size:longint; posit:longint; ofs:longint; top:bptrtype; cptr:bptrtype end; Procedure init_btree(var b:btreetype;size:longint;var success:boolean); Procedure btree_fromdisk(var b:btreetype;var f:file); Procedure btree_todisk(var b:btreetype;var f:file); Procedure btree_write(var b:btreetype;x:byte); Function btree_read(var b:btreetype):byte; Function btree_size(var b:btreetype):longint; Function btree_posit(var b:btreetype):longint; Procedure btree_insert(var b:btreetype;x:longint;var success:boolean); Procedure btree_seek(var b:btreetype; x:longint); Procedure btree_del(var b:btreetype;x:longint); Procedure destroy_btree(var b:btreetype); implementation {$F+} function heapfunc(size:word):integer; {$F-} begin heapfunc := 1 end; Function min(x,y:longint):longint; begin if x < y then min := x else min := y end; Procedure init_btree(var b:btreetype;size:longint;var success:boolean); var cnt:longint; p,q:bptrtype; c:integer; begin success := true; if size <= 0 then begin success := false; exit end; b.size := size; b.ofs := 0; b.posit := 0; new(b.top); if b.top = nil then begin success := false; exit end; b.cptr := b.top; b.top^.prev := nil; b.top^.next := nil; if size < MAXESIZE then begin b.top^.size := size end else begin b.top^.size := (size mod ESIZE) + ESIZE; p := b.top; for cnt := 0 to (size - MAXESIZE) div ESIZE do begin new(q); if q = nil then begin success := false; while (p <> nil) do begin q := p^.prev; dispose(p); p := q end; exit end; q^.prev := p; p^.next := q; q^.next := nil; q^.size := ESIZE; p := q end end end; Procedure btree_fromdisk(var b:btreetype;var f:file); var p:bptrtype; numread:word; begin p := b.top; seek(f,0); while p <> nil do begin blockread(f,p^.data,p^.size,numread); p := p^.next end end; Procedure btree_todisk(var b:btreetype;var f:file); var p:bptrtype; numwritten:word; begin p := b.top; seek(f,0); while p <> nil do begin blockwrite(f,p^.data,p^.size,numwritten); p := p^.next end; truncate(f) end; Procedure btree_write(var b:btreetype;x:byte); begin b.cptr^.data[b.ofs] := x end; Function btree_read(var b:btreetype):byte; begin btree_read := b.cptr^.data[b.ofs] end; Function btree_size(var b:btreetype):longint; begin btree_size := b.size end; Function btree_posit(var b:btreetype):longint; begin btree_posit := b.posit end; Procedure btree_insert(var b:btreetype;x:longint;var success:boolean); var newposit,oldsize,c:integer; q,p,r,q1:bptrtype; cnt:longint; begin success := true; if x <= 0 then begin success := false; exit end; if b.cptr^.size + x < MAXESIZE then begin for c := b.cptr^.size - 1 downto b.ofs do b.cptr^.data[c + x] := b.cptr^.data[c]; for c := 0 to x-1 do b.cptr^.data[b.ofs + c] := 0; b.cptr^.size := b.cptr^.size + x; b.size := b.size + x end else begin b.size := b.size + x; q := b.cptr^.next; q1 := q; for cnt := 0 to (b.cptr^.size + x - MAXESIZE) div ESIZE do begin new(p); if p = nil then begin success := false; b.size := b.size - x; while (q <> q1) do begin p := q^.next; dispose(q); q := p end; exit end; if cnt = 0 then r := p; p^.size := ESIZE; for c := 0 to ESIZE - 1 do p^.data[c] := 0; p^.next := q; if q <> nil then q^.prev := p; p^.prev := b.cptr; b.cptr^.next := p; q := p end; oldsize := b.cptr^.size; b.cptr^.size := ((b.cptr^.size + x - MAXESIZE) mod ESIZE) + ESIZE; newposit := ESIZE - 1; for c := oldsize - 1 downto b.ofs do begin r^.data[newposit] := b.cptr^.data[c]; if newposit = 0 then begin r := r^.prev; newposit := r^.size end; newposit := newposit - 1 end; if b.ofs - 1 >= b.cptr^.size then for c := b.ofs - 1 downto b.cptr^.size do b.cptr^.next^.data[c-b.cptr^.size] := b.cptr^.data[c] else for c := b.ofs to min(b.cptr^.size - 1,b.ofs + x - 1) do b.cptr^.data[c] := 0; if b.ofs >= b.cptr^.size then begin b.ofs := b.ofs - b.cptr^.size; b.cptr := b.cptr^.next end end end; Procedure btree_seek(var b:btreetype; x:longint); var tdiff,diff:longint; temp:byte; success:boolean; begin if x < 0 then x := 0; if x > b.size then x := b.size; if x = b.size then begin btree_seek(b,x-1); temp := btree_read(b); btree_write(b,0); btree_insert(b,1,success); btree_write(b,temp); if success then btree_seek(b,x) end else begin if x > b.posit then begin diff := x - b.posit; while (diff > 0) do begin tdiff := min(diff,b.cptr^.size - b.ofs); b.ofs := b.ofs + tdiff; diff := diff - tdiff; if b.ofs = b.cptr^.size then begin b.cptr := b.cptr^.next; b.ofs := 0 end end end else begin diff := b.posit - x; while (diff > 0) do begin if b.ofs = 0 then begin b.cptr := b.cptr^.prev; b.ofs := b.cptr^.size end; tdiff := min(diff,b.ofs); b.ofs := b.ofs - tdiff; diff := diff - tdiff end end; b.posit := x end end; Procedure comb_btree(p:bptrtype;x:integer); var c:integer; q:bptrtype; begin if x = -1 then begin q := p^.prev; for c := p^.size - 1 downto 0 do p^.data[c + q^.size] := p^.data[c]; for c := 0 to q^.size - 1 do p^.data[c] := q^.data[c]; p^.size := p^.size + q^.size; q^.prev^.next := p; p^.prev := q^.prev; dispose(q) end else begin q := p^.next; for c := 0 to q^.size - 1 do p^.data[p^.size + c] := q^.data[c]; p^.size := p^.size + q^.size; q^.next^.prev := p; p^.next := q^.next; dispose(q) end end; Procedure bal_btree(p:bptrtype;x:integer); var c:integer; q:bptrtype; begin if x = - 1 then begin q := p^.prev; for c := p^.size - 1 downto 0 do p^.data[c + ESIZE - p^.size] := p^.data[c]; for c := 0 to ESIZE - p^.size - 1 do p^.data[c] := q^.data[q^.size + p^.size - ESIZE + c]; q^.size := q^.size + p^.size - ESIZE; p^.size := ESIZE end else begin q := p^.next; for c := p^.size to ESIZE - 1 do p^.data[c] := q^.data[c - p^.size]; for c := 0 to q^.size + p^.size - ESIZE - 1 do q^.data[c] := q^.data[c + ESIZE - p^.size]; q^.size := q^.size + p^.size - ESIZE; p^.size := ESIZE end end; Procedure btree_del(var b:btreetype;x:longint); var diff,tdiff:longint; p,q:bptrtype; lposit:longint; oldsize,c:integer; begin if x <= 0 then exit; if x > b.size - b.posit - 1 then x := b.size - b.posit - 1; lposit := b.posit; if x < b.cptr^.size - b.ofs then begin for c := b.ofs to b.cptr^.size - 1 - x do b.cptr^.data[c] := b.cptr^.data[c+x]; b.cptr^.size := b.cptr^.size - x; if b.cptr^.size < ESIZE then begin if b.cptr^.prev <> nil then begin if b.cptr^.size + b.cptr^.prev^.size < MAXESIZE then begin if b.cptr^.prev = b.top then b.top := b.cptr; comb_btree(b.cptr,-1) end else bal_btree(b.cptr,-1) end else if b.cptr^.next <> nil then begin if b.cptr^.size + b.cptr^.next^.size < MAXESIZE then comb_btree(b.cptr,1) else bal_btree(b.cptr,1) end end end else begin diff := x; if b.ofs > 0 then begin tdiff := b.cptr^.size - b.ofs; b.cptr^.size := b.ofs; diff := diff - tdiff; b.cptr := b.cptr^.next end; while (diff > 0) do begin oldsize := b.cptr^.size; tdiff := min(diff, b.cptr^.size); b.cptr^.size := b.cptr^.size - tdiff; diff := diff - tdiff; if b.cptr^.size = 0 then begin p := b.cptr^.prev; q := b.cptr^.next; if p = nil then begin b.top := q; q^.prev := nil end else begin p^.next := q; q^.prev := p end; dispose(b.cptr); b.cptr := q end else for c := 0 to b.cptr^.size - 1 do b.cptr^.data[c] := b.cptr^.data[c+oldsize-b.cptr^.size] end; if b.cptr^.prev <> nil then begin if b.cptr^.prev^.size + b.cptr^.size < MAXESIZE then begin if b.cptr^.prev = b.top then b.top := b.cptr; comb_btree(b.cptr,-1); if b.cptr^.size < ESIZE then begin if b.cptr^.prev <> nil then begin if b.cptr^.size + b.cptr^.prev^.size < MAXESIZE then begin if b.cptr^.prev = b.top then b.top := b.cptr; comb_btree(b.cptr,-1) end else bal_btree(b.cptr,-1) end else if b.cptr^.next <> nil then begin if b.cptr^.size + b.cptr^.next^.size < MAXESIZE then comb_btree(b.cptr,1) else bal_btree(b.cptr,1) end end end else begin if (b.cptr^.prev^.size < ESIZE) then begin b.cptr := b.cptr^.prev; bal_btree(b.cptr,1) end else if b.cptr^.size < ESIZE then bal_btree(b.cptr,-1) end end else if b.cptr^.next <> nil then begin if b.cptr^.size + b.cptr^.next^.size < MAXESIZE then comb_btree(b.cptr,1) else bal_btree(b.cptr,1) end end; b.cptr := b.top; b.ofs := 0; b.posit := 0; b.size := b.size - x; btree_seek(b,lposit) end; Procedure destroy_btree(var b:btreetype); var p,q:bptrtype; begin p := b.top; while (p <> nil) do begin q := p^.next; dispose(p); p := q end end; begin heaperror := @heapfunc end. 
{ Date Created: 5/25/00 5:01:01 PM } unit InfoDIRYCODETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoDIRYCODERecord = record PCode: String[6]; PDescription: String[30]; PLeadTime: String[4]; End; TInfoDIRYCODEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoDIRYCODERecord end; TEIInfoDIRYCODE = (InfoDIRYCODEPrimaryKey); TInfoDIRYCODETable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFLeadTime: TStringField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPLeadTime(const Value: String); function GetPLeadTime:String; procedure SetEnumIndex(Value: TEIInfoDIRYCODE); function GetEnumIndex: TEIInfoDIRYCODE; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoDIRYCODERecord; procedure StoreDataBuffer(ABuffer:TInfoDIRYCODERecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFLeadTime: TStringField read FDFLeadTime; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PLeadTime: String read GetPLeadTime write SetPLeadTime; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoDIRYCODE read GetEnumIndex write SetEnumIndex; end; { TInfoDIRYCODETable } procedure Register; implementation procedure TInfoDIRYCODETable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFLeadTime := CreateField( 'LeadTime' ) as TStringField; end; { TInfoDIRYCODETable.CreateFields } procedure TInfoDIRYCODETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoDIRYCODETable.SetActive } procedure TInfoDIRYCODETable.Validate; begin { Enter Validation Code Here } end; { TInfoDIRYCODETable.Validate } procedure TInfoDIRYCODETable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoDIRYCODETable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoDIRYCODETable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoDIRYCODETable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoDIRYCODETable.SetPLeadTime(const Value: String); begin DFLeadTime.Value := Value; end; function TInfoDIRYCODETable.GetPLeadTime:String; begin result := DFLeadTime.Value; end; procedure TInfoDIRYCODETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 6, N'); Add('Description, String, 30, N'); Add('LeadTime, String, 4, N'); end; end; procedure TInfoDIRYCODETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoDIRYCODETable.SetEnumIndex(Value: TEIInfoDIRYCODE); begin case Value of InfoDIRYCODEPrimaryKey : IndexName := ''; end; end; function TInfoDIRYCODETable.GetDataBuffer:TInfoDIRYCODERecord; var buf: TInfoDIRYCODERecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PLeadTime := DFLeadTime.Value; result := buf; end; procedure TInfoDIRYCODETable.StoreDataBuffer(ABuffer:TInfoDIRYCODERecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFLeadTime.Value := ABuffer.PLeadTime; end; function TInfoDIRYCODETable.GetEnumIndex: TEIInfoDIRYCODE; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoDIRYCODEPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoDIRYCODETable, TInfoDIRYCODEBuffer ] ); end; { Register } function TInfoDIRYCODEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PLeadTime; end; end; end. { InfoDIRYCODETable }
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clTranslator; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, System.Types, {$ENDIF} clUtils, clWUtils; type TclXLATTable = record Name: string[20]; Table: array [0..255] of Byte; ReverseTable: array [0..255] of Byte; end; TclTranslator = class private class function GetXLATByID(const ATableID: string): TclXLATTable; class function ToUtf8(Source: PWideChar; SourceLength: Integer; Dest: PclChar; DestLength: Integer): Integer; class function FromUtf8(Source: PclChar; SourceLength: Integer; Dest: PWideChar; DestLength: Integer): Integer; {$IFDEF DELPHI2009} class function GetEncoding(const ACharSet: string): TEncoding; class function WideStringToString(const ws: WideString; codePage: Word): AnsiString; class function StringToWideString(const s: AnsiString; codePage: Word): WideString; {$ELSE} class function WideStringToString(const ws: WideString; codePage: Word): string; class function StringToWideString(const s: string; codePage: Word): WideString; {$ENDIF} public class function TranslateToUtf8(const ASource: WideString): string; class function TranslateFromUtf8(const ASource: string): WideString; class function TranslateTo(const ACharSet, ASource: string): string; overload; class function TranslateFrom(const ACharSet, ASource: string): string; overload; class procedure TranslateTo(const ACharSet: string; ASource, ADestination: TStream); overload; class procedure TranslateFrom(const ACharSet: string; ASource, ADestination: TStream); overload; class procedure GetSupportedCharSets(ACharSets: TStrings); class function GetString(const ABytes: TclByteArray; AIndex, ACount: Integer; const ACharSet: string): string; overload; class function GetString(const ABytes: TclByteArray; AIndex, ACount: Integer): string; overload; class function GetString(const ABytes: TclByteArray; const ACharSet: string): string; overload; class function GetString(const ABytes: TclByteArray): string; overload; class function GetString(ABytes: PclChar; ACount: Integer; const ACharSet: string): string; overload; class function GetBytes(const AText: string; const ACharSet: string): TclByteArray; overload; class function GetBytes(const AText: string): TclByteArray; overload; class procedure GetBytes(const AText: string; ABytes: PclChar; AByteCount: Integer; const ACharSet: string); overload; class function GetByteCount(const AText, ACharSet: string): Integer; overload; class function GetByteCount(const AText: string): Integer; overload; class function GetUtf8Bytes(const AText: WideString): TclByteArray; class function GetUtf8ByteCount(const AText: WideString): Integer; class function GetStringFromUtf8(const ABytes: TclByteArray): WideString; class function IsUtf8(AStream: TStream): Boolean; overload; class function IsUtf8(const ABytes: TclByteArray): Boolean; overload; class function IsUtf8(const ABytes: TclByteArray; AIndex, ACount: Integer): Boolean; overload; end; implementation uses {$IFNDEF DELPHIXE2} Windows; {$ELSE} Winapi.Windows; {$ENDIF} const CharSetTables: array [0..11] of TclXLATTable = ( ( Name: 'ISO-8859-1'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff) ), ( Name: 'ISO-8859-2'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f, $10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f, $20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f, $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f, $40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f, $60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f, $70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f, $80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f, $90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f, $a0,$a1,$a2,$a3,$a4,$a5,$8c,$a7,$a8,$8a,$aa,$ab,$8f,$ad,$8e,$af, $b0,$b1,$b2,$b3,$b4,$b5,$9c,$a1,$b8,$9a,$ba,$bb,$9f,$bd,$9e,$bf, $c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf, $d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df, $e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef, $f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f, $10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f, $20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f, $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f, $40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f, $60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f, $70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f, $80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$a9,$8b,$a6,$8d,$ae,$ac, $90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$b9,$9b,$b6,$9d,$be,$bc, $a0,$b7,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af, $b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf, $c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf, $d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df, $e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef, $f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff) ), ( Name: 'Windows-1250'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff) ), ( Name: 'ibm866'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14//21 ,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29//42 ,$2a,$2b,$2c,$2d,$2e,$2f,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e//63 ,$3f,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53//84 ,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f,$60,$61,$62,$63,$64,$65,$66,$67,$68//105 ,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7a,$7b,$7c,$7d//126 ,$7e,$7f,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2//147 ,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7//168 ,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc//189 ,$bd,$be,$bf,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1//210 ,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$f0,$f1,$f2,$f3,$f4,$f5,$f6//231 ,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff,$a8,$a3,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb//252 ,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14//21 ,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29//42 ,$2a,$2b,$2c,$2d,$2e,$2f,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e//63 ,$3f,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53//84 ,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f,$60,$61,$62,$63,$64,$65,$66,$67,$68//105 ,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7a,$7b,$7c,$7d//126 ,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91,$92//147 ,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$f1,$a4,$a5,$a6,$a7//168 ,$f0,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$f0,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc//189 ,$bd,$be,$bf,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91//210 ,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6//231 ,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb//252 ,$ec,$ed,$ee,$ef) ), ( Name: 'ISO-8859-5'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7 ,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf ,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7 ,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$90,$91,$92,$93,$94,$95,$96,$97 ,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af ,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7 ,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df ,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef) ), ( Name: 'koi8-r'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$b8,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$a8,$b4,$b5,$b6,$b7,$a3,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$fe,$e0,$e1,$f6,$e4,$e5,$f4,$e3,$f5,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$ff,$f0,$f1,$f2,$f3,$e6,$e2 ,$fc,$fb,$e7,$f8,$fd,$f9,$f7,$fa,$de,$c0,$c1,$d6,$c4,$c5,$d4,$c3,$d5,$c8,$c9,$ca,$cb,$cc,$cd,$ce ,$cf,$df,$d0,$d1,$d2,$d3,$c6,$c2,$dc,$db,$c7,$d8,$dd,$d9,$d7,$da); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$b8,$a4,$a5,$a6,$a7 ,$b3,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$a3,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$e1,$e2,$f7,$e7,$e4,$e5,$f6,$fa,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2,$f3,$f4,$f5,$e6,$e8,$e3,$fe ,$fb,$fd,$ff,$f9,$f8,$fc,$e0,$f1,$c1,$c2,$d7,$c7,$c4,$c5,$d6,$da,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0 ,$d2,$d3,$d4,$d5,$c6,$c8,$c3,$de,$db,$dd,$df,$d9,$d8,$dc,$c0,$d1) ), ( Name: 'koi8-u'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$b8,$ba,$a5,$b3,$bf ,$a8,$a9,$aa,$ab,$ac,$b4,$ae,$af,$b0,$b1,$b2,$a8,$aa,$b5,$b2,$af,$b8,$b9,$ba,$bb,$bc,$a5,$be,$bf ,$fe,$e0,$e1,$f6,$e4,$e5,$f4,$e3,$f5,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$ff,$f0,$f1,$f2,$f3,$e6,$e2 ,$fc,$fb,$e7,$f8,$fd,$f9,$f7,$fa,$de,$c0,$c1,$d6,$c4,$c5,$d4,$c3,$d5,$c8,$c9,$ca,$cb,$cc,$cd,$ce ,$cf,$df,$d0,$d1,$d2,$d3,$c6,$c2,$dc,$db,$c7,$d8,$dd,$d9,$d7,$da); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$bd,$a6,$a7 ,$b3,$a9,$b4,$ab,$ac,$ad,$ae,$b7,$b0,$b1,$b6,$a6,$ad,$b5,$b6,$b7,$a3,$b9,$a4,$bb,$bc,$bd,$be,$a7 ,$e1,$e2,$f7,$e7,$e4,$e5,$f6,$fa,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2,$f3,$f4,$f5,$e6,$e8,$e3,$fe ,$fb,$fd,$ff,$f9,$f8,$fc,$e0,$f1,$c1,$c2,$d7,$c7,$c4,$c5,$d6,$da,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0 ,$d2,$d3,$d4,$d5,$c6,$c8,$c3,$de,$db,$dd,$df,$d9,$d8,$dc,$c0,$d1) ), ( Name: 'KOI8-WIN'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$da,$9b,$9c,$9d,$9e,$9f,$a0,$e7,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$d7,$de,$c0,$c6,$c4,$c5,$d2,$d6,$d3,$d5,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$d1,$cf,$df,$d0,$d1,$d4,$c1 ,$dd,$d8,$c3,$dc,$d9,$db,$c2,$c7,$f7,$fe,$e0,$e6,$e4,$e5,$f2,$f6,$f3,$f5,$e8,$e9,$ea,$eb,$ec,$ed ,$ee,$fa,$ef,$ff,$f0,$f1,$f4,$e1,$fd,$f8,$e3,$fc,$f9,$fb,$e2,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c2,$d7,$de,$da,$c4,$c5,$c3,$df,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d2,$d4,$d5,$c6,$c8,$d6,$c9,$c7,$c0 ,$d9,$dc,$9a,$dd,$db,$d8,$c1,$d3,$e2,$f7,$fe,$fa,$e4,$e5,$e3,$a1,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2 ,$f4,$f5,$e6,$e8,$f6,$e9,$e7,$e0,$f9,$fc,$f1,$fd,$fb,$f8,$e1,$f3) ), ( Name: 'WIN-KOI8'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$ff,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$e1,$e2,$f7,$e7,$e4,$e5,$f6,$fa,$c8,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2,$f3,$f4,$f5,$e6,$e8,$e3,$fe ,$fb,$fd,$da,$f9,$f8,$fc,$e0,$f1,$c1,$c2,$d7,$c7,$c4,$c5,$d6,$ff,$e8,$ca,$cb,$cc,$cd,$ce,$cf,$d0 ,$d2,$d3,$d4,$d5,$c6,$c8,$c3,$de,$db,$dd,$df,$d9,$d8,$dc,$c0,$d1); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 //23 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f//47 ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47//71 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f//95 ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77//119 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f//143 ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7//167 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf//191 ,$fe,$e0,$e1,$f6,$e4,$e5,$f4,$e3,$f5,$c9,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$ff,$f0,$f1,$f2,$f3,$e6,$e2//215 ,$fc,$fb,$da,$f8,$fd,$f9,$f7,$fa,$de,$c0,$c1,$d6,$c4,$c5,$d4,$c3,$d5,$e9,$c9,$ca,$cb,$cc,$cd,$ce//239 ,$cf,$df,$d0,$d1,$d2,$d3,$c6,$c2,$dc,$db,$c7,$d8,$dd,$d9,$d7,$e7) ), ( Name: 'Windows-1251'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff) ), ( Name: 'x-mac-cyrillic'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf ,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$a8,$b8,$ff,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$dd,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$de,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91,$92,$93,$94,$95,$96,$97 ,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$df) ), ( Name: 'Latin1'; Table: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff); ReverseTable: ($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 ,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f ,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47 ,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f ,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77 ,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f ,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7 ,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf ,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7 ,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef ,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff) ) ); {$IFDEF DELPHI2009} {$IFNDEF DELPHIXE} type TclCharSetCodePage = record CodePage: Integer; Name: string[20]; end; const CharSetCodePages: array [0..34] of TclCharSetCodePage = ( (CodePage: 1250; Name: 'windows-1250'), (CodePage: 1251; Name: 'windows-1251'), (CodePage: 1252; Name: 'windows-1252'), (CodePage: 1253; Name: 'windows-1253'), (CodePage: 1254; Name: 'windows-1254'), (CodePage: 1255; Name: 'windows-1255'), (CodePage: 1256; Name: 'windows-1256'), (CodePage: 1257; Name: 'windows-1257'), (CodePage: 1258; Name: 'windows-1258'), (CodePage: 28591; Name: 'iso-8859-1'), (CodePage: 28592; Name: 'iso-8859-2'), (CodePage: 28593; Name: 'iso-8859-3'), (CodePage: 28594; Name: 'iso-8859-4'), (CodePage: 28595; Name: 'iso-8859-5'), (CodePage: 28596; Name: 'iso-8859-6'), (CodePage: 28597; Name: 'iso-8859-7'), (CodePage: 28598; Name: 'iso-8859-8'), (CodePage: 28599; Name: 'iso-8859-9'), (CodePage: 28603; Name: 'iso-8859-13'), (CodePage: 28605; Name: 'iso-8859-15'), (CodePage: 866; Name: 'ibm866'), (CodePage: 866; Name: 'cp866'), (CodePage: 1200; Name: 'utf-16'), (CodePage: 12000; Name: 'utf-32'), (CodePage: 65000; Name: 'utf-7'), (CodePage: 65001; Name: 'utf-8'), (CodePage: 20127; Name: 'us-ascii'), (CodePage: 28591; Name: 'Latin1'), (CodePage: 10007; Name: 'x-mac-cyrillic'), (CodePage: 21866; Name: 'koi8-u'), (CodePage: 20866; Name: 'koi8-r'), (CodePage: 932; Name: 'shift-jis'), (CodePage: 932; Name: 'shift_jis'), (CodePage: 50220; Name: 'iso-2022-jp'), (CodePage: 50220; Name: 'csISO2022JP') ); {$ENDIF} class function TclTranslator.GetEncoding(const ACharSet: string): TEncoding; {$IFNDEF DELPHIXE} function GetCodePage(const ACharSet: string): Integer; var i: Integer; begin for i := Low(CharSetCodePages) to High(CharSetCodePages) do begin if SameText(string(CharSetCodePages[i].Name), ACharSet) then begin Result := CharSetCodePages[i].CodePage; Exit; end; end; Result := GetACP(); end; {$ENDIF} begin {$IFNDEF DELPHIXE} try Result := TEncoding.GetEncoding(GetCodePage(ACharSet)); except Result := TEncoding.GetEncoding(GetACP()); end; {$ELSE} try if (Trim(ACharSet) = '') then begin Result := TEncoding.Default.Clone(); end else begin Result := TEncoding.GetEncoding(ACharSet); end; except Result := TEncoding.Default.Clone(); end; {$ENDIF} end; {$ENDIF} { TclTranslator } class function TclTranslator.GetByteCount(const AText, ACharSet: string): Integer; var {$IFDEF DELPHI2009} enc: TEncoding; {$ENDIF} res: string; begin {$IFDEF DELPHI2009} try enc := GetEncoding(ACharSet); try Result := enc.GetByteCount(AText); finally enc.Free(); end; Exit; except on EEncodingError do; end; {$ENDIF} if SameText('utf-8', ACharSet) then begin res := TranslateToUtf8(StringToWideString(GetTclString(AText), CP_ACP)); end else begin res := TranslateTo(ACharSet, AText); end; Result := Length(res); end; class function TclTranslator.GetBytes(const AText, ACharSet: string): TclByteArray; var len: Integer; begin len := GetByteCount(AText, ACharSet); SetLength(Result, len); GetBytes(AText, PclChar(Result), len, ACharSet); end; class function TclTranslator.GetBytes(const AText: string): TclByteArray; begin Result := GetBytes(AText, ''); end; class function TclTranslator.GetByteCount(const AText: string): Integer; begin Result := GetByteCount(AText, ''); end; class procedure TclTranslator.GetBytes(const AText: string; ABytes: PclChar; AByteCount: Integer; const ACharSet: string); var cnt: Integer; {$IFDEF DELPHI2009} enc: TEncoding; buf: TBytes; {$ENDIF} res: string; begin {$IFDEF DELPHI2009} try enc := GetEncoding(ACharSet); try cnt := enc.GetByteCount(AText); if (cnt > AByteCount) then begin cnt := AByteCount; end; SetLength(buf, cnt); enc.GetBytes(AText, 1, Length(AText), buf, 0); if (cnt > 0) then begin system.Move(buf[0], ABytes[0], cnt); end; finally enc.Free(); end; Exit; except on EEncodingError do; end; {$ENDIF} if SameText('utf-8', ACharSet) then begin res := TranslateToUtf8(StringToWideString(GetTclString(AText), CP_ACP)); end else begin res := TranslateTo(ACharSet, AText); end; cnt := Length(res); if (cnt > AByteCount) then begin cnt := AByteCount; end; if (cnt > 0) then begin system.Move(PChar(res)^, ABytes^, cnt); end; end; {$IFDEF DELPHI2009} class function TclTranslator.WideStringToString(const ws: WideString; codePage: Word): AnsiString; {$ELSE} class function TclTranslator.WideStringToString(const ws: WideString; codePage: Word): string; {$ENDIF} var len: Integer; begin if (ws = '') then begin Result := ''; end else begin len := WideCharToMultiByte(codePage, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, @ws[1], -1, nil, 0, nil, nil); SetLength(Result, len - 1); if (len > 1) then begin WideCharToMultiByte(codePage, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, @ws[1], -1, @Result[1], len - 1, nil, nil); end; end; end; {$IFDEF DELPHI2009} class function TclTranslator.StringToWideString(const s: AnsiString; codePage: Word): WideString; {$ELSE} class function TclTranslator.StringToWideString(const s: string; codePage: Word): WideString; {$ENDIF} var len: integer; begin if (s = '') then begin Result := ''; end else begin len := MultiByteToWideChar(codePage, MB_PRECOMPOSED, PclChar(@s[1]), -1, nil, 0); SetLength(Result, len - 1); if (len > 1) then begin MultiByteToWideChar(CodePage, MB_PRECOMPOSED, PclChar(@s[1]), -1, PWideChar(@Result[1]), len - 1); end; end; end; class function TclTranslator.GetString(ABytes: PclChar; ACount: Integer; const ACharSet: string): string; {$IFDEF DELPHI2009} var enc: TEncoding; cnt: Integer; buf: TBytes; {$ENDIF} begin if (ACount = 0) then begin Result := ''; Exit; end; {$IFDEF DELPHI2009} try enc := GetEncoding(ACharSet); try cnt := ACount; if (ABytes[ACount - 1] = #0) then begin Dec(cnt); end; SetLength(buf, cnt); if (cnt > 0) then begin Move(ABytes[0], buf[0], cnt); end; Result := enc.GetString(buf, 0, cnt); if (cnt > 0) and (Result = '') then begin Result := TEncoding.ASCII.GetString(buf, 0, cnt); end; finally enc.Free(); end; Exit; except on EEncodingError do; end; {$ENDIF} if SameText('utf-8', ACharSet) then begin Result := GetString_(WideStringToString(TranslateFromUtf8(system.Copy(string(ABytes), 1, ACount)), CP_ACP)); end else begin Result := TranslateFrom(ACharSet, system.Copy(string(ABytes), 1, ACount)); end; end; class function TclTranslator.GetStringFromUtf8(const ABytes: TclByteArray): WideString; var len: Integer; begin if (Length(ABytes) = 0) then Exit; SetLength(Result, Length(ABytes)); len := FromUtf8(PclChar(ABytes), Length(ABytes), PWideChar(Result), Length(Result) + 1); if (len > 0) then begin SetLength(Result, len - 1); end else begin Result := ''; end; end; class function TclTranslator.GetString(const ABytes: TclByteArray; const ACharSet: string): string; begin Result := GetString(ABytes, 0, Length(ABytes), ACharSet); end; class function TclTranslator.GetString(const ABytes: TclByteArray): string; begin Result := GetString(ABytes, 0, Length(ABytes), ''); end; class function TclTranslator.GetString(const ABytes: TclByteArray; AIndex, ACount: Integer; const ACharSet: string): string; begin if (ACount > 0) then begin Result := GetString(PclChar(@ABytes[AIndex]), ACount, ACharSet); end else begin Result := ''; end; end; class function TclTranslator.GetString(const ABytes: TclByteArray; AIndex, ACount: Integer): string; begin Result := GetString(ABytes, AIndex, ACount, ''); end; class procedure TclTranslator.GetSupportedCharSets(ACharSets: TStrings); {$IFNDEF DELPHIXE} var i: Integer; {$ENDIF} begin ACharSets.Clear(); {$IFNDEF DELPHI2009} for i := Low(CharSetTables) to High(CharSetTables) do begin ACharSets.Add(string(CharSetTables[i].Name)); end; {$ELSE} {$IFNDEF DELPHIXE} for i := Low(CharSetCodePages) to High(CharSetCodePages) do begin ACharSets.Add(string(CharSetCodePages[i].Name)); end; {$ELSE} {$ENDIF} {$ENDIF} end; class function TclTranslator.GetUtf8ByteCount(const AText: WideString): Integer; var res: TclByteArray; begin res := GetUtf8Bytes(AText); Result := Length(res); end; class function TclTranslator.GetUtf8Bytes(const AText: WideString): TclByteArray; var len: Integer; begin SetLength(Result, Length(AText) * 3); if (AText = '') then Exit; len := ToUtf8(PWideChar(AText), Length(AText), PclChar(Result), Length(Result) + 1); if (len > 0) then begin SetLength(Result, len - 1); end else begin SetLength(Result, 0); end; end; class function TclTranslator.GetXLATByID(const ATableID: string): TclXLATTable; var i: Integer; begin Result.Name := ''; for i := Low(CharSetTables) to High(CharSetTables) do begin if CompareText(string(CharSetTables[i].Name), ATableID) = 0 then begin Result := CharSetTables[i]; Break; end; end; end; class function TclTranslator.IsUtf8(AStream: TStream): Boolean; var oldPos: Int64; buf: TclByteArray; len: Integer; begin Result := False; oldPos := AStream.Position; try len := AStream.Size - AStream.Position; SetLength(buf, len); if (len > 0) then begin AStream.Read(buf[0], len); Result := IsUtf8(buf); end; finally AStream.Position := oldPos; end; end; class function TclTranslator.IsUtf8(const ABytes: TclByteArray): Boolean; begin Result := IsUtf8(ABytes, 0, Length(ABytes)); end; class function TclTranslator.IsUtf8(const ABytes: TclByteArray; AIndex, ACount: Integer): Boolean; var c: Byte; ind, cnt: Integer; begin Result := False; cnt := ACount; if (cnt + AIndex > Length(ABytes)) then begin cnt := Length(ABytes) - AIndex; end; ind := 0; while (ind < cnt) do begin if ABytes[AIndex + ind] >= $80 then Break; Inc(ind); end; if (ind = cnt) then Exit; while (ind < cnt) do begin c := ABytes[AIndex + ind]; case c of $00..$7F: Inc(ind); $C2..$DF: if (ind + 1 < cnt) and ((ABytes[AIndex + ind + 1]) in [$80..$BF]) then begin Inc(ind, 2); end else begin Break; end; $E0: if (ind + 2 < cnt) and (ABytes[AIndex + ind + 1] in [$A0..$BF]) and (ABytes[AIndex + ind + 2] in [$80..$BF]) then begin Inc(ind, 3); end else begin Break; end; $E1..$EF: if (ind + 2 < cnt) and (ABytes[AIndex + ind + 1] in [$80..$BF]) and (ABytes[AIndex + ind + 2] in [$80..$BF]) then begin Inc(ind, 3); end else begin Break; end; $F0: if (ind + 3 < cnt) and (ABytes[AIndex + ind + 1] in [$90..$BF]) and (ABytes[AIndex + ind + 2] in [$80..$BF]) and (ABytes[AIndex + ind + 3] in [$80..$BF]) then begin Inc(ind, 4); end else begin Break; end; $F1..$F3: if (ind + 3 < cnt) and (ABytes[AIndex + ind + 1] in [$80..$BF]) and (ABytes[AIndex + ind + 2] in [$80..$BF]) and (ABytes[AIndex + ind + 3] in [$80..$BF]) then begin Inc(ind, 4); end else begin Break; end; $F4: if (ind + 3 < cnt) and (ABytes[AIndex + ind + 1] in [$80..$8F]) and (ABytes[AIndex + ind + 2] in [$80..$BF]) and (ABytes[AIndex + ind + 3] in [$80..$BF]) then begin Inc(ind, 4); end else begin Break; end; else Break; end; end; Result := (ind = cnt); end; class procedure TclTranslator.TranslateTo(const ACharSet: string; ASource, ADestination: TStream); var i: Integer; Xlat: TclXLATTable; Ch: Byte; PrevSourcePos, PrevDestPos: Integer; begin Xlat := GetXLATByID(ACharSet); PrevSourcePos := ASource.Position; PrevDestPos := ADestination.Position; ASource.Position := 0; ADestination.Position := 0; if (Xlat.Name <> '') then begin for i := 0 to ASource.Size - 1 do begin ASource.Read(Ch, 1); Ch := Xlat.ReverseTable[Ch]; ADestination.Write(Ch, 1); end; end else begin ADestination.CopyFrom(ASource, ASource.Size); end; ASource.Position := PrevSourcePos; ADestination.Position := PrevDestPos; end; class procedure TclTranslator.TranslateFrom(const ACharSet: string; ASource, ADestination: TStream); var i: Integer; Xlat: TclXLATTable; Ch: Byte; PrevSourcePos, PrevDestPos: Integer; begin Xlat := GetXLATByID(ACharSet); PrevSourcePos := ASource.Position; PrevDestPos := ADestination.Position; ASource.Position := 0; ADestination.Position := 0; if (Xlat.Name <> '') then begin for i := 0 to ASource.Size - 1 do begin ASource.Read(Ch, 1); Ch := Xlat.Table[Ch]; ADestination.Write(Ch, 1); end; end else begin ADestination.CopyFrom(ASource, ASource.Size); end; ASource.Position := PrevSourcePos; ADestination.Position := PrevDestPos; end; class function TclTranslator.TranslateTo(const ACharSet, ASource: string): string; var src, dst: TStringStream; begin src := nil; dst := nil; try src := TStringStream.Create(ASource); dst := TStringStream.Create(''); TranslateTo(ACharSet, src, dst); Result := dst.DataString; finally dst.Free(); src.Free(); end; end; class function TclTranslator.TranslateFrom(const ACharSet, ASource: string): string; var src, dst: TStringStream; begin src := nil; dst := nil; try src := TStringStream.Create(ASource); dst := TStringStream.Create(''); TranslateFrom(ACharSet, src, dst); Result := dst.DataString; finally dst.Free(); src.Free(); end; end; class function TclTranslator.ToUtf8(Source: PWideChar; SourceLength: Integer; Dest: PclChar; DestLength: Integer): Integer; var i, count: Integer; c: Cardinal; begin count := 0; i := 0; while (i < SourceLength) and (count < DestLength) do begin c := Cardinal(Source[i]); Inc(i); if c <= $7F then begin Dest[count] := TclChar(c); Inc(count); end else if c > $7FF then begin if count + 3 > DestLength then Break; Dest[count] := TclChar($E0 or (c shr 12)); Dest[count+1] := TclChar($80 or ((c shr 6) and $3F)); Dest[count+2] := TclChar($80 or (c and $3F)); Inc(count,3); end else begin if count + 2 > DestLength then Break; Dest[count] := TclChar($C0 or (c shr 6)); Dest[count + 1] := TclChar($80 or (c and $3F)); Inc(count, 2); end; end; if count >= DestLength then begin count := DestLength - 1; end; Dest[count] := #0; Result := count + 1; end; class function TclTranslator.FromUtf8(Source: PclChar; SourceLength: Integer; Dest: PWideChar; DestLength: Integer): Integer; var i, count: Integer; c: Byte; wc: Cardinal; begin Result := -1; count := 0; i := 0; while (i < SourceLength) and (count < DestLength) do begin wc := Cardinal(Source[i]); Inc(i); if (wc and $80) <> 0 then begin wc := wc and $3F; if i > SourceLength then Exit; if (wc and $20) <> 0 then begin c := Byte(Source[i]); Inc(i); if (c and $C0) <> $80 then begin if (c = $20) then begin Dest[count] := #32; end else begin Dest[count] := #128; end; Inc(count); continue; end; if i > SourceLength then Exit; wc := (wc shl 6) or (c and $3F); end; c := Byte(Source[i]); Inc(i); if (c and $C0) <> $80 then begin if (c = $20) then begin Dest[count] := #32; end else begin Dest[count] := #128; end; Inc(count); continue; end; Dest[count] := WideChar((wc shl 6) or (c and $3F)); end else begin Dest[count] := WideChar(wc); end; Inc(count); end; if count >= DestLength then begin count := DestLength - 1; end; Dest[count] := #0; Result := count + 1; end; class function TclTranslator.TranslateFromUtf8(const ASource: string): WideString; var len: Integer; ws: WideString; s: TclString; begin Result := ''; if (ASource = '') then Exit; s := GetTclString(ASource); SetLength(ws, Length(s)); len := FromUtf8(PclChar(s), Length(s), PWideChar(ws), Length(ws) + 1); if (len > 0) then begin SetLength(ws, len - 1); end else begin ws := ''; end; Result := ws; end; class function TclTranslator.TranslateToUtf8(const ASource: WideString): string; var len: Integer; s: TclString; begin Result := ''; if (ASource = '') then Exit; SetLength(s, Length(ASource) * 3); len := ToUtf8(PWideChar(ASource), Length(ASource), PclChar(s), Length(s) + 1); if (len > 0) then begin SetLength(s, len - 1); end else begin s := ''; end; Result := string(s); end; end.
unit pengo_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,namco_snd,controls_engine,gfx_engine,rom_engine, pal_engine,sound_engine,sega_decrypt; function iniciar_pengo:boolean; implementation const pengo_rom:array[0..7] of tipo_roms=( (n:'ep1689c.8';l:$1000;p:0;crc:$f37066a8),(n:'ep1690b.7';l:$1000;p:$1000;crc:$baf48143), (n:'ep1691b.15';l:$1000;p:$2000;crc:$adf0eba0),(n:'ep1692b.14';l:$1000;p:$3000;crc:$a086d60f), (n:'ep1693b.21';l:$1000;p:$4000;crc:$b72084ec),(n:'ep1694b.20';l:$1000;p:$5000;crc:$94194a89), (n:'ep5118b.32';l:$1000;p:$6000;crc:$af7b12c4),(n:'ep5119c.31';l:$1000;p:$7000;crc:$933950fe)); pengo_pal:array[0..1] of tipo_roms=( (n:'pr1633.78';l:$20;p:0;crc:$3a5844ec),(n:'pr1634.88';l:$400;p:$20;crc:$766b139b)); pengo_sound:tipo_roms=(n:'pr1635.51';l:$100;p:0;crc:$c29dea27); pengo_sprites:array[0..1] of tipo_roms=( (n:'ep1640.92';l:$2000;p:$0;crc:$d7eec6cd),(n:'ep1695.105';l:$2000;p:$4000;crc:$5bfd26e9)); pengo_dip_a:array [0..6] of def_dip=( (mask:$1;name:'Bonus Life';number:2;dip:((dip_val:$0;dip_name:'30K'),(dip_val:$1;dip_name:'50K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Lives';number:4;dip:((dip_val:$18;dip_name:'2'),(dip_val:$10;dip_name:'3'),(dip_val:$8;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Rack Test';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$c0;dip_name:'Easy'),(dip_val:$80;dip_name:'Medium'),(dip_val:$40;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),()); pengo_dip_b:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$08;dip_name:'3C 1C'),(dip_val:$04;dip_name:'2C 1C'),(dip_val:$09;dip_name:'2C 1C/5C 3C'),(dip_val:$05;dip_name:'2C 1C/4C 3C'),(dip_val:$0c;dip_name:'1C 1C'),(dip_val:$0d;dip_name:'1C 1C/5C 6C'),(dip_val:$03;dip_name:'1C 1C/4C 5C'),(dip_val:$0b;dip_name:'1C 2C/2C 3C'),(dip_val:$02;dip_name:'1C 2C'),(dip_val:$07;dip_name:'1C 2C/5C 11C'),(dip_val:$0f;dip_name:'1C 3C/4C 9C'),(dip_val:$0a;dip_name:'1C 3C'),(dip_val:$06;dip_name:'1C 4C'),(dip_val:$0e;dip_name:'1C 5C'),(dip_val:$01;dip_name:'1C 6C'))), (mask:$f0;name:'Coin B';number:16;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$80;dip_name:'3C 1C'),(dip_val:$40;dip_name:'2C 1C'),(dip_val:$90;dip_name:'2C 1C/5C 3C'),(dip_val:$50;dip_name:'2C 1C/4C 3C'),(dip_val:$c0;dip_name:'1C 1C'),(dip_val:$d0;dip_name:'1C 1C/5C 6C'),(dip_val:$30;dip_name:'1C 1C/4C 5C'),(dip_val:$b0;dip_name:'1C 2C/2C 3C'),(dip_val:$20;dip_name:'1C 2C'),(dip_val:$70;dip_name:'1C 2C/5C 11C'),(dip_val:$f0;dip_name:'1C 3C/4C 9C'),(dip_val:$a0;dip_name:'1C 3C'),(dip_val:$60;dip_name:'1C 4C'),(dip_val:$e0;dip_name:'1C 5C'),(dip_val:$10;dip_name:'1C 6C'))),()); var irq_enable:boolean; rom_opcode:array[0..$7fff] of byte; colortable_bank,gfx_bank,pal_bank:byte; procedure update_video_pengo; var x,y,f,color,nchar,offs:word; sx,sy,atrib:byte; begin for x:=0 to 27 do begin for y:=0 to 35 do begin sx:=29-x; sy:=y-2; if (sy and $20)<>0 then offs:=sx+((sy and $1f) shl 5) else offs:=sy+(sx shl 5); if gfx[0].buffer[offs] then begin color:=(((memoria[$8400+offs]) and $1f) or (colortable_bank shl 5) or (pal_bank shl 6)) shl 2 ; nchar:=memoria[$8000+offs]+(gfx_bank shl 8); put_gfx(x*8,y*8,nchar,color,1,0); gfx[0].buffer[offs]:=false; end; end; end; actualiza_trozo(0,0,224,288,1,0,0,224,288,2); for f:=7 downto 0 do begin atrib:=memoria[$8ff0+(f*2)]; nchar:=(atrib shr 2) or (gfx_bank shl 6); color:=(((memoria[$8ff1+(f*2)]) and $1f) or (colortable_bank shl 5) or (pal_bank shl 6)) shl 2 ; x:=(240-memoria[$9020+(f*2)]-1) and $ff; y:=272-memoria[$9021+(f*2)]; put_gfx_sprite_mask(nchar,color,(atrib and 2)<>0,(atrib and 1)<>0,1,0,$f); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(0,0,224,288,2); end; procedure eventos_pengo; begin if event.arcade then begin //marcade.in0 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //marcade.in1 if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); end; end; procedure pengo_principal; var frame:single; f:word; begin init_controls(false,false,false,true); frame:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin z80_0.run(frame); frame:=frame+z80_0.tframes-z80_0.contador; if f=223 then begin update_video_pengo; if irq_enable then z80_0.change_irq(HOLD_LINE); end; end; eventos_pengo; video_sync; end; end; function pengo_getbyte(direccion:word):byte; begin case direccion of 0..$7fff:if z80_0.opcode then pengo_getbyte:=rom_opcode[direccion] else pengo_getbyte:=memoria[direccion]; $8000..$8fff:pengo_getbyte:=memoria[direccion]; $9000..$903f:pengo_getbyte:=marcade.dswb; $9040..$907f:pengo_getbyte:=marcade.dswa; $9080..$90bf:pengo_getbyte:=marcade.in1; $90c0..$90ff:pengo_getbyte:=marcade.in0; end; end; procedure pengo_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:if memoria[direccion]<>valor then begin gfx[0].buffer[(direccion and $3ff)]:=true; memoria[direccion]:=valor; end; $8800..$8fff,$9020..$902f:memoria[direccion]:=valor; $9000..$901f:namco_snd_0.regs[direccion and $1f]:=valor; $9040:irq_enable:=(valor<>0); $9041:namco_snd_0.enabled:=valor<>0; $9042:if pal_bank<>valor then begin pal_bank:=valor; fillchar(gfx[0].buffer,$400,1); end; $9043:main_screen.flip_main_screen:=(valor and 1)<>0; $9046:if colortable_bank<>valor then begin colortable_bank:=valor; fillchar(gfx[0].buffer,$400,1); end; $9047:if gfx_bank<>(valor and $1) then begin gfx_bank:=valor and $1; fillchar(gfx[0].buffer,$400,1); end; $9070:; //watchdog end; end; procedure pengo_sound_update; begin namco_snd_0.update; end; //Main procedure reset_pengo; begin z80_0.reset; namco_snd_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; irq_enable:=false; gfx_bank:=0; pal_bank:=0; colortable_bank:=0; end; function iniciar_pengo:boolean; var colores:tpaleta; f:word; bit0,bit1,bit2:byte; memoria_temp:array[0..$ffff] of byte; rweights,gweights,bweights:array[0..3] of single; const ps_x:array[0..15] of dword=(8*8, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3, 0, 1, 2, 3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8); pc_x:array[0..7] of dword=(8*8+0, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3); resistances:array[0..2] of integer=(1000,470,220); begin llamadas_maquina.bucle_general:=pengo_principal; llamadas_maquina.reset:=reset_pengo; llamadas_maquina.fps_max:=18432000/3/384/264; iniciar_pengo:=false; iniciar_audio(false); screen_init(1,224,288); screen_init(2,224,288,false,true); screen_mod_sprites(2,256,512,$ff,$1ff); iniciar_video(224,288); //Main CPU z80_0:=cpu_z80.create(18432000 div 6,264); z80_0.change_ram_calls(pengo_getbyte,pengo_putbyte); z80_0.init_sound(pengo_sound_update); //cargar roms if not(roms_load(@memoria,pengo_rom)) then exit; decrypt_sega(@memoria,@rom_opcode,2); //cargar sonido & iniciar_sonido namco_snd_0:=namco_snd_chip.create(3); if not(roms_load(namco_snd_0.get_wave_dir,pengo_sound)) then exit; //organizar y convertir gfx if not(roms_load(@memoria_temp,pengo_sprites)) then exit; copymemory(@memoria_temp[$2000],@memoria_temp[$1000],$1000); copymemory(@memoria_temp[$1000],@memoria_temp[$4000],$1000); copymemory(@memoria_temp[$3000],@memoria_temp[$5000],$1000); //chars init_gfx(0,8,8,$200); gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,true,false); //sprites init_gfx(1,16,16,$80); gfx_set_desc_data(2,0,64*8,0,4); convert_gfx(1,0,@memoria_temp[$2000],@ps_x,@ps_y,true,false); //poner la paleta if not(roms_load(@memoria_temp,pengo_pal)) then exit; compute_resistor_weights(0, 255, -1.0, 3,@resistances,@rweights,0,0, 3,@resistances,@gweights,0,0, 2,@resistances[1],@bweights,0,0); for f:=0 to $1f do begin // red component bit0:=(memoria_temp[f] shr 0) and $01; bit1:=(memoria_temp[f] shr 1) and $01; bit2:=(memoria_temp[f] shr 2) and $01; colores[f].r:=combine_3_weights(@rweights, bit0, bit1, bit2); // green component bit0:=(memoria_temp[f] shr 3) and $01; bit1:=(memoria_temp[f] shr 4) and $01; bit2:=(memoria_temp[f] shr 5) and $01; colores[f].g:=combine_3_weights(@gweights, bit0, bit1, bit2); // blue component bit0:=(memoria_temp[f] shr 6) and $01; bit1:=(memoria_temp[f] shr 7) and $01; colores[f].b:=combine_2_weights(@bweights, bit0, bit1); end; set_pal(colores,$20); for f:=0 to 255 do begin gfx[0].colores[f]:=memoria_temp[$20+f] and $f; gfx[1].colores[f]:=memoria_temp[$20+f] and $f; gfx[0].colores[f+$100]:=(memoria_temp[$20+f] and $f)+$10; gfx[1].colores[f+$100]:=(memoria_temp[$20+f] and $f)+$10; end; //DIP marcade.dswa:=$b0; marcade.dswb:=$cc; marcade.dswa_val:=@pengo_dip_a; marcade.dswb_val:=@pengo_dip_b; //final reset_pengo; iniciar_pengo:=true; end; end.
unit Core; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, StrUtils, DateUtils; const SECONDS_PER_POMODORO = 1500; type { TPomodoro } TPomodoro = class private FCurrentPomodoro: integer; FStartTime: TDateTime; function PrepareDigits(Digits: integer): string; public constructor Create; procedure StartNewPomodoro; function GetFormattedTime: string; function GetPendingSeconds: integer; function GetStatus: string; function GetTitle: string; end; implementation { TPomodoro } constructor TPomodoro.Create; begin StartNewPomodoro; end; procedure TPomodoro.StartNewPomodoro; begin FStartTime := Now; Inc(FCurrentPomodoro); end; function TPomodoro.GetFormattedTime: string; var SecondsPending, Minutes, Seconds: integer; begin SecondsPending := GetPendingSeconds; DivMod(SecondsPending, 60, Minutes, Seconds); Result := Concat(PrepareDigits(Minutes), ':', PrepareDigits(Seconds)); if SecondsPending < 0 then Result := Concat('-', Result); end; function TPomodoro.GetPendingSeconds: integer; begin Result := SECONDS_PER_POMODORO - SecondsBetween(Now, FStartTime); end; function TPomodoro.PrepareDigits(Digits: integer): string; begin if Digits < 0 then Digits := -Digits; Result := AddChar('0', IntToStr(Digits), 2); end; function TPomodoro.GetStatus: string; begin Result := 'Focus on your task'; if GetPendingSeconds < 0 then Result := 'Take a break, click to continue'; end; function TPomodoro.GetTitle: string; begin Result := Format('Pomodoro #%d', [FCurrentPomodoro]); end; end.
unit lopes.TestHelper.Utils; interface uses Winapi.Windows, Vcl.Menus, ToolsAPI, Vcl.Graphics, System.Classes, System.Contnrs, System.SysUtils, Vcl.ComCtrls, System.Generics.Collections, Vcl.ActnList; type TProcInfoType = (pitEXE, pitParam, pitDir); TCustoMessage = class(TNotifierObject, IOTACustomMessage, INTACustomDrawMessage) strict private FMsg: String; FFonteName: String; FForeColour: TColor; FStyle: TFontStyles; FBackColour: TColor; FMessagePntr: Pointer; strict protected procedure SetForeColour(iColour: TColor); public constructor Create(strMsg: String; FontName: String; ForeColour: TColor = clBlack; Style: TFontStyles = []; BackColour: TColor = clWindow); property ForeColour: TColor write SetForeColour; Property MessagePntr: Pointer Read FMessagePntr Write FMessagePntr; Function GetColumnNumber: Integer; Function GetFileName: String; Function GetLineNumber: Integer; Function GetLineText: String; Procedure ShowHelp; Function CalcRect(Canvas: TCanvas; MaxWidth: Integer; Wrap: Boolean): TRect; Procedure Draw(Canvas: TCanvas; Const Rect: TRect; Wrap: Boolean); end; TClearMessage = (cmCompiler, cmSearch, cmTool); TClearMessages = Set of TClearMessage; TVersionInfo = Record iMajor: Integer; iMinor: Integer; iBugfix: Integer; iBuild: Integer; End; THelperUtils = class class function AddImageToIDE(strImageName: String; iMaskColour: TColor): Integer; class function CreateMenuItem(strName, strCaption, strParentMenu: String; ClickProc, UpdateProc: TNotifyEvent; boolBefore, boolChildMenu: Boolean; strShortCut: String; iMaskColour: TColor = clLime): TMenuItem; class function FindMenuItem(strParentMenu: String): TMenuItem; class function IterateSubMenus(strParentMenu: String; Menu: TMenuItem): TMenuItem; class procedure PatchActionShortcuts(Sender: TObject); class procedure RemoveToolbarButtonsAssociatedWithActions; class function IsCustomAction(Action: TBasicAction): Boolean; class procedure RemoveAction(Tb: TToolbar); class function Actions: TObjectList<TAction>; class function ITHHTMLHelpFile(strContext: String = ''): String; class procedure OutPutText(Writer: IOTAEditWriter; iIndent: Integer; strText: String); class function AddMsg(strText: String; boolGroup, boolAutoScroll: Boolean; strFontName: String; iForeColour: TColor; fsStyle: TFontStyles; iBackColour: TColor = clWindow; ptrParent: Pointer = Nil): Pointer; class function EditorAsString(SourceEditor: IOTASourceEditor): String; class function SourceEditor(Module: IOTAModule): IOTASourceEditor; class function ActiveSourceEditor: IOTASourceEditor; class function ProjectModule(project: IOTAProject): IOTAModule; class function ActiveProject: IOTAProject; class function ProjectGroup: IOTAProjectGroup; class function GetProjectName(project: IOTAProject): String; class procedure OutputMessage(strText: String); Overload; class procedure OutputMessage(strText: String; strGroupName: String); Overload; class procedure OutputMessage(strFileName, strText, strPrefix: String; iLine, iCol: Integer); overload; class function ExpandMacro(strPath: String; project: IOTAProject): String; class procedure ShowMessages(strGroupName: String = ''); class procedure ClearMessages(Msg: TClearMessages); class procedure ShowHelperMessages; class procedure BuildNumber(var VersionInfo: TVersionInfo); class function GetProcInfo(strText: String; ProcInfoType: TProcInfoType): String; class function ResolvePath(Const strFName, strPath: String): String; end; implementation uses Vcl.Forms, Vcl.Controls; resourcestring strITHelperGroup = 'ITHelper'; { THelperUtils } var FOTAActions: TObjectList<TAction>; class function THelperUtils.Actions: TObjectList<TAction>; begin Result := FOTAActions; end; class function THelperUtils.ActiveProject: IOTAProject; var vProjectActive: IOTAProjectGroup; begin Result := nil; vProjectActive := THelperUtils.ProjectGroup; if vProjectActive <> nil then Result := vProjectActive.ActiveProject; end; class function THelperUtils.ActiveSourceEditor: IOTASourceEditor; var CM: IOTAModule; begin Result := nil; if BorlandIDEServices = nil then Exit; CM := (BorlandIDEServices as IOTAModuleServices).CurrentModule; Result := THelperUtils.SourceEditor(CM); end; class function THelperUtils.AddImageToIDE(strImageName: String; iMaskColour: TColor): Integer; var NTAS: INTAServices; iIImages: TImageList; BM: TBitmap; begin Result := -1; if FindResource(HInstance, PChar(strImageName + 'Image'), RT_BITMAP) > 0 then begin NTAS := (BorlandIDEServices as INTAServices); iIImages := TImageList.Create(nil); try BM := TBitmap.Create; try BM.LoadFromResourceName(HInstance, strImageName + 'Image'); iIImages.AddMasked(BM, iMaskColour); Result := NTAS.AddImages(iIImages); finally BM.Free; end; finally iIImages.Free; end; end; end; class function THelperUtils.AddMsg(strText: String; boolGroup, boolAutoScroll: Boolean; strFontName: String; iForeColour: TColor; fsStyle: TFontStyles; iBackColour: TColor; ptrParent: Pointer): Pointer; Const strMessageGroupName = 'My Custom Messages'; Var M: TCustoMessage; G: IOTAMessageGroup; Begin With (BorlandIDEServices As IOTAMessageServices) Do Begin M := TCustoMessage.Create(strText, strFontName, iForeColour, fsStyle, iBackColour); Result := M; If ptrParent = Nil Then Begin G := Nil; If boolGroup Then G := AddMessageGroup(strMessageGroupName) Else G := GetMessageGroup(0); If boolAutoScroll <> G.AutoScroll Then G.AutoScroll := boolAutoScroll; M.MessagePntr := AddCustomMessagePtr(M As IOTACustomMessage, G); AddCustomMessage(M As IOTACustomMessage, G); AddCustomMessage(M As IOTACustomMessage); End Else AddCustomMessage(M As IOTACustomMessage, ptrParent); End; end; class procedure THelperUtils.BuildNumber(var VersionInfo: TVersionInfo); Var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; strBuffer: Array [0 .. MAX_PATH] Of Char; begin GetModuleFileName(HInstance, strBuffer, MAX_PATH); VerInfoSize := GetFileVersionInfoSize(strBuffer, Dummy); if VerInfoSize <> 0 then begin GetMem(VerInfo, VerInfoSize); try GetFileVersionInfo(strBuffer, 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); VersionInfo.iMajor := VerValue^.dwFileVersionMS shr 16; VersionInfo.iMinor := VerValue^.dwFileVersionMS and $FFFF; VersionInfo.iBugfix := VerValue^.dwFileVersionLS shr 16; VersionInfo.iBuild := VerValue^.dwFileVersionLS and $FFFF; finally FreeMem(VerInfo, VerInfoSize); end; end; end; class procedure THelperUtils.ClearMessages(Msg: TClearMessages); begin if cmCompiler in Msg then (BorlandIDEServices as IOTAMessageServices).ClearCompilerMessages; if cmSearch in Msg then (BorlandIDEServices as IOTAMessageServices).ClearSearchMessages; if cmTool in Msg then (BorlandIDEServices as IOTAMessageServices).ClearToolMessages; end; class function THelperUtils.CreateMenuItem(strName, strCaption, strParentMenu: String; ClickProc, UpdateProc: TNotifyEvent; boolBefore, boolChildMenu: Boolean; strShortCut: String; iMaskColour: TColor): TMenuItem; var NTAS: INTAServices; vAction: TAction; miMenuItem: TMenuItem; iImageIndex: Integer; begin NTAS := (BorlandIDEServices as INTAServices); iImageIndex := AddImageToIDE(strName, iMaskColour); vAction := nil; Result := TMenuItem.Create(NTAS.MainMenu); if Assigned(ClickProc) then begin vAction := TAction.Create(NTAS.ActionList); vAction.ActionList := NTAS.ActionList; vAction.Name := strName + 'Action'; vAction.Caption := strCaption; vAction.OnExecute := ClickProc; vAction.OnUpdate := UpdateProc; vAction.ShortCut := TextToShortCut(strShortCut); vAction.Tag := TextToShortCut(strShortCut); vAction.ImageIndex := iImageIndex; vAction.Category := 'ITHelperMenus'; FOTAActions.Add(vAction); end else if not strCaption.IsEmpty then begin Result.Caption := strCaption; Result.ShortCut := TextToShortCut(strShortCut); Result.ImageIndex := iImageIndex; end else Result.Caption := '-'; Result.Action := vAction; Result.Name := strName + 'Menu'; miMenuItem := FindMenuItem(strParentMenu + 'Menu'); If miMenuItem <> Nil Then Begin If Not boolChildMenu Then Begin If boolBefore Then miMenuItem.Parent.Insert(miMenuItem.MenuIndex, Result) Else miMenuItem.Parent.Insert(miMenuItem.MenuIndex + 1, Result); End Else miMenuItem.Add(Result); End; end; class function THelperUtils.EditorAsString(SourceEditor: IOTASourceEditor): String; const iBufferSize: Integer = 1024; var vReader: IOTAEditReader; iRead: Integer; iPosition: Integer; strBuffer: AnsiString; begin Result := EmptyStr; vReader := SourceEditor.CreateReader; try iPosition := 0; repeat SetLength(strBuffer, iBufferSize); iRead := vReader.GetText(iPosition, PAnsiChar(strBuffer), iBufferSize); SetLength(strBuffer, iRead); Result := Result + String(strBuffer); Inc(iPosition, iRead); until iRead < iBufferSize; finally vReader := nil; end; end; class function THelperUtils.ExpandMacro(strPath: String; project: IOTAProject): String; begin Result := strPath; Result := StringReplace(Result, '{$PROJPATH$}', ExtractFilePath(project.FileName), [rfReplaceAll, rfIgnoreCase]); Result := StringReplace(Result, '{$PROJDRIVE$}', ExtractFileDrive(project.FileName), [rfReplaceAll, rfIgnoreCase]); end; class function THelperUtils.FindMenuItem(strParentMenu: String): TMenuItem; var iMenu: Integer; NTAS: INTAServices; Items: TMenuItem; begin Result := nil; NTAS := (BorlandIDEServices as INTAServices); for iMenu := 0 to NTAS.MainMenu.Items.Count - 1 do begin Items := NTAS.MainMenu.Items; if CompareText(strParentMenu, Items[iMenu].Name) = 0 then Result := Items[iMenu] else Result := IterateSubMenus(strParentMenu, Items); if Assigned(Result) then Break; end; end; class function THelperUtils.GetProcInfo(strText: String; ProcInfoType: TProcInfoType): String; Var iPos: Integer; Begin Result := ''; iPos := Pos('|', strText); If iPos > 0 Then Begin Result := Copy(strText, 1, iPos - 1); If ProcInfoType = pitEXE Then Exit; Delete(strText, 1, iPos); iPos := Pos('|', strText); If iPos > 0 Then Begin Result := Copy(strText, 1, iPos - 1); If ProcInfoType = pitParam Then Exit; Delete(strText, 1, iPos); Result := strText; End; End; end; class function THelperUtils.GetProjectName(project: IOTAProject): String; var i: Integer; strText: String; begin Result := ExtractFileName(project.FileName); for i := 0 to project.ModuleFileCount - 1 do begin strText := LowerCase(ExtractFileExt(project.ModuleFileEditors[i].FileName)); if (strText = 'dpr') or (strText = 'dpk') then begin Result := ChangeFileExt(Result, strText); Break; end; end; end; class function THelperUtils.IsCustomAction(Action: TBasicAction): Boolean; var i: Integer; begin Result := False; for i := 0 to FOTAActions.Count - 1 do begin if Action = FOTAActions[i] then begin Result := True; Break; end; end; end; class function THelperUtils.IterateSubMenus(strParentMenu: String; Menu: TMenuItem): TMenuItem; var iSubMenu: Integer; begin Result := nil; for iSubMenu := 0 to Menu.Count - 1 do begin if CompareText(strParentMenu, Menu.Items[iSubMenu].Name) = 0 then Result := Menu.Items[iSubMenu] else Result := Menu[iSubMenu]; if Result <> nil then Break; end; end; class function THelperUtils.ITHHTMLHelpFile(strContext: String): String; var iSize: Cardinal; begin SetLength(Result, MAX_PATH); iSize := GetModuleFileName(HInstance, PChar(Result), MAX_PATH); SetLength(Result, iSize); Result := ExtractFilePath(Result) + 'IThelper.chm'; if strContext <> '' then Result := Result + Format('::/%s.html', [strContext]); end; class procedure THelperUtils.OutputMessage(strText: String); begin (BorlandIDEServices as IOTAMessageServices).AddTitleMessage(strText); end; class procedure THelperUtils.OutputMessage(strFileName, strText, strPrefix: String; iLine, iCol: Integer); begin (BorlandIDEServices as IOTAMessageServices).AddToolMessage(strFileName, strText, strPrefix, iLine, iCol); end; class procedure THelperUtils.OutputMessage(strText, strGroupName: String); var vGroup: IOTAMessageGroup; begin vGroup := (BorlandIDEServices as IOTAMessageServices).GetGroup(strGroupName); if vGroup = nil then vGroup := (BorlandIDEServices as IOTAMessageServices).AddMessageGroup(strGroupName); (BorlandIDEServices as IOTAMessageServices).AddTitleMessage(strText, vGroup); end; class procedure THelperUtils.OutPutText(Writer: IOTAEditWriter; iIndent: Integer; strText: String); begin Writer.Insert(PAnsiChar(StringOfChar(#32, iIndent) + strText)); end; class procedure THelperUtils.PatchActionShortcuts(Sender: TObject); var iAction: Integer; vAction: TAction; begin for iAction := 0 to FOTAActions.Count - 1 do begin vAction := FOTAActions[iAction] as TAction; vAction.ShortCut := vAction.Tag; end; end; class function THelperUtils.ProjectGroup: IOTAProjectGroup; var aModuleService: IOTAModuleServices; aModule: IOTAModule; i: Integer; AProjectGroup: IOTAProjectGroup; begin Result := nil; aModuleService := (BorlandIDEServices as IOTAModuleServices); for i := 0 to aModuleService.ModuleCount - 1 do begin aModule := aModuleService.Modules[i]; if aModule.QueryInterface(IOTAProjectGroup, AProjectGroup) = S_OK then begin Break; end; end; Result := AProjectGroup; end; class function THelperUtils.ProjectModule(project: IOTAProject): IOTAModule; var aModuleService: IOTAModuleServices; aModule: IOTAModule; i: Integer; aProject: IOTAProject; begin Result := nil; aModuleService := (BorlandIDEServices as IOTAModuleServices); for i := 0 to aModuleService.ModuleCount - 1 do begin aModule := aModuleService.Modules[i]; if (aModule.QueryInterface(IOTAProject, aProject) = S_OK) and (project = aProject) then begin Break; end; end; Result := aProject; end; class procedure THelperUtils.RemoveAction(Tb: TToolbar); var i: Integer; begin if Assigned(Tb) then begin for i := 0 to Tb.ButtonCount - 1 do begin if IsCustomAction(Tb.Buttons[i].Action) then Tb.RemoveControl(Tb.Buttons[i]); end; end; end; class procedure THelperUtils.RemoveToolbarButtonsAssociatedWithActions; var NTAS: INTAServices; begin NTAS := (BorlandIDEServices as INTAServices); RemoveAction(NTAS.ToolBar[sCustomToolBar]); RemoveAction(NTAS.ToolBar[sStandardToolBar]); RemoveAction(NTAS.ToolBar[sDebugToolBar]); RemoveAction(NTAS.ToolBar[sViewToolBar]); RemoveAction(NTAS.ToolBar[sDesktopToolBar]); RemoveAction(NTAS.ToolBar[sInternetToolBar]); RemoveAction(NTAS.ToolBar[sCORBAToolBar]); RemoveAction(NTAS.ToolBar[sAlignToolbar]); RemoveAction(NTAS.ToolBar[sBrowserToolbar]); RemoveAction(NTAS.ToolBar[sHTMLDesignToolbar]); RemoveAction(NTAS.ToolBar[sHTMLFormatToolbar]); RemoveAction(NTAS.ToolBar[sHTMLTableToolbar]); RemoveAction(NTAS.ToolBar[sPersonalityToolBar]); RemoveAction(NTAS.ToolBar[sPositionToolbar]); RemoveAction(NTAS.ToolBar[sSpacingToolbar]); end; class function THelperUtils.ResolvePath(const strFName, strPath: String): String; Var strFileName: String; strPathName: String; begin strFileName := strFName; strPathName := strPath; If strFileName[1] = '.' Then Begin Repeat If Copy(strFileName, 1, 2) = '.\' Then strFileName := Copy(strFileName, 3, Length(strFileName) - 2); If Copy(strFileName, 1, 3) = '..\' Then Begin strFileName := Copy(strFileName, 4, Length(strFileName) - 3); strPathName := ExtractFilePath(Copy(strPathName, 1, Length(strPathName) - 1)); End; Until strFileName[1] <> '.'; Result := strPathName + strFileName; End Else Begin If ExtractFilePath(strFileName) = '' Then Result := strPathName + strFileName Else Result := strFileName; End; end; class procedure THelperUtils.ShowHelperMessages; var vGroup: IOTAMessageGroup; begin vGroup := (BorlandIDEServices as IOTAMessageServices).GetGroup(strITHelperGroup); if Application.MainForm.Visible then (BorlandIDEServices as IOTAMessageServices).ShowMessageView(vGroup); end; class procedure THelperUtils.ShowMessages(strGroupName: String); var vMessageGroup: IOTAMessageGroup; begin vMessageGroup := (BorlandIDEServices as IOTAMessageServices).GetGroup(strGroupName); (BorlandIDEServices as IOTAMessageServices).ShowMessageView(vMessageGroup); end; class function THelperUtils.SourceEditor(Module: IOTAModule): IOTASourceEditor; Var iFileCount: Integer; i: Integer; begin Result := nil; if not Assigned(Module) then Exit; iFileCount := Module.GetModuleFileCount; for i := 0 to iFileCount - 1 do begin if Module.GetModuleFileEditor(i).QueryInterface(IOTASourceEditor, Result) = S_OK then Break; end; end; { TCustoMessage } function TCustoMessage.CalcRect(Canvas: TCanvas; MaxWidth: Integer; Wrap: Boolean): TRect; begin Canvas.Font.Name := FFonteName; Canvas.Font.Style := FStyle; Result := Canvas.ClipRect; Result.Bottom := Result.Top + Canvas.TextHeight('Wp'); Result.Right := Result.Left + Canvas.TextWidth(FMsg); end; constructor TCustoMessage.Create(strMsg, FontName: String; ForeColour: TColor; Style: TFontStyles; BackColour: TColor); Const strValidChars: Set Of AnsiChar = [#10, #13, #32 .. #128]; Var i: Integer; iLength: Integer; begin SetLength(FMsg, Length(strMsg)); iLength := 0; for i := 0 to Length(strMsg) do begin if CharInSet(strMsg[i], strValidChars) then begin FMsg[iLength + 1] := strMsg[i]; Inc(iLength); end; end; SetLength(FMsg, iLength); FFonteName := FontName; FForeColour := ForeColour; FStyle := Style; FBackColour := BackColour; FMessagePntr := Nil; end; procedure TCustoMessage.Draw(Canvas: TCanvas; const Rect: TRect; Wrap: Boolean); begin if Canvas.Brush.Color = clWindow then begin Canvas.Font.Color := FForeColour; Canvas.Brush.Color := FBackColour; Canvas.FillRect(Rect); end; Canvas.Font.Name := FFonteName; Canvas.Font.Style := FStyle; Canvas.TextOut(Rect.Left, Rect.Top, FMsg); end; function TCustoMessage.GetColumnNumber: Integer; begin Result := 0; end; function TCustoMessage.GetFileName: String; begin Result := ''; end; function TCustoMessage.GetLineNumber: Integer; begin Result := 0; end; function TCustoMessage.GetLineText: String; begin Result := FMsg; end; procedure TCustoMessage.SetForeColour(iColour: TColor); begin if FForeColour <> iColour then FForeColour := iColour; end; procedure TCustoMessage.ShowHelp; begin end; initialization FOTAActions := TObjectList<TAction>.Create(True); finalization {$IFNDEF CONSOLE_TESTRUNNER} THelperUtils.RemoveToolbarButtonsAssociatedWithActions; {$ENDIF} FreeAndNil(FOTAActions); end.
unit Model.Cadastro; interface uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao; type TCadastro = class private FCadastro: Integer; FFuncionario: String; FEntregador: Integer; FDoc: String; FNome: String; FFantasia: String; FCPFCNPJ: String; FIERG: String; FNascimento: TDate; FUFRG: String; FEMissaoRG: TDate; FUFNascimento: String; FCidadeNascimento: String; FPai: String; FMae: String; FIEST: String; FIM: String; FCNAE: String; FCRT: Integer; FNumeroCNH: String; FRegistroCNH: String; FCategoriaCNH: String; FValidadeCNH: TDate; FUFCNH: String; FDataPrimeiraCNH: TDate; FURL: String; FAgente: Integer; FStatus: Integer; FObs: String; FDataCadastro: TDate; FUsuario: Integer; FVerba: Double; FCombustivel: Double; FTipoConta: String; FBanco: String; FAgenciaConta: String; FNumeroConta: String; FNomeFavorecido: String; FCPFCNPJFavorecido: String; FFormaPagamento: String; FCentroCusto: Integer; FRoubo: String; FQuantosRoubos: Integer; FAcidentes: String; FQuantosAcidentes: String; FTransporteEmpresa: String; FQuantosTransporteEmptresa: Integer; FGV: String; FDataGV: TDate; FExecutante: String; FDataAlteracao: TDateTime; FChave: String; FGrupo: Integer; FRoteiro: String; FMEI: String; FRazaoMEI: String; FFantasiaMEI: String; FCNPJMEI: String; FConexao : TConexao; FAcao: TAcao; FEmissorRG: String; FEmissaoCNH: TDate; FCodigoCNH: String; FNumeroConsultaGR: String; FEmpresaGR: String; FQuery: TFDQuery; FNomeTabela: String; public property Cadastro: Integer read FCadastro write FCadastro; property Funcionario: String read FFuncionario write FFuncionario; property Entregador: Integer read FEntregador write FEntregador; property Doc: String read FDoc write FDoc; property Nome: String read FNome write FNome; property Fantasia: String read FFantasia write FFantasia; property CPFCNPJ: String read FCPFCNPJ write FCPFCNPJ; property IERG: String read FIERG write FIERG; property Nascimento: TDate read FNascimento write FNascimento; property UFRG: String read FUFRG write FUFRG; property EMissaoRG: TDate read FEMissaoRG write FEMissaoRG; property UFNascimento: String read FUFNascimento write FUFNascimento; property CidadeNascimento: String read FCidadeNascimento write FCidadeNascimento; property Pai: String read FPai write FPai; property Mae: String read FMae write FMae; property IEST: String read FIEST write FIEST; property IM: String read FIM write FIM; property CNAE: String read FCNAE write FCNAE; property CRT: Integer read FCRT write FCRT; property NumeroCNH: String read FNumeroCNH write FNumeroCNH; property RegistroCNH: String read FRegistroCNH write FRegistroCNH; property CategoriaCNH: String read FCategoriaCNH write FCategoriaCNH; property ValidadeCNH: TDate read FValidadeCNH write FValidadeCNH; property EmissaoCNH: TDate read FEmissaoCNH write FEmissaoCNH; property UFCNH: String read FUFCNH write FUFCNH; property DataPrimeiraCNH: TDate read FDataPrimeiraCNH write FDataPrimeiraCNH; property URL: String read FURL write FURL; property Agente: Integer read FAgente write FAgente; property Status: Integer read FStatus write FStatus; property Obs: String read FObs write FObs; property DataCadastro: TDate read FDataCadastro write FDataCadastro; property Usuario: Integer read FUsuario write FUsuario; property Verba: Double read FVerba write FVerba; property Combustivel: Double read FCombustivel write FCombustivel; property TipoConta: String read FTipoConta write FTipoConta; property Banco: String read FBanco write FBanco; property AgenciaConta: String read FAgenciaConta write FAgenciaConta; property NumeroConta: String read FNumeroConta write FNumeroConta; property NomeFavorecido: String read FNomeFavorecido write FNomeFavorecido; property CPFCNPJFavorecido: String read FCPFCNPJFavorecido write FCPFCNPJFavorecido; property FormaPagamento: String read FFormaPagamento write FFormaPagamento; property CentroCusto: Integer read FCentroCusto write FCentroCusto; property Roubo: String read FRoubo write FRoubo; property QuantosRoubos: Integer read FQuantosRoubos write FQuantosRoubos; property Acidentes: String read FAcidentes write FAcidentes; property QuantosAcidentes: String read FQuantosAcidentes write FQuantosAcidentes; property TransporteEmpresa: String read FTransporteEmpresa write FTransporteEmpresa; property QuantosTransporteEmptresa: Integer read FQuantosTransporteEmptresa write FQuantosTransporteEmptresa; property GV: String read FGV write FGV; property DataGV: TDate read FDataGV write FDataGV; property Executante: String read FExecutante write FExecutante; property DataAlteracao: TDateTime read FDataAlteracao write FDataAlteracao; property Chave: String read FChave write FChave; property Grupo: Integer read FGrupo write FGrupo; property Roteiro: String read FRoteiro write FRoteiro; property MEI: String read FMEI write FMEI; property RazaoMEI: String read FRazaoMEI write FRazaoMEI; property FantasiaMEI: String read FFantasiaMEI write FFantasiaMEI; property CNPJMEI: String read FCNPJMEI write FCNPJMEI; property EmissorRG: String read FEmissorRG write FEmissorRG; property CodigoCNH: String read FCodigoCNH write FCodigoCNH; property EmpresaGR: String read FEmpresaGR write FEmpresaGR; property NumeroConsultaGR: String read FNumeroConsultaGR write FNumeroConsultaGR; property Acao: TAcao read FAcao write FAcao; property Query: TFDQuery read FQuery write FQuery; property NomeTabela: String read FNomeTabela write FNomeTabela; constructor Create; function Localizar(aParam: array of variant): Boolean; function Gravar(): Boolean; function GetID(): Integer; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; function GetField(sField: String; sKey: String; sKeyValue: String): String; function SetupModel(FDCadastro: TFDQuery): Boolean; end; const TABLENAME = 'tbentregadores'; implementation { TCadastro } uses Control.Sistema; function TCadastro.Alterar: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET dom_funcionario = :dom_funcionario, cod_entregador = :cod_entregador, ' + 'des_tipo_doc = :des_tipo_doc, des_razao_social = :des_razao_social, nom_fantasia = :nom_fantasia, ' + 'num_cnpj = :num_cnpj, num_ie = :num_ie, dat_nascimento = :dat_nascimento, dat_emissao_RG = :dat_emissao_RG,' + 'nom_emissor_RG = :nom_emissor_RG, uf_nascimento = :uf_nascimento, ' + 'nom_cidade_nascimento = :nom_cidade_nascimento, nom_pai = :nom_pai, nom_mae = :nom_mae, num_iest = :num_iest,' + 'num_im, cod_cnae = :num_im, cod_cnae, cod_crt = :cod_crt, num_cnh = :num_cnh, ' + 'num_registro_cnh = :num_registro_cnh, des_categoria_cnh = :des_categoria_cnh, ' + 'dat_validade_cnh = :dat_validade_cnh, dat_emissao_cnh = :dat_emissao_cnh, uf_cnh = :uf_cnh, ' + 'dat_1_habilitacao = :dat_1_habilitacao, des_pagina = :des_pagina, cod_agente = :cod_agente, ' + 'cod_status = :cod_status, des_observacao = :des_observacao, dat_cadastro = :dat_cadastro, ' + 'cod_usuario = :cod_usuario, val_verba = :val_verba, val_verba_combustivel = :val_verba_combustivel, ' + 'des_tipo_conta = :des_tipo_conta, cod_banco = :cod_banco, cod_agencia = :cod_agencia, ' + 'num_conta = :num_conta, nom_favorecido = :nom_favorecido, ' + 'num_cpf_cnpj_favorecido = :num_cpf_cnpj_favorecido, des_forma_pagamento = :des_forma_pagamento, ' + 'cod_centro_custo = :cod_centro_custo, dom_vitima_roubo = :dom_vitima_roubo, ' + 'qtd_vitima_roubo = :qtd_vitima_roubo, dom_acidentes = :dom_acidentes, qtd_acidentes = :qtd_acidentes, ' + 'dom_transporte_empresa = :dom_transporte_empresa, qtd_transporte_empresa = :qtd_transporte_empresa, ' + 'dom_gr = :dom_gr, dat_gv = :dat_gv, nom_executante = nom_executante, dat_alteracao = :dat_alteracao, ' + 'des_chave = :des_chave, cod_grupo = :cod_grupo, cod_roteiro = :cod_roteiro, cod_mei = :cod_mei, ' + 'nom_razao_mei = :nom_razao_mei, nom_fantasia_mei = :nom_fantasia_mei, num_cnpj_mei = :num_cnpj_mei, ' + 'cod_cnh = :cod_cnh, des_empresa_gr = :des_empresa_gr, num_consulta = :num_consulta ' + 'WHERE ' + 'cod_cadastro = :cod_cadastro;', [FFuncionario, FEntregador, FDoc, FNome, FFantasia, FCPFCNPJ, FIERG, FNascimento, FEMissaoRG,FUFRG, FEmissorRG, FUFNascimento, FCidadeNascimento, FPai, FMae, FIEST, FIM, FCNAE, FCRT, FNumeroCNH, FRegistroCNH, FCategoriaCNH, FValidadeCNH, FEmissaoCNH, FUFCNH, FDataPrimeiraCNH, FURL, FAgente, FStatus, FObs, FDataCadastro, FUsuario, FVerba, FCombustivel, FTipoConta, FBanco, FAgenciaConta, FNumeroConta, FNomeFavorecido, FCPFCNPJFavorecido, FFormaPagamento, FCentroCusto, FRoubo, FQuantosRoubos, FAcidentes, FQuantosAcidentes, FTransporteEmpresa, FQuantosTransporteEmptresa, FGV, FDataGV, FExecutante, FDataAlteracao, FChave, FGrupo, FRoteiro, FMEI, FRazaoMEI, FFantasiaMEI, FCNPJMEI, FCodigoCNH, FEmpresaGR, FNumeroConsultaGR, FCadastro]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TCadastro.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; FNomeTabela := TABLENAME; end; function TCadastro.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where WHERE COD_CADASTRO = :COD_CADASTRO', [FCadastro]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TCadastro.GetField(sField, sKey, sKeyValue: String): String; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FDQuery.Open(); if not FDQuery.IsEmpty then Result := FDQuery.FieldByName(sField).AsString; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastro.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(COD_CADASTRO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastro.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Self.Inserir(); Common.ENum.tacAlterar: Result := Self.Alterar(); Common.ENum.tacExcluir: Result := Self.Excluir(); end; end; function TCadastro.Inserir: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(cod_cadastro, dom_funcionario, cod_entregador, des_tipo_doc, ' + 'des_razao_social, nom_fantasia, num_cnpj, num_ie, dat_nascimento, dat_emissao_RG, nom_emissor_RG, ' + 'uf_nascimento, nom_cidade_nascimento, nom_pai, nom_mae, num_iest, num_im, cod_cnae, cod_crt, num_cnh, ' + 'num_registro_cnh, des_categoria_cnh, dat_validade_cnh, dat_emissao_cnh, uf_cnh, dat_1_habilitacao, ' + 'des_pagina, cod_agente, cod_status, des_observacao, dat_cadastro, cod_usuario, val_verba, ' + 'val_verba_combustivel, des_tipo_conta, cod_banco, cod_agencia, num_conta, nom_favorecido, ' + 'num_cpf_cnpj_favorecido, des_forma_pagamento, cod_centro_custo, dom_vitima_roubo, qtd_vitima_roubo, ' + 'dom_acidentes, qtd_acidentes, dom_transporte_empresa, qtd_transporte_empresa, dom_gr, dat_gv, ' + 'nom_executante, dat_alteracao, des_chave, cod_grupo, cod_roteiro, cod_mei, nom_razao_mei, ' + 'nom_fantasia_mei, num_cnpj_mei, cod_cnh, des_empresa_gr, num_consulta) ' + 'VALUES ' + '(:cod_cadastro, :dom_funcionario, :cod_entregador, :des_tipo_doc, ' + ':des_razao_social, :nom_fantasia, :num_cnpj, num_ie, :dat_nascimento, :dat_emissao_RG, :nom_emissor_RG, ' + ':uf_nascimento, :nom_cidade_nascimento, :nom_pai, :nom_mae, :num_iest, :num_im, :cod_cnae, :cod_crt, :num_cnh, ' + ':num_registro_cnh, :des_categoria_cnh, :dat_validade_cnh, :dat_emissao_cnh, :uf_cnh, :dat_1_habilitacao, ' + ':des_pagina, :cod_agente, :cod_status, :des_observacao, :dat_cadastro, :cod_usuario, :val_verba, ' + ':val_verba_combustivel, :des_tipo_conta, :cod_banco, :cod_agencia, :num_conta, :nom_favorecido, ' + ':num_cpf_cnpj_favorecido, :des_forma_pagamento, :cod_centro_custo, :dom_vitima_roubo, :qtd_vitima_roubo, ' + ':dom_acidentes, :qtd_acidentes, :dom_transporte_empresa, :qtd_transporte_empresa, :dom_gr, :dat_gv, ' + ':nom_executante, :dat_alteracao, :des_chave, :cod_grupo, :cod_roteiro, :cod_mei, :nom_razao_mei, ' + ':nom_fantasia_mei, :num_cnpj_mei, :cod_cnh, :des_empresa_gr, :num_consulta);', [FCadastro, FFuncionario, FEntregador, FDoc, FNome, FFantasia, FCPFCNPJ, FIERG, FNascimento, FEMissaoRG,FUFRG, FEmissorRG, FUFNascimento, FCidadeNascimento, FPai, FMae, FIEST, FIM, FCNAE, FCRT, FNumeroCNH, FRegistroCNH, FCategoriaCNH, FValidadeCNH, FEmissaoCNH, FUFCNH, FDataPrimeiraCNH, FURL, FAgente, FStatus, FObs, FDataCadastro, FUsuario, FVerba, FCombustivel, FTipoConta, FBanco, FAgenciaConta, FNumeroConta, FNomeFavorecido, FCPFCNPJFavorecido, FFormaPagamento, FCentroCusto, FRoubo, FQuantosRoubos, FAcidentes, FQuantosAcidentes, FTransporteEmpresa, FQuantosTransporteEmptresa, FGV, FDataGV, FExecutante, FDataAlteracao, FChave, FGrupo, FRoteiro, FMEI, FRazaoMEI, FFantasiaMEI, FCNPJMEI, FCodigoCNH, FEmpresaGR, FNumeroConsultaGR]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastro.Localizar(aParam: array of variant): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CADASTRO' then begin FDQuery.SQL.Add('WHERE COD_CADASTRO = :COD_CADASTRO'); FDQuery.ParamByName('COD_CADASTRO').AsInteger := aParam[1]; end; if aParam[0] = 'CPF' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ = :NUM_CNPJ'); FDQuery.ParamByName('NUM_CNPJ').AsString := aParam[1]; end; if aParam[0] = 'RG' then begin FDQuery.SQL.Add('WHERE NUM_IE = :NUM_IE'); FDQuery.ParamByName('NUM_IE').AsString := aParam[1]; end; if aParam[0] = 'CNPJIMEI' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ_MEI = :NUM_CNPJ_MEI'); FDQuery.ParamByName('NUM_CNPJ_MEI').AsString := aParam[1]; end; if aParam[0] = 'IMEI' then begin FDQuery.SQL.Add('WHERE COD_MEI = :COD_MEI'); FDQuery.ParamByName('COD_MEI').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('WHERE DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL'); FDQuery.ParamByName('DES_RAZAO_SOCIAL').AsString := aParam[1]; end; if aParam[0] = 'FANTASIA' then begin FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA'); FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; if FDQuery.IsEmpty then begin Exit; end; Self.Query := FDQuery; Result := True; finally FDquery.Connection.Close; FDQuery.Free; end; end; function TCadastro.SetupModel(FDCadastro: TFDQuery): Boolean; begin try Result := False; Cadastro := FDCadastro.FieldByName('cod_cadastro').AsInteger; Funcionario := FDCadastro.FieldByName('dom_funcionario').AsString; Entregador := FDCadastro.FieldByName('cod_entregador').AsInteger; Doc := FDCadastro.FieldByName('des_tipo_doc').AsString; Nome := FDCadastro.FieldByName('des_razao_social').AsString; Fantasia := FDCadastro.FieldByName('nom_fantasia').AsString; CPFCNPJ := FDCadastro.FieldByName('num_cnpj').AsString; IERG := FDCadastro.FieldByName('num_ie').AsString; Nascimento := FDCadastro.FieldByName('dat_nascimento').AsDateTime; UFRG := FDCadastro.FieldByName('uf_rg').AsString; EMissaoRG := FDCadastro.FieldByName('dat_emissao_rg').AsDateTime; UFNascimento := FDCadastro.FieldByName('uf_nascimento').AsString; CidadeNascimento := FDCadastro.FieldByName('nom_cidade_nascimento').AsString; Pai := FDCadastro.FieldByName('nom_pai').AsString; Mae := FDCadastro.FieldByName('nom_mae').AsString; IEST := FDCadastro.FieldByName('num_iest').AsString; IM := FDCadastro.FieldByName('num_im').AsString; CNAE := FDCadastro.FieldByName('cod_cnae').AsString; CRT := FDCadastro.FieldByName('cod_crt').AsInteger; NumeroCNH := FDCadastro.FieldByName('num_cnh').AsString; RegistroCNH := FDCadastro.FieldByName('num_registro_cnh').AsString; CategoriaCNH := FDCadastro.FieldByName('des_categoria_cnh').AsString; ValidadeCNH := FDCadastro.FieldByName('dat_validade_cnh').AsDateTime; UFCNH := FDCadastro.FieldByName('uf_cnh').AsString; DataPrimeiraCNH := FDCadastro.FieldByName('dat_1_habilitacao').AsDateTime; URL := FDCadastro.FieldByName('des_pagina').AsString; Agente := FDCadastro.FieldByName('cod_agente').AsInteger; Status := FDCadastro.FieldByName('cod_status').AsInteger; Obs := FDCadastro.FieldByName('des_observacao').AsString; DataCadastro := FDCadastro.FieldByName('dat_cadastro').AsDateTime; Usuario := FDCadastro.FieldByName('cod_usuario').AsInteger; Verba := FDCadastro.FieldByName('val_verba').AsFloat; Combustivel := FDCadastro.FieldByName('val_verba_combustivel').AsFloat; TipoConta := FDCadastro.FieldByName('des_tipo_conta').AsString; Banco := FDCadastro.FieldByName('cod_banco').AsString; AgenciaConta := FDCadastro.FieldByName('cod_agencia').AsString; NumeroConta := FDCadastro.FieldByName('num_conta').AsString; NomeFavorecido := FDCadastro.FieldByName('nom_favorecido').AsString; CPFCNPJFavorecido := FDCadastro.FieldByName('num_cpf_cnpj_favorecido').AsString; FormaPagamento := FDCadastro.FieldByName('des_forma_pagamento').AsString; CentroCusto := FDCadastro.FieldByName('cod_centro_custo').AsInteger; Roubo := FDCadastro.FieldByName('dom_vitima_roubo').AsString; QuantosRoubos := FDCadastro.FieldByName('qtd_vitima_roubo').AsInteger; Acidentes := FDCadastro.FieldByName('dom_acidentes').AsString; QuantosAcidentes := FDCadastro.FieldByName('qtd_acidentes').AsString; TransporteEmpresa := FDCadastro.FieldByName('dom_transporte_empresa').AsString; QuantosTransporteEmptresa := FDCadastro.FieldByName('qtd_transporte').AsInteger; GV := FDCadastro.FieldByName('dom_gv').AsString; DataGV := FDCadastro.FieldByName('dat_gv').AsDateTime; Executante := FDCadastro.FieldByName('nom_executante').AsString; DataAlteracao := FDCadastro.FieldByName('dat_alteracao').AsDateTime; Chave := FDCadastro.FieldByName('des_chave').AsString; Grupo := FDCadastro.FieldByName('cod_grupo').AsInteger; Roteiro := FDCadastro.FieldByName('cod_roteiro').AsString; MEI := FDCadastro.FieldByName('cod_mei').AsString; RazaoMEI := FDCadastro.FieldByName('nom_razao_mei').AsString; FantasiaMEI := FDCadastro.FieldByName('nom_fantasia_mei').AsString; CNPJMEI := FDCadastro.FieldByName('num_cnpj_mei').AsString; finally Result := True; end; end; end.
unit uData; (* 1 - Caso o servidor de banco de dados for Linux buscar a data de lá 2 - Caso não tenha internet buscar da tabela que armazena a ultima data 3 - Caso o servidor nao for linux tentar buscar da internet *) interface uses System.SysUtils, FireDAC.Comp.Client, IdSNTP, Vcl.Dialogs, Vcl.Forms; function getDataHoje(Maquina: Boolean = True): TDate; function getUltimaDataLigado(): TDate; procedure setUltimaDataLigado(data: TDate); function setDataVerdadeira(): Boolean; implementation uses dmPrincipal, uConstantes, internet; function getDataWeb(): TDateTime; var IdSNTP: TIDSntp; begin IdSNTP := TIDSntp.Create(nil); try IdSNTP.Host := 'pool.ntp.br'; Result := IdSNTP.DateTime; finally FreeAndNil(IdSNTP); end; end; { TODO -oJonathan -c : Alterar qnd estiver trabalhando com servidor 21/01/2016 20:33:33 } function getDataHoje(Maquina: Boolean = True): TDate; var ultimaData: TDate; begin // Implementar // if servidorLinux() then // begin // Result := getdataServidor(); // Exit; // end; ultimaData := getUltimaDataLigado(); if ultimaData <> Date() then // Verifica se a data da maquina está correta! begin Result := ultimaData; // Ja que houve algum problema verifique com a internet if verificarConexaoComInternet() then begin Result := getDataWeb(); setUltimaDataLigado(Result); end; // Implementar // enviarInformacaoClienteMudandoDataSistema(); Exit; end else Result := ultimaData; // if Maquina then // Result := getDataHoje() // else // Result := getUltimaDataLigado() end; procedure setUltimaDataLigado(data: TDate); const INSERT = 'INSERT INTO RADIUS_DATA (ULT_DATA) VALUES (''%s'');'; begin dmPrincipal.frmDmPrincipal.FDConnexao.ExecSQL (Format(INSERT, [FormatDateTime('dd.mm.yyyy', data)])) end; function getUltimaDataLigado(): TDate; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT' + #13#10 + 'MAX(U.ULT_DATA) AS ULT_DATA ' + #13#10 + 'FROM RADIUS_DATA U'; dsConsulta := TFDQuery.Create(conexaoSistema); dsConsulta.Connection := conexaoSistema; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName('ULT_DATA').AsDateTime; finally FreeAndNil(dsConsulta) end; end; // Caso tenha internet garante que a data do sistema será a buscada online // pois será buscada pela função: getDataHoje() function setDataVerdadeira(): Boolean; begin if getUltimaDataLigado() <> Date() then if verificarConexaoComInternet() then setUltimaDataLigado(getDataWeb()) else begin ShowMessage ('Por favor corrija a data e hora atual do computador, ou conecte-o com a ' + 'internet para que isso se faça automaticamente!'); Application.Terminate(); end; end; end.
unit RasterImageTools; interface uses types,classes,controls,command_class_lib,image_on_demand,RasterImageCommands; type TRasterImageTool = class (TAbstractToolAction) protected function doc: TRasterImageDocument; end; TBrushTool = class (TRasterImageTool) private fBrushing: Boolean; fShowBrush: Boolean; fBrushCommand: TBrushCommand; fBrushPosX,fBrushPosY: Integer; procedure DrawBrush; public function Select: Boolean; override; procedure Unselect; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X,Y: Integer); override; procedure MouseMove(Shift: TShiftState; X,Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseWheelUp(Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); override; procedure MouseWheelDown(Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); override; end; Procedure Register; implementation uses graphics,ActnList; resourcestring BrushToolCaption='Кисть'; procedure Register; begin RegisterActions('RasterImageActions',[TBrushTool],nil); end; (* TRasterImageTool *) function TRasterImageTool.doc: TRasterImageDocument; begin Result:=owner as TRasterImageDocument; end; (* TBrushTool *) function TBrushTool.Select: Boolean; begin SetStatusPanel(BrushToolCaption); Result:=true; end; procedure TBrushTool.Unselect; begin SetStatusPanel(''); end; procedure TBrushTool.MouseDown(Button: TMouseButton; Shift: TShiftState; X,Y: Integer); begin fBrushing:=true; fShowBrush:=false; fBrushCommand:=TBrushCommand.Create(nil); MouseMove(Shift,X,Y); end; procedure TBrushTool.MouseMove(Shift: TShiftState; X,Y: Integer); var BrushRect: TRect; begin if fBrushing then begin fBrushCommand.Draw(Round(X/doc.get_Scale),Round(Y/doc.Get_Scale)); BrushRect:=Rect(X-doc.BrushSize div 2,Y-doc.BrushSize div 2, (X+(doc.BrushSize-1) div 2)+1, (Y+(doc.BrushSize-1) div 2)+1); with doc.Image.Canvas do begin Brush.Color:=doc.PrimaryColor; Brush.Style:=bsSolid; Pen.Width:=0; if doc.BrushShape=bsSquare then FillRect(BrushRect) else if doc.BrushShape=bsRound then Ellipse(BrushRect); end; end else begin if fShowBrush then DrawBrush; fShowBrush:=true; fBrushPosX:=X; fBrushPosY:=Y; DrawBrush; end; end; procedure TBrushTool.MouseUp(Button: TMouseButton; Shift: TShiftState; X,Y: Integer); begin fBrushing:=false; //сейчас рамочку сотрут, и мы должны про это сказать fShowBrush:=false; if not doc.DispatchCommand(fBrushCommand) then fShowBrush:=true; end; procedure TBrushTool.DrawBrush; var BrushSize: Integer; begin BrushSize:=doc.BrushSize; with doc.Image.Picture.Bitmap.Canvas do begin Pen.Mode:=pmNotXor; Pen.Width:=1; // Pen.Mode:=pmBlack; // Pen.Mode:=pmNot; Pen.Color:=clBlack; // Brush.Color:=clWhite; // Brush.Style:=bsClear; Pen.Width:=1; Rectangle(Rect(fBrushPosX-BrushSize,fBrushPosY-BrushSize, fBrushPosX+BrushSize,fBrushPosY+BrushSize)); end; end; procedure TBrushTool.MouseWheelDown(Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin if doc.BrushSize>0 then begin DrawBrush; doc.BrushSize:=doc.BrushSize-1; DrawBrush; end; Handled:=true; end; procedure TBrushTool.MouseWheelUp(Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin DrawBrush; doc.BrushSize:=doc.BrushSize+1; DrawBrush; Handled:=true; end; initialization RegisterClasses([TBrushTool]); end.
{ Subroutine SST_W_C_EXP2 (TERM_FIRST1, N_TERMS1, TERM_FIRST2, N_TERMS2, OP, * ENCLOSE) * * Write two expressions with an operator in between. TERM_FIRST1 is the * descriptor for the first term in the expression before the operator. * N_TERMS1 is the number of terms in the chain starting at TERM_FIRST1. * TERM_FIRST2 and N_TERMS2 work in a likewise fashion. OP identifies the * operator between the two expressions. ENCLOSE * indicates whether the final expression should be enclosed in parentheses. * Value of ENCLOSE are: * * ENCLOSE_YES_K - Enclose in parentheses, if needed to make the entire * expression be one term. * * ENCLOSE_NO_K - Don't enclose expression in parentheses, even if is is * written as more than one term with operators in between. } module sst_W_C_EXP2; define sst_w_c_exp2; %include 'sst_w_c.ins.pas'; procedure sst_w_c_exp2 ( {write 2 expressions with operator in between} in term_first1: sst_exp_term_t; {first term in expression 1} in n_terms1: sys_int_machine_t; {number of terms in expression 1} in term_first2: sst_exp_term_t; {first term in expression 2} in n_terms2: sys_int_machine_t; {number of terms in expression 2} in op: sst_op2_k_t; {operator acting between the terms} in enclose: enclose_k_t); {enclose in () yes/no} const max_msg_parms = 1; {max parameters we can pass to a message} var term_p: sst_exp_term_p_t; {scratch pointer to a term in expression} i: sys_int_machine_t; {scratch integer and loop counter} dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor} sym1_p, sym2_p: sst_symbol_p_t; {pointers to implicit variables} dt: sst_dtype_k_t; {scratch data type ID} opname: string_var4_t; {operator name when direct C operator exists} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label op2_eq_ne, op_map_direct, leave; { ******************************** * * Local subroutine WRITE_EXP (T,N,ENC) * * Write an expression starting at term T, with N terms in it. ENC is * the standard parentheses enclose yes/no selector. It must be either * ENCLOSE_YES_K, or ENCLOSE_NO_K. These have the same meaning as for the * ENCLOSE argument of the main routine. See comment header for main routine. } procedure write_exp ( in t: sst_exp_term_t; {descriptor for first term in expression} in n: sys_int_machine_t; {number of terms in expression chain} in enc: enclose_k_t); {enclose in () yes/no flag} var last_p: sst_exp_term_p_t; {points to last term in expression} i: sys_int_machine_t; {loop counter} begin if n <= 1 then begin {the expression is just one term} sst_w_c_term (t, 0, enc); {write the expression as a term} end else begin {this is a compound expression} last_p := t.next_p; {init last term pointer to second term in exp} for i := 3 to n do begin {once for each time to advance LAST_P} last_p := last_p^.next_p; {advance LAST_P to point to next term in exp} end; sst_w_c_exp2 ( {write exp as 2 expressions with operator} t, {first term in expression before operator} n - 1, {number of terms in expression before op} last_p^, {first term in expression after operator} 1, {number of terms in expression after op} last_p^.op2, {operator between the two expressions} enc); {enclose in () yes/no flag} end ; end; { ******************************** * * Start of main routine. } begin opname.max := sizeof(opname.str); {init local var string} opname.len := 0; {init operator name string to empty} case op of {what is the operator between expressions ?} { * The following operators map directly to target language operators. * The cases for these operators will fall thru to the general code that * assumes OPNAME is set to the name of the operator in the target language. } sst_op2_add_k: string_appendn (opname, '+', 1); {term1 + term2} sst_op2_sub_k: string_appendn (opname, '-', 1); {term1 - term2} sst_op2_mult_k: string_appendn (opname, '*', 1); {term1 * term2} sst_op2_rem_k: string_appendn (opname, '%', 1); {remainder of term1 / term2} sst_op2_btand_k: string_appendn (opname, '&', 1); {bitwise and} sst_op2_btor_k: string_appendn (opname, '|', 1); {bitwise or} sst_op2_ge_k: string_appendn (opname, '>=', 2); {TRUE if term1 greater than or equal to term2} sst_op2_gt_k: string_appendn (opname, '>', 1); {TRUE if term1 greater than term2} sst_op2_le_k: string_appendn (opname, '<=', 2); {TRUE if term1 less than or equal to term2} sst_op2_lt_k: string_appendn (opname, '<', 1); {TRUE if term1 less than term2} sst_op2_and_k: string_appendn (opname, '&&', 2); {logical AND} sst_op2_or_k: string_appendn (opname, '||', 2); {logical OR} sst_op2_andthen_k: string_appendn (opname, '&&', 2); {logical AND, first op evaluated first} sst_op2_orelse_k: string_appendn (opname, '||', 2); {logical OR, first op evaluated first} sst_op2_union_k: string_appendn (opname, '|', 1); {term1 UNION term2} sst_op2_isect_k: string_appendn (opname, '&', 1); {term1 INTERSECTION term2} { * The following operators do not map directly to target language operators in * all cases. When the mapping IS direct, set OPNAME to the name of the target * language operator and either fall thru to after the CASE statement or jump * to OP_MAP_DIRECT. When the operator does not map directly, each case * must handle this itself, and jump to LEAVE when all done. } { ********** } sst_op2_eq_k: begin {TRUE if term1 = term2} string_appendn (opname, '==', 2); goto op2_eq_ne; end; sst_op2_ne_k: begin {TRUE if term1 <> term2} string_appendn (opname, '!=', 2); op2_eq_ne: {doing = or <> operator} dt_p := term_first2.dtype_p; {determine base data type of second term} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; case dt_p^.dtype of sst_dtype_rec_k, sst_dtype_array_k: begin syo_error (term_first2.str_h, 'sst_c_write', 'op_compare_dtype_bad', nil, 0); end; end; end; { ********** * * Real number divide. The C compiler will do an integer divide if both * terms have integer data type. If both TERM1 and TERM2 have at least one * component that does not have floating point type then we will explicitly * type-cast the second term to force a real number divide. } sst_op2_div_k: begin {term1 / term2, all treated as real numbers} term_p := addr(term_first1); {init curr term to first in exp1} for i := 1 to n_terms1 do begin {scan all the terms in first expression} sst_dtype_resolve ( {resolve term's base data type} term_p^.dtype_p^, dt_p, dt); if dt <> sst_dtype_float_k then exit; {not all terms have floating point type ?} if i = n_terms1 then begin {all terms have floating point data type ?} string_appendn (opname, '/', 1); {we can use regular "/" operator} goto op_map_direct; end; term_p := term_p^.next_p; {advance to next term in first expression} end; { * At least one term in the first expression does not have floating point data * type. This means we need to check second expression. } term_p := addr(term_first2); {init curr term to first in exp2} for i := 1 to n_terms2 do begin {scan all the terms in second expression} sst_dtype_resolve ( {resolve term's base data type} term_p^.dtype_p^, dt_p, dt); if dt <> sst_dtype_float_k then exit; {not all terms have floating point type ?} if i = n_terms1 then begin {all terms have floating point data type ?} string_appendn (opname, '/', 1); {we can use regular "/" operator} goto op_map_direct; end; term_p := term_p^.next_p; {advance to next term in first expression} end; { * At least one term in both expressions does not have floating point data * type. We now definately need to type-cast at least one of the expressions * to prevent the C compiler from doing an integer divide. We will type cast * the second expression. } if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; write_exp (term_first1, n_terms1, enclose_yes_k); {write first expression} sst_w.delimit^; sst_w.appendn^ ('/', 1); sst_w.delimit^; sst_w.appendn^ ('(double)', 8); {force second expression to be floating point} write_exp (term_first2, n_terms2, enclose_yes_k); {write second expression} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** } sst_op2_divi_k: begin {term1 / term2, term2 and result are integer} term_p := addr(term_first1); {init curr term to first in exp1} for i := 1 to n_terms1 do begin {scan all the terms in first expression} sst_dtype_resolve ( {resolve term's base data type} term_p^.dtype_p^, dt_p, dt); if dt <> sst_dtype_int_k then exit; {not all terms have integer value ?} if i = n_terms1 then begin {all terms have integer data type ?} string_appendn (opname, '/', 1); {we can use regular "/" operator} goto op_map_direct; end; term_p := term_p^.next_p; {advance to next term in first expression} end; { * At least one term in the first expression does not have an integer value. * This means we have to explicitly cast the first expression as an integer * before using the "/" operator. } if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; sst_w.appendn^ ('(int)', 5); {integer type-case operator} write_exp (term_first1, n_terms1, enclose_yes_k); {write first expression} sst_w.delimit^; sst_w.appendn^ ('/', 1); sst_w.delimit^; write_exp (term_first2, n_terms2, enclose_yes_k); {write second expression} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** } sst_op2_pwr_k: begin {term1 to-power-of term2} sst_w_c_intrinsic (intr_pow_k); {write POW function name} sst_w.appendn^ ('(', 1); sst_w.allow_break^; write_exp (term_first1, n_terms1, enclose_no_k); {write first expression} sst_w.appendn^ (',', 1); sst_w.allow_break^; write_exp (term_first2, n_terms2, enclose_no_k); {write second expression} sst_w.appendn^ (')', 1); goto leave; end; { ********** * * True if EXP1 is member of EXP2. Form will be: * * ((1 << exp1) & exp2) != 0 } sst_op2_in_k: begin {TRUE if term1 is member of term2} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; sst_w.appendn^ ('((1', 3); sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; write_exp (term_first1, n_terms1, enclose_yes_k); {write first expression} sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; write_exp (term_first2, n_terms2, enclose_yes_k); {write second expression} sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('!=', 2); sst_w.delimit^; sst_w.appendn^ ('0', 1); if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** * * Remove all members in EXP2 from EXP1. * * exp1 & ~exp2 } sst_op2_remov_k: begin {REMOVE all members of term2 from term1} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; write_exp (term_first1, n_terms1, enclose_yes_k); {write first expression} sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; sst_w.appendn^ ('~', 1); {indicate one's complement of expression 2} write_exp (term_first2, n_terms2, enclose_yes_k); {write second expression} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** * * TRUE if EXP1 is a proper subset of EXP2. This means that EXP1 <> EXP2. * * (exp1 & exp2) == exp1 && exp1 != exp2 * * This may require implicit variables be created for exp1 and exp2. } sst_op2_subset_k: begin {TRUE if term1 is proper subset of term2} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; sst_w_c_terms_implicit ( {make implicit var for exp1 if needed} term_first1, {first term in expression} n_terms1, {number of terms in expression} term_first1.dtype_p^, {data type for implicit variable} sym1_p); {returned pointer to implicit var, if any} sst_w_c_terms_implicit ( {make implicit var for exp2 if needed} term_first2, {first term in expression} n_terms2, {number of terms in expression} term_first2.dtype_p^, {data type for implicit variable} sym2_p); {returned pointer to implicit var, if any} sst_w.appendn^ ('(', 1); if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('==', 2); sst_w.delimit^; if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ ('&&', 2); sst_w.delimit^; if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ ('!=', 2); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** * * TRUE if EXP1 is a subset of EXP2. This means that EXP1 may equal EXP2. * * (exp1 & exp2) == exp1 * * This may require an implicit variable be created for EXP1. } sst_op2_subset_eq_k: begin {TRUE if term1 is subset or equal to term2} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; sst_w_c_terms_implicit ( {make implicit var for exp1 if needed} term_first1, {first term in expression} n_terms1, {number of terms in expression} term_first1.dtype_p^, {data type for implicit variable} sym1_p); {returned pointer to implicit var, if any} sst_w.appendn^ ('(', 1); if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; write_exp (term_first2, n_terms2, enclose_yes_k); {write value of expression 2} sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('==', 2); sst_w.delimit^; if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** * * TRUE if EXP1 is a proper superset of EXP2. This means that EXP1 <> EXP2. * * (exp1 & exp2) == exp2 && exp1 != exp2 * * This may require implicit variables be created for exp1 and exp2. } sst_op2_superset_k: begin {TRUE if term1 is proper superset of term2} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; sst_w_c_terms_implicit ( {make implicit var for exp1 if needed} term_first1, {first term in expression} n_terms1, {number of terms in expression} term_first1.dtype_p^, {data type for implicit variable} sym1_p); {returned pointer to implicit var, if any} sst_w_c_terms_implicit ( {make implicit var for exp2 if needed} term_first2, {first term in expression} n_terms2, {number of terms in expression} term_first2.dtype_p^, {data type for implicit variable} sym2_p); {returned pointer to implicit var, if any} sst_w.appendn^ ('(', 1); if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('==', 2); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); sst_w.delimit^; sst_w.appendn^ ('&&', 2); sst_w.delimit^; if sym1_p = nil {write value of expression 1} then write_exp (term_first1, n_terms1, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ ('!=', 2); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** * * TRUE if EXP1 is a superset of EXP2. This means that EXP1 may equal EXP2. * * (exp1 & exp2) == exp2 * * This may require an implicit variable be created for EXP2. } sst_op2_superset_eq_k: begin {TRUE if term1 is superset or equal to term2} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; sst_w_c_terms_implicit ( {make implicit var for exp2 if needed} term_first2, {first term in expression} n_terms2, {number of terms in expression} term_first2.dtype_p^, {data type for implicit variable} sym2_p); {returned pointer to implicit var, if any} sst_w.appendn^ ('(', 1); write_exp (term_first1, n_terms1, enclose_yes_k); {write value of expression 1} sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('==', 2); sst_w.delimit^; if sym2_p = nil {write value of expression 2} then write_exp (term_first2, n_terms2, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; goto leave; end; { ********** } otherwise {illegal or unimplemented operator} sys_msg_parm_int (msg_parm[1], ord(op)); sys_message_bomb ('sst', 'operator_unknown_diadic', msg_parm, 1); end; {end of operator cases} { * All the cases that fall thru here are where the SST operator maps directly * to a target language operator. OPNAME is set to the operator name. } op_map_direct: {jump here when OPNAME is target language op} if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ ('(', 1); {write leading paren} end; write_exp ( {write expression before operator} term_first1, n_terms1, enclose_yes_k); sst_w.delimit^; sst_w.append^ (opname); {write operator} sst_w.delimit^; write_exp ( {write expression after operator} term_first2, n_terms2, enclose_yes_k); if enclose = enclose_yes_k then begin {enclose expression in () to make 1 term ?} sst_w.appendn^ (')', 1); {write trailing paren} end; leave: {common exit point} end;
unit UBingMapsGPS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Math, JPEG, ExtCtrls, XPMan, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, GPS, ComCtrls, CPortCtl, Buttons; type TFBingMapsGPS = class(TForm) IMG_Carte: TImage; GPS1: TGPS; BV_Barre: TBevel; GPSSpeed1: TGPSSpeed; GPSSatellitesPosition1: TGPSSatellitesPosition; GPSSatellitesReception1: TGPSSatellitesReception; GPSCompass1: TGPSCompass; PNL_GPS: TPanel; LBL_Port: TLabel; CCMB_Port: TComComboBox; BTN_DemarrerGPS: TSpeedButton; HTTP_BingMaps: TIdHTTP; LBL_Latitude: TLabel; LBL_Longitude: TLabel; LBL_Altitude: TLabel; CHK_Valide: TCheckBox; XPManifest1: TXPManifest; CHK_Satellite: TCheckBox; TIM_BingMaps: TTimer; TB_Zoom: TTrackBar; procedure FormDestroy(Sender: TObject); procedure CCMB_PortChange(Sender: TObject); procedure BTN_DemarrerGPSClick(Sender: TObject); procedure GPS1GPSDatasChange(Sender: TObject; GPSDatas: TGPSDatas); procedure TIM_BingMapsTimer(Sender: TObject); procedure CHK_ValideClick(Sender: TObject); procedure CHK_SatelliteClick(Sender: TObject); procedure TB_ZoomChange(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } end; const // Placez ici la clé récupérée sur le site Bing Maps Account Center Clef = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; Serveur = 'http://dev.virtualearth.net/REST/v1/'; Imagerie = Serveur + 'Imagery/Map/%s/%s,%s/%d?ms=%d,%d&pp=%s,%s;6&key=' + Clef; var FBingMapsGPS: TFBingMapsGPS; Latitude, Longitude: Double; implementation {$R *.dfm} procedure TFBingMapsGPS.FormDestroy(Sender: TObject); begin // Arrête le GPS à la fermeture de l'application GPS1.Close(); end; procedure TFBingMapsGPS.CCMB_PortChange(Sender: TObject); begin // Change le port utilisé par le GPS GPS1.Port := CCMB_Port.Text; end; procedure TFBingMapsGPS.BTN_DemarrerGPSClick(Sender: TObject); begin try // Démarre le GPS si le bouton est enfoncé GPS1.Connected := BTN_DemarrerGPS.Down; // Démarre le rafraîchisement automatique de la carte TIM_BingMaps.Enabled := BTN_DemarrerGPS.Down; except on E: Exception do begin // Remonte le bouton BTN_DemarrerGPS.Down := False; // Affiche un message d'erreur MessageDlg('Erreur lors du démarrage du GPS.'#13#10 + E.ClassName + ' : ' + E.Message, mtError, [mbOk], 0); end; end; // Change le texte du bouton case BTN_DemarrerGPS.Down of True : BTN_DemarrerGPS.Caption := '&Démarrer le GPS'; False : BTN_DemarrerGPS.Caption := '&Arrêter le GPS'; end; end; procedure TFBingMapsGPS.GPS1GPSDatasChange(Sender: TObject; GPSDatas: TGPSDatas); begin with GPSDatas do begin // Change le contenu des TLabel pour avoir la position GPS LBL_Latitude.Caption := Format('Latitude : %2.6f°', [Latitude]); LBL_Longitude.Caption := Format('Longitude : %2.6f°', [Longitude]); LBL_Altitude.Caption := Format('Altitude : %f m', [HeightAboveSea]); // Coche la case si la position captée est valide CHK_Valide.Checked := Valid; end; end; procedure TFBingMapsGPS.TIM_BingMapsTimer(Sender: TObject); // Retourne le répertoire temporaire de Windows function RepertoireTemporaire(): String; var lpBuffer: array[0..255] of Char; begin GetTempPath(SizeOf(lpBuffer), lpBuffer); Result := lpBuffer; end; // Transforme un nombre réel en chaîne function ReelVersStr(Nombre: Double): String; var FrmNmb: TFormatSettings; begin try // -> http://msdn.microsoft.com/library/0h88fahh GetLocaleFormatSettings($0409, FrmNmb); Result := FloatToStr(Nombre, FrmNmb); except Result := '0'; end; end; var Adresse, Carte, LatStr, LongStr, TypeVue: String; Reponse: TFileStream; begin // Si le GPS est connecté if GPS1.Connected then begin // Si la position a changée (attention : utilise l'unité Math) if not SameValue(GPS1.GPSDatas.Latitude, Latitude, 0.0001) and not SameValue(GPS1.GPSDatas.Longitude, Longitude, 0.0001) then begin // Récupère la position Latitude := GPS1.GPSDatas.Latitude; Longitude := GPS1.GPSDatas.Longitude; // Converti la position en texte LatStr := ReelVersStr(Latitude); LongStr := ReelVersStr(Longitude); // Si la vue satellite est cochée if CHK_Satellite.Checked then begin TypeVue := 'AerialWithLabels'; end else begin TypeVue := 'Road'; end; // Ne pas oublier d'ajouter l'unité JPEG Carte := RepertoireTemporaire() + 'Carte.jpeg'; // Prépare l'adresse de l'image à charger Adresse := Format(Imagerie, [TypeVue, LatStr, LongStr, TB_Zoom.Position, IMG_Carte.Width, IMG_Carte.Height, LatStr, LongStr]); // Charge l'image à partir de Bing Maps Reponse := TFileStream.Create(Carte, fmCreate); try HTTP_BingMaps.Get(Adresse, Reponse); finally Reponse.Free(); end; IMG_Carte.Picture.LoadFromFile(Carte); end; end; end; procedure TFBingMapsGPS.CHK_ValideClick(Sender: TObject); begin // Coche la case uniquement si le signal est valide CHK_Valide.Checked := GPS1.GPSDatas.Valid; end; procedure TFBingMapsGPS.CHK_SatelliteClick(Sender: TObject); begin // Force le rafraîchissement de la carte Latitude := 0; Longitude := 0; TIM_BingMapsTimer(TIM_BingMaps); end; procedure TFBingMapsGPS.TB_ZoomChange(Sender: TObject); begin // Force le rafraîchissement de la carte Latitude := 0; Longitude := 0; TIM_BingMapsTimer(TIM_BingMaps); end; end.
unit fmuCustomerInternet; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AtrPages, ToolCtrlsEh, ComCtrls, ToolWin, DBCtrlsEh, StdCtrls, Mask, ExtCtrls, GridsEh, DBGridEh, DB, FIBDataSet, pFIBDataSet, ActnList, ibase, DBGridEhToolCtrls, DBAxisGridsEh, System.Actions, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, FIBDatabase, pFIBDatabase; type TDllForm = procedure(AppHandle: THandle; DBHandle: TISC_DB_HANDLE; ID: Integer; UserName: PWChar; Password: PWChar); StdCall; TDisconnectInDLL = procedure; stdcall; EDLLLoadError = class(Exception); TapgCustomerInternet = class(TA4onPage) srcInternet: TDataSource; dsInternet: TpFIBDataSet; dbgrdBill: TDBGridEh; tlbButtons: TToolBar; btnInfo: TToolButton; btnBillEdit: TToolButton; btnUnblock: TToolButton; btnBillDelete: TToolButton; ActListCustomers: TActionList; actEdit: TAction; actAdd: TAction; actDelete: TAction; actUnblock: TAction; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; procedure actUnblockExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure srcInternetStateChange(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure dbgrdBillDblClick(Sender: TObject); private { Private declarations } bView: Boolean; bEdit: Boolean; bFull: Boolean; procedure EnableControls; public procedure InitForm; override; procedure OpenData; override; procedure CloseData; override; class function GetPageName: string; override; end; implementation {$R *.dfm} uses MAIN, AtrCommon, DM, BillEditForma; class function TapgCustomerInternet.GetPageName: string; begin Result := rsInternet; end; procedure TapgCustomerInternet.InitForm; begin dsInternet.DataSource := FDataSource; bEdit := dmMain.AllowedAction(rght_Billing_edit); bView := dmMain.AllowedAction(rght_Billing_view); bFull := dmMain.AllowedAction(rght_Customer_full); end; procedure TapgCustomerInternet.EnableControls; begin actAdd.Enabled := (bEdit or bFull); btnInfo.Visible := False; // просмотр биллинг actUnblock.Visible := False; // правка биллинга actEdit.Enabled := (bEdit or bFull); // правка биллинга actDelete.Enabled := (bEdit or bFull); // правка биллинга tlbButtons.Visible := actAdd.Enabled or actEdit.Enabled or actDelete.Enabled; end; procedure TapgCustomerInternet.OpenData; begin dsInternet.Open; EnableControls; end; procedure TapgCustomerInternet.srcInternetStateChange(Sender: TObject); begin EnableControls; end; procedure TapgCustomerInternet.actDeleteExecute(Sender: TObject); var s: string; DLLHandle: THandle; ShowDeleteForm: TDllForm; begin if (dsInternet.RecordCount = 0) or dsInternet.FieldByName('BLNG_ID').IsNull then Exit; s := ExtractFilePath(Application.ExeName); s := s + 'internet.dll'; if FileExists(s) then begin DLLHandle := LoadLibrary(PChar(s)); try if DLLHandle <= 0 then MessageDlg('Error loading ' + QuotedStr(s), mtError, [mbOk], 0) else begin @ShowDeleteForm := GetProcAddress(DLLHandle, 'ShowDeleteForm'); if Assigned(ShowDeleteForm) then ShowDeleteForm(Application.Handle, dmMain.dbTV.Handle, dsInternet.FieldByName('UNIT_ID').AsInteger, PChar(dmMain.USER), PChar(dmMain.Password)) else MessageDlg('Error execute ShowDeleteForm', mtError, [mbOk], 0); end; finally FreeLibrary(DLLHandle); end; end else begin if MessageDlg(format(rsDeleteWithName, [dsInternet['LOGIN']]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then dsInternet.Delete; end; dsInternet.CloseOpen(true); end; procedure TapgCustomerInternet.actEditExecute(Sender: TObject); var s: string; DLLHandle: THandle; UnblockUser: TDllForm; begin if (not(bEdit or bFull)) then Exit; if (dsInternet.RecordCount = 0) or dsInternet.FieldByName('BLNG_ID').IsNull then Exit; s := ExtractFilePath(Application.ExeName); s := s + 'internet.dll'; if FileExists(s) then begin DLLHandle := LoadLibrary(PChar(s)); try if DLLHandle <= 0 then MessageDlg('Error loading ' + QuotedStr(s), mtError, [mbOk], 0) else begin @UnblockUser := GetProcAddress(DLLHandle, 'EditUser'); if Assigned(UnblockUser) then UnblockUser(Application.Handle, dmMain.dbTV.Handle, dsInternet.FieldByName('UNIT_ID').AsInteger, PChar(dmMain.USER), PChar(dmMain.Password)) else MessageDlg('Error execute UnblockUser', mtError, [mbOk], 0); end finally FreeLibrary(DLLHandle); end; end else begin if EditBillInfo(dsInternet['BLNG_ID'], FDataSource.DataSet.FieldByName('CUSTOMER_ID').AsInteger, FDataSource.DataSet.FieldByName('ACCOUNT_NO').AsString) > 0 then dsInternet.Refresh; end; end; procedure TapgCustomerInternet.actAddExecute(Sender: TObject); var s: string; DLLHandle: THandle; AddUserForm: TDllForm; begin if (not(bEdit or bFull)) then Exit; s := ExtractFilePath(Application.ExeName) + 'internet.dll'; if FileExists(s) then begin DLLHandle := LoadLibrary(PChar(s)); try if DLLHandle <= 0 then MessageDlg('Error loading ' + QuotedStr(s), mtError, [mbOk], 0) else begin @AddUserForm := GetProcAddress(DLLHandle, 'AddInternetUser'); if Assigned(AddUserForm) then begin AddUserForm(Application.Handle, dmMain.dbTV.Handle, FDataSource.DataSet.FieldByName('CUSTOMER_ID').AsInteger, PWChar(dmMain.USER), PWChar(dmMain.Password)); dsInternet.CloseOpen(true); end else MessageDlg('Error execute AddInternetUser', mtError, [mbOk], 0); end; finally FreeLibrary(DLLHandle); end; end else begin if EditBillInfo(-1, FDataSource.DataSet.FieldByName('CUSTOMER_ID').AsInteger, FDataSource.DataSet.FieldByName('ACCOUNT_NO').AsString) > 0 then dsInternet.CloseOpen(true); end; end; procedure TapgCustomerInternet.actUnblockExecute(Sender: TObject); var s: string; DLLHandle: THandle; UnblockUser: TDllForm; begin s := ExtractFilePath(Application.ExeName); s := s + 'internet.dll'; if FileExists(s) then begin DLLHandle := LoadLibrary(PChar(s)); try if DLLHandle <= 0 then MessageDlg('Error loading ' + QuotedStr(s), mtError, [mbOk], 0) else begin @UnblockUser := GetProcAddress(DLLHandle, 'UnblockUser'); if Assigned(UnblockUser) then UnblockUser(Application.Handle, dmMain.dbTV.Handle, dsInternet.FieldByName('UNIT_ID').AsInteger, PChar(dmMain.USER), PChar(dmMain.Password)) else MessageDlg('Error execute UnblockUser', mtError, [mbOk], 0); end finally FreeLibrary(DLLHandle); end; end end; procedure TapgCustomerInternet.CloseData; begin dsInternet.Close; end; procedure TapgCustomerInternet.dbgrdBillDblClick(Sender: TObject); begin if (not(Sender as TDBGridEh).DataSource.DataSet.Active) then Exit; if (Sender as TDBGridEh).DataSource.DataSet.RecordCount = 0 then actAdd.Execute else actEdit.Execute; end; end.
unit MapSprites; interface uses Windows, Classes, GameTypes, ShutDown, TimerTypes, LanderTypes, MapTypes; type TSpriteImages = array [TAngle] of TGameImage; type IMapSprite = interface function GetId : integer; function GetFrame : integer; function GetAngle : TAngle; function GetMapX : integer; function GetMapY : integer; function GetOldMapX : integer; function GetOldMapY : integer; procedure AnimationTick; procedure NewView(const View : IGameView); function GetBlockX(const View : IGameView) : integer; function GetBlockY(const View : IGameView) : integer; function GetOldBlockX(const View : IGameView) : integer; function GetOldBlockY(const View : IGameView) : integer; function GetWidth(const View : IGameView) : integer; function GetHeight(const View : IGameView) : integer; property Id : integer read GetId; property Frame : integer read GetFrame; property Angle : TAngle read GetAngle; property MapX : integer read GetMapX; property MapY : integer read GetMapY; property OldMapX : integer read GetOldMapX; property OldMapY : integer read GetOldMapY; end; type IMapSpriteManager = interface function GetSpriteCount : integer; function GetSprite(i : integer) : IMapSprite; procedure UpdateSpriteRect(const Sprite : IMapSprite); procedure SpriteMapPosChanged(const Sprite : IMapSprite); function RegisterSprite(const Sprite : IMapSprite) : integer; procedure UnregisterSprite(const Sprite : IMapSprite); function IsSpriteVisible(const Sprite : IMapSprite) : boolean; function GetSpriteImages(const Sprite : IMapSprite; const View : IGameView; out Images : TSpriteImages) : boolean; procedure AttachFocus(const focus : IGameFocus); procedure DetachFocus(const focus : IGameFocus); procedure NewView(const View : IGameView); procedure RecacheSoundTargets(soundsenabled : boolean); procedure Enable; procedure Disable; property SpriteCount : integer read GetSpriteCount; property Sprites[i : integer] : IMapSprite read GetSprite; default; end; type TMapSpriteManager = class(TInterfacedObject, IMapSpriteManager, IShutDownTarget, ITickeable) public constructor Create(const Map : IWorldMap; const Converter : ICoordinateConverter; const Manager : ILocalCacheManager; MinAnimInterval : integer; OwnsSprites : boolean); destructor Destroy; override; protected // IMapSpriteManager function GetSpriteCount : integer; virtual; abstract; function GetSprite(i : integer) : IMapSprite; virtual; abstract; procedure UpdateSpriteRect(const Sprite : IMapSprite); procedure SpriteMapPosChanged(const Sprite : IMapSprite); virtual; abstract; function RegisterSprite(const Sprite : IMapSprite) : integer; virtual; abstract; procedure UnregisterSprite(const Sprite : IMapSprite); virtual; abstract; function IsSpriteVisible(const Sprite : IMapSprite) : boolean; virtual; function GetSpriteImages(const Sprite : IMapSprite; const View : IGameView; out Images : TSpriteImages) : boolean; virtual; procedure AttachFocus(const focus : IGameFocus); procedure DetachFocus(const focus : IGameFocus); procedure NewView(const View : IGameView); virtual; procedure RecacheSoundTargets(soundsenabled : boolean); virtual; abstract; procedure Enable; virtual; procedure Disable; virtual; protected // IShutDownTarget function GetPriority : integer; procedure OnSuspend; procedure OnResume; procedure OnShutDown; protected // ITickeable fInterval : integer; fLastUpdate : integer; fEnabled : boolean; function Enabled : boolean; function Tick : integer; protected fMap : IWorldMap; fConverter : ICoordinateConverter; fManager : ILocalCacheManager; fOwnsSprites : boolean; procedure AnimationTick; virtual; function GetFullSpriteId(const Sprite : IMapSprite) : integer; virtual; abstract; protected fExternallyDisabled : boolean; protected fFocuses : TList; end; implementation uses TimerTicker, Animations; const cNoTimerInterval = -1; // this interval will cause not timer to be created at all // Utils function min(i, j : integer) : integer; begin if i <= j then Result := i else Result := j; end; function max(i, j : integer) : integer; begin if i >= j then Result := i else Result := j; end; // TMapSpriteManager constructor TMapSpriteManager.Create(const Map : IWorldMap; const Converter : ICoordinateConverter; const Manager : ILocalCacheManager; MinAnimInterval : integer; OwnsSprites : boolean); begin inherited Create; fMap := Map; fMap._Release; // >> cross referenced fConverter := Converter; fConverter._Release; // >> cross referenced fManager := Manager; fFocuses := TList.Create; if MinAnimInterval <> cNoTimerInterval then begin AttachTickeable(Self); fEnabled := true; end; ShutDown.AttachTarget(Self); end; destructor TMapSpriteManager.Destroy; begin ShutDown.DetachTarget(Self); DetachTickeable(Self); fFocuses.Free; pointer(fConverter) := nil; // >> cross referenced pointer(fMap) := nil; // >> cross referenced inherited; end; procedure TMapSpriteManager.UpdateSpriteRect(const Sprite : IMapSprite); var R : TRect; OldArea : TRect; oldx, oldy : integer; Area : TRect; x, y : integer; i : integer; focus : IGameFocus; view : IGameView; begin with fConverter do for i := 0 to pred(fFocuses.Count) do begin focus := IGameFocus(fFocuses[i]); view := focus.GetView; MapToScreen(view, Sprite.OldMapY, Sprite.OldMapX, oldx, oldy); oldx := oldx + Sprite.GetOldBlockX(view); oldy := oldy + Sprite.GetOldBlockY(view); OldArea := Rect(max(oldx, 0), max(oldy, 0), oldx + Sprite.GetWidth(view), oldy + Sprite.GetHeight(view)); MapToScreen(view, Sprite.MapY, Sprite.MapX, x, y); x := x + Sprite.GetBlockX(view); y := y + Sprite.GetBlockY(view); Area := Rect(max(x, 0), max(y, 0), x + Sprite.GetWidth(view), y + Sprite.GetHeight(view)); UnionRect(R, Area, OldArea); (focus as IAnimationCache).AddAnimationRect(R); end; end; function TMapSpriteManager.IsSpriteVisible(const Sprite : IMapSprite) : boolean; var i : integer; FocusCount : integer; imin, jmin : integer; imax, jmax : integer; Visible : boolean; begin with fMap do begin i := 0; FocusCount := fFocuses.Count; if FocusCount > 0 then repeat fConverter.GetViewRegion(IGameFocus(fFocuses[i]).GetView, imin, jmin, imax, jmax); Visible := (Sprite.MapX >= jmin) and (Sprite.MapY >= imin) and (Sprite.MapX <= jmax) and (Sprite.MapY <= imax); inc(i); until (i >= FocusCount) or Visible else Visible := false; end; Result := Visible; end; function TMapSpriteManager.GetSpriteImages(const Sprite : IMapSprite; const View : IGameView; out Images : TSpriteImages) : boolean; var Focus : IGameFocus; Imager : IImager; id : integer; angle : TAngle; begin Focus := View.GetFocus; if Focus <> nil then begin Imager := Focus.GetImager; if Imager <> nil then begin id := GetFullSpriteId(Sprite); for angle := low(angle) to high(angle) do Images[angle] := Imager.GetObjectImage(id, angle); Result := true; end else Result := false; end else Result := false; end; procedure TMapSpriteManager.AttachFocus(const focus : IGameFocus); begin fFocuses.Add(pointer(focus)); end; procedure TMapSpriteManager.DetachFocus(const focus : IGameFocus); begin fFocuses.Remove(pointer(focus)); end; procedure TMapSpriteManager.NewView(const View : IGameView); var Sprite : IMapSprite; i : integer; begin for i := 0 to pred(GetSpriteCount) do begin Sprite := GetSprite(i); if Sprite <> nil then Sprite.NewView(View); end; end; procedure TMapSpriteManager.Enable; begin fExternallyDisabled := false; fEnabled := true; end; procedure TMapSpriteManager.Disable; var Sprite : IMapSprite; i : integer; begin fExternallyDisabled := true; fEnabled := false; try for i := 0 to pred(GetSpriteCount) do try begin Sprite := GetSprite(i); if Sprite <> nil then Sprite._Release; end; except end; except end; end; function TMapSpriteManager.GetPriority : integer; begin Result := 100; end; procedure TMapSpriteManager.OnSuspend; begin fEnabled := false; end; procedure TMapSpriteManager.OnResume; begin if not fExternallyDisabled then fEnabled := true; end; procedure TMapSpriteManager.OnShutDown; var i : integer; CurSprite : IMapSprite; begin fEnabled := false; for i := 0 to pred(GetSpriteCount) do begin CurSprite := GetSprite(i); if CurSprite <> nil then CurSprite._Release; // >> is this always valid? end; end; function TMapSpriteManager.Enabled : boolean; begin Result := fEnabled; end; function TMapSpriteManager.Tick; var CurrentTicks : integer; ElapsedTicks : integer; FrameDelay : integer; begin CurrentTicks := GetTickCount; ElapsedTicks := CurrentTicks - fLastUpdate; FrameDelay := fInterval; if ElapsedTicks >= FrameDelay then begin AnimationTick; fLastUpdate := CurrentTicks; Result := FrameDelay; { inc(fLastUpdate, FrameDelay); // we could do this Result := FrameDelay - (CurrentTicks - fLastUpdate); } end else Result := FrameDelay - ElapsedTicks; end; procedure TMapSpriteManager.AnimationTick; var i : integer; CurSprite : IMapSprite; begin for i := 0 to pred(fFocuses.Count) do (IGameFocus(fFocuses[i]) as IAnimationCache).StartCaching; try for i := 0 to pred(GetSpriteCount) do begin CurSprite := GetSprite(i); try if CurSprite <> nil then CurSprite.AnimationTick; except // a sprite generating an exception shouldn't affect the others (blinking bug???) end; end; finally for i := 0 to pred(fFocuses.Count) do (IGameFocus(fFocuses[i]) as IAnimationCache).StopCaching; end; end; end.
unit googleAPI; interface uses sysUtils, classes; {$I Delphi.inc} type TGoogleMapDistance = class; TGoogleDirecoesItem = class(TCollectionItem) public route: integer; endereco: string; distancia: integer; // em km distancia_text: string; duracao: integer; duracao_text: string; function getText: string; end; TGoogleDirecoes = class(TCollection) private FWayPoints: TStringList; FMapDistancias: TGoogleMapDistance; function GetItems(idx: integer): TGoogleDirecoesItem; procedure SetItems(idx: integer; const Value: TGoogleDirecoesItem); procedure SetMapDistancias(const Value: TGoogleMapDistance); published public Response: string; constructor create; destructor Destroy; override; function GetDirecoes(de, para: string): string; property WayPoints: TStringList read FWayPoints; property Items[idx: integer]: TGoogleDirecoesItem read GetItems write SetItems; function getText: string; property MapDistancias: TGoogleMapDistance read FMapDistancias write SetMapDistancias; end; TGoogleMapDistanceItem = class(TCollectionItem) public route: integer; endereco: string; distancia: integer; // em km distancia_text: string; duracao: integer; duracao_text: string; Latitude: string; Longitude: string; end; TGoogleMapDistance = class(TCollection) private FDestino: string; FOrigem: string; FRoutes: TStringList; procedure SetDestino(const Value: string); procedure SetOrigem(const Value: string); function GetItems(idx: integer): TGoogleMapDistanceItem; procedure SetItems(idx: integer; const Value: TGoogleMapDistanceItem); public Response: string; constructor create; destructor Destroy; override; property Origem: string read FOrigem write SetOrigem; property Destino: string read FDestino write SetDestino; function GetDistancia(de, para: string): string; property Items[idx: integer]: TGoogleMapDistanceItem read GetItems write SetItems; function getText: string; end; procedure LocalizarNoGoogleMap(url: string); procedure LocalizarNoGoogleImage(url: string); procedure LocalizarNoGoogle(url: string); procedure LocalizarNoTanslate(url: string); procedure InitWebLinks; function GetWebLink(key: string; texto: string = ''): string; implementation uses mFunctions, IniFileList, {$ifndef BPL} ACBrSocket, {$endif} uJson, IniFilesEx; const lnk = 'Links'; var webLinksInited: boolean = false; const googleMapsMatrix = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=%s&destinations=%s&mode=driving&language=pt-BR&sensor=false'; googleDirecoes = 'http://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&sensor=false&language=pt-BR'; procedure InitWebLinks; var n: integer; begin if webLinksInited then exit; // nao mudar a mask {texto} {$IFNDEF BPL} with GetIniFile('store.ini') do begin n := GetValuesCount(lnk); ReadStringDefault(lnk, 'translate', 'http://translate.google.com.br/m?hl=pt-BR&sl=pt-BR&tl=en&ie=UTF-8&prev=_m&q={texto}'); ReadStringDefault(lnk, 'map', 'http://maps.google.com.br/maps?q={texto}&bl=pt-BR'); ReadStringDefault(lnk, 'image', 'http://images.google.com.br/images?q={texto}&bl=pt-BR'); ReadStringDefault(lnk, 'google', 'http://www.google.com.br/search?q={texto}&bl=pt-BR'); if n <> GetValuesCount(lnk) then UpdateFile; end; {$ENDIF} webLinksInited := true; end; function GetWebLink(key: string; texto: string = ''): string; begin if not webLinksInited then InitWebLinks; with GetIniFile('store.ini') do begin result := ReadString(lnk, key, ''); if texto <> '' then begin result := StringReplace(result, '{texto}', StringReplace(texto, ' ', '%20', [rfReplaceAll]), [rfReplaceAll]); end; end; end; procedure LocalizarNoGoogleMap(url: string); var s: string; begin s := GetWebLink('map'); url := StringReplace(s, '{texto}', StringReplace(url, ' ', '%20', [rfReplaceAll]), [rfReplaceAll]); ShellExec('"' + url + '"', '', '', false, 0); end; procedure LocalizarNoGoogleImage(url: string); var s: string; begin s := GetWebLink('image'); url := StringReplace(s, '{texto}', StringReplace(url, ' ', '%20', [rfReplaceAll]), [rfReplaceAll]); ShellExec('"' + url + '"', '', '', false, 0); end; procedure LocalizarNoTanslate(url: string); var s: string; begin s := GetWebLink('translate'); url := StringReplace(s, '{texto}', StringReplace(url, ' ', '%20', [rfReplaceAll]), [rfReplaceAll]); ShellExec('"' + url + '"', '', '', false, 0); end; procedure LocalizarNoGoogle(url: string); var s: string; begin s := GetWebLink('google'); url := StringReplace(s, '{texto}', StringReplace(url, ' ', '%20', [rfReplaceAll]), [rfReplaceAll]); ShellExec('"' + url + '"', '', '', false, 0); end; { TGoogleMapDistance } constructor TGoogleMapDistance.create; begin inherited create(TGoogleMapDistanceItem); FRoutes := TStringList.create; end; destructor TGoogleMapDistance.Destroy; begin FRoutes.Free; inherited; end; function TGoogleMapDistance.GetDistancia(de, para: string): string; var // rsp: string; {$ifndef BPL} http: TACBrHTTP; {$endif} js, jsRows: IJson; aJS, aLocal: IJSONArray; n: integer; begin FOrigem := de; FDestino := para; clear; Response := ''; result := ''; {$ifndef BPL} http := TACBrHTTP.create(nil); try http.HTTPGet(Format(googleMapsMatrix, [StringReplace(de, ' ', '%20', [rfReplaceAll]), StringReplace(para, ' ', '%20', [rfReplaceAll])])); Response := http.RespHTTP.Text; finally http.Free; end; {$endif} //JSONFree; js := TJSON.parse(Response); try if js.s('status') <> 'OK' then exit; aLocal := js.O('destination_addresses').AsArray ; n := aLocal.Length; if aLocal.Length = 0 then exit; for n := 0 to aLocal.Length - 1 do with TGoogleMapDistanceItem(add) do begin endereco := aLocal.Get(n).Value; // .asString; FRoutes.add(aLocal.Get(n).Value); // .asString); end; aJS := js.O('rows').asArray; if aJS.Length > 0 then begin js := aJS.Get(0) as TJSON; aJS := js.O('elements').asArray; for n := 0 to aJS.Length - 1 do begin jsRows := aJS.Get(n) as TJSON; if jsRows.s('status') = 'OK' then begin js := jsRows.O('distance'); Items[n].route := n; Items[n].distancia := js.I('value'); Items[n].distancia_text := js.s('text'); result := FloatToStr(Items[n].distancia / 1000); js := jsRows.O('duration'); Items[n].duracao := js.I('value'); Items[n].duracao_text := js.s('text'); end else begin Items[n].distancia_text := jsRows.s('status'); end; end; end; finally js.Free; end; end; function TGoogleMapDistance.GetItems(idx: integer): TGoogleMapDistanceItem; begin result := TGoogleMapDistanceItem(inherited Items[idx]); end; procedure TGoogleMapDistance.SetDestino(const Value: string); begin FDestino := Value; end; procedure TGoogleMapDistance.SetItems(idx: integer; const Value: TGoogleMapDistanceItem); begin Items[idx] := Value; end; procedure TGoogleMapDistance.SetOrigem(const Value: string); begin FOrigem := Value; end; function TGoogleMapDistance.getText: string; var I: integer; begin result := ''; for I := 0 to Count - 1 do result := result + iff(I > 0, '#10', '') + Items[I].endereco + '=' + FloatToStr(Items[I].distancia / 1000) + '(' + Items[I].duracao_text + ')'; end; { TGoogleDirecoes } constructor TGoogleDirecoes.create; begin inherited create(TGoogleDirecoesItem); FWayPoints := TStringList.create; end; destructor TGoogleDirecoes.Destroy; begin FWayPoints.Free; inherited; end; function TGoogleDirecoes.GetDirecoes(de, para: string): string; var {$ifndef BPL} http: TACBrHTTP; {$endif} wp: string; I, x, y: integer; js: IJson; jLegs, jSteps: IJSONArray; ja: IJSONArray; s: string; begin if assigned(FMapDistancias) then FMapDistancias.clear; wp := ''; if FWayPoints.Count > 0 then begin for I := 0 to FWayPoints.Count - 1 do begin if I = 0 then wp := '&waypoints='; wp := wp + iff(I > 0, '|', '') + StringReplace(FWayPoints[I], ' ', '+', [rfReplaceAll]); end; // waypoints=Charlestown,MA|Lexington end; {$ifndef BPL} http := TACBrHTTP.create(nil); try http.HTTPGet(Format(googleDirecoes + wp, [StringReplace(de, ' ', '%20', [rfReplaceAll]), StringReplace(para, ' ', '%20', [rfReplaceAll])])); Response := http.RespHTTP.Text; finally http.Free; end; {$endif} js := TJSON.parse(Response); try ja := js.O('routes').asArray; for I := 0 to ja.Length - 1 do begin // legs... jLegs := (ja.Get(I) as TJSON).O('legs').asArray; for x := 0 to jLegs.Length - 1 do begin jSteps := (jLegs.Get(x) as TJSON).O('steps').asArray; if assigned(FMapDistancias) then begin with TGoogleMapDistanceItem(FMapDistancias.add) do begin route := I; endereco := (jLegs.Get(x) as TJSON).s('end_address'); FMapDistancias.FRoutes.add(endereco); js := (jLegs.Get(x) as TJSON).O('distance'); distancia := js.I('value'); distancia_text := js.s('text'); js := (jLegs.Get(x) as TJSON).O('duration'); duracao := js.I('value'); duracao_text := js.s('text'); js := (jLegs.Get(x) as TJSON).O('end_location'); Latitude := js.S('lat');//.AsString; Longitude := js.S('lng');//.AsString; (* "end_location" : { "lat" : -23.592780, "lng" : -46.602350 }, *) end; end; for y := 0 to jSteps.Length - 1 do begin s := (jSteps.Get(y) as TJSON).s('html_instructions'); with TGoogleDirecoesItem(add) do begin route := I; endereco := s; js := (jSteps.Get(y) as TJSON).O('distance'); distancia := js.I('value'); distancia_text := js.s('text'); js := (jSteps.Get(y) as TJSON).O('duration'); duracao := js.I('value'); duracao_text := js.s('text'); end; end; end; end; result := iff(Response <> '', 'OK', ''); result := Response; finally js.Free; end; end; function TGoogleDirecoes.GetItems(idx: integer): TGoogleDirecoesItem; begin result := TGoogleDirecoesItem(inherited Items[idx]); end; function TGoogleDirecoes.getText: string; var I: integer; begin result := ''; for I := 0 to Count - 1 do result := result + iff(I > 0, #10, '') + Items[I].getText; end; procedure TGoogleDirecoes.SetItems(idx: integer; const Value: TGoogleDirecoesItem); begin Items[idx] := Value; end; procedure TGoogleDirecoes.SetMapDistancias(const Value: TGoogleMapDistance); begin FMapDistancias := Value; end; (* { "routes" : [ { "bounds" : { "northeast" : { "lat" : -23.493080, "lng" : -46.597490 }, "southwest" : { "lat" : -23.592780, "lng" : -46.65495000000001 } }, "copyrights" : "Dados cartográficos ©2013 Google, MapLink", "legs" : [ { "distance" : { "text" : "9,9 km", "value" : 9869 }, "duration" : { "text" : "20 minutos", "value" : 1198 }, "end_address" : "Rua Lino Coutinho - Ipiranga, São Paulo, República Federativa do Brasil", "end_location" : { "lat" : -23.592780, "lng" : -46.602350 }, "start_address" : "Avenida Paulista - São Paulo, República Federativa do Brasil", "start_location" : { "lat" : -23.563070, "lng" : -46.654360 }, "steps" : [ { "distance" : { "text" : "82 m", "value" : 82 }, "duration" : { "text" : "1 min", "value" : 7 }, "end_location" : { "lat" : -23.562570, "lng" : -46.65495000000001 }, "html_instructions" : "Siga na direção \u003cb\u003enoroeste\u003c/b\u003e na \u003cb\u003eAv. Paulista\u003c/b\u003e em direção à \u003cb\u003eR. Itapeva\u003c/b\u003e", "polyline" : { "points" : "ddynCvdw{GcBtB" }, "start_location" : { "lat" : -23.563070, "lng" : -46.654360 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,8 km", "value" : 801 }, "duration" : { "text" : "2 minutos", "value" : 131 }, "end_location" : { "lat" : -23.557520, "lng" : -46.64971000000001 }, "html_instructions" : "Pegue a 1ª \u003cb\u003eà direita\u003c/b\u003e para \u003cb\u003eR. Itapeva\u003c/b\u003e", "polyline" : { "points" : "`aynClhw{GcBgBYY}@oAwFyB_E}AGOuBcFqAwCeA{AgBeC" }, "start_location" : { "lat" : -23.562570, "lng" : -46.65495000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,2 km", "value" : 163 }, "duration" : { "text" : "1 min", "value" : 30 }, "end_location" : { "lat" : -23.556060, "lng" : -46.64989000000001 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eR. Rocha\u003c/b\u003e", "polyline" : { "points" : "naxnCtgv{GcHb@" }, "start_location" : { "lat" : -23.557520, "lng" : -46.64971000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,5 km", "value" : 467 }, "duration" : { "text" : "2 minutos", "value" : 95 }, "end_location" : { "lat" : -23.555390, "lng" : -46.64550000000001 }, "html_instructions" : "Na \u003cb\u003ePraça Quatorze-bis\u003c/b\u003e, pegue a \u003cb\u003e1ª\u003c/b\u003e saída para a \u003cb\u003eR. Manuel Dutra\u003c/b\u003e", "polyline" : { "points" : "jxwnCxhv{GCSIQMSMKOMQKSeHGcBIwCOkEAOAO" }, "start_location" : { "lat" : -23.556060, "lng" : -46.64989000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,1 km", "value" : 142 }, "duration" : { "text" : "1 min", "value" : 44 }, "end_location" : { "lat" : -23.554120, "lng" : -46.645670 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eR. João Passaláqua\u003c/b\u003e", "polyline" : { "points" : "dtwnCjmu{G}F`@" }, "start_location" : { "lat" : -23.555390, "lng" : -46.64550000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,2 km", "value" : 204 }, "duration" : { "text" : "1 min", "value" : 22 }, "end_location" : { "lat" : -23.554850, "lng" : -46.64416000000001 }, "html_instructions" : "Curva suave à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eR. Prof. Laerte Ramos de Carvalho\u003c/b\u003e", "polyline" : { "points" : "flwnClnu{Ga@KESHSTYb@e@`AuAr@cB" }, "start_location" : { "lat" : -23.554120, "lng" : -46.645670 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,2 km", "value" : 241 }, "duration" : { "text" : "1 min", "value" : 19 }, "end_location" : { "lat" : -23.55547000000001, "lng" : -46.64190000000001 }, "html_instructions" : "Pegue a rampa de acesso à \u003cb\u003eesquerda\u003c/b\u003e para a \u003cb\u003eVd. Júlio de Mesquita Filho\u003c/b\u003e", "polyline" : { "points" : "xpwnC~du{GJm@FY@MRmARoADQ\\_BX}A" }, "start_location" : { "lat" : -23.554850, "lng" : -46.64416000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,6 km", "value" : 595 }, "duration" : { "text" : "1 min", "value" : 31 }, "end_location" : { "lat" : -23.556410, "lng" : -46.636160 }, "html_instructions" : "Continue para \u003cb\u003eVd. Jaceguai\u003c/b\u003e", "polyline" : { "points" : "ttwnCzvt{G@IBe@HqAPiD?K@Q@Q@I?GDUN{@BSD]LqA\\iDLeA@KBU@IBSBQ@YXsCDUBU@G@I?I" }, "start_location" : { "lat" : -23.55547000000001, "lng" : -46.64190000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,3 km", "value" : 322 }, "duration" : { "text" : "1 min", "value" : 17 }, "end_location" : { "lat" : -23.556530, "lng" : -46.633020 }, "html_instructions" : "Continue para \u003cb\u003eAv. Radial Leste-oeste\u003c/b\u003e", "polyline" : { "points" : "pzwnC~rs{GBOZsD@I?KBsD?M?KKwDAS" }, "start_location" : { "lat" : -23.556410, "lng" : -46.636160 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,4 km", "value" : 373 }, "duration" : { "text" : "1 min", "value" : 30 }, "end_location" : { "lat" : -23.556290, "lng" : -46.629380 }, "html_instructions" : "Pegue a saída à \u003cb\u003eesquerda\u003c/b\u003e em direção a \u003cb\u003eR. Glicério\u003c/b\u003e", "polyline" : { "points" : "h{wnCj_s{GEq@OkBIqDSqFCcBBSB]" }, "start_location" : { "lat" : -23.556530, "lng" : -46.633020 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "52 m", "value" : 52 }, "duration" : { "text" : "1 min", "value" : 18 }, "end_location" : { "lat" : -23.556730, "lng" : -46.62956000000001 }, "html_instructions" : "Vire à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eR. Glicério\u003c/b\u003e", "polyline" : { "points" : "xywnCrhr{GXHTFf@P" }, "start_location" : { "lat" : -23.556290, "lng" : -46.629380 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,3 km", "value" : 298 }, "duration" : { "text" : "1 min", "value" : 50 }, "end_location" : { "lat" : -23.55755000000001, "lng" : -46.626820 }, "html_instructions" : "Pegue a 1ª \u003cb\u003eà esquerda\u003c/b\u003e para \u003cb\u003eR. São Paulo\u003c/b\u003e", "polyline" : { "points" : "p|wnCvir{GpAiE~@_DNs@@eC" }, "start_location" : { "lat" : -23.556730, "lng" : -46.62956000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "86 m", "value" : 86 }, "duration" : { "text" : "1 min", "value" : 19 }, "end_location" : { "lat" : -23.556780, "lng" : -46.62681000000001 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eAv. Pref. Passos\u003c/b\u003e", "polyline" : { "points" : "taxnCrxq{GyCA" }, "start_location" : { "lat" : -23.55755000000001, "lng" : -46.626820 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,4 km", "value" : 429 }, "duration" : { "text" : "1 min", "value" : 70 }, "end_location" : { "lat" : -23.55630, "lng" : -46.622630 }, "html_instructions" : "Vire à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eR. Leopoldo Miguez\u003c/b\u003e", "polyline" : { "points" : "z|wnCpxq{GCi@m@uKIyAO{B@EMwBGo@" }, "start_location" : { "lat" : -23.556780, "lng" : -46.62681000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "1,4 km", "value" : 1382 }, "duration" : { "text" : "2 minutos", "value" : 132 }, "end_location" : { "lat" : -23.563070, "lng" : -46.612230 }, "html_instructions" : "Curva suave à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eAv. do Estado\u003c/b\u003e", "polyline" : { "points" : "zywnCl~p{Gj@_BfA}EViAl@mCl@gC|AkH`AwEn@gCz@iCRe@P_@lAgBbAoA^c@ZYx@k@hBgAfD{AbBc@l@MvAa@j@K" }, "start_location" : { "lat" : -23.55630, "lng" : -46.622630 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "3,1 km", "value" : 3107 }, "duration" : { "text" : "5 minutos", "value" : 315 }, "end_location" : { "lat" : -23.586450, "lng" : -46.598480 }, "html_instructions" : "Pegue a rampa de acesso à \u003cb\u003eesquerda\u003c/b\u003e para a \u003cb\u003eAv. do Estado\u003c/b\u003e", "polyline" : { "points" : "ddynCl}n{Gb@a@tAaATKpAo@TQ^WFCLGbPyHbBw@t@a@dBkBJONSN]Jm@LWJWvAkD\\q@tBiEbAoB^k@d@a@l@c@t@Y\\Kj@IbBG`BC|@Gr@Mj@Wn@c@`@W|AuARSbB_BjAiAfEeDtBwAdCeAlEuBjBk@ZIfC[lLNz@@T?R@T@zB?tBKnAIt@SvAi@lEsCx@e@" }, "start_location" : { "lat" : -23.563070, "lng" : -46.612230 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,4 km", "value" : 391 }, "duration" : { "text" : "1 min", "value" : 31 }, "end_location" : { "lat" : -23.589940, "lng" : -46.59807000000001 }, "html_instructions" : "Curva suave à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eAv. das Juntas Provisórias\u003c/b\u003e", "polyline" : { "points" : "hv}nCngl{GdFk@|EStFQ" }, "start_location" : { "lat" : -23.586450, "lng" : -46.598480 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,3 km", "value" : 336 }, "duration" : { "text" : "1 min", "value" : 64 }, "end_location" : { "lat" : -23.590250, "lng" : -46.601350 }, "html_instructions" : "Pegue a 3ª \u003cb\u003eà direita\u003c/b\u003e para \u003cb\u003eR. Alm. Lobo\u003c/b\u003e", "polyline" : { "points" : "bl~nC|dl{GP~CRpFV|F" }, "start_location" : { "lat" : -23.589940, "lng" : -46.59807000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,3 km", "value" : 272 }, "duration" : { "text" : "1 min", "value" : 48 }, "end_location" : { "lat" : -23.592680, "lng" : -46.601120 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na 3ª rua transversal para \u003cb\u003eR. Silva Bueno\u003c/b\u003e", "polyline" : { "points" : "`n~nClyl{GhFUzFW" }, "start_location" : { "lat" : -23.590250, "lng" : -46.601350 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,1 km", "value" : 126 }, "duration" : { "text" : "1 min", "value" : 25 }, "end_location" : { "lat" : -23.592780, "lng" : -46.602350 }, "html_instructions" : "Pegue a 2ª \u003cb\u003eà direita\u003c/b\u003e para \u003cb\u003eR. Lorde Cockrane\u003c/b\u003e", "polyline" : { "points" : "f}~nC~wl{GRtF" }, "start_location" : { "lat" : -23.592680, "lng" : -46.601120 }, "travel_mode" : "DRIVING" } ], "via_waypoint" : [] }, { "distance" : { "text" : "13,7 km", "value" : 13741 }, "duration" : { "text" : "27 minutos", "value" : 1598 }, "end_address" : "Rua Domingos Luís - Santana, São Paulo, República Federativa do Brasil", "end_location" : { "lat" : -23.493080, "lng" : -46.615160 }, "start_address" : "Rua Lino Coutinho - Ipiranga, São Paulo, República Federativa do Brasil", "start_location" : { "lat" : -23.592780, "lng" : -46.602350 }, "steps" : [ { "distance" : { "text" : "0,5 km", "value" : 498 }, "duration" : { "text" : "1 min", "value" : 89 }, "end_location" : { "lat" : -23.592360, "lng" : -46.597490 }, "html_instructions" : "Siga na direção \u003cb\u003eleste\u003c/b\u003e na \u003cb\u003eR. Lorde Cockrane\u003c/b\u003e em direção à \u003cb\u003eR. Silva Bueno\u003c/b\u003e", "polyline" : { "points" : "z}~nCt_m{GSuFUyFK_CGqBMcDA]Eg@" }, "start_location" : { "lat" : -23.592780, "lng" : -46.602350 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,4 km", "value" : 410 }, "duration" : { "text" : "1 min", "value" : 65 }, "end_location" : { "lat" : -23.588680, "lng" : -46.59782000000001 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eAv. das Juntas Provisórias\u003c/b\u003e", "polyline" : { "points" : "f{~nChal{GkEPm@@mFVcFRS@" }, "start_location" : { "lat" : -23.592360, "lng" : -46.597490 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,2 km", "value" : 217 }, "duration" : { "text" : "1 min", "value" : 51 }, "end_location" : { "lat" : -23.586750, "lng" : -46.598060 }, "html_instructions" : "Curva suave à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eVd. Gazeta do Ipiranga\u003c/b\u003e", "polyline" : { "points" : "fd~nCjcl{GWFQDMBKBmAF}@DG?eCHc@@" }, "start_location" : { "lat" : -23.588680, "lng" : -46.59782000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "3,0 km", "value" : 2991 }, "duration" : { "text" : "5 minutos", "value" : 309 }, "end_location" : { "lat" : -23.564150, "lng" : -46.610950 }, "html_instructions" : "Pegue a rampa de acesso para a \u003cb\u003eAv. do Estado\u003c/b\u003e", "polyline" : { "points" : "dx}nCzdl{GW@w@Fg@N[L_A~@u@l@e@V_AXaBf@kC^kDEmAEG?SAK?M?a@CeICoBFiAJkCr@gGfCkFpC_B`AqB`Bw@v@iCfCwBrBg@\\_@Pq@Tw@JmELm@Bs@Nm@Pq@`@q@p@u@fAcBbDkCrFs@rAaAhBUt@e@v@S^g@d@w@f@mAj@mBx@mCrAi@TsErBq@^WPYR" }, "start_location" : { "lat" : -23.586750, "lng" : -46.598060 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "2,0 km", "value" : 2008 }, "duration" : { "text" : "3 minutos", "value" : 180 }, "end_location" : { "lat" : -23.55324000000001, "lng" : -46.62550 }, "html_instructions" : "Continue para \u003cb\u003eAv. do Estado - Pista Central\u003c/b\u003e", "polyline" : { "points" : "|jynClun{GYVyAr@OH{B~@iD|A{Ap@{CvAqAr@{@l@aAt@_A~@m@t@m@z@s@lAIRSb@M\\M^Wx@s@jCs@hDeAlEs@dDcAvEQr@WjA{@vDeAvCMT_ApBiAdBm@x@o@l@gB~AkA|@]TEBEDIDUNGBc@V" }, "start_location" : { "lat" : -23.564150, "lng" : -46.610950 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "2,5 km", "value" : 2528 }, "duration" : { "text" : "4 minutos", "value" : 234 }, "end_location" : { "lat" : -23.531830, "lng" : -46.625480 }, "html_instructions" : "Continue para \u003cb\u003eAv. do Estado\u003c/b\u003e", "polyline" : { "points" : "vfwnCjpq{GWJODQDKBkBTSBKDIBKBMBEBODSFs@RyA`@kEnAy@Zk@R}@f@{@`@QFi@VgBz@QHSJ{@d@sB|@eDv@_BVq@BuANe@@G?k@@}@BeCIiAMUCYEQCi@GyA_@eBi@{@YQISGa@OWIo@UICoAa@e@QiAa@yAi@{IsCUI[KwIcDoBs@uCi@eACu@?aBJs@LuElA" }, "start_location" : { "lat" : -23.55324000000001, "lng" : -46.62550 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "3,7 km", "value" : 3653 }, "duration" : { "text" : "7 minutos", "value" : 393 }, "end_location" : { "lat" : -23.4990, "lng" : -46.624490 }, "html_instructions" : "Curva suave à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eAv. Cruzeiro do Sul\u003c/b\u003e", "polyline" : { "points" : "|`snCfpq{G{BKgFAS?sSQa@?]?cA?}BAo@A_BAo@Aw@AqEKcA@yDCiDCsBCS?I?[?I?S?O?MAU?W?U?OAo@A]AYAK?M?G@G?E?I?G?O?}@AqEGmKWiCEeFGW?aDE}C@MAQ?iHGqDGcB?uB@uBGUAK?M?gCGS?_FMgBAkB?wBCeAAgAKkA?S?gA?sE?_D?e@AY?yCC" }, "start_location" : { "lat" : -23.531830, "lng" : -46.625480 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,5 km", "value" : 543 }, "duration" : { "text" : "2 minutos", "value" : 103 }, "end_location" : { "lat" : -23.499210, "lng" : -46.61917000000001 }, "html_instructions" : "Vire à \u003cb\u003edireita\u003c/b\u003e na \u003cb\u003eR. Cnso. Saraiva\u003c/b\u003e", "polyline" : { "points" : "vslnC`jq{GDqBB_BBkBD{BAoADwCDiCDmCDmB" }, "start_location" : { "lat" : -23.4990, "lng" : -46.624490 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,4 km", "value" : 360 }, "duration" : { "text" : "1 min", "value" : 57 }, "end_location" : { "lat" : -23.49640, "lng" : -46.61741000000001 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eR. Antônio Guganis\u003c/b\u003e", "polyline" : { "points" : "`ulnCxhp{GqP_J" }, "start_location" : { "lat" : -23.499210, "lng" : -46.61917000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "73 m", "value" : 73 }, "duration" : { "text" : "1 min", "value" : 17 }, "end_location" : { "lat" : -23.496080, "lng" : -46.618030 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eR. Padre Azevedo\u003c/b\u003e", "polyline" : { "points" : "nclnCx}o{Gg@jAWn@" }, "start_location" : { "lat" : -23.49640, "lng" : -46.61741000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0,5 km", "value" : 452 }, "duration" : { "text" : "2 minutos", "value" : 92 }, "end_location" : { "lat" : -23.493130, "lng" : -46.615110 }, "html_instructions" : "Pegue a 1ª \u003cb\u003eà direita\u003c/b\u003e para \u003cb\u003eR. Prof. Fábio Fanucchi\u003c/b\u003e", "polyline" : { "points" : "nalnCtap{G]Sq@_@_@SkAq@_Ac@aAm@_@e@CCk@aAYi@o@iA}@qAw@iA" }, "start_location" : { "lat" : -23.496080, "lng" : -46.618030 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "8 m", "value" : 8 }, "duration" : { "text" : "1 min", "value" : 8 }, "end_location" : { "lat" : -23.493080, "lng" : -46.615160 }, "html_instructions" : "Vire à \u003cb\u003eesquerda\u003c/b\u003e na \u003cb\u003eR. Domingos Luís\u003c/b\u003e", "polyline" : { "points" : "`oknCloo{GIH" }, "start_location" : { "lat" : -23.493130, "lng" : -46.615110 }, "travel_mode" : "DRIVING" } ], "via_waypoint" : [] } ], "overview_polyline" : { "points" : "ddynCvdw{GcBtBcBgBYY}@oAwLwE}BsFqAwCeA{AgBeCcHb@CSIQ[_@a@Y[iK]cK}F`@a@KESHSx@_A`AuAr@cBRgAT{AXaBv@}D`@kHDy@XmB~@_JJ_ADk@^iDFq@`@yEBaEKcEGeAOkBIqDWuIFq@n@Pf@PpAiE~@_DNs@@eCyCAq@_MYuEK}BGo@j@_B~AgHzAuG~CcOn@gCz@iCd@eAlAgBbAoAz@}@bDsBfD{AbBc@dCo@j@Kb@a@tAaATKpAo@TQf@[pPaIxCyApB{B^q@Jm@LWbBcErC{FbAoB^k@rAeArAe@j@IbBG`BC|@Gr@Mj@WpA{@`HsGfEeDtBwAdCeAlEuBfCu@fC[lLNpA@h@BzB?tBKnAIt@SvAi@lEsCx@e@dFk@rMe@d@pKV|FhFUzFWRtFi@oNSqFOaEEg@kEP{GXwFTcATyGV{@Bw@Fg@N[L_A~@u@l@e@VaD`AkC^kDEuAE_@Ao@CeICoBFiAJkCr@gGfCkFpC_B`AqB`BaE~DwBrBg@\\qAf@w@JmELm@Bs@Nm@Pq@`@q@p@u@fAoFvKuB|DUt@e@v@S^g@d@w@f@mAj@mBx@mCrA}FhCiAp@s@j@iB|@eH|CwFhCqAr@{@l@aAt@_A~@{ApB}@`Ba@`Ae@xAs@jCs@hDyBrJiDnOsAlD_ApBiAdBm@x@o@l@gB~AkA|@c@XOJ]R{@b@a@JwBXu@Pw@TmCt@kEnAy@Zk@R}@f@mAh@wDhB{@d@sB|@eDv@_BVq@BuANm@@iBDeCIiAMo@I{@K_EiAmAc@}Bw@iEyAgNsEgMwEuCi@eACu@?aBJs@LuElA{BKgFAgTQaGAwFGqEKcA@cJGmDCoCCsBEc@@_BA_R_@oJMyDEkD?{HGuGGuB@uBGa@AiKUsEA}DEgAKkA?{A?sLAyCCDqBFkED{BAoAJaHJ{FqP_Jg@jAWn@]SqAs@kCuAaAm@_@e@o@eAiAsBuB{CIH" }, "summary" : "Av. do Estado e Av. Cruzeiro do Sul", "warnings" : [], "waypoint_order" : [ 0 ] } ], "status" : "OK" } *) { TGoogleDirecoesItem } function TGoogleDirecoesItem.getText: string; begin result := endereco + ' (' + distancia_text + ') '; end; end.
unit SpeedImage; // Copyright (c) 1997 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, Graphics, Controls, Forms, Classes, BufferColors, CanvasBmp, SpeedBmp; type TSpeedImage = class( TGraphicControl ) private fPicture : TSpeedBitmap; fOnProgress : TProgressEvent; fAutoSize : boolean; fCenter : boolean; fIncrementalDisplay : boolean; fDrawing : boolean; fStretch : boolean; fTile : boolean; fColorTint : TColor; fColorBase : TColor; function GetCanvas : TBufferCanvas; procedure SetAutoSize( Value : boolean ); procedure SetCenter( Value : boolean ); procedure SetPicture( Value : TSpeedBitmap ); procedure SetStretch( Value : boolean ); procedure SetColorTint( Value : TColor ); procedure SetColorBase( Value : TColor ); procedure SetTile( Value : boolean ); procedure PictureChanged( Sender : TObject ); protected function DestRect : TRect; function GetPalette : HPALETTE; override; procedure Paint; override; procedure Tint; function DoPaletteChange : boolean; procedure Progress( Sender : TObject; Stage : TProgressStage; PercentDone : byte; RedrawNow : boolean; const R : TRect; const Msg : string ); dynamic; procedure Loaded; override; public constructor Create( AOwner : TComponent ); override; destructor Destroy; override; procedure SetBounds( aLeft, aTop, aWidth, aHeight : integer ); override; property Canvas : TBufferCanvas read GetCanvas; published property IncrementalDisplay : boolean read fIncrementalDisplay write fIncrementalDisplay default false; property AutoSize : boolean read fAutoSize write SetAutoSize default false; property Center : boolean read fCenter write SetCenter default true; property Stretch : boolean read fStretch write SetStretch default false; property Tile : boolean read fTile write SetTile default false; property Picture : TSpeedBitmap read fPicture write SetPicture; property OnProgress : TProgressEvent read fOnProgress write fOnProgress; property ColorTint : TColor read fColorTint write SetColorTint default clNone; property ColorBase : TColor read fColorBase write SetColorBase default clNone; published property DragCursor; property Align; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation {$R *.DCR} // SpeedImage constructor TSpeedImage.Create( AOwner : TComponent ); begin inherited; fPicture := TSpeedBitmap.Create; fPicture.OnChange := PictureChanged; fPicture.OnProgress := Progress; fCenter := true; fColorTint := clNone; fColorBase := clNone; Height := 32; Width := 32; ControlStyle := ControlStyle + [csReplicatable]; end; destructor TSpeedImage.Destroy; begin fPicture.Free; inherited; end; procedure TSpeedImage.Loaded; begin inherited; if (ColorTint <> clNone) and Assigned( Picture ) and not Picture.Empty and not (csDesigning in ComponentState) then Tint; end; procedure TSpeedImage.Tint; begin BitmapTint( Picture, ColorTint, ColorBase ); PictureChanged( Self ); end; procedure TSpeedImage.SetColorTint( Value : TColor ); begin // Just change tint color, later we may add more code: fColorTint := Value; end; procedure TSpeedImage.SetColorBase( Value : TColor ); begin // Just change base color, later we may add more code: fColorBase := Value; end; procedure TSpeedImage.SetTile( Value : boolean ); begin if Value <> fTile then begin fTile := Value; PictureChanged( Self ); end; end; function TSpeedImage.GetPalette : HPALETTE; begin if Assigned( fPicture ) then Result := fPicture.Palette else Result := 0; end; function TSpeedImage.DestRect : TRect; begin if Stretch or Tile then Result := ClientRect else if Center then Result := Bounds( ( Width - Picture.Width ) div 2, ( Height - Picture.Height ) div 2, Picture.Width, Picture.Height ) else Result := Rect( 0, 0, Picture.Width, Picture.Height ); end; procedure TSpeedImage.Paint; var Save : boolean; begin if csDesigning in ComponentState then with inherited Canvas do begin Pen.Style := psDash; Brush.Style := bsClear; Rectangle( 0, 0, Width, Height ); end; Save := fDrawing; fDrawing := true; try if not Picture.Empty then if not Tile then Picture.StretchDraw( inherited Canvas, DestRect ) else Picture.Tile( inherited Canvas, 0, 0, DestRect ); finally fDrawing := Save; end; end; function TSpeedImage.DoPaletteChange : boolean; var ParentForm : TCustomForm; begin Result := false; if Visible and ( not ( csLoading in ComponentState ) ) and Assigned( Picture ) and ( Picture.PaletteModified ) then begin if ( Picture.Palette = 0 ) then Picture.PaletteModified := false else begin ParentForm := GetParentForm( Self ); if Assigned( ParentForm ) and ParentForm.Active and Parentform.HandleAllocated then begin if fDrawing then ParentForm.Perform( WM_QueryNewPalette, 0, 0 ) else PostMessage( ParentForm.Handle, WM_QueryNewPalette, 0, 0 ); Picture.PaletteModified := false; Result := true; end; end; end; end; procedure TSpeedImage.Progress( Sender : TObject; Stage : TProgressStage; PercentDone : byte; RedrawNow : boolean; const R : TRect; const Msg : string ); begin if fIncrementalDisplay and RedrawNow then if DoPaletteChange then Update else Paint; if Assigned( fOnProgress ) then fOnProgress( Sender, Stage, PercentDone, RedrawNow, R, Msg ); end; function TSpeedImage.GetCanvas : TBufferCanvas; begin Result := Picture.Canvas; end; procedure TSpeedImage.SetAutoSize( Value : boolean ); begin fAutoSize := Value; PictureChanged( Self ); end; procedure TSpeedImage.SetCenter( Value : boolean ); begin if fCenter <> Value then begin fCenter := Value; PictureChanged( Self ); end; end; procedure TSpeedImage.SetPicture( Value : TSpeedBitmap ); begin if not Assigned( Picture ) then fPicture := TSpeedBitmap.Create; fPicture.Assign( Value ); end; procedure TSpeedImage.SetStretch( Value : boolean ); begin if Value <> fStretch then begin fStretch := Value; PictureChanged( Self ); end; end; procedure TSpeedImage.SetBounds( aLeft, aTop, aWidth, aHeight : integer ); begin if (aWidth = Width) or (aHeight = Height) then inherited else begin inherited; fAutoSize := false; PictureChanged( Self ); end; end; procedure TSpeedImage.PictureChanged( Sender : TObject ); begin if AutoSize and not Picture.Empty then inherited SetBounds( Left, Top, Picture.Width, Picture.Height ); if Assigned( Picture ) and ( not Picture.Empty ) then begin if ( not Picture.Transparent ) and ( Stretch or ( Picture.Width >= Width ) and ( Picture.Height >= Height ) ) then ControlStyle := ControlStyle + [csOpaque] else ControlStyle := ControlStyle - [csOpaque]; if DoPaletteChange and fDrawing then Update; end else ControlStyle := ControlStyle - [csOpaque]; if not fDrawing then Invalidate; end; procedure Register; begin RegisterComponents( 'Merchise', [TSpeedImage] ); end; end.
unit BackupAgentRegistry; interface procedure RegisterBackupAgent(aClass, anAgent : TClass); procedure GetClassAgent(const ClassName : string; var TheAgent, TheClass : TClass); implementation uses Classes, DataRegistry; // Aux class type TBackupRegistryEntry = class public constructor Create(aClass, anAgent : TClass); private fClass : TClass; fAgent : TClass; public property TheClass : TClass read fClass; property TheAgent : TClass read fAgent; end; constructor TBackupRegistryEntry.Create(aClass, anAgent : TClass); begin inherited Create; fClass := aClass; fAgent := anAgent; end; // Backup agents var RegClasses : TDataRegistry = nil; ClassCount : integer = 0; AgentInquires : integer = 0; procedure RegisterBackupAgent(aClass, anAgent : TClass); begin RegClasses.Add(aClass.ClassName, TBackupRegistryEntry.Create(aClass, anAgent)); inc(ClassCount); end; procedure GetClassAgent(const ClassName : string; var TheAgent, TheClass : TClass); var aux : TBackupRegistryEntry; begin inc(AgentInquires); aux := TBackupRegistryEntry(RegClasses[ClassName]); if aux <> nil then begin TheAgent := aux.TheAgent; TheClass := aux.TheClass; end else begin TheAgent := nil; TheClass := nil; end; end; initialization RegClasses := TDataRegistry.Create; finalization RegClasses.Free; end.
unit AddRectangularTerritoryUnit; interface uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit; type TAddRectangularTerritory = class(TBaseExample) public function Execute: NullableString; end; implementation uses TerritoryContourUnit, TerritoryUnit; function TAddRectangularTerritory.Execute: NullableString; var ErrorString: String; TerritoryContour: TTerritoryContour; TerritoryName, TerritoryColor: String; TerritoryId: NullableString; begin Result := NullableString.Null; TerritoryName := 'Rect Territory'; TerritoryColor := 'ff0000'; TerritoryContour := TTerritoryContour.MakeRectangularContour( 43.5166885350291, -109.3798828125, 46.9802523552188, -101.865234375); TerritoryId := Route4MeManager.Territory.Add( TerritoryName, TerritoryColor, TerritoryContour, ErrorString); WriteLn(''); if (TerritoryId.IsNotNull) then begin WriteLn('AddRectangularTerritory executed successfully'); WriteLn(Format('Territory ID: %s', [Result.Value])); end else WriteLn(Format('AddRectangularTerritory error: "%s"', [ErrorString])); Result := TerritoryId; end; end.