text
stringlengths
14
6.51M
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PaxProgram.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PaxProgram; interface uses Classes, PAXCOMP_BASERUNNER, PAXCOMP_PROG, PAXCOMP_EMIT, PaxRunner; type TPaxProgram = class(TPaxRunner) protected function GetRunnerClass: TBaseRunnerClass; override; public constructor Create(AOwner: TComponent); override; end; implementation constructor TPaxProgram.Create(AOwner: TComponent); begin inherited; EmitProc := EmitProgProc; end; function TPaxProgram.GetRunnerClass: TBaseRunnerClass; begin result := TProgram; end; end.
unit uFrmModelStateTax; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, Mask, SuperComboADO, ADODB, DB; type TFrmModelStateTax = class(TFrmParent) btOk: TButton; lbState: TLabel; scEstado: TSuperComboADO; lbSaleTax: TLabel; scSaleTax: TSuperComboADO; lblDepartmentRequired: TLabel; Label1: TLabel; cmdInsertStateTax: TADOCommand; quConsultStateTax: TADODataSet; quConsultStateTaxIDModel: TIntegerField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btOkClick(Sender: TObject); procedure btCloseClick(Sender: TObject); private iIDModel : Integer; function Validate : Boolean; procedure SaveStateTax; public function Start(IDModel : Integer) : Boolean; end; implementation uses uDM, Math, uMsgBox, uMsgConstant; {$R *.dfm} { TFrmModelStateTax } function TFrmModelStateTax.Start(IDModel: Integer): Boolean; begin iIDModel := IDModel; ShowModal; Result := True; end; procedure TFrmModelStateTax.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; function TFrmModelStateTax.Validate: Boolean; begin Result := False; if scEstado.LookUpValue = '' then begin MsgBox(MSG_INF_SELECT_FIELD + '._' + Copy(lbState.Caption, 1, Length(lbState.Caption)-2), vbOKOnly + vbInformation); scEstado.SetFocus; Exit; end; if scSaleTax.LookUpValue = '' then begin MsgBox(MSG_INF_SELECT_FIELD + '._' + Copy(lbSaleTax.Caption, 1, Length(lbSaleTax.Caption)-2), vbOKOnly + vbInformation); Exit; end; with quConsultStateTax do try if Active then Close; Parameters.ParamByName('IDModel').Value := iIDModel; Parameters.ParamByName('IDEstado').Value := scEstado.LookUpValue; Open; if not IsEmpty then begin MsgBox(MSG_EXC_MODEL_EXISTE, vbOKOnly + vbInformation); Exit; end; finally Close; end; Result := True; end; procedure TFrmModelStateTax.btOkClick(Sender: TObject); begin inherited; if Validate then begin SaveStateTax; Close; end; end; procedure TFrmModelStateTax.SaveStateTax; begin with cmdInsertStateTax do begin Parameters.ParamByName('IDModel').Value := iIDModel; Parameters.ParamByName('IDEstado').Value := scEstado.LookUpValue; Parameters.ParamByName('IDTaxCategory').Value := StrToInt(scSaleTax.LookUpValue); Execute; end; end; procedure TFrmModelStateTax.btCloseClick(Sender: TObject); begin inherited; Close; end; end.
unit Ils.Kafka.Conf; interface uses SysUtils, IniFiles, ULibKafka, Ils.Logger, StrUtils; type TKafkaConsumerParams = record BootStrap: string; Group: string; Topic: string; constructor Create( const AIniFile, AOffsetIniFile: TIniFile; const ASectionSuffix, ABootstrapDef, AGroupDef, ATopicDef: string; out ROffset: Int64 ); end; TKafkaProducerParams = record BootStrap: string; Topic: string; BackupPath: string; BackupTimeout: Integer; Enabled: Boolean; constructor Create( const AIniFile: TIniFile; const ASectionSuffix, ABootstrapDef, ATopicDef, ABackupDef: string; const ABackupTimeout: Integer ); end; implementation uses CINIFilesData; { TKafkaConsumerParams } constructor TKafkaConsumerParams.Create( const AIniFile, AOffsetIniFile: TIniFile; const ASectionSuffix, ABootstrapDef, AGroupDef, ATopicDef: string; out ROffset: Int64 ); var SectionName: string; OffsetStr: string; begin SectionName := CIniKafkaSection + IfThen(ASectionSuffix <> '', '.' + ASectionSuffix, ''); BootStrap := AIniFile.ReadString(SectionName, CIniKafkaBootstrap, ABootstrapDef); Group := AIniFile.ReadString(SectionName, CIniKafkaGroup, AGroupDef); Topic := AIniFile.ReadString(SectionName, CIniKafkaTopic, ATopicDef); ToLog(Format('"%s" kafka: %s:%s:%s', [ASectionSuffix, BootStrap, Group, Topic])); if not Assigned(AOffsetIniFile) then Exit; OffsetStr := AOffsetIniFile.ReadString(CIniKafkaOffsetSection, CIniKafkaOffset + '_' + Topic, ''); ToLog(Format('"%s" kafka start offset: %s', [ASectionSuffix, OffsetStr])); ROffset := StrToInt64Def(OffsetStr, RD_KAFKA_OFFSET_BEGINNING); end; { TKafkaProducerParams } constructor TKafkaProducerParams.Create( const AIniFile: TIniFile; const ASectionSuffix, ABootstrapDef, ATopicDef, ABackupDef: string; const ABackupTimeout: Integer ); var SectionName: string; begin SectionName := CIniKafkaSection + IfThen(ASectionSuffix <> '', '.' + ASectionSuffix, ''); BootStrap := AIniFile.ReadString(SectionName, CIniKafkaBootstrap, ABootstrapDef); Topic := AIniFile.ReadString(SectionName, CIniKafkaTopic, ATopicDef); BackupPath := AIniFile.ReadString(SectionName, CIniKafkaBackupPath, ABackupDef); BackupTimeout := AIniFile.ReadInteger(SectionName, CIniKafkaBackupTimeout, ABackupTimeout); Enabled := AIniFile.ReadBool(SectionName, CIniKafkaTopicEnabled, True); ToLog(Format('"%s" kafka producer: %s:%s', [ASectionSuffix, BootStrap, Topic])); end; end.
{$I CetusOptions.inc} unit ctsThreads; interface uses Classes, SysUtils, JclSynch, ctsSyncObjects, ctsBaseInterfaces, ctsBaseClasses, ctsIInterfaceInclude, ctsPointerInclude; type TCheckDuplicate = (cdQueue, cdProcessing); TCheckDuplicates = set of TCheckDuplicate; TThreadState = (ctsInitializing, ctsWaiting, ctsGetting, ctsProcessing, ctsProcessed, ctsTerminating, ctsForReduce); IctsTaskData = interface(IctsBaseInterface) ['{C6B157E2-6CDF-41F0-9A39-3A0F8A7D6AF4}'] function Clone: IctsTaskData; function Duplicate(aTaskData: IctsTaskData; const aProcessing: Boolean): Boolean; function Info: string; end; { TctsTaskData } TctsTaskData = class(TctsBaseClass, IctsTaskData) public function Clone: IctsTaskData; virtual; abstract; function Duplicate(aTaskData: IctsTaskData; const aProcessing: Boolean): Boolean; virtual; function Info: string; virtual; end; TctsTaskArray = array of IctsTaskData; TctsTaskQueue = class; TQueueEmpty = procedure(Sender: TctsTaskQueue) of object; TctsTaskList = class(TctsIntfCustomVector) protected function GetItems(AIndex: LongInt): IctsTaskData; public property Items[AIndex: LongInt]: IctsTaskData read GetItems; default; end; { TctsTaskQueue } TctsTaskQueue = class(TctsTaskList) protected FDeadTaskList: TctsTaskList; FLastGetPoint: LongInt; FOnQueueEmpty: TQueueEmpty; FQueueLock: TJclCriticalSection; FQueuePackCount: LongInt; FTaskCount: LongInt; procedure DoQueueEmpty; function Duplicate(aTaskData: IctsTaskData): Boolean; procedure GetRequest(out aTaskData: IctsTaskData); public constructor Create; destructor Destroy; override; procedure Add(const AItem: IctsTaskData); procedure ClearDeadTask; function HasTask: Boolean; procedure Remove(const AItem: IctsTaskData); function TaskIsEmpty: Boolean; property QueuePackCount: LongInt read FQueuePackCount write FQueuePackCount default 127; property TaskCount: LongInt read FTaskCount; property OnQueueEmpty: TQueueEmpty read FOnQueueEmpty write FOnQueueEmpty; end; { TctsPoolingThread } TctsThreadPool = class; TctsPoolingThread = class(TThread) private FInitError: string; FInitFinished: TJclEvent; procedure ForceTerminate; {$IFDEF DEBUG} procedure Trace(const Str: string); {$ENDIF DEBUG} protected FProcessLock: TJclCriticalSection; FAverageProcessing: LongInt; FAverageWaitingTime: LongInt; FCurState: TThreadState; FPool: TctsThreadPool; FProcessingData: IctsTaskData; FProcessingStart: LongWord; FStillWorking: LongWord; FEventTerminated: TJclEvent; FWaitingStart: LongWord; FWorkCount: Int64; function AverageProcessingTime: LongWord; function AverageWaitingTime: LongWord; function CloneData: IctsTaskData; function Duplicate(aTaskData: IctsTaskData): Boolean; virtual; procedure Execute; override; function Info: string; virtual; function IsDead: Boolean; virtual; function IsFinished: Boolean; virtual; function IsIdle: Boolean; virtual; function NewAverage(OldAvg, NewVal: LongInt): LongInt; virtual; public constructor Create(aPool: TctsThreadPool); virtual; destructor Destroy; override; procedure StillWorking; procedure Terminate(const Force: Boolean = False); end; TctsPoolingThreadClass = class of TctsPoolingThread; TGetInfo = procedure(Sender: TctsThreadPool; var InfoText: string) of object; TProcessRequest = procedure(Sender: TctsThreadPool; aTaskData: IctsTaskData; aThread: TctsPoolingThread) of object; TTaskEmpty = procedure(Sender: TctsThreadPool) of object; TThreadInPoolInitializing = procedure(Sender: TctsThreadPool; aThread: TctsPoolingThread) of object; TThreadInPoolFinalizing = procedure(Sender: TctsThreadPool; aThread: TctsPoolingThread) of object; { TctsThreadVector } TctsThreadVector = class(TctsPtrCustomVector) protected procedure DoClear; override; function GetItems(AIndex: LongInt): TctsPoolingThread; public property Items[AIndex: LongInt]: TctsPoolingThread read GetItems; default; end; { TctsThreadPool } TctsThreadPool = class(TctsNamedClass) private FAdjustInterval: LongWord; FDeadCheckCount: LongInt; FDeadTaskAsNew: Boolean; FGetInfo: TGetInfo; FIdleThreadCount: LongInt; FMaxDeadTaskCheckCount: LongInt; FMinAtLeast: Boolean; FProcessRequest: TProcessRequest; FTaskQueue: TctsTaskQueue; FTerminateWaitTime: LongWord; FThreadClass: TctsPoolingThreadClass; FThreadDeadTimeout: LongWord; FThreadFinalizing: TThreadInPoolFinalizing; FThreadInitializing: TThreadInPoolInitializing; FThreadLock: IReadWriteSync; FThreads: TctsThreadVector; FThreadsKilling: TctsThreadVector; FThreadsMaxCount: LongInt; FThreadsMinCount: LongInt; procedure AddThread; inline; procedure CopyToKillingList(const AThread: TctsPoolingThread; const AIndex: LongInt); inline; procedure SetAdjustInterval(const Value: LongWord); protected FOnTaskEmpty: TTaskEmpty; FSemaphoreRequest: TJclSemaphore; FTimerReduce: TJclWaitableTimer; procedure CheckTaskEmpty; procedure DecreaseThreads; procedure DefaultGetInfo(Sender: TctsThreadPool; var InfoText: string); procedure DoProcessRequest(aTaskData: IctsTaskData; aThread: TctsPoolingThread); virtual; procedure DoTaskEmpty; procedure DoThreadFinalizing(aThread: TctsPoolingThread); virtual; procedure DoThreadInitializing(aThread: TctsPoolingThread); virtual; function DuplicateInThreads(aTaskData: IctsTaskData): Boolean; function FinishedThreadsAreFull: Boolean; virtual; procedure FreeFinishedThreads; procedure IncreaseThreads; procedure ReAddDeadRequest; public constructor Create; constructor CreateSpecial(AClass: TctsPoolingThreadClass); destructor Destroy; override; function AddRequest(aTaskData: IctsTaskData; CheckDuplicate: TCheckDuplicates = [cdQueue]): Boolean; procedure AddRequests(const aTaskDatas: TctsTaskArray; CheckDuplicate: TCheckDuplicates = [cdQueue]); function AverageProcessingTime: LongInt; function AverageWaitingTime: LongInt; function HasProcessingThread: Boolean; function HasSpareThread: Boolean; function HasThread: Boolean; function Info: string; procedure RemoveRequest(aTaskData: IctsTaskData); procedure TerminateAllThread(const AForce: Boolean = False); function ThreadCount: LongInt; function ThreadInfo(const I: LongInt): string; function ThreadKillingCount: LongInt; function ThreadKillingInfo(const I: LongInt): string; property AdjustInterval: LongWord read FAdjustInterval write SetAdjustInterval default 10000; property DeadTaskAsNew: Boolean read FDeadTaskAsNew write FDeadTaskAsNew default True; property MaxDeadTaskCheckCount: LongInt read FMaxDeadTaskCheckCount write FMaxDeadTaskCheckCount default 50; property MinAtLeast: Boolean read FMinAtLeast write FMinAtLeast default False; property TaskQueue: TctsTaskQueue read FTaskQueue write FTaskQueue; property TerminateWaitTime: LongWord read FTerminateWaitTime write FTerminateWaitTime; property ThreadDeadTimeout: LongWord read FThreadDeadTimeout write FThreadDeadTimeout default 0; property Threads: TctsThreadVector read FThreads; property ThreadsKilling: TctsThreadVector read FThreadsKilling; property ThreadsMaxCount: LongInt read FThreadsMaxCount write FThreadsMaxCount default 10; property ThreadsMinCount: LongInt read FThreadsMinCount write FThreadsMinCount default 0; property OnGetInfo: TGetInfo read FGetInfo write FGetInfo; property OnProcessRequest: TProcessRequest read FProcessRequest write FProcessRequest; property OnTaskEmpty: TTaskEmpty read FOnTaskEmpty write FOnTaskEmpty; property OnThreadFinalizing: TThreadInPoolFinalizing read FThreadFinalizing write FThreadFinalizing; property OnThreadInitializing: TThreadInPoolInitializing read FThreadInitializing write FThreadInitializing; end; const cThreadState: array[TThreadState] of string = ( 'ctsInitializing', 'ctsWaiting', 'ctsGetting', 'ctsProcessing', 'ctsProcessed', 'ctsTerminating', 'ctsForReduce'); implementation uses Windows, Math, {$IFDEF USE_CODESITE} CodeSiteLogging, {$ENDIF USE_CODESITE} ctsUtils, ctsConsts; const MaxInt64 = High(int64); function GetTickDiff(const AOldTickCount, ANewTickCount: LongWord): LongWord; inline; begin if ANewTickCount >= AOldTickCount then Result := ANewTickCount - AOldTickCount else Result := High(LongWord) - AOldTickCount + ANewTickCount; end; { TctsTaskData } function TctsTaskData.Duplicate(aTaskData: IctsTaskData; const aProcessing: Boolean): Boolean; begin Result := False; end; function TctsTaskData.Info: string; begin Result := IntToHex(LongWord(Self), 8); end; function TctsTaskList.GetItems(AIndex: LongInt): IctsTaskData; begin Result := nil; if not OutRange(AIndex, 0, FCount) then Result := FArray[AIndex] as IctsTaskData; end; { TctsTaskQueue } constructor TctsTaskQueue.Create; begin inherited; FLastGetPoint := 0; FTaskCount := 0; FQueuePackCount := 127; FQueueLock := TJclCriticalSection.Create; FDeadTaskList := TctsTaskList.Create; end; destructor TctsTaskQueue.Destroy; begin FQueueLock.Enter; try FreeAndNil(FDeadTaskList); inherited Destroy; finally FQueueLock.Free; end; end; procedure TctsTaskQueue.Add(const AItem: IctsTaskData); begin {$IFDEF USE_CODESITE}CodeSite.EnterMethod(Self, 'Add');{$ENDIF} FQueueLock.Enter; try DoAdd(AItem); Inc(FTaskCount); finally FQueueLock.Leave; end; {$IFDEF USE_CODESITE}CodeSite.ExitMethod(Self, 'Add');{$ENDIF} end; procedure TctsTaskQueue.ClearDeadTask; begin {$IFDEF USE_CODESITE}CodeSite.EnterMethod(Self, 'ClearDeadTask');{$ENDIF} FQueueLock.Enter; try FDeadTaskList.DoClear; finally FQueueLock.Leave; end; {$IFDEF USE_CODESITE}CodeSite.ExitMethod(Self, 'ClearDeadTask');{$ENDIF} end; procedure TctsTaskQueue.DoQueueEmpty; begin if Assigned(FOnQueueEmpty) then begin FQueueLock.Enter; try FOnQueueEmpty(Self); finally FQueueLock.Leave; end; end; end; function TctsTaskQueue.Duplicate(aTaskData: IctsTaskData): Boolean; var I: LongInt; Task: IctsTaskData; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Duplicate' ); {$ENDIF} Result := False; FQueueLock.Enter; try for I := 0 to FCount - 1 do begin Task := FArray[I] as IctsTaskData; if (Task <> nil) and aTaskData.Duplicate(Task, False) then begin {$IFDEF DEBUG} CodeSite.Send('Duplicate: ( ' + Task.Info + ' )'); {$ENDIF DEBUG} aTaskData := nil; Result := True; Break; end; end; finally FQueueLock.Leave; end; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Duplicate' ); {$ENDIF} end; procedure TctsTaskQueue.GetRequest(out aTaskData: IctsTaskData); var DeadCount: LongInt; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'GetRequest' ); {$ENDIF DEBUG} FQueueLock.Enter; try while (FLastGetPoint < FCount) and (FArray[FLastGetPoint] = nil) do Inc(FLastGetPoint); if (FCount > FQueuePackCount) and (FLastGetPoint >= FCount * 3 div 4) then begin DoPack; FTaskCount := FCount; FLastGetPoint := 0 end; FArray[FLastGetPoint].QueryInterface(IctsTaskData, aTaskData); FArray[FLastGetPoint] := nil; DeadCount := FDeadTaskList.FCount; if DeadCount > 0 then begin FArray[FLastGetPoint] := FDeadTaskList[DeadCount - 1]; FDeadTaskList.DoDelete(DeadCount - 1); end else Dec(FTaskCount); Inc(FLastGetPoint); {$IFDEF DEBUG} CodeSite.Send('GetRequest: ( ' + aTaskData.Info + ' )'); {$ENDIF DEBUG} if TaskIsEmpty then begin DoQueueEmpty; FTaskCount := 0; FLastGetPoint := 0; DoClear; end; finally FQueueLock.Leave; end; {$IFDEF DEBUG} CodeSite.Send(aTaskData.Info); CodeSite.ExitMethod( Self, 'GetRequest' ); {$ENDIF} end; function TctsTaskQueue.HasTask: Boolean; begin Result := FTaskCount > 0; end; procedure TctsTaskQueue.Remove(const AItem: IctsTaskData); var I: LongInt; begin FQueueLock.Enter; try I := 0; while (I < FCount) and (FArray[I] <> AItem) do Inc(I); if I < FCount then begin DoDelete(I); Dec(FTaskCount); end; finally FQueueLock.Leave; end; end; function TctsTaskQueue.TaskIsEmpty: Boolean; begin Result := FLastGetPoint >= FCount; end; { TctsPoolingThread } constructor TctsPoolingThread.Create(aPool: TctsThreadPool); begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Create' ); {$ENDIF DEBUG} inherited Create(True); FPool := aPool; FAverageWaitingTime := 0; FAverageProcessing := 0; FWorkCount := 0; FInitError := ''; FreeOnTerminate := False; FInitFinished := TJclEvent.Create(nil, True, False, ''); FEventTerminated := TJclEvent.Create(nil, True, False, ''); FProcessLock := TJclCriticalSection.Create; try Resume; FInitFinished.WaitForever; {$IFDEF DEBUG} CodeSite.Send( 'Wait InitFinished' ); {$ENDIF DEBUG} if FInitError <> '' then raise Exception.Create(FInitError); finally FInitFinished.Free; end; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Create' ); {$ENDIF DEBUG} end; destructor TctsPoolingThread.Destroy; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Destroy' ); {$ENDIF DEBUG} FProcessLock.Enter; try FProcessingData := nil; finally FProcessLock.Free; end; FEventTerminated.Free; inherited Destroy; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Destroy' ); {$ENDIF} end; function TctsPoolingThread.AverageProcessingTime: LongWord; begin if FCurState in [ctsProcessing] then Result := NewAverage(FAverageProcessing, GetTickDiff(FProcessingStart, GetTickCount)) else Result := FAverageProcessing; end; function TctsPoolingThread.AverageWaitingTime: LongWord; begin if FCurState in [ctsWaiting, ctsForReduce] then Result := NewAverage(FAverageWaitingTime, GetTickDiff(FWaitingStart, GetTickCount)) else Result := FAverageWaitingTime; end; function TctsPoolingThread.CloneData: IctsTaskData; begin FProcessLock.Enter; try Result := nil; if FProcessingData <> nil then Result := FProcessingData.Clone; finally FProcessLock.Leave; end; end; function TctsPoolingThread.Duplicate(aTaskData: IctsTaskData): Boolean; begin FProcessLock.Enter; try Result := (FProcessingData <> nil) and aTaskData.Duplicate(FProcessingData, True); finally FProcessLock.Leave; end; end; const WAIT_REQUEST = WAIT_OBJECT_0; WAIT_REDURE = WAIT_REQUEST + 1; WAIT_TERMINATE = WAIT_REDURE + 1; procedure TctsPoolingThread.Execute; var WaitedTime: LongInt; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Execute' ); {$ENDIF DEBUG} FCurState := ctsInitializing; try FPool.DoThreadInitializing(Self); except on E: Exception do FInitError := E.Message; end; FInitFinished.SetEvent; {$IFDEF DEBUG} Trace('Initialized'); {$ENDIF DEBUG} FWaitingStart := GetTickCount; FProcessingData := nil; while not Terminated do begin if not (FCurState in [ctsWaiting, ctsForReduce]) then LockedInc(FPool.FIdleThreadCount); FCurState := ctsWaiting; ///////////////////////////////////////////////////////////////////////////////////////////// case JclSynch.WaitForMultipleObjects([FPool.FSemaphoreRequest, FPool.FTimerReduce, FEventTerminated], False, INFINITE) of WAIT_REQUEST: begin {$IFDEF DEBUG} Trace('FSemaphoreRequest'); {$ENDIF DEBUG} WaitedTime := GetTickDiff(FWaitingStart, GetTickCount); FAverageWaitingTime := NewAverage(FAverageWaitingTime, WaitedTime); if FCurState in [ctsWaiting, ctsForReduce] then LockedDec(FPool.FIdleThreadCount); FCurState := ctsGetting; FPool.FTaskQueue.GetRequest(FProcessingData); if FWorkCount < MaxInt64 then Inc(FWorkCount); FProcessingStart := GetTickCount; FStillWorking := FProcessingStart; FCurState := ctsProcessing; try {$IFDEF DEBUG} Trace('Processing: ' + FProcessingData.Info); {$ENDIF DEBUG} FPool.DoProcessRequest(FProcessingData, Self) except {$IFDEF DEBUG} on E: Exception do Trace('OnProcessRequest Exception: ' + E.Message); {$ENDIF DEBUG} end; FProcessLock.Enter; try FProcessingData := nil; FAverageProcessing := NewAverage(FAverageProcessing, GetTickDiff(FProcessingStart, GetTickCount)); finally FProcessLock.Leave; end; FCurState := ctsProcessed; FPool.CheckTaskEmpty; FWaitingStart := GetTickCount; end; WAIT_REDURE: begin {$IFDEF DEBUG} Trace('FTimerReduce'); {$ENDIF DEBUG} if not (FCurState in [ctsWaiting, ctsForReduce]) then LockedInc(FPool.FIdleThreadCount); FCurState := ctsForReduce; FPool.DecreaseThreads; end; WAIT_TERMINATE: begin {$IFDEF DEBUG} Trace('FEventTerminated'); {$ENDIF DEBUG} if FCurState in [ctsWaiting, ctsForReduce] then LockedDec(FPool.FIdleThreadCount); FCurState := ctsTerminating; Break; end; end; end; if FCurState in [ctsWaiting, ctsForReduce] then InterlockedDecrement(FPool.FIdleThreadCount); FCurState := ctsTerminating; FPool.DoThreadFinalizing(Self); {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Execute' ); {$ENDIF} end; procedure TctsPoolingThread.ForceTerminate; begin TerminateThread(Handle, 0); end; function TctsPoolingThread.Info: string; const cInfoFormat = 'AverageWaitingTime=%d; AverageProcessingTime=%d; FCurState=%s; FWorkCount=%d'; begin Result := Format(cInfoFormat, [AverageWaitingTime, AverageProcessingTime, cThreadState[FCurState], FWorkCount]); FProcessLock.Enter; try Result := Result + '; FProcessingData='; if FProcessingData = nil then Result := Result + 'nil' else Result := Result + FProcessingData.Info; finally FProcessLock.Leave; end; end; function TctsPoolingThread.IsDead: Boolean; begin Result := Terminated or ((FCurState = ctsProcessing) and (FPool.ThreadDeadTimeout > 0) and (GetTickDiff(FStillWorking, GetTickCount) > FPool.ThreadDeadTimeout)); {$IFDEF DEBUG} if Result then Trace('Thread is dead, Info = ' + Info); {$ENDIF DEBUG} end; function TctsPoolingThread.IsFinished: Boolean; begin Result := WaitForSingleObject(Handle, 0) = WAIT_OBJECT_0; end; function TctsPoolingThread.IsIdle: Boolean; begin Result := (FCurState in [ctsWaiting, ctsForReduce]) and (AverageWaitingTime > 200) and (AverageWaitingTime * 2 > AverageProcessingTime); end; function TctsPoolingThread.NewAverage(OldAvg, NewVal: LongInt): LongInt; begin if FWorkCount >= 8 then Result := (OldAvg * 7 + NewVal) div 8 else if FWorkCount > 0 then Result := (OldAvg * FWorkCount + NewVal) div FWorkCount else Result := NewVal; end; procedure TctsPoolingThread.StillWorking; begin FStillWorking := GetTickCount; end; procedure TctsPoolingThread.Terminate(const Force: Boolean); begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Terminate' ); CodeSite.Send('Force', Force); {$ENDIF DEBUG} inherited Terminate; if Force then begin ForceTerminate; Free; end else FEventTerminated.SetEvent; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Terminate' ); {$ENDIF} end; {$IFDEF DEBUG} procedure TctsPoolingThread.Trace(const Str: string); begin CodeSite.Send(IntToStr(ThreadID) + ': ( ' + Str + ' )'); end; {$ENDIF DEBUG} { TctsThreadVector } procedure TctsThreadVector.DoClear; var I: LongInt; begin for I := 0 to FCount - 1 do TObject(FArray[I]).Free; inherited DoClear; end; function TctsThreadVector.GetItems(AIndex: LongInt): TctsPoolingThread; begin Result := nil; if not OutRange(AIndex, 0, FCount) then Result := FArray[AIndex]; end; { TctsThreadPool } constructor TctsThreadPool.Create; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Create' ); {$ENDIF DEBUG} inherited Create; //FThreadLock := TMultiReadExclusiveWriteSynchronizer.Create; FThreadLock := TSimpleRWSync.Create; FTaskQueue := TctsTaskQueue.Create; FThreads := TctsThreadVector.Create; FThreadsKilling := TctsThreadVector.Create; FThreadsMinCount := 0; FThreadsMaxCount := 10; FThreadDeadTimeout := 0; FThreadClass := TctsPoolingThread; FAdjustInterval := 10000; FMaxDeadTaskCheckCount := 50; FDeadTaskAsNew := True; FDeadCheckCount := 0; FMinAtLeast := False; FTerminateWaitTime := 10000; FIdleThreadCount := 0; FSemaphoreRequest := TJclSemaphore.Create(nil, 0, MAXLONG, ''); FTimerReduce := TJclWaitableTimer.Create(nil, False, ''); FTimerReduce.SetTimer(-1, FAdjustInterval, False); {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Create' ); {$ENDIF} end; constructor TctsThreadPool.CreateSpecial(AClass: TctsPoolingThreadClass); begin Create; if AClass <> nil then FThreadClass := AClass; end; destructor TctsThreadPool.Destroy; var I, N: LongInt; Thread: TctsPoolingThread; Handles: array of THandle; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'Destroy' ); {$ENDIF DEBUG} with FThreads, FThreadLock do begin BeginWrite; try if FCount > 0 then begin SetLength(Handles, FCount); N := 0; for I := 0 to FCount - 1 do begin Thread := FArray[I]; if Thread <> nil then begin Handles[N] := Thread.Handle; Thread.Terminate(False); Inc(N); end; end; WaitForMultipleObjects(N, @Handles[0], True, FTerminateWaitTime); end; FThreads.Free; FThreadsKilling.Free; finally FThreadLock.EndWrite; FThreadLock := nil; end; end; FTaskQueue.Free; FSemaphoreRequest.Free; FTimerReduce.Free; inherited Destroy; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'Destroy' ); {$ENDIF} end; function TctsThreadPool.AddRequest(aTaskData: IctsTaskData; CheckDuplicate: TCheckDuplicates = [cdQueue]): Boolean; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'AddRequest' ); {$ENDIF} Result := False; if aTaskData = nil then Exit; {$IFDEF DEBUG} CodeSite.Send('AddRequest:' + aTaskData.Info); {$ENDIF DEBUG} if ((cdQueue in CheckDuplicate) and FTaskQueue.Duplicate(aTaskData)) or ((cdProcessing in CheckDuplicate) and DuplicateInThreads(aTaskData)) then Exit; FTaskQueue.Add(aTaskData); IncreaseThreads; {$IFDEF DEBUG} CodeSite.Send('FSemaphoreRequest.Release'); {$ENDIF} FSemaphoreRequest.Release(1); Result := True; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'AddRequest' ); {$ENDIF DEBUG} end; procedure TctsThreadPool.AddRequests(const aTaskDatas: TctsTaskArray; CheckDuplicate: TCheckDuplicates = [cdQueue]); var I: LongInt; begin for I := Low(aTaskDatas) to High(aTaskDatas) do AddRequest(aTaskDatas[I], CheckDuplicate); end; procedure TctsThreadPool.AddThread; {$IFDEF DEBUG} const cNewThreadExceptionFormat = 'New thread Exception on %s: %s'; {$ENDIF} begin try FThreads.DoAdd(FThreadClass.Create(Self)); except {$IFDEF DEBUG} on E: Exception do CodeSite.Send(Format(cNewThreadExceptionFormat, [E.ClassName, E.Message])); {$ENDIF DEBUG} end; end; function TctsThreadPool.AverageProcessingTime: LongInt; var I, N: LongInt; begin N := FThreads.FCount; if N > 0 then begin Result := 0; for I := 0 to N - 1 do Inc(Result, TctsPoolingThread(FThreads.FArray[I]).AverageProcessingTime); Result := Result div N; end else Result := 20; end; function TctsThreadPool.AverageWaitingTime: LongInt; var I, N: LongInt; begin N := FThreads.FCount; if N > 0 then begin Result := 0; for I := 0 to N - 1 do Inc(Result, TctsPoolingThread(FThreads.FArray[I]).AverageWaitingTime); Result := Result div N; end else Result := 10; end; procedure TctsThreadPool.CheckTaskEmpty; begin if FTaskQueue.TaskIsEmpty and (not HasProcessingThread) then DoTaskEmpty; end; procedure TctsThreadPool.CopyToKillingList(const AThread: TctsPoolingThread; const AIndex: LongInt); begin AThread.Terminate(False); FThreadsKilling.DoAdd(AThread); FThreads.DoDelete(AIndex); end; procedure TctsThreadPool.DecreaseThreads; var I: LongInt; Thread: TctsPoolingThread; NotFinished: Boolean; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'DecreaseThreads' ); {$ENDIF DEBUG} ReAddDeadRequest(); with FThreads, FThreadLock do if (FCount <> 0) and not FinishedThreadsAreFull and BeginWrite then try NotFinished := True; for I := FCount - 1 downto 0 do begin Thread := FArray[I]; if Thread.IsDead then begin {$IFDEF DEBUG} CodeSite.Send( 'Dead Thread' ); {$ENDIF DEBUG} if FDeadTaskAsNew then FTaskQueue.FDeadTaskList.DoAdd(Thread.CloneData); CopyToKillingList(Thread, I); end else if Thread.IsIdle and (I >= FThreadsMinCount) and NotFinished then begin CopyToKillingList(Thread, I); NotFinished := False; end; end; finally EndWrite; end; FreeFinishedThreads; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'DecreaseThreads' ); {$ENDIF} end; procedure TctsThreadPool.DefaultGetInfo(Sender: TctsThreadPool; var InfoText: string); const cInfoFormat = 'MinCount=%d; MaxCount=%d; AdjustInterval=%d; DeadTimeOut=%d'#13#10'' + 'ThreadCount=%d; KillingCount=%d; SpareThreadCount=%d; TaskCount=%d; DeadTaskCount=%d; DeadCheckCount=%d'#13#10'' + 'AverageWaitingTime=%d; AverageProcessingTime=%d'#13#10'' + '===============Working Threads Info===============%s'#10#13'' + ''#10#13'===============Killing Threads Info===============%s'; cFormat = '%s'#13#10'%s'; var I: LongInt; sThreadInfo, sThreadKillingInfo: string; begin with Sender do begin FreeFinishedThreads; for I := 0 to ThreadCount - 1 do sThreadInfo := Format(cFormat, [sThreadInfo, ThreadInfo(I)]); for I := 0 to ThreadKillingCount - 1 do sThreadKillingInfo := Format(cFormat, [sThreadKillingInfo, ThreadKillingInfo(I)]); InfoText := Format(cInfoFormat, [ThreadsMinCount, ThreadsMaxCount, AdjustInterval, ThreadDeadTimeout, ThreadCount, ThreadKillingCount, FIdleThreadCount, FTaskQueue.FTaskCount, FTaskQueue.FDeadTaskList.FCount, FDeadCheckCount, AverageWaitingTime, AverageProcessingTime, sThreadInfo, sThreadKillingInfo]); end; end; procedure TctsThreadPool.DoProcessRequest(aTaskData: IctsTaskData; aThread: TctsPoolingThread); begin if Assigned(FProcessRequest) then FProcessRequest(Self, aTaskData, aThread); end; procedure TctsThreadPool.DoTaskEmpty; begin if Assigned(FOnTaskEmpty) then begin FThreadLock.BeginRead; try FOnTaskEmpty(Self); finally FThreadLock.EndRead; end; end; end; procedure TctsThreadPool.DoThreadFinalizing(aThread: TctsPoolingThread); begin if Assigned(FThreadFinalizing) then FThreadFinalizing(Self, aThread); end; procedure TctsThreadPool.DoThreadInitializing(aThread: TctsPoolingThread); begin if Assigned(FThreadInitializing) then FThreadInitializing(Self, aThread); end; function TctsThreadPool.DuplicateInThreads(aTaskData: IctsTaskData): Boolean; var I: LongInt; Thread: TctsPoolingThread; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'DuplicateInThreads' ); {$ENDIF} Result := False; with FThreads, FThreadLock do if FCount <> 0 then begin BeginRead; try for I := 0 to FCount - 1 do begin Thread := FThreads.FArray[I]; if Thread.Duplicate(aTaskData) then begin {$IFDEF DEBUG} CodeSite.Send('Duplicate:' + Thread.FProcessingData.Info); {$ENDIF DEBUG} Result := True; aTaskData := nil; Break; end; end; finally EndRead; end; end; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'DuplicateInThreads' ); {$ENDIF} end; function TctsThreadPool.FinishedThreadsAreFull: Boolean; begin FThreadLock.BeginRead; try if FThreadsMaxCount > 0 then Result := FThreadsKilling.FCount >= FThreadsMaxCount div 2 else Result := FThreadsKilling.FCount >= 50; finally FThreadLock.EndRead; end; end; procedure TctsThreadPool.FreeFinishedThreads; var I: LongInt; Thread: TctsPoolingThread; begin with FThreadsKilling, FThreadLock do if (FCount <> 0) and BeginWrite then try for I := FCount - 1 downto 0 do begin Thread := FArray[I]; if Thread.IsFinished then begin Thread.Free; DoDelete(I); end; end; finally EndWrite; end; end; function TctsThreadPool.HasProcessingThread: Boolean; var I: LongInt; begin Result := False; if FThreads.FCount = 0 then Exit; FThreadLock.BeginRead; try for I := 0 to FThreads.FCount - 1 do if TctsPoolingThread(FThreads.FArray[I]).FCurState in [ctsProcessing] then begin Result := True; Break; end; finally FThreadLock.EndRead; end; end; function TctsThreadPool.HasSpareThread: Boolean; begin Result := FIdleThreadCount > 0; end; function TctsThreadPool.HasThread: Boolean; begin Result := FThreads.FCount > 0; end; procedure TctsThreadPool.IncreaseThreads; {$IFDEF DEBUG} const cIncreaseThreadsFormat = 'IncreaseThreads: %s'; {$ENDIF} var I, iAvgWait, iAvgProc: LongInt; Thread: TctsPoolingThread; begin {$IFDEF DEBUG} CodeSite.EnterMethod( Self, 'IncreaseThreads' ); {$ENDIF} with FThreads, FThreadLock do begin BeginWrite; try if not FinishedThreadsAreFull then for I := FCount - 1 downto 0 do begin Thread := FArray[I]; if Thread.IsDead then begin if FDeadTaskAsNew then FTaskQueue.FDeadTaskList.DoAdd(Thread.CloneData); CopyToKillingList(Thread, I); end; end; if FCount <= FThreadsMinCount then begin {$IFDEF DEBUG} CodeSite.Send(Format(cIncreaseThreadsFormat, ['FThreads.FCount < FThreadsMinCount'])); {$ENDIF DEBUG} if FMinAtLeast then for I := FCount to FThreadsMinCount - 1 do AddThread() else AddThread(); end else if (FCount < FThreadsMaxCount) and FTaskQueue.HasTask and not HasSpareThread then begin {$IFDEF DEBUG} CodeSite.Send(Format(cIncreaseThreadsFormat, ['FThreads.FCount < FThreadsMaxCount'])); {$ENDIF DEBUG} iAvgWait := Max(AverageWaitingTime, 1); if iAvgWait <= 100 then begin iAvgProc := Max(AverageProcessingTime, 2); {$IFDEF DEBUG} CodeSite.Send(Format('ThreadCount(%D); ThreadsMaxCount(%D); AvgWait(%D); AvgProc(%D); Killing(%D)', [FCount, FThreadsMaxCount, iAvgWait, iAvgProc, ThreadKillingCount])); {$ENDIF DEBUG} if ((iAvgProc + iAvgWait) * FTaskQueue.FTaskCount > iAvgProc * FCount) then AddThread(); end; end; finally EndWrite; end; end; {$IFDEF DEBUG} CodeSite.ExitMethod( Self, 'IncreaseThreads' ); {$ENDIF} end; function TctsThreadPool.Info: string; begin FThreadLock.BeginRead; try if Assigned(FGetInfo) then FGetInfo(Self, Result) else DefaultGetInfo(Self, Result) finally FThreadLock.EndRead; end; end; procedure TctsThreadPool.ReAddDeadRequest; var I: LongInt; begin with FTaskQueue.FDeadTaskList do begin if FCount = 0 then Exit; I := FCount - 1; AddRequest(FArray[I] as IctsTaskData); DoDelete(I); end; end; procedure TctsThreadPool.RemoveRequest(aTaskData: IctsTaskData); begin FTaskQueue.Remove(aTaskData); end; procedure TctsThreadPool.SetAdjustInterval(const Value: LongWord); begin FAdjustInterval := Value; if FTimerReduce <> nil then FTimerReduce.SetTimer(-1, Value, False); end; procedure TctsThreadPool.TerminateAllThread(const AForce: Boolean = False); var I: LongInt; Thread: TctsPoolingThread; begin with FThreads, FThreadLock do begin BeginWrite; try if FCount > 0 then for I := 0 to FCount - 1 do begin Thread := FArray[I]; if Thread <> nil then Thread.Terminate(AForce); end; FThreads.Free; FThreadsKilling.Free; finally FThreadLock.EndWrite; end; end; end; function TctsThreadPool.ThreadCount: LongInt; begin FThreadLock.BeginRead; try Result := FThreads.FCount; finally FThreadLock.EndRead; end; end; function TctsThreadPool.ThreadInfo(const I: LongInt): string; begin Result := ''; FThreadLock.BeginRead; try if I < FThreads.FCount then Result := FThreads[I].Info; finally FThreadLock.EndRead; end; end; function TctsThreadPool.ThreadKillingCount: LongInt; begin FThreadLock.BeginRead; try Result := FThreadsKilling.FCount; finally FThreadLock.EndRead; end; end; function TctsThreadPool.ThreadKillingInfo(const I: LongInt): string; begin Result := ''; FThreadLock.BeginRead; try if I < FThreadsKilling.FCount then Result := FThreadsKilling[I].Info; finally FThreadLock.EndRead; end; end; end.
unit TestUUsuarioVO; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, SysUtils, Atributos, UGenericVO, Generics.Collections, Classes, UUsuarioVO, Constantes, UPessoasVO; type // Test methods for class TUsuarioVO TestTUsuarioVO = class(TTestCase) strict private FUsuarioVO: TUsuarioVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposObrigatorios; procedure TestValidarCamposObrigatoriosNaoEncontrado; end; implementation procedure TestTUsuarioVO.SetUp; begin FUsuarioVO := TUsuarioVO.Create; end; procedure TestTUsuarioVO.TearDown; begin FUsuarioVO.Free; FUsuarioVO := nil; end; procedure TestTUsuarioVO.TestValidarCamposObrigatorios; var Usuario : TUsuarioVO; begin Usuario := TUsuarioVo.Create; Usuario.idPessoa := 36; Usuario.Login := 'naay'; Usuario.senha := '123'; try Usuario.ValidarCamposObrigatorios; Check(true,'Sucesso!') except on E: Exception do Check(false,'Erro!'); end; end; procedure TestTUsuarioVO.TestValidarCamposObrigatoriosNaoEncontrado; var Usuario : TUsuarioVO; begin Usuario := TUsuarioVo.Create; Usuario.idPessoa := 0; Usuario.Login := ''; Usuario.senha := ''; try Usuario.ValidarCamposObrigatorios; Check(false,'Erro!') except on E: Exception do Check(true,'Sucesso!'); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTUsuarioVO.Suite); end.
unit Scene; interface uses Generics.Collections, Shape, Light; type TScene = class public shapes: TArray<Cardinal>; ligths: TArray<TLight>; constructor Create(shapes: TArray<Cardinal>; ligths: TArray<TLight>); end; implementation { TScene } constructor TScene.Create(shapes: TArray<Cardinal>; ligths: TArray<TLight>); begin Self.shapes := shapes; Self.ligths := ligths; end; end.
unit utils; interface uses classes; type TDelimiter = set of #0..'ÿ' ; const StandartDelimiters: TDelimiter = [' ', '!', '(', ')', '-', '|', '\', ';', ':', '"', '/', '?', '.', '>', ',', '<']; function StringToWords(const DelimitedText: string; ResultList: TStrings; Delimiters: TDelimiter = []; ListClear: boolean = true): boolean; implementation function StringToWords(const DelimitedText: string; ResultList: TStrings; Delimiters: TDelimiter = []; ListClear: boolean = true): boolean; var i, Len, Prev: word; TempList: TStringList; begin Result := false; if (ResultList <> nil) and (DelimitedText <> '') then try TempList := TStringList.Create; if Delimiters = [] then Delimiters := StandartDelimiters; Len := 1; Prev := 0; for i := 1 to Length(DelimitedText) do begin if Prev <> 0 then begin if DelimitedText[i] in Delimiters then begin if Len = 0 then Prev := i + 1 else begin TempList.Add(copy(DelimitedText, Prev, Len)); Len := 0; Prev := i + 1 end end else Inc(Len) end else if not (DelimitedText[i] in Delimiters) then Prev := i end; if Len > 0 then TempList.Add(copy(DelimitedText, Prev, Len)); if TempList.Count > 0 then begin if ListClear then ResultList.Assign(TempList) else ResultList.AddStrings(TempList); Result := true end; finally TempList.Free end end; end.
unit Nullpobug.Example.Spring4d.Calculator; interface uses System.SysUtils , Nullpobug.Example.Spring4d.ServiceLocator , Nullpobug.Example.Spring4d.MathServiceIntf , Nullpobug.Example.Spring4d.CalculatorUIIntf ; type TCalculator = class private FMathService: IMathService; FCalculatorUI: ICalcuratorUI; public constructor Create; function Addition(A, B: Integer): Integer; function Multiplication(A, B: Integer): Integer; procedure WriteLine(S: String); property MathService: IMathService read FMathService; property CalculatorUI: ICalcuratorUI read FCalculatorUI; class procedure Main; end; implementation constructor TCalculator.Create; begin FMathService := ServiceLocator.Resolve<IMathService>; FCalculatorUI := ServiceLocator.Resolve<ICalcuratorUI>; end; function TCalculator.Addition(A, B: Integer): Integer; begin Result := FMathService.Add(A, B); end; function TCalculator.Multiplication(A, B: Integer): Integer; begin Result := FMathService.Multiply(A, B); end; procedure TCalculator.WriteLine(S: String); begin FCalculatorUI.WriteLine(S); end; class procedure TCalculator.Main; var FCalculator: TCalculator; begin FCalculator := TCalculator.Create; try FCalculator.WriteLine('MathService: ' + FCalculator.MathService.Name); FCalculator.WriteLine('CalculatorUI: ' + FCalculator.CalculatorUI.Name); FCalculator.WriteLine(Format('10 + 20 = %d', [FCalculator.Addition(10, 20)])); FCalculator.WriteLine(Format('10 * 20 = %d', [FCalculator.Multiplication(10, 20)])); finally FCalculator.Free; end; end; end.
unit uEditSertifikat; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxControls, cxContainer, cxEdit, cxLabel; type TfrmEditSertifikat = class(TForm) cxButtonOK: TcxButton; cxButtonCansel: TcxButton; ActionListKlassSpravEdit: TActionList; ActionOK: TAction; ActionCansel: TAction; cxLabelNOMER: TcxLabel; cxLabelPIN: TcxLabel; cxMaskEditNOMER: TcxMaskEdit; cxMaskEditPIN: TcxMaskEdit; cxLabelYEAR: TcxLabel; cxMaskEditYEAR: TcxMaskEdit; procedure ActionOKExecute(Sender: TObject); procedure ActionCanselExecute(Sender: TObject); private ILLangEdit: integer; procedure inicCaption; public constructor Create(aOwner: TComponent);overload; end; implementation uses uPrK_Resources,uConstants,uPRK_DT_ABIT; {$R *.dfm} constructor TfrmEditSertifikat.Create(aOwner: TComponent); begin ILLangEdit:=SelectLanguage; inherited Create(aOwner); inicCaption; end; procedure TfrmEditSertifikat.inicCaption; begin ActionOK.Caption :=nActiont_OK[ILLangEdit]; ActionCansel.Caption :=nActiont_Cansel[ILLangEdit]; ActionOK.Hint :=nHintActiont_OK[ILLangEdit]; ActionCansel.Hint :=nHintActiont_Cansel[ILLangEdit]; cxLabelNOMER.Caption :=nLabelSertifikatNumber[ILLangEdit]; cxLabelPIN.Caption :=nLabelSertifikatPIN[ILLangEdit]; cxLabelYEAR.Caption :=nLabelSertifikatYEAR[ILLangEdit]; end; procedure TfrmEditSertifikat.ActionOKExecute(Sender: TObject); begin if trim(cxMaskEditNOMER.Text)='' then begin ShowMessage(nMsgSertifikarEmptyNomer[ILLangEdit]); cxMaskEditNOMER.SetFocus; exit; end; if trim(cxMaskEditPIN.Text)='' then begin ShowMessage(nMsgSertifikarEmptyPIN[ILLangEdit]); cxMaskEditPIN.SetFocus; exit; end; if cxMaskEditYEAR.Text='' then begin ShowMessage(nMsgSertifikarEmptyYEAR[ILLangEdit]); cxMaskEditYEAR.SetFocus; Exit; end; ModalResult := mrOk; end; procedure TfrmEditSertifikat.ActionCanselExecute(Sender: TObject); begin ModalResult := mrCancel; end; end.
unit UniTypes; interface uses SysUtils, Classes; const MAPNAMELEN = 16; ACTORNAMELEN = 14; type TListArray = array [Ord('A')..Ord('Z') + 10 + 1] of TStrings; pTQuickInfo = ^TQuickInfo; TQuickInfo = packed record sChrName : string[16]; nPosition : Cardinal; end; //size 124 ID.DB 数据头 TDBHeader = packed record sDesc: string[34]; //0x00 # n23: Integer; //0x23 n28: Integer; //0x27 n2C: Integer; //0x2B n30: Integer; //0x2F n34: Integer; //0x33 n38: Integer; //0x37 n3C: Integer; //0x3B n40: Integer; //0x3F n44: Integer; //0x43 n48: Integer; //0x47 n4B: Byte; //0x4B n4C: Integer; //0x4C n50: Integer; //0x50 n54: Integer; //0x54 n58: Integer; //0x58 nLastIndex: Integer; //0x5C 最后的索引 # dLastDate: TDateTime; //0x60 # nIDCount: Integer; //0x68 ID数量 # n6C: Integer; //0x6C nDeletedIdx: Integer; //0x70 := -1 # dUpdateDate: TDateTime; //0x74 # end; pTDBHeader = ^TDBHeader; //人物数据头 TDBHeader1 = packed record //Size 124 sDesc: string[$23]; //0x00 36 n24: Integer; //0x24 n28: Integer; //0x28 n2C: Integer; //0x2C n30: Integer; //0x30 n34: Integer; //0x34 n38: Integer; //0x38 n3C: Integer; //0x3C n40: Integer; //0x40 n44: Integer; //0x44 n48: Integer; //0x48 n4C: Integer; //0x4C n50: Integer; //0x50 n54: Integer; //0x54 n58: Integer; //0x58 nLastIndex: Integer; //0x5C dLastDate: TDateTime; //最后退登日期 nHumCount: Integer; //0x68 n6C: Integer; //0x6C n70: Integer; //0x70 dUpdateDate: TDateTime; //更新日期 end; TRecordHeader = packed record //Size 12 boDeleted: Boolean; //是否删除 nSelectID: Byte; //ID boIsHero: Boolean; //是否英雄 bt2: Byte; dCreateDate: TDateTime; //创建时间 sName: string[15]; //0x15 //角色名称 28 end; pTRecordHeader = ^TRecordHeader; {THumInfo} pTDBHum = ^TDBHum; TDBHum = packed record //FileHead 72字节 //Size 72 Header: TRecordHeader; sChrName: string[14]; //0x14 //角色名称 44 sAccount: string[10]; //账号 boDeleted: Boolean; //是否删除 bt1: Byte; //未知 dModDate: TDateTime;//操作日期 btCount: Byte; //操作计次 boSelected: Boolean; //是否选择 n6: array[0..5] of Byte; end; pTUserItem = ^TUserItem; TUserItem = record // 20080313 修改 MakeIndex: Integer; wIndex: Word; //物品id Dura: Word; //当前持久值 DuraMax: Word; //最大持久值 btValue: array[0..20] of Byte;//附加属性 12-发光 13-自定义名称 end; TOAbility = packed record Level: Word; AC: Word; MAC: Word; DC: Word; MC: Word; SC: Word; HP: Word; MP: Word; MaxHP: Word; MaxMP: Word; {btReserved1: Byte;//20081001 注释 btReserved2: Byte; btReserved3: Byte; btReserved4: Byte;} NG: Word;//20081001 当前内力值 MaxNG: Word;//20081001 内力值上限 Exp: LongWord; MaxExp: LongWord; Weight: Word; MaxWeight: Word; //背包 WearWeight: Byte; MaxWearWeight: Byte; //负重 HandWeight: Byte; MaxHandWeight: Byte; //腕力 end; pTNakedAbility=^TNakedAbility; TNakedAbility = packed record //Size 20 DC: Word; MC: Word; SC: Word; AC: Word; MAC: Word; HP: Word; MP: Word; Hit: Word; Speed: Word; X2: Word; end; pTHumMagicInfo= ^THumMagicInfo; THumMagicInfo = record wMagIdx: Word; btLevel: Byte; btKey: Byte; nTranPoint: Integer; //当前持久值 end; TStatusTime = array[0..11] of Word; TQuestUnit = Array[0..127] of Byte; TQuestFlag = array[0..127] of Byte; THumItems=Array[0..8] of TUserItem; THumAddItems=Array[9..13] of TUserItem;//支持斗笠 20080416 TBagItems=Array[0..45] of TUserItem; TUnKnow = array[0..39] of Byte; THumMagic= Array[0..19] of THumMagicInfo; THumNGMagics = array[0..19] of THumMagicInfo;//内功技能 20081001 //扩展后的数据格式 20081231 TUnKnow1 = array[0..29] of Byte; THumMagic1= Array[0..29] of THumMagicInfo; THumNGMagics1 = array[0..29] of THumMagicInfo;//内功技能 TStorageItems=Array[0..45] of TUserItem; //20071115 TAddBagItems=Array[46..51] of TUSerItem; TSearchLikeMode = (slAny, slBlack, slFront); pTnewHumData = ^TnewHumData; TnewHumData = packed record //新的数据结构 1231 sChrName: string[14]; sCurMap: string[16]; wCurX: Word; wCurY: Word; btDir: Byte; btHair: Byte; btSex: Byte; btJob: Byte; nGold: Integer; Abil: TOAbility; //+40 wStatusTimeArr: TStatusTime; //+24 sHomeMap: string[16]; //btUnKnow1: Byte;不使用,去掉 wHomeX: Word; wHomeY: Word; sDearName: string[14]; sMasterName: string[14];//师傅名字 boMaster: Boolean; btCreditPoint: Integer;//声望点 20080118 btDivorce: Byte; //是否结婚 btMarryCount: Byte; //结婚次数 sStoragePwd: string[7]; btReLevel: Byte; btUnKnow2: array[0..2] of Byte; BonusAbil: TNakedAbility; //+20 nBonusPoint: Integer; nGameGold: Integer;//游戏币 nGameDiaMond: Integer;//金刚石 20071226 nGameGird:Integer;//灵符 20071226 nGamePoint: Integer; btGameGlory: Byte; //荣誉 20080511 nPayMentPoint: Integer; //充值点 nLoyal: Integer;//英雄的忠诚度(20080109) nPKPOINT: Integer; btAllowGroup: Byte; btF9: Byte; btAttatckMode: Byte; btIncHealth: Byte; btIncSpell: Byte; btIncHealing: Byte; btFightZoneDieCount: Byte; sAccount: string[10]; //btEE: Byte;//不使用,去掉 btEF: Byte; boLockLogon: Boolean; wContribution: Word; nHungerStatus: Integer; boAllowGuildReCall: Boolean; // 是否允许行会合一 wGroupRcallTime: Word; //队传送时间 dBodyLuck: Double; //幸运度 8 boAllowGroupReCall: Boolean; // 是否允许天地合一 nEXPRATE: Integer; //经验倍数 nExpTime: Integer; //经验倍数时间 btLastOutStatus: Byte; //2006-01-12增加 退出状态 1为死亡退出 wMasterCount: Word; //出师徒弟数 boHasHero: Boolean; //是否有英雄 boIsHero: Boolean; //是否是英雄 btStatus: Byte; //状态 sHeroChrName: string[14]; UnKnow: TUnKnow1; QuestFlag: TQuestFlag; //脚本变量 HumItems: THumItems; //9格装备 衣服 武器 蜡烛 头盔 项链 手镯 手镯 戒指 戒指 BagItems: TBagItems; //包裹装备 HumMagics: THumMagic1; //魔法 StorageItems: TStorageItems; //仓库物品 HumAddItems: THumAddItems; //新增4格 护身符 腰带 鞋子 宝石 n_WinExp:longWord;//累计经验 20081001 n_UsesItemTick: Integer;//聚灵珠聚集时间 20080221 nReserved: Integer; //酿酒的时间,即还有多长时间可以取回酒 20080620 nReserved1: Integer; //当前药力值 20080623 nReserved2: Integer; //药力值上限 20080623 nReserved3: Integer; //使用药酒时间,计算长时间没使用药酒 20080623 n_Reserved: Word; //当前酒量值 20080622 n_Reserved1: Word; //酒量上限 20080622 n_Reserved2: Word; //当前醉酒度 20080623 n_Reserved3: Word; //药力值等级 20080623 boReserved: Boolean; //是否请过酒 T-请过酒 boReserved1: Boolean;//是否有卧龙英雄 20080519 boReserved2: Boolean;//是否酿酒 T-正在酿酒 20080620 boReserved3: Boolean;//人是否喝酒醉了 20080627 m_GiveDate:Integer;//人物领取行会酒泉日期 20080625 Exp68: LongWord;//酒气护体当前经验 20080625 MaxExp68: LongWord;//酒气护体升级经验 20080625 nExpSkill69: Integer;//内功当前经验 20080930 HumNGMagics: THumNGMagics1;//内功技能 20081001 m_nReserved1: Word;//保留 m_nReserved2: Word;//保留 m_nReserved3: Word;//保留 m_nReserved4: LongWord;//保留 m_nReserved5: LongWord;//保留 m_nReserved6: Integer;//保留 m_nReserved7: Integer;//保留 end; TNewHumDataInfo = packed record //新的数据结构 1231 Header: TRecordHeader; Data: TNewHumData; end; //----------------------------------------------------------------------------- pTHumData = ^THumData; THumData = packed record //旧的数据结构 0929 sChrName: string[14];//姓名 sCurMap: string[16]; //地图 wCurX: Word; //坐标X wCurY: Word; //坐标Y btDir: Byte; //方向 btHair: Byte;//头发 btSex: Byte; //性别 btJob: Byte;//职业 0-战 1-法 2-道 3-刺客 nGold: Integer; //金币数 Abil: TOAbility; //+40 人物其它属性 wStatusTimeArr: TStatusTime; //+24 人物状态属性值,一般是持续多少秒 sHomeMap: string[16];//Home 家 btUnKnow1: Byte;//(20080404 未使用) wHomeX: Word;//Home X wHomeY: Word;//Home Y sDearName: string[14]; //别名(配偶) sMasterName: string[14];//师傅名字 boMaster: Boolean;//是否有徒弟 btCreditPoint: Integer;//声望点 20080118 btDivorce: Byte; //是否结婚 btMarryCount: Byte; //结婚次数 sStoragePwd: string[7];//仓库密码 btReLevel: Byte;//转生等级 btUnKnow2: array[0..2] of Byte;//0-是否开通元宝寄售(1-开通) 1-是否寄存英雄(1-存有英雄) 2-饮酒时酒的品质 BonusAbil: TNakedAbility; //+20 奖金 nBonusPoint: Integer;//奖励点 nGameGold: Integer;//游戏币 nGameDiaMond: Integer;//金刚石 20071226 nGameGird:Integer;//灵符 20071226 nGamePoint: Integer;//声望 btGameGlory: Byte; //荣誉 20080511 nPayMentPoint: Integer; //充值点 nLoyal: Integer;//英雄的忠诚度(20080109) nPKPOINT: Integer;//PK点数 btAllowGroup: Byte;//允许组队 btF9: Byte; btAttatckMode: Byte;//攻击模式 btIncHealth: Byte;//增加健康数 btIncSpell: Byte;//增加攻击点 btIncHealing: Byte;//增加治愈点 btFightZoneDieCount: Byte;//在行会占争地图中死亡次数 sAccount: string[10];//登录帐号 btEE: Byte; btEF: Byte;//英雄类型 0-白日门英雄 1-卧龙英雄 20080514 boLockLogon: Boolean;//是否锁定登陆 wContribution: Word;//贡献值 nHungerStatus: Integer;//饥饿状态 boAllowGuildReCall: Boolean; // 是否允许行会合一 wGroupRcallTime: Word; //队传送时间 dBodyLuck: Double; //幸运度 8 boAllowGroupReCall: Boolean; // 是否允许天地合一 nEXPRATE: Integer; //经验倍数 nExpTime: Integer; //经验倍数时间 btLastOutStatus: Byte; //退出状态 1为死亡退出 wMasterCount: Word; //出师徒弟数 boHasHero: Boolean; //是否有白日门英雄 boIsHero: Boolean; //是否是英雄 btStatus: Byte; //状态 sHeroChrName: string[14];//英雄名称 UnKnow: TUnKnow;//预留 array[0..39] of Byte; 0-3酿酒使用 20080620 4-饮酒时的度数 5-魔法盾等级 QuestFlag: TQuestFlag; //脚本变量 HumItems: THumItems; //9格装备 衣服 武器 蜡烛 头盔 项链 手镯 手镯 戒指 戒指 BagItems: TBagItems; //包裹装备 HumMagics: THumMagic; //魔法 StorageItems: TStorageItems; //仓库物品 HumAddItems: THumAddItems; //新增4格 护身符 腰带 鞋子 宝石 n_WinExp: Integer;//累计经验(longWord与integer字节一样,修改会不会影响? 20080918) n_UsesItemTick: Integer;//聚灵珠聚集时间 20080221 nReserved: Integer; //酿酒的时间,即还有多长时间可以取回酒 20080620 nReserved1: Integer; //当前药力值 20080623 nReserved2: Integer; //药力值上限 20080623 nReserved3: Integer; //使用药酒时间,计算长时间没使用药酒 20080623 n_Reserved: Word; //当前酒量值 20080622 n_Reserved1: Word; //酒量上限 20080622 n_Reserved2: Word; //当前醉酒度 20080623 n_Reserved3: Word; //药力值等级 20080623 boReserved: Boolean; //是否请过酒 T-请过酒 boReserved1: Boolean;//是否有卧龙英雄 20080519 boReserved2: Boolean;//是否酿酒 T-正在酿酒 20080620 boReserved3: Boolean;//人是否喝酒醉了 20080627 m_GiveDate:Integer;//人物领取行会酒泉日期 20080625 Exp68: LongWord;//酒气护体当前经验 20080625 MaxExp68: LongWord;//酒气护体升级经验 20080625 m_nReserved1: Integer;//保留 m_nReserved2: Integer;//保留 sReserved1:string[21];//保留 end; THumDataInfo = packed record //Size 3176 0929前格式 Header: TRecordHeader; Data: THumData; end; //----------------------------------------------------------------------------- THumData1014 = packed record //人物数据类 Size = 4286 1014 sChrName: string[ACTORNAMELEN];//姓名 sCurMap: string[MAPNAMELEN]; //地图 wCurX: Word; //坐标X wCurY: Word; //坐标Y btDir: Byte; //方向 btHair: Byte;//头发 btSex: Byte; //性别 btJob: Byte;//职业 0-战 1-法 2-道 3-刺客 nGold: Integer; //金币数 Abil: TOAbility; //+40 人物其它属性 wStatusTimeArr: TStatusTime; //+24 人物状态属性值,一般是持续多少秒 sHomeMap: string[MAPNAMELEN];//Home 家 btUnKnow1: Byte;//(20080404 未使用) wHomeX: Word;//Home X wHomeY: Word;//Home Y sDearName: string[ACTORNAMELEN]; //别名(配偶) sMasterName: string[ACTORNAMELEN];//师傅名字 boMaster: Boolean;//是否有徒弟 btCreditPoint: Integer;//声望点 20080118 btDivorce: Byte; //是否结婚 btMarryCount: Byte; //结婚次数 sStoragePwd: string[7];//仓库密码 btReLevel: Byte;//转生等级 btUnKnow2: array[0..2] of Byte;//0-是否开通元宝寄售(1-开通) 1-是否寄存英雄(1-存有英雄) 2-饮酒时酒的品质 BonusAbil: TNakedAbility; //+20 奖金 nBonusPoint: Integer;//奖励点 nGameGold: Integer;//游戏币 nGameDiaMond: Integer;//金刚石 20071226 nGameGird:Integer;//灵符 20071226 nGamePoint: Integer;//声望 btGameGlory: Byte; //荣誉 20080511 nPayMentPoint: Integer; //充值点 nLoyal: Integer;//英雄的忠诚度(20080109) nPKPOINT: Integer;//PK点数 btAllowGroup: Byte;//允许组队 btF9: Byte; btAttatckMode: Byte;//攻击模式 btIncHealth: Byte;//增加健康数 btIncSpell: Byte;//增加攻击点 btIncHealing: Byte;//增加治愈点 btFightZoneDieCount: Byte;//在行会占争地图中死亡次数 sAccount: string[10];//登录帐号 btEE: Byte;//未使用 btEF: Byte;//英雄类型 0-白日门英雄 1-卧龙英雄 20080514 boLockLogon: Boolean;//是否锁定登陆 wContribution: Word;//贡献值 nHungerStatus: Integer;//饥饿状态 boAllowGuildReCall: Boolean; // 是否允许行会合一 wGroupRcallTime: Word; //队传送时间 dBodyLuck: Double; //幸运度 8 boAllowGroupReCall: Boolean; // 是否允许天地合一 nEXPRATE: Integer; //经验倍数 nExpTime: Integer; //经验倍数时间 btLastOutStatus: Byte; //退出状态 1为死亡退出 wMasterCount: Word; //出师徒弟数 boHasHero: Boolean; //是否有白日门英雄 boIsHero: Boolean; //是否是英雄 btStatus: Byte; //状态 sHeroChrName: string[ACTORNAMELEN];//英雄名称 UnKnow: TUnKnow;//预留 array[0..39] of Byte; 0-3酿酒使用 20080620 4-饮酒时的度数 5-魔法盾等级 6-是否学过内功 7-内功等级 QuestFlag: TQuestFlag; //脚本变量 HumItems: THumItems; //9格装备 衣服 武器 蜡烛 头盔 项链 手镯 手镯 戒指 戒指 BagItems: TBagItems; //包裹装备 HumMagics: THumMagic; //魔法 StorageItems: TStorageItems; //仓库物品 HumAddItems: THumAddItems; //新增4格 护身符 腰带 鞋子 宝石 n_WinExp: longWord;//累计经验(longWord与integer字节一样,修改会不会影响? 20081001) n_UsesItemTick: Integer;//聚灵珠聚集时间 20080221 nReserved: Integer; //酿酒的时间,即还有多长时间可以取回酒 20080620 nReserved1: Integer; //当前药力值 20080623 nReserved2: Integer; //药力值上限 20080623 nReserved3: Integer; //使用药酒时间,计算长时间没使用药酒 20080623 n_Reserved: Word; //当前酒量值 20080622 n_Reserved1: Word; //酒量上限 20080622 n_Reserved2: Word; //当前醉酒度 20080623 n_Reserved3: Word; //药力值等级 20080623 boReserved: Boolean; //是否请过酒 T-请过酒 boReserved1: Boolean;//是否有卧龙英雄 20080519 boReserved2: Boolean;//是否酿酒 T-正在酿酒 20080620 boReserved3: Boolean;//人是否喝酒醉了 20080627 m_GiveDate:Integer;//人物领取行会酒泉日期 20080625 Exp68: LongWord;//酒气护体当前经验 20080625 MaxExp68: LongWord;//酒气护体升级经验 20080625 nExpSkill69: Integer;//内功当前经验 20080930 HumNGMagics: THumNGMagics;//内功技能 20081001 m_nReserved1: Word;//保留 m_nReserved2: Word;//保留 m_nReserved3: Word;//保留 m_nReserved4: LongWord;//保留 m_nReserved5: LongWord;//保留 m_nReserved6: Integer;//保留 m_nReserved7: Integer;//保留 end; THumDataInfo1014 = packed record Header: TRecordHeader; Data: THumData1014; end; //----------------------------------------------------------------------------- THumData1107 = packed record //人物数据类 Size = 4286 预留N个变量 1107 sChrName: string[ACTORNAMELEN];//姓名 sCurMap: string[MAPNAMELEN];//地图 wCurX: Word; //坐标X wCurY: Word; //坐标Y btDir: Byte; //方向 btHair: Byte;//头发 btSex: Byte; //性别 btJob: Byte;//职业 0-战 1-法 2-道 3-刺客 nGold: Integer;//金币数 Abil: TOAbility;//+40 人物其它属性 wStatusTimeArr: TStatusTime; //+24 人物状态属性值,一般是持续多少秒 sHomeMap: string[MAPNAMELEN];//Home 家 btUnKnow1: Byte;//(20080404 未使用) wHomeX: Word;//Home X wHomeY: Word;//Home Y sDearName: string[ACTORNAMELEN]; //别名(配偶) sMasterName: string[ACTORNAMELEN];//师傅名字 boMaster: Boolean;//是否有徒弟 btCreditPoint: Integer;//声望点 20080118 btDivorce: Byte; //是否结婚 btMarryCount: Byte; //结婚次数 sStoragePwd: string[7];//仓库密码 btReLevel: Byte;//转生等级 btUnKnow2: array[0..2] of Byte;//0-是否开通元宝寄售(1-开通) 1-是否寄存英雄(1-存有英雄) 2-饮酒时酒的品质 BonusAbil: TNakedAbility; //+20 奖金 nBonusPoint: Integer;//奖励点 nGameGold: Integer;//游戏币 nGameDiaMond: Integer;//金刚石 20071226 nGameGird:Integer;//灵符 20071226 nGamePoint: Integer;//声望 btGameGlory: Byte; //荣誉 20080511 nPayMentPoint: Integer; //充值点 nLoyal: Integer;//英雄的忠诚度(20080109) nPKPOINT: Integer;//PK点数 btAllowGroup: Byte;//允许组队 btF9: Byte; btAttatckMode: Byte;//攻击模式 btIncHealth: Byte;//增加健康数 btIncSpell: Byte;//增加攻击点 btIncHealing: Byte;//增加治愈点 btFightZoneDieCount: Byte;//在行会占争地图中死亡次数 sAccount: string[10];//登录帐号 btEE: Byte;//未使用 btEF: Byte;//英雄类型 0-白日门英雄 1-卧龙英雄 20080514 boLockLogon: Boolean;//是否锁定登陆 wContribution: Word;//贡献值 nHungerStatus: Integer;//饥饿状态 boAllowGuildReCall: Boolean; // 是否允许行会合一 wGroupRcallTime: Word; //队传送时间 dBodyLuck: Double; //幸运度 8 boAllowGroupReCall: Boolean; // 是否允许天地合一 nEXPRATE: Integer; //经验倍数 nExpTime: Integer; //经验倍数时间 btLastOutStatus: Byte; //退出状态 1为死亡退出 wMasterCount: Word; //出师徒弟数 boHasHero: Boolean; //是否有白日门英雄 boIsHero: Boolean; //是否是英雄 btStatus: Byte; //状态 sHeroChrName: string[ACTORNAMELEN];//英雄名称 UnKnow: TUnKnow;//预留 array[0..39] of Byte; 0-3酿酒使用 20080620 4-饮酒时的度数 5-魔法盾等级 6-是否学过内功 7-内功等级 QuestFlag: TQuestFlag; //脚本变量 HumItems: THumItems; //9格装备 衣服 武器 蜡烛 头盔 项链 手镯 手镯 戒指 戒指 BagItems: TBagItems; //包裹装备 HumMagics: THumMagic; //魔法 StorageItems: TStorageItems; //仓库物品 HumAddItems: THumAddItems; //新增4格 护身符 腰带 鞋子 宝石 n_WinExp: longWord;//累计经验 20081001 n_UsesItemTick: Integer;//聚灵珠聚集时间 20080221 nReserved: Integer; //酿酒的时间,即还有多长时间可以取回酒 20080620 nReserved1: Integer; //当前药力值 20080623 nReserved2: Integer; //药力值上限 20080623 nReserved3: Integer; //使用药酒时间,计算长时间没使用药酒 20080623 n_Reserved: Word; //当前酒量值 20080622 n_Reserved1: Word; //酒量上限 20080622 n_Reserved2: Word; //当前醉酒度 20080623 n_Reserved3: Word; //药力值等级 20080623 boReserved: Boolean; //是否请过酒 T-请过酒 boReserved1: Boolean;//是否有卧龙英雄 20080519 boReserved2: Boolean;//是否酿酒 T-正在酿酒 20080620 boReserved3: Boolean;//人是否喝酒醉了 20080627 m_GiveDate:Integer;//人物领取行会酒泉日期 20080625 Exp68: LongWord;//酒气护体当前经验 20080625 MaxExp68: LongWord;//酒气护体升级经验 20080625 nExpSkill69: Integer;//内功当前经验 20080930 HumNGMagics: THumNGMagics;//内功技能 20081001 m_nReserved1: Word;//保留 m_nReserved2: Word;//保留 m_nReserved3: Word;//保留 m_nReserved4: LongWord;//保留 m_nReserved5: LongWord;//保留 m_nReserved6: Integer;//保留 m_nReserved7: Integer;//保留 end; THumDataInfo1107 = packed record //Size 4126 Header: TRecordHeader; Data: THumData1107; end; //----------------------------------------------------------------------------- THumData1219 = packed record //人物数据类 Size = 4286 预留N个变量 1219 sChrName: string[ACTORNAMELEN];//姓名 sCurMap: string[MAPNAMELEN];//地图 wCurX: Word; //坐标X wCurY: Word; //坐标Y btDir: Byte; //方向 btHair: Byte;//头发 btSex: Byte; //性别 btJob: Byte;//职业 0-战 1-法 2-道 3-刺客 nGold: Integer;//金币数 Abil: TOAbility;//+40 人物其它属性 wStatusTimeArr: TStatusTime; //+24 人物状态属性值,一般是持续多少秒 sHomeMap: string[MAPNAMELEN];//Home 家 btUnKnow1: Byte;//(20080404 未使用) wHomeX: Word;//Home X wHomeY: Word;//Home Y sDearName: string[ACTORNAMELEN]; //别名(配偶) sMasterName: string[ACTORNAMELEN];//师傅名字 boMaster: Boolean;//是否有徒弟 btCreditPoint: Integer;//声望点 20080118 btDivorce: Byte; //是否结婚 btMarryCount: Byte; //结婚次数 sStoragePwd: string[7];//仓库密码 btReLevel: Byte;//转生等级 btUnKnow2: array[0..2] of Byte;//0-是否开通元宝寄售(1-开通) 1-是否寄存英雄(1-存有英雄) 2-饮酒时酒的品质 BonusAbil: TNakedAbility; //+20 奖金 nBonusPoint: Integer;//奖励点 nGameGold: Integer;//游戏币 nGameDiaMond: Integer;//金刚石 20071226 nGameGird:Integer;//灵符 20071226 nGamePoint: Integer;//声望 btGameGlory: Byte; //荣誉 20080511 nPayMentPoint: Integer; //充值点 nLoyal: Integer;//英雄的忠诚度(20080109) nPKPOINT: Integer;//PK点数 btAllowGroup: Byte;//允许组队 btF9: Byte; btAttatckMode: Byte;//攻击模式 btIncHealth: Byte;//增加健康数 btIncSpell: Byte;//增加攻击点 btIncHealing: Byte;//增加治愈点 btFightZoneDieCount: Byte;//在行会占争地图中死亡次数 sAccount: string[10];//登录帐号 btEE: Byte;//未使用 btEF: Byte;//英雄类型 0-白日门英雄 1-卧龙英雄 20080514 boLockLogon: Boolean;//是否锁定登陆 wContribution: Word;//贡献值 nHungerStatus: Integer;//饥饿状态 boAllowGuildReCall: Boolean; // 是否允许行会合一 wGroupRcallTime: Word; //队传送时间 dBodyLuck: Double; //幸运度 8 boAllowGroupReCall: Boolean; // 是否允许天地合一 nEXPRATE: Integer; //经验倍数 nExpTime: Integer; //经验倍数时间 btLastOutStatus: Byte; //退出状态 1为死亡退出 wMasterCount: Word; //出师徒弟数 boHasHero: Boolean; //是否有白日门英雄 boIsHero: Boolean; //是否是英雄 btStatus: Byte; //状态 sHeroChrName: string[ACTORNAMELEN];//英雄名称 UnKnow: TUnKnow;//预留 array[0..39] of Byte; 0-3酿酒使用 20080620 4-饮酒时的度数 5-魔法盾等级 6-是否学过内功 7-内功等级 QuestFlag: TQuestFlag; //脚本变量 HumItems: THumItems; //9格装备 衣服 武器 蜡烛 头盔 项链 手镯 手镯 戒指 戒指 BagItems: TBagItems; //包裹装备 HumMagics: THumMagic; //魔法 StorageItems: TStorageItems; //仓库物品 HumAddItems: THumAddItems; //新增4格 护身符 腰带 鞋子 宝石 n_WinExp: longWord;//累计经验 20081001 n_UsesItemTick: Integer;//聚灵珠聚集时间 20080221 nReserved: Integer; //酿酒的时间,即还有多长时间可以取回酒 20080620 nReserved1: Integer; //当前药力值 20080623 nReserved2: Integer; //药力值上限 20080623 nReserved3: Integer; //使用药酒时间,计算长时间没使用药酒 20080623 n_Reserved: Word; //当前酒量值 20080622 n_Reserved1: Word; //酒量上限 20080622 n_Reserved2: Word; //当前醉酒度 20080623 n_Reserved3: Word; //药力值等级 20080623 boReserved: Boolean; //是否请过酒 T-请过酒 boReserved1: Boolean;//是否有卧龙英雄 20080519 boReserved2: Boolean;//是否酿酒 T-正在酿酒 20080620 boReserved3: Boolean;//人是否喝酒醉了 20080627 m_GiveDate:Integer;//人物领取行会酒泉日期 20080625 Exp68: LongWord;//酒气护体当前经验 20080625 MaxExp68: LongWord;//酒气护体升级经验 20080625 nExpSkill69: Integer;//内功当前经验 20080930 HumNGMagics: THumNGMagics;//内功技能 20081001 m_nReserved1: Word;//保留 m_nReserved2: Word;//保留 m_nReserved3: Word;//保留 m_nReserved4: LongWord;//保留 m_nReserved5: LongWord;//保留 m_nReserved6: Integer;//保留 m_nReserved7: Integer;//保留 end; THumDataInfo1219 = packed record //Size 4126 Header: TRecordHeader; Data: THumData1219; end; //----------------------------------------------------------------------------- //用户注册信息,即ID账号 TUserEntry = packed record sAccount: string[10];//账号 sPassword: string[10]; //密码 sUserName: string[20];//用户名 sSSNo: string[14]; //身份证 sPhone: string[14]; sQuiz: string[20]; sAnswer: string[12]; sEMail: string[40]; //邮箱 end; TUserEntryAdd = packed record sQuiz2: string[20]; sAnswer2: string[12]; sBirthDay: string[10]; sMobilePhone: string[13]; sMemo: string[20]; sMemo2: string[20]; end; //账号记录头 size 32 TIDRecordHeader = packed record boDeleted: Boolean;//是否删除 bt1: Byte; bt2: Byte; bt3: Byte; CreateDate: TDateTime; //创建时间 UpdateDate: TDateTime; //最后登录时间 sAccount: string[11]; //账号 end; TAccountDBRecord = packed record //size 328 Header: TIDRecordHeader; UserEntry: TUserEntry; //ID账号信息 UserEntryAdd: TUserEntryAdd; nErrorCount: Integer; dwActionTick: LongWord; N: array[0..38] of Byte; end; const DBFileDesc = '清客网络数据库文件 2008/12/27'; function GetFirstChar(const AHzStr: string): string; function GetWWIndex(const S: string): Integer; function _Max14ReName(S: string; DefChar: Char): string; function _Max10ReName(S: string; DefChar: Char): string; implementation function GetFirstChar(const AHzStr: string): string; const ChinaCode: array[0..25, 0..1] of Integer = ((1601, 1636), (1637, 1832), (1833, 2077), (2078, 2273), (2274, 2301), (2302, 2432), (2433, 2593), (2594, 2786), (9999, 0000), (2787, 3105), (3106, 3211), (3212, 3471), (3472, 3634), (3635, 3722), (3723, 3729), (3730, 3857), (3858, 4026), (4027, 4085), (4086, 4389), (4390, 4557), (9999, 0000), (9999, 0000), (4558, 4683), (4684, 4924), (4925, 5248), (5249, 5589)); var i, j, HzOrd: Integer; begin i := 1; while i <= Length(AHzStr) do begin if (AHzStr[i] >= #160) and (AHzStr[i + 1] >= #160) then begin HzOrd := (Ord(AHzStr[i]) - 160) * 100 + Ord(AHzStr[i + 1]) - 160; for j := 0 to 25 do begin if (HzOrd >= ChinaCode[j][0]) and (HzOrd <= ChinaCode[j][1]) then begin Result := Result + Char(Byte('A') + j); Break; end; end; Inc(i); end else Result := Result + AHzStr[i]; Inc(i); end; Result := UpperCase(Result); end; function GetWWIndex(const S: string): Integer; var Str2: string; begin Str2 := GetFirstChar(S); Result := High(TListArray); if Str2 <> '' then begin Result := Ord(Str2[1]); if Result < 65 then Result := Result - 47 + 90; end; if Result > High(TListArray) - 1 then Result := High(TListArray); end; function _Max14ReName(S: string; DefChar: Char): string; begin if Length(S) >= 14 then begin case ByteType(S, Length(S)) of mbSingleByte: S := Copy(S, 1, Length(S) - 1); mbLeadByte, mbTrailByte : S := Copy(S, 1, Length(S) - 2); end; end; Result := S + DefChar; end; function _Max10ReName(S: string; DefChar: Char): string; begin if Length(S) >= 10 then begin case ByteType(S, Length(S)) of mbSingleByte: S := Copy(S, 1, Length(S) - 1); mbLeadByte, mbTrailByte : S := Copy(S, 1, Length(S) - 2); end; end; Result := S + DefChar; end; end.
unit MulOpFhtTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, Math, TestHelper, uEnums, uIntXLibTypes, uIntX; type { TTestMulOpFht } TTestMulOpFht = class(TTestCase) private F_length: integer; const StartLength = integer(256); LengthIncrement = integer(101); RepeatCount = integer(10); RandomStartLength = integer(256); RandomEndLength = integer(1000); RandomRepeatCount = integer(50); published procedure CompareWithClassic(); procedure SmallLargeCompareWithClassic(); procedure CompareWithClassicRandom(); private function GetAllOneDigits(mlength: integer): TIntXLibUInt32Array; function GetRandomDigits(mlength: integer): TIntXLibUInt32Array; overload; function GetRandomDigits(): TIntXLibUInt32Array; overload; procedure Inner(); procedure InnerTwo(); protected procedure SetUp; override; end; implementation procedure TTestMulOpFht.CompareWithClassic(); begin TTestHelper.Repeater(RepeatCount, @Inner); end; procedure TTestMulOpFht.SmallLargeCompareWithClassic(); var x, y, classic, fht: TIntX; begin x := TIntX.Create(GetAllOneDigits(50000), False); y := TIntX.Create(GetAllOneDigits(512), False); classic := TIntX.Multiply(x, y, TMultiplyMode.mmClassic); fht := TIntX.Multiply(x, y, TMultiplyMode.mmAutoFht); AssertTrue(classic = fht); end; procedure TTestMulOpFht.CompareWithClassicRandom(); begin TTestHelper.Repeater(RandomRepeatCount, @InnerTwo); end; function TTestMulOpFht.GetAllOneDigits(mlength: integer): TIntXLibUInt32Array; var i: integer; begin SetLength(Result, mlength); for i := 0 to Pred(Length(Result)) do begin Result[i] := $7F7F7F7F; end; end; function TTestMulOpFht.GetRandomDigits(mlength: integer): TIntXLibUInt32Array; var i: integer; begin SetLength(Result, mlength); for i := 0 to Pred(Length(Result)) do begin Result[i] := UInt32(Random(RandomEndLength) + 1) * UInt32(2); end; end; function TTestMulOpFht.GetRandomDigits: TIntXLibUInt32Array; begin Result := GetRandomDigits(RandomRange(RandomStartLength, RandomEndLength)); end; procedure TTestMulOpFht.Inner(); var x, classic, fht: TIntX; begin x := TIntX.Create(GetAllOneDigits(F_length), True); classic := TIntX.Multiply(x, x, TMultiplyMode.mmClassic); fht := TIntX.Multiply(x, x, TMultiplyMode.mmAutoFht); AssertTrue(classic = fht); F_length := F_length + LengthIncrement; end; procedure TTestMulOpFht.InnerTwo(); var x, classic, fht: TIntX; begin x := TIntX.Create(GetRandomDigits(), False); classic := TIntX.Multiply(x, x, TMultiplyMode.mmClassic); fht := TIntX.Multiply(x, x, TMultiplyMode.mmAutoFht); AssertTrue(classic = fht); end; procedure TTestMulOpFht.SetUp; begin inherited SetUp; F_length := StartLength; Randomize; end; initialization RegisterTest(TTestMulOpFht); end.
unit XLSVarStack2; {- ******************************************************************************** ******* XLSReadWriteII V3.00 ******* ******* ******* ******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$H+} {$R-} {$I XLSRWII2.inc} interface uses SysUtils, Classes, Math, BIFFRecsII2, ExcelFuncII2, XLSUtils2, XLSReadWriteII2, Cell2; type TVarStack = class(TObject) private FStack: array of TFormulaValue; FStackPtr: integer; protected FXLS: TXLSReadWriteII2; FSheetIndex: integer; public constructor Create(XLS: TXLSReadWriteII2; SheetIndex: integer); destructor Destroy; override; procedure IncStack; procedure Push; overload; procedure Push(Value: TFormulaValue); overload; procedure Push(Value: WideString); overload; procedure Push(Value: double); overload; procedure Push(Value: boolean); overload; procedure Push(Value: TCellError); overload; procedure PushRef(Col,Row: word); procedure PushArea(Col1,Row1,Col2,Row2: word); procedure PushXRef(Col,Row,Sheet: word); procedure PushXArea(Col1,Row1,Col2,Row2,Sheet: word); function Pop: TFormulaValue; function Peek: TFormulaValue; procedure Operator(Op: Byte); end; implementation { TVarStack } constructor TVarStack.Create(XLS: TXLSReadWriteII2; SheetIndex: integer); begin FXLS := XLS; FSheetIndex := SheetIndex; SetLength(FStack,32); FStackPtr := -1; end; destructor TVarStack.Destroy; begin SetLength(FStack,0); inherited; end; procedure TVarStack.Operator(Op: Byte); var F1,F2: double; FV1,FV2: TFormulaValue; FVResult: TFormulaValue; V: integer; function GetValue(FV: TFormulaValue): TFormulaValue; begin case FV.ValType of fvRef : Result := FXLS.Sheets[FSheetIndex].FVRefToFV(FV); fvExtRef: Result := FXLS.Sheets[FV.vExtRef[2]].FVRefToFV(FV); else Result := FV; end; end; function GetFloatValue(FV: TFormulaValue): double; var S: string; begin Result := 0; case FV.ValType of fvFloat: Result := FV.vFloat; fvBoolean: Result := Integer(FV.vBoolean); fvError: FVResult := FV; fvString: begin {$ifdef DELPHI_6_OR_LATER} if not TextToFloat(PChar(S),Result,fvExtended) then FVSetError(FVResult,errValue); {$else} try Result := StrToFloat(FV.vString); except FVSetError(FVResult,errValue); end; {$endif} end; fvArea: FVSetError(FVResult,errValue); fvExtArea: FVSetError(FVResult,errValue); fvNull: Result := 0; end; end; function GetStrValue(FV: TFormulaValue): WideString; begin case FV.ValType of fvFloat: Result := FloatToStr(FV.vFloat); fvError: Result := CellErrorNames[Integer(FV.vError)]; fvBoolean: begin if FV.vBoolean then Result := FXLS.StrTRUE else Result := FXLS.StrFALSE; end; else Result := FVGetString(FV); end; end; begin if FStackPtr < 0 then raise Exception.Create('Value is missing'); FVSetNull(FVResult); F1 := 0; F2 := 0; if OP in [ptgAdd..ptgConcat,ptgLT..ptgNE,ptgUPlus,ptgUMinus,ptgPercent] then begin FV1 := GetValue(FStack[FStackPtr]); F1 := GetFloatValue(FV1); if (FVResult.ValType <> fvError) and (not (Op in [ptgUPlus,ptgUMinus,ptgPercent])) then begin FV2 := GetValue(FStack[FStackPtr - 1]); F2 := GetFloatValue(FV2); end; end; if FVResult.ValType <> fvError then begin case Op of ptgAdd: FVSetFloat(FVResult,F2 + F1); ptgSub: FVSetFloat(FVResult,F2 - F1); ptgMul: FVSetFloat(FVResult,F2 * F1); ptgDiv: begin if F1 = 0 then FVSetError(FVResult,errDiv0) else FVSetFloat(FVResult,F2 / F1); end; ptgPower: FVSetFloat(FVResult,Power(F2,F1)); ptgUPlus: FVSetFloat(FVResult,F1); ptgUMinus: FVSetFloat(FVResult,-F1); // This is probably not correct... ptgUnion: FVSetString(FVResult,GetStrValue(FV1)); { ptgPercent: UnaryOperator('%'); } ptgConcat: FVSetString(FVResult,GetStrValue(FV2) + GetStrValue(FV1)); else begin if (FV1.ValType in [fvString,fvNull]) or (FV2.ValType in [fvString,fvNull]) then begin {$ifdef OLD_COMPILER} V := AnsiCompareStr(AnsiUppercase(GetStrValue(FV1)),AnsiUppercase(GetStrValue(FV2))); {$else} V := WideCompareStr(MyWideUppercase(GetStrValue(FV1)),MyWideUppercase(GetStrValue(FV2))); {$endif} case Op of ptgLT: FVSetBoolean(FVResult,V < 0); ptgLE: FVSetBoolean(FVResult,V <= 0); ptgEQ: FVSetBoolean(FVResult,V = 0); ptgGE: FVSetBoolean(FVResult,V >= 0); ptgGT: FVSetBoolean(FVResult,V > 0); ptgNE: FVSetBoolean(FVResult,V <> 0); end; end else begin if FVResult.ValType <> fvError then begin case Op of ptgLT: FVSetBoolean(FVResult,F2 < F1); ptgLE: FVSetBoolean(FVResult,F2 <= F1); ptgEQ: FVSetBoolean(FVResult,F2 = F1); ptgGE: FVSetBoolean(FVResult,F2 >= F1); ptgGT: FVSetBoolean(FVResult,F2 > F1); ptgNE: FVSetBoolean(FVResult,F2 <> F1); end; end; end; end; end; end; if not (Op in [ptgUPlus,ptgUMinus,ptgPercent]) then Dec(FStackPtr); FStack[FStackPtr] := FVResult; end; function TVarStack.Pop: TFormulaValue; begin if FStackPtr < 0 then raise Exception.Create('Empty stack'); Result := FStack[FStackPtr]; Dec(FStackPtr); end; function TVarStack.Peek: TFormulaValue; begin if FStackPtr < 0 then raise Exception.Create('Empty stack'); Result := FStack[FStackPtr]; end; procedure TVarStack.IncStack; begin Inc(FStackPtr); if FStackPtr >= High(FStack) then SetLength(FStack,Length(FStack) + 32); end; procedure TVarStack.Push(Value: TFormulaValue); begin IncStack; FStack[FStackPtr] := Value; end; procedure TVarStack.Push(Value: double); begin IncStack; FVSetFloat(FStack[FStackPtr],Value); end; procedure TVarStack.Push(Value: WideString); begin IncStack; FVSetString(FStack[FStackPtr],Value); end; procedure TVarStack.Push(Value: boolean); begin IncStack; FVSetBoolean(FStack[FStackPtr],Value); end; procedure TVarStack.Push(Value: TCellError); begin IncStack; FVSetError(FStack[FStackPtr],Value); end; procedure TVarStack.PushArea(Col1, Row1, Col2, Row2: word); begin IncStack; FVSetArea(FStack[FStackPtr],Col1, Row1, Col2, Row2); end; procedure TVarStack.PushRef(Col, Row: word); begin IncStack; FVSetRef(FStack[FStackPtr],Col, Row); end; procedure TVarStack.PushXArea(Col1, Row1, Col2, Row2, Sheet: word); begin IncStack; FVSetXArea(FStack[FStackPtr],Col1, Row1, Col2, Row2, Sheet); end; procedure TVarStack.PushXRef(Col, Row, Sheet: word); begin IncStack; FVSetXRef(FStack[FStackPtr],Col, Row, Sheet); end; procedure TVarStack.Push; begin IncStack; FVSetNull(FStack[FStackPtr]); end; end.
unit EST0001C.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CadastroBase.View, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, cxControls, cxContainer, cxEdit, cxLabel, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, Base.View.Interf, Tipos.Controller.Interf, Produto.Controller.Interf, cxTextEdit, cxMemo, dxGDIPlusClasses, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver; type TFEST0001CView = class(TFCadastroView, IBaseCadastroView) TeCodigoSinapi: TcxTextEdit; TeUnidMedida: TcxTextEdit; TePrMedioSinapi: TcxTextEdit; cxLabel2: TcxLabel; cxLabel3: TcxLabel; cxLabel4: TcxLabel; cxLabel5: TcxLabel; cxLabel6: TcxLabel; TeIdProduto: TcxTextEdit; TeOrigemPreco: TcxTextEdit; cxLabel7: TcxLabel; TeDescricao: TcxMemo; cxLabel8: TcxLabel; TePrecoMedio: TcxTextEdit; procedure FormCreate(Sender: TObject); procedure BtSalvarClick(Sender: TObject); procedure TeCodigoSinapiKeyPress(Sender: TObject; var Key: Char); private FProduto: IProdutoController; FRegistro: string; procedure salvarDados; procedure exibirDadosNaTela; procedure desabilitaCampos; public { Public declarations } class function New: IBaseCadastroView; function operacao(AValue: TTipoOperacao): IBaseCadastroView; function registroSelecionado(AValue: string): IBaseCadastroView; procedure &executar; end; var FEST0001CView: TFEST0001CView; implementation {$R *.dfm} uses FacadeController; { TFEST0001CView } procedure TFEST0001CView.BtSalvarClick(Sender: TObject); begin salvarDados; inherited; end; procedure TFEST0001CView.desabilitaCampos; begin if FOperacao in [toConsultar, toExcluir] then begin TeCodigoSinapi.Enabled := False; TeDescricao.Enabled := False; TeUnidMedida.Enabled := False; TeOrigemPreco.Enabled := False; TePrecoMedio.Enabled := False; TePrMedioSinapi.Enabled := False; end; end; procedure TFEST0001CView.executar; begin exibirDadosNaTela; desabilitaCampos; exibirTituloOperacao(FOperacao); ShowModal; end; procedure TFEST0001CView.exibirDadosNaTela; begin if FOperacao = toIncluir then Exit; FProduto.localizar(FRegistro); TeIdProduto.Text := FProduto.idProduto; TeCodigoSinapi.Text := FProduto.codigoSinapi; TeDescricao.Text := FProduto.descricao; TeUnidMedida.Text := FProduto.unidMedida; TeOrigemPreco.Text := FProduto.origemPreco; TePrecoMedio.Text := FProduto.prMedio; TePrMedioSinapi.Text := FProduto.prMedioSinapi; end; procedure TFEST0001CView.FormCreate(Sender: TObject); begin inherited; FProduto := TFacadeController.New .modulosFacadeController .estoqueFactoryController .Produto end; class function TFEST0001CView.New: IBaseCadastroView; begin Result := Self.Create(nil); end; function TFEST0001CView.operacao(AValue: TTipoOperacao): IBaseCadastroView; begin Result := Self; FOperacao := AValue; end; function TFEST0001CView.registroSelecionado(AValue: string): IBaseCadastroView; begin Result := Self; FRegistro := AValue; end; procedure TFEST0001CView.salvarDados; begin case FOperacao of toIncluir: begin FProduto .Incluir .codigoSinapi(TeCodigoSinapi.Text) .descricao(TeDescricao.Text) .unidMedida(TeUnidMedida.Text) .origemPreco(TeOrigemPreco.Text) .prMedio(TePrecoMedio.Text) .prMedioSinapi(TePrMedioSinapi.Text) .finalizar; end; toAlterar: begin FProduto .Alterar .codigoSinapi(TeCodigoSinapi.Text) .descricao(TeDescricao.Text) .unidMedida(TeUnidMedida.Text) .origemPreco(TeOrigemPreco.Text) .prMedio(TePrecoMedio.Text) .prMedioSinapi(TePrMedioSinapi.Text) .finalizar; end; toConsultar: ; toExcluir: begin FProduto .Excluir .finalizar; end; toDuplicar: begin FProduto .Duplicar .codigoSinapi(TeCodigoSinapi.Text) .descricao(TeDescricao.Text) .unidMedida(TeUnidMedida.Text) .origemPreco(TeOrigemPreco.Text) .prMedio(TePrecoMedio.Text) .prMedioSinapi(TePrMedioSinapi.Text) .finalizar; end; end; end; procedure TFEST0001CView.TeCodigoSinapiKeyPress(Sender: TObject; var Key: Char); begin inherited; if not (CharInSet(Key,['0'..'9', #8])) then key := #0; end; end.
unit UniqueInstance; { UniqueInstance is a component to allow only a instance by program Copyright (C) 2006 Luiz Americo Pereira Camara pascalive@bol.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. } {$mode objfpc}{$H+} interface uses {$ifdef unix} process, math, { TODO : can be removed if using fpc 2.5.1 or heigher } // http://bugs.freepascal.org/view.php?id=15219 // solved by fpc 2.5.1 cdcsimpleipc, {$else} simpleipc, {$endif} Forms, Classes, SysUtils, ExtCtrls; type TOnOtherInstance = procedure (Sender : TObject; ParamCount: Integer; Parameters: array of String) of object; { TUniqueInstance } TUniqueInstance = class(TComponent) private FEnabled: Boolean; FIdentifier: String; FIPCServer: TSimpleIPCServer; FIPCClient: TSimpleIPCClient; FOnOtherInstance: TOnOtherInstance; FOnInstanceRunning: TNotifyEvent; {$ifdef unix} FTimer: TTimer; {$endif} FUpdateInterval: Cardinal; function GetServerId: String; procedure ReceiveMessage(Sender: TObject); procedure SetUpdateInterval(const AValue: Cardinal); {$ifdef unix} procedure CheckMessage(Sender: TObject); {$endif} protected procedure Loaded; override; public constructor Create(AOwner: TComponent); override; published property Enabled: Boolean read FEnabled write FEnabled; property Identifier: String read FIdentifier write FIdentifier; property UpdateInterval: Cardinal read FUpdateInterval write SetUpdateInterval; property OnOtherInstance: TOnOtherInstance read FOnOtherInstance write FOnOtherInstance; property OnInstanceRunning: TNotifyEvent read FOnInstanceRunning write FOnInstanceRunning; end; { TCdCUniqueInstance } TCdCUniqueInstance = class(TUniqueInstance) private retrycount: integer; {$ifdef unix} Process1: TProcess; function GetPid:string; function OtherRunning:boolean; procedure DeleteLock; {$endif} public constructor Create(AOwner: TComponent); override; procedure RetryOrHalt; procedure Loaded; override; end; implementation uses StrUtils; const BaseServerId = 'tuniqueinstance_'; Separator = '|'; { TUniqueInstance } procedure TUniqueInstance.ReceiveMessage(Sender: TObject); var TempArray: array of String; Count,i: Integer; procedure GetParams(const AStr: String); var pos1,pos2:Integer; begin SetLength(TempArray, Count); //fill params i := 0; pos1:=1; pos2:=pos(Separator, AStr); while pos1 < pos2 do begin TempArray[i] := Copy(AStr, pos1, pos2 - pos1); pos1 := pos2+1; pos2 := posex(Separator, AStr, pos1); inc(i); end; end; begin if Assigned(FOnOtherInstance) then begin //MsgType stores ParamCount Count := FIPCServer.MsgType; GetParams(FIPCServer.StringMessage); FOnOtherInstance(Self, Count, TempArray); SetLength(TempArray, 0); end; end; {$ifdef unix} procedure TUniqueInstance.CheckMessage(Sender: TObject); begin FIPCServer.PeekMessage(1, True); end; {$endif} procedure TUniqueInstance.SetUpdateInterval(const AValue: Cardinal); begin if FUpdateInterval = AValue then Exit; FUpdateInterval := AValue; {$ifdef unix} FTimer.Interval := AValue; {$endif} end; function TUniqueInstance.GetServerId: String; begin if FIdentifier <> '' then Result := BaseServerId + FIdentifier else Result := BaseServerId + ExtractFileName(ParamStr(0)); end; procedure TUniqueInstance.Loaded; var TempStr: String; i: Integer; begin try if not (csDesigning in ComponentState) and FEnabled then begin FIPCClient.ServerId := GetServerId; if FIPCClient.ServerRunning then begin //A instance is already running //Send a message and then exit if Assigned(FOnOtherInstance) then begin TempStr := ''; for i := 1 to ParamCount do TempStr := TempStr + ParamStr(i) + Separator; FIPCClient.Active := True; FIPCClient.SendStringMessage(ParamCount, TempStr); end; if Assigned(FOnInstanceRunning) then FOnInstanceRunning(self) else begin Application.ShowMainForm := False; Application.Terminate; end; end else begin //It's the first instance. Init the server if FIPCServer = nil then FIPCServer := TSimpleIPCServer.Create(Self); with FIPCServer do begin ServerID := FIPCClient.ServerId; Global := True; OnMessage := @ReceiveMessage; StartServer; end; //there's no more need for FIPCClient FIPCClient.Free; {$ifdef unix} if Assigned(FOnOtherInstance) then FTimer.Enabled := True; {$endif} end; end;//if inherited; except halt(1); end; end; constructor TUniqueInstance.Create(AOwner: TComponent); begin inherited Create(AOwner); FIPCClient := TSimpleIPCClient.Create(Self); FUpdateInterval := 1000; {$ifdef unix} FTimer := TTimer.Create(Self); FTimer.Enabled := false; FTimer.OnTimer := @CheckMessage; {$endif} end; ////////////// TCdCUniqueInstance //////////////////// constructor TCdCUniqueInstance.Create(AOwner: TComponent); begin inherited Create(AOwner); retrycount:=0; end; procedure TCdCUniqueInstance.Loaded; begin {$ifdef unix} if not OtherRunning then DeleteLock; {$endif} inherited; end; Procedure TCdCUniqueInstance.RetryOrHalt; begin {$ifdef unix} inc(retrycount); if retrycount<=1 then begin if OtherRunning then Halt(1) else begin DeleteLock; Loaded; end; end; {$else} Halt(1); {$endif} end; {$ifdef unix} procedure TCdCUniqueInstance.DeleteLock; var D : String; begin D:='/tmp/'; // See fcl-process/src/unix/simpleipc.inc TPipeServerComm.Create DeleteFile(D+GetServerId); end; function TCdCUniqueInstance.GetPid:string; var i: integer; s: array[0..1024] of char; begin result:=''; try Process1:=TProcess.Create(nil); FillChar(s,sizeof(s),' '); {$ifdef darwin} {$IF (FPC_VERSION = 2) and (FPC_RELEASE < 5)} Process1.CommandLine:='killall -s '+ExtractFileName(Application.ExeName); {$ELSE} Process1.Executable:='killall'; Process1.Parameters.Add('-s'); Process1.Parameters.Add(ExtractFileName(Application.ExeName)); {$ENDIF} {$ELSE} {$IF (FPC_VERSION = 2) and (FPC_RELEASE < 5)} Process1.CommandLine:='pidof '+ExtractFileName(Application.ExeName); {$ELSE} Process1.Executable:='pidof'; Process1.Parameters.Add(ExtractFileName(Application.ExeName)); {$ENDIF} {$endif} Process1.Options:=[poWaitOnExit,poUsePipes,poNoConsole]; Process1.Execute; if Process1.ExitStatus=0 then begin i:=Min(1024,process1.Output.NumBytesAvailable); process1.Output.Read(s,i); result:=Trim(s); end; Process1.Free; except end; end; function TCdCUniqueInstance.OtherRunning:boolean; var i : integer; s:string; const {$ifdef darwin} sep=#10; {$else} sep=' '; {$endif} begin s:=GetPid; i:=pos(sep,s); result:= i>0; end; {$endif} end.
unit uframeEditorHtml; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, SynEditHighlighter, SynHighlighterHtml, System.Actions, Vcl.ActnList, Vcl.ToolWin, System.ImageList, Vcl.ImgList, Vcl.StdCtrls, JvExStdCtrls, JvCheckBox, JvCombobox, JvColorCombo, Vcl.OleCtrls, SHDocVw, SynEdit, Vcl.ExtCtrls, Vcl.Imaging.pngimage, MSHTML, ActiveX; type TWebBrowser = class(SHDocVw.TWebBrowser) //Código para ignorar caracteres acelerados (atalho do Alt + Letra quando utilizando o &) procedure CNChar(var Message: TWMChar); message CN_CHAR; end; type TframeEditorHtml = class(TFrame) tbarFerramentas: TToolBar; dlgColorColor: TColorDialog; aclAcoes: TActionList; acNegrito: TAction; acItalico: TAction; acSublinhado: TAction; acCorFonte: TAction; acListaOrd: TAction; acListaNaoOrd: TAction; acRecuoReduzir: TAction; acRecuoAumentar: TAction; acAlinEsquerda: TAction; acAlinCentro: TAction; acAlinDireita: TAction; acGaleriaImagens: TAction; acBancodeImagens: TAction; acLinhaHorizontal: TAction; acCortar: TAction; acCopiar: TAction; acColar: TAction; acDesfazer: TAction; acHyperlink: TAction; acTabela: TAction; acSalvar: TAction; acPublicar: TAction; synhtmlsynHighLight: TSynHTMLSyn; btnSalvar: TToolButton; btnPublicar: TToolButton; btnSep1: TToolButton; btnNegrito: TToolButton; btnItalico: TToolButton; btnSublinhado: TToolButton; btnCorFonte: TToolButton; btnListaOrd: TToolButton; btnListaNaoOrd: TToolButton; btnRecuoDiminuir: TToolButton; btnRecuoAumentar: TToolButton; btnAlinharEsquerda: TToolButton; btnAlinharCentro: TToolButton; btnAlinharDireita: TToolButton; btnSep2: TToolButton; btnRecortar: TToolButton; btnCopiar: TToolButton; btnColar: TToolButton; btnDesfazer: TToolButton; btnSep3: TToolButton; btnHiperlink: TToolButton; btnTabela: TToolButton; btnSep4: TToolButton; mmHtml: TSynEdit; wbHtml: TWebBrowser; pTop: TPanel; pControles: TPanel; cmbFonte: TJvFontComboBox; cmbFonteTam: TJvComboBox; chbVerCodigo: TJvCheckBox; dlgSaveHtml: TSaveDialog; btnAbrir: TToolButton; acAbrir: TAction; dlgOpenHtml: TOpenDialog; btnRealce: TToolButton; acCorRealce: TAction; acCorFundo: TAction; btnCorFundo: TToolButton; btnLinhaHorizontal: TToolButton; procedure chbVerCodigoClick(Sender: TObject); procedure acNegritoExecute(Sender: TObject); procedure acItalicoExecute(Sender: TObject); procedure acSublinhadoExecute(Sender: TObject); procedure acCorFonteExecute(Sender: TObject); procedure acListaOrdExecute(Sender: TObject); procedure acListaNaoOrdExecute(Sender: TObject); procedure acRecuoReduzirExecute(Sender: TObject); procedure acRecuoAumentarExecute(Sender: TObject); procedure acAlinEsquerdaExecute(Sender: TObject); procedure acAlinCentroExecute(Sender: TObject); procedure acAlinDireitaExecute(Sender: TObject); procedure acGaleriaImagensExecute(Sender: TObject); procedure acBancodeImagensExecute(Sender: TObject); procedure acLinhaHorizontalExecute(Sender: TObject); procedure acCortarExecute(Sender: TObject); procedure acCopiarExecute(Sender: TObject); procedure acColarExecute(Sender: TObject); procedure acDesfazerExecute(Sender: TObject); procedure acHyperlinkExecute(Sender: TObject); procedure acTabelaExecute(Sender: TObject); procedure cmbFonteChange(Sender: TObject); procedure cmbFonteTamChange(Sender: TObject); procedure acSalvarExecute(Sender: TObject); procedure acAbrirExecute(Sender: TObject); procedure acCorRealceExecute(Sender: TObject); procedure acCorFundoExecute(Sender: TObject); procedure wbHtmlCommandStateChange(ASender: TObject; Command: Integer; Enable: WordBool); private HtmlOriginal : TStrings; HtmlModificado : TStrings; ArqAnterior : String; FPodeAlterar : Boolean; FPodeSalvar : Boolean; FOcultarBotoes : Boolean; FPodeAbrir : Boolean; procedure SetPodeAlterar(const Value: Boolean); procedure SetPodeSalvar(const Value: Boolean); procedure AtualizaCodigo; procedure SetOcultarBotoes(const Value: Boolean); procedure SetPodeAbrir(const Value: Boolean); public { Public declarations } procedure CarregaDocumento(CodigoHtml : String); function DocumentoAlterado : Boolean; function RetornaCodigoHtml : String; function SalvarHtml : Boolean; function FocarEditor : Boolean; function ObterImagemClient(Imagem : TImage) : Boolean; property PodeAlterar : Boolean read FPodeAlterar write SetPodeAlterar; property OcultarBotoes : Boolean read FOcultarBotoes write SetOcultarBotoes; //Indica se o documento poderá ser alterado property PodeSalvar : Boolean read FPodeSalvar write SetPodeSalvar; //Indica se poderá salvar o documento em arquivo .html property PodeAbrir : Boolean read FPodeAbrir write SetPodeAbrir; procedure PrevenirNavegacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); end; var HTMLDocumento : IHTMLDocument2; const IDM_MARCADOR = 2184; IDM_MARCADOR_LISTA = 2185; IDM_OUTDENT = 2187; IDM_INDENT = 2186; IDM_ALINHARESQ = 59; IDM_CENTRALIZAR = 57; IDM_ALINHADIR = 60; IDM_IMAGEM = 2168; IDM_LINHAHORIZ = 2150; IDM_RECORTAR = 16; IDM_COPIAR = 15; IDM_COLAR = 26; IDM_HYPERLINK = 2124; IDM_DESFAZER = 43; implementation uses uFuncoes, StrUtils, DateUtils, Math, {MSHTML_TLB,} JPEG, ComObj, udmImagens; {$R *.dfm} function GetIEHandle(WebBrowser: TWebbrowser; ClassName: string): HWND; var hwndChild, hwndTmp: HWND; oleCtrl: TOleControl; szClass: array [0..255] of char; begin oleCtrl :=WebBrowser; hwndTmp := oleCtrl.Handle; while (true) do begin hwndChild := GetWindow(hwndTmp, GW_CHILD); GetClassName(hwndChild, szClass, SizeOf(szClass)); if (string(szClass)=ClassName) then begin Result :=hwndChild; Exit; end; hwndTmp := hwndChild; end; Result := 0; end; procedure DocumentoEmBranco(WebBrowser: TWebBrowser); begin WebBrowser.Navigate('about:blank'); Application.ProcessMessages; end; procedure WebBrowserScreenShot(const wb: TWebBrowser; const fileName: TFileName) ; var viewObject : IViewObject; r : TRect; bitmap : TBitmap; begin if wb.Document <> nil then begin wb.Document.QueryInterface(IViewObject, viewObject) ; if Assigned(viewObject) then try bitmap := TBitmap.Create; try r := Rect(0, 0, wb.Width, wb.Height) ; bitmap.Height := wb.Height; bitmap.Width := wb.Width; viewObject.Draw(DVASPECT_CONTENT, 1, nil, nil, Application.Handle, bitmap.Canvas.Handle, @r, nil, nil, 0) ; with TJPEGImage.Create do try Assign(bitmap) ; SaveToFile(fileName) ; finally Free; end; finally bitmap.Free; end; finally viewObject._Release; end; end; end; procedure TframeEditorHtml.acAbrirExecute(Sender: TObject); var Abrir, Alterar, Salvar, Ocultar : Boolean; begin Abrir := PodeAbrir; Alterar := PodeAlterar; Salvar := PodeSalvar; Ocultar := OcultarBotoes; if not dlgOpenHtml.Execute then Exit; HtmlOriginal.LoadFromFile(dlgOpenHtml.FileName); CarregaDocumento(HtmlOriginal.Text); Application.ProcessMessages; PodeAbrir := Abrir; PodeAlterar := Alterar; PodeSalvar := Salvar; OcultarBotoes := Ocultar; end; procedure TframeEditorHtml.acAlinCentroExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_CENTRALIZAR, 0); end; procedure TframeEditorHtml.acAlinDireitaExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_ALINHADIR, 0); end; procedure TframeEditorHtml.acAlinEsquerdaExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_ALINHARESQ, 0); end; procedure TframeEditorHtml.acBancodeImagensExecute(Sender: TObject); begin MessageBox(Handle,pchar('... em desenvolvimento!'),'Alerta',MB_OK+MB_ICONWARNING); // fConFormCatImagens := TfConFormCatImagens.Create(Self); // fConFormCatImagens.ShowModal; end; procedure TframeEditorHtml.acColarExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_COLAR, 0); end; procedure TframeEditorHtml.acCopiarExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_COPIAR, 0); end; procedure TframeEditorHtml.acCorFonteExecute(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; if dlgColorColor.Execute then HTMLDocumento.execCommand('ForeColor', False,dlgColorColor.Color) else Exit; end; procedure TframeEditorHtml.acCorFundoExecute(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; if dlgColorColor.Execute then //HTMLDocumento.execCommand('Documento.bgColor', False,dlgColorColor.Color) HTMLDocumento.bgColor := dlgColorColor.Color else Exit; end; procedure TframeEditorHtml.acCorRealceExecute(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; if dlgColorColor.Execute then HTMLDocumento.execCommand('BackColor', False, dlgColorColor.Color) else Exit; end; procedure TframeEditorHtml.acCortarExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_RECORTAR, 0); end; procedure TframeEditorHtml.acDesfazerExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_DESFAZER,0); end; procedure TframeEditorHtml.acGaleriaImagensExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_IMAGEM,0); end; procedure TframeEditorHtml.acHyperlinkExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_HYPERLINK,0); end; procedure TframeEditorHtml.acItalicoExecute(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; HTMLDocumento.execCommand('Italic', False,0); end; procedure TframeEditorHtml.acLinhaHorizontalExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_LINHAHORIZ, 0); end; procedure TframeEditorHtml.acListaNaoOrdExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_MARCADOR_LISTA, 0); end; procedure TframeEditorHtml.acListaOrdExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_MARCADOR, 0); end; procedure TframeEditorHtml.acNegritoExecute(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; HTMLDocumento.execCommand('Bold', False,0); end; procedure TframeEditorHtml.acRecuoAumentarExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_INDENT, 0); end; procedure TframeEditorHtml.acRecuoReduzirExecute(Sender: TObject); begin SendMessage(GetIEHandle(wbHtml, 'Internet Explorer_Server'), WM_COMMAND,IDM_OUTDENT, 0); end; procedure TframeEditorHtml.acSalvarExecute(Sender: TObject); begin AtualizaCodigo; if not dlgSaveHtml.Execute then Exit; HtmlModificado.SaveToFile(dlgSaveHtml.FileName); end; procedure TframeEditorHtml.acSublinhadoExecute(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; HTMLDocumento.execCommand('Underline', False,0); end; procedure TframeEditorHtml.acTabelaExecute(Sender: TObject); var tbl : IHTMLTable; begin Exit; HTMLDocumento := wbHtml.Document as IHTMLDocument2; HTMLDocumento.execCommand('Tbody', True, 0); end; procedure TframeEditorHtml.AtualizaCodigo; var doc: OleVariant; begin doc := wbHtml.Document; try mmHtml.Lines.Clear; mmHtml.Lines.Text := doc.documentElement.outerHtml; if HtmlModificado <> nil then HtmlModificado.Text := mmHtml.Lines.Text; except end; Application.ProcessMessages; end; procedure TframeEditorHtml.CarregaDocumento(CodigoHtml: String); var Html : TStrings; Arq : String; begin if HtmlOriginal <> nil then FreeAndNil(HtmlOriginal); if HtmlModificado <> nil then FreeAndNil(HtmlModificado); PodeAlterar := False; PodeAlterar := False; PodeSalvar := True; PodeAbrir := True; OcultarBotoes := False; HtmlOriginal := TStringList.Create; HtmlModificado := TStringList.Create; HtmlOriginal.Text := CodigoHtml; HtmlModificado.Text := CodigoHtml; wbHtml.Stop; DocumentoEmBranco(wbHtml); if CodigoHtml <> '' then begin try if ArqAnterior <> '' then DeleteFile(ArqAnterior); Arq := Funcoes.GeraStringRandomica(4,2); Arq := ExtractFilePath(ParamStr(0))+'EditorHml_'+Arq+'.html'; ArqAnterior := Arq; if FileExists(Arq) then DeleteFile(Arq); Html := TStringList.Create; Html.Text := CodigoHtml; Html.SaveToFile(Arq); Funcoes.OcultarArquivo(Arq); wbHtml.Navigate(PWideChar(Arq)); //Funcoes.CarregarHtmlWebBrowser(wbHtml,CodigoHtml); finally FreeAndNil(Html); end; end; Application.ProcessMessages; chbVerCodigo.Checked := False; chbVerCodigoClick(nil); end; procedure TframeEditorHtml.chbVerCodigoClick(Sender: TObject); begin AtualizaCodigo; if chbVerCodigo.Checked then begin wbHtml.Visible := False; mmHtml.Visible := True; wbHtml.SendToBack; mmHtml.BringToFront; end else begin wbHtml.Visible := True; mmHtml.Visible := False; wbHtml.BringToFront; mmHtml.SendToBack; end; end; procedure TframeEditorHtml.cmbFonteChange(Sender: TObject); begin HTMLDocumento := wbHtml.Document as IHTMLDocument2; HTMLDocumento.execCommand('FontName', False,cmbFonte.Text); end; procedure TframeEditorHtml.cmbFonteTamChange(Sender: TObject); begin //altera o tamanho da fonte HTMLDocumento := wbHtml.Document as IHTMLDocument2; case cmbFonteTam.ItemIndex of 0: HTMLDocumento.execCommand('FontSize', False,1); 1: HTMLDocumento.execCommand('FontSize', False,2); 2: HTMLDocumento.execCommand('FontSize', False,3); 3: HTMLDocumento.execCommand('FontSize', False,5); 4: HTMLDocumento.execCommand('FontSize', False,6); 5: HTMLDocumento.execCommand('FontSize', False,7); end; end; function TframeEditorHtml.DocumentoAlterado: Boolean; begin AtualizaCodigo; if (HtmlOriginal <> nil) and (HtmlModificado <> nil) then begin Result := HtmlOriginal.Text <> HtmlModificado.Text; end else Result := False; end; function TframeEditorHtml.FocarEditor: Boolean; begin Result := wbHtml.CanFocus; if wbHtml.CanFocus then wbHtml.SetFocus; end; function TframeEditorHtml.ObterImagemClient(Imagem: TImage): Boolean; var bmp : TBitmap; Arq : String; begin if Imagem = nil then begin Imagem := TImage.Create(Application.MainForm); end; try Arq := ExtractFilePath(ParamStr(0))+'WebBrowserPic.jpeg'; WebBrowserScreenShot(wbHtml, Arq); // bmp := TBitmap.Create; // bmp.Width := wbHtml.ClientWidth; // bmp.Height := wbHtml.ClientHeight; // // wbHtml.PaintTo(bmp.Canvas.Handle, 0, 0); // // bmp.SaveToFile('C:\temp\html-orig.bmp'); // Imagem.Picture.Assign(bmp); Imagem.Picture.LoadFromFile(Arq); finally // FreeAndNil(bmp); end; end; procedure TframeEditorHtml.PrevenirNavegacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin {if Screen.ActiveControl = wbHtml then begin if not Self.PodeAlterar then begin if ((Key= VK_LEFT) and (Shift = [ssAlt])) or ((Key= VK_RIGHT) and (Shift = [ssAlt])) or (Key= VK_BROWSER_BACK) or (Key= VK_BROWSER_FORWARD) or (Key = VK_BACK) then begin Key := 0; Exit; end; end; end;} end; function TframeEditorHtml.RetornaCodigoHtml: String; begin AtualizaCodigo; if HtmlModificado <> nil then Result := HtmlModificado.Text else Result := ''; end; function TframeEditorHtml.SalvarHtml: Boolean; begin if not PodeSalvar then Result := False else begin Result := True; end; end; procedure TframeEditorHtml.SetOcultarBotoes(const Value: Boolean); begin if Value = Self.FOcultarBotoes then Exit; FOcultarBotoes := Value; pTop.Visible := not Value; end; procedure TframeEditorHtml.SetPodeAbrir(const Value: Boolean); begin if Value = Self.FPodeAbrir then Exit; FPodeAbrir := Value; acAbrir.Enabled := Value; end; procedure TframeEditorHtml.SetPodeAlterar(const Value: Boolean); begin if Value = Self.FPodeAlterar then Exit; if wbHtml.Document <> nil then (wbHtml.Document as IHTMLDocument2).designMode := IfThen(Value,'On','Off'); FPodeAlterar := Value; pTop.Enabled := Value; mmHtml.ReadOnly := True; if Value then begin //Sleep(2000); Application.ProcessMessages; end; end; procedure TframeEditorHtml.SetPodeSalvar(const Value: Boolean); begin if Value = Self.FPodeSalvar then Exit; FPodeSalvar := Value; acSalvar.Enabled := Value; end; procedure TframeEditorHtml.wbHtmlCommandStateChange(ASender: TObject; Command: Integer; Enable: WordBool); begin if (Command = CSC_NAVIGATEBACK) and (not Self.PodeAlterar) then begin keybd_event(VK_MENU, 0, 0, 0); keybd_event(VK_RIGHT, 0, 0, 0); keybd_event(VK_RIGHT, 0, KEYEVENTF_KEYUP, 0); keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0); end; end; { TWebBrowser } procedure TWebBrowser.CNChar(var Message: TWMChar); begin Message.Result := 0; end; end.
unit DAW.Adb.Parser; interface uses DAW.Model.Device.New; type TdawAdbParser = class private function parseDeviceName(const ALine: string): string; public function parseGetDevicesOutput(const AAdbDevicesOutput: string) : TArray<TdawDevice>; function parseGetDeviceIp(const AIpInfo: string): string; function parseAdbServiceTcpPort(getPropOutput: string): string; end; implementation uses DAW.Tools, System.SysUtils, System.Generics.Collections; { TdawAdbParser } function TdawAdbParser.parseAdbServiceTcpPort(getPropOutput: string): string; begin end; function TdawAdbParser.parseDeviceName(const ALine: string): string; const MODEL_INDICATOR = 'model:'; DEVICE_INDICATOR = 'device:'; var LData: TArray<string>; begin LData := TDawTools.GetInTag(ALine, MODEL_INDICATOR, DEVICE_INDICATOR); if Length(LData) > 0 then Result := LData[0]; end; function TdawAdbParser.parseGetDeviceIp(const AIpInfo: string): string; const START_DEVICE_IP_INDICATOR = 'inet '; END_DEVICE_IP_INDICATOR = '/'; var LData: TArray<string>; begin LData := TDawTools.GetInTag(AIpInfo, START_DEVICE_IP_INDICATOR, END_DEVICE_IP_INDICATOR); if Length(LData) > 0 then Result := LData[0]; end; function TdawAdbParser.parseGetDevicesOutput(const AAdbDevicesOutput: string) : TArray<TdawDevice>; var LDevices: TList<TdawDevice>; splittedOutput: TArray<string>; i: integer; line: string; deviceLine: TArray<string>; id: string; name: string; Device: TdawDevice; begin // 'List of devices attached'#$D#$A'0123456789ABCDEF device product:havoc_santoni model:Redmi_4X device:santoni transport_id:1'#$D#$A#$D#$A Result := nil; if AAdbDevicesOutput.contains('daemon') then Exit(nil); splittedOutput := AAdbDevicesOutput.Split([#$D#$A], TStringSplitOptions.ExcludeEmpty); if Length(splittedOutput) <= 1 then Exit(nil); LDevices := TList<TdawDevice>.Create(); try for i := 1 to High(splittedOutput) do begin line := splittedOutput[i]; deviceLine := line.Split([' '], TStringSplitOptions.ExcludeEmpty); id := deviceLine[0].Split([':'])[0]; name := parseDeviceName(line); Device := TdawDevice.Create(name, id); LDevices.add(Device); end; Result := LDevices.ToArray; finally LDevices.Free; end; end; end.
unit DPM.IDE.PackageDetailsPanel; interface uses System.Types, System.Classes, Vcl.Graphics, Vcl.Controls, ToolsApi, WinApi.Windows, WinApi.Messages, DPM.Core.Package.Interfaces; {$I ..\DPMIDE.inc} type TPackageDetailsPanel = class; TDetailElement = (deNone, deLicense, deProjectUrl, deReportUrl, deRepositoryUrl, deTags); TDetailElements = set of TDetailElement; TDetailsLayout = record PaddingX : integer; PaddingY : integer; LineSpacing : integer; VersionPadding : integer; VersionLabelRect : TRect; VersionRect : TRect; DescriptionLabelRect : TRect; DescriptionRect : TRect; DescriptionHeight : integer; AuthorsLabelRect : TRect; AuthorsRect : TRect; LicenseLabelRect : TRect; LicenseRect : TRect; PublishDateLabelRect : TRect; PublishDateRect : TRect; ProjectUrlLabelRect : TRect; ProjectUrlRect : TRect; ReportUrlLabelRect : TRect; ReportUrlRect : TRect; RepositoryUrlLabelRect : TRect; RepositoryUrlRect : TRect; TagsLabelRect : TRect; TagsRect : TRect; Tags : string; DependLabelRect : TRect; DependRect : TRect; LayoutHeight : integer; procedure ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND}); procedure Update(const ACanvas : TCanvas; const AControl : TPackageDetailsPanel; const package : IPackageSearchResultItem; const optionalElements : TDetailElements); constructor Create(dummy : integer); end; TUriClickEvent = procedure(Sender : TObject; const uri : string; const element : TDetailElement) of object; TPackageDetailsPanel = class(TCustomControl) private FLayout : TDetailsLayout; FOptionalElements : TDetailElements; FHitElement : TDetailElement; FUpdating : boolean; FOnUriClickEvent : TUriClickEvent; FPackage : IPackageSearchResultItem; protected procedure UpdateLayout; procedure Paint; override; procedure Resize; override; procedure WMEraseBkgnd(var Message : TWmEraseBkgnd); message WM_ERASEBKGND; function HitTest(const pt : TPoint) : TDetailElement; procedure MouseDown(Button : TMouseButton; Shift : TShiftState; X : Integer; Y : Integer); override; procedure MouseMove(Shift : TShiftState; X : Integer; Y : Integer); override; procedure CMMouseLeave(var Msg : TMessage); message CM_MouseLeave; procedure ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND}); override; public constructor Create(AOwner : TComponent); override; procedure SetDetails(const package : IPackageSearchResultItem); published property OnUriClick : TUriClickEvent read FOnUriClickEvent write FOnUriClickEvent; property Color; property Font; property ParentColor; property ParentBackground; property ParentFont; property ParentDoubleBuffered; property DoubleBuffered; {$IFDEF STYLEELEMENTS} property StyleElements; {$ENDIF} end; implementation uses System.SysUtils, System.UITypes, Vcl.Themes, Vcl.Forms, Spring.Collections, VSoft.Uri, DPM.Core.Types, DPM.Core.Utils.Strings; { TPackageDetailsPanel } procedure TPackageDetailsPanel.ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND}); begin inherited; //for some reason this is not happening in D11.x Canvas.Font.Height := MulDiv(Canvas.Font.Height, M, D ); FLayout.ChangeScale(M, D{$IF CompilerVersion > 33}, isDpiChange{$IFEND} ); UpdateLayout; end; procedure TPackageDetailsPanel.CMMouseLeave(var Msg : TMessage); begin if FHitElement <> deNone then begin FHitElement := deNone; Cursor := crDefault; invalidate; end; end; constructor TPackageDetailsPanel.Create(AOwner : TComponent); begin inherited; DoubleBuffered := true; ParentColor := false; ParentFont := true; {$IFDEF STYLEELEMENTS} StyleElements := [seFont,seClient]; {$ENDIF} FLayout := TDetailsLayout.Create(0); end; function TPackageDetailsPanel.HitTest(const pt : TPoint) : TDetailElement; begin result := deNone; if FPackage = nil then exit; if (deLicense in FOptionalElements) then begin if FLayout.LicenseRect.Contains(pt) then exit(deLicense); end; if deProjectUrl in FOptionalElements then begin if FLayout.ProjectUrlRect.Contains(pt) then exit(deProjectUrl); end; if deReportUrl in FOptionalElements then begin if FLayout.ReportUrlRect.Contains(pt) then exit(deReportUrl); end; if deRepositoryUrl in FOptionalElements then begin if FLayout.RepositoryUrlRect.Contains(pt) then exit(deRepositoryUrl); end; end; procedure TPackageDetailsPanel.MouseDown(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); var sUri : string; uri : IUri; begin if not Assigned(FOnUriClickEvent) then exit; if FPackage = nil then exit; if Button = mbLeft then begin FHitElement := HitTest(Point(X, Y)); if FHitElement <> deNone then begin case FHitElement of deLicense : begin //TODO : There can be multiple licenses, comma separated. This does not deal with that. if TUriFactory.TryParse(FPackage.License,false, uri) then sUri := FPackage.License else sUri := 'https://spdx.org/licenses/' + FPackage.License + '.html'; end; deProjectUrl : sUri := FPackage.ProjectUrl; deReportUrl : sUri := FPackage.ProjectUrl; else exit; end; FOnUriClickEvent(self, sUri, FHitElement); end; end; end; procedure TPackageDetailsPanel.MouseMove(Shift : TShiftState; X, Y : Integer); var prevElement : TDetailElement; begin inherited; prevElement := FHitElement; FHitElement := HitTest(Point(X, Y)); if FHitElement <> prevElement then Invalidate; if FHitElement in [deProjectUrl, deReportUrl, deLicense] then Cursor := crHandPoint else Cursor := crDefault; end; procedure TPackageDetailsPanel.Paint; var fontStyle : TFontStyles; fillColor : TColor; fontColor : TColor; uriColor : TColor; dependRect : TRect; packageDep : IPackageDependency; textSize : TSize; value : string; begin Canvas.Brush.Style := bsSolid; fillColor := Self.Color; fontColor := Self.Font.Color; Canvas.Font.Color := fontColor; Canvas.Brush.Color := fillColor; Canvas.FillRect(ClientRect); uriColor := $00C57321; if FPackage = nil then exit; fontStyle := Canvas.Font.Style; Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Description', Length('Description'), FLayout.DescriptionLabelRect, DT_LEFT); Canvas.Font.Style := []; DrawText(Canvas.Handle, FPackage.Description, Length(FPackage.Description), FLayout.DescriptionRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Version :', Length('Version :'), FLayout.VersionLabelRect, DT_LEFT); Canvas.Font.Style := []; DrawText(Canvas.Handle, FPackage.Version.ToStringNoMeta, Length(FPackage.Version.ToStringNoMeta), FLayout.VersionRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Authors :', Length('Authors :'), FLayout.AuthorsLabelRect, DT_LEFT); Canvas.Font.Style := []; DrawText(Canvas.Handle, FPackage.Authors, Length(FPackage.Authors), FLayout.AuthorsRect, DT_LEFT + DT_WORDBREAK); if (deLicense in FOptionalElements) then begin Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'License :', Length('License :'), FLayout.LicenseLabelRect, DT_LEFT); Canvas.Font.Color := uriColor; Canvas.Font.Style := []; if FHitElement = deLicense then Canvas.Font.Style := [fsUnderline]; // if FLicenseIsUri then // DrawText(Canvas.Handle, 'View License', Length('View License'), FLayout.LicenseRect, DT_LEFT) // else DrawText(Canvas.Handle, FPackage.License, Length(FPackage.License), FLayout.LicenseRect, DT_LEFT + DT_WORDBREAK); end; Canvas.Font.Color := fontColor; Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Date published :', Length('Date published :'), FLayout.PublishDateLabelRect, DT_LEFT); Canvas.Font.Style := []; if FHitElement = deLicense then Canvas.Font.Style := [fsUnderline]; DrawText(Canvas.Handle, FPackage.PublishedDate, Length(FPackage.PublishedDate), FLayout.PublishDateRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Project URL :', Length('Project URL :'), FLayout.ProjectUrlLabelRect, DT_LEFT); Canvas.Font.Color := uriColor; Canvas.Font.Style := []; if FHitElement = deProjectUrl then Canvas.Font.Style := [fsUnderline]; DrawText(Canvas.Handle, FPackage.ProjectUrl, Length(FPackage.ProjectUrl), FLayout.ProjectUrlRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Color := fontColor; Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Report URL :', Length('Report URL :'), FLayout.ReportUrlLabelRect, DT_LEFT); Canvas.Font.Color := uriColor; Canvas.Font.Style := []; if FHitElement = deReportUrl then Canvas.Font.Style := [fsUnderline]; DrawText(Canvas.Handle, FPackage.ReportUrl, Length(FPackage.ReportUrl), FLayout.ReportUrlRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Color := fontColor; Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Repository URL :', Length('Repository URL :'), FLayout.RepositoryUrlLabelRect, DT_LEFT); Canvas.Font.Color := uriColor; Canvas.Font.Style := []; if FHitElement = deRepositoryUrl then Canvas.Font.Style := [fsUnderline]; DrawText(Canvas.Handle, FPackage.RepositoryUrl, Length(FPackage.RepositoryUrl), FLayout.RepositoryUrlRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Color := fontColor; if (deTags in FOptionalElements) then begin Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Tags :', Length('Tags :'), FLayout.TagsLabelRect, DT_LEFT); Canvas.Font.Style := []; DrawText(Canvas.Handle, FLayout.Tags, Length(FLayout.Tags), FLayout.TagsRect, DT_LEFT + DT_WORDBREAK); end; //draw dependencies Canvas.Font.Style := [fsBold]; DrawText(Canvas.Handle, 'Dependencies', Length('Dependencies'), FLayout.DependLabelRect, DT_LEFT); Canvas.Font.Style := []; dependRect := FLayout.DependRect; if FPackage.Dependencies.Any then begin textSize := Canvas.TextExtent('Win32'); dependRect.Left := FLayout.DependRect.Left + textSize.cy; dependRect.Bottom := dependRect.Top + textSize.cy; value := '- ' + DPMPlatformToString(FPackage.Platform); DrawText(Canvas.Handle, value, Length(value), dependRect, DT_LEFT); dependRect.Left := dependRect.Left + textSize.cy; dependRect.Offset(0, textSize.cy * 2); for packageDep in FPackage.Dependencies do begin value := '- ' + packageDep.Id + ' ( ' + packageDep.VersionRange.ToDisplayString + ' )'; DrawText(Canvas.Handle, value, Length(value), dependRect, DT_LEFT); dependRect.Offset(0, textSize.cy * 2); end; end else DrawText(Canvas.Handle, 'No dependencies.', Length('No dependencies.'), dependRect, DT_LEFT + DT_WORDBREAK); Canvas.Font.Style := fontStyle; end; procedure TPackageDetailsPanel.Resize; begin inherited; UpdateLayout; end; procedure TPackageDetailsPanel.SetDetails(const package : IPackageSearchResultItem); begin FPackage := package; if FPackage <> nil then begin FOptionalElements := []; if package.License <> '' then begin Include(FOptionalElements, deLicense); //TODO : check for multiple licenses. end; if package.ProjectUrl <> '' then Include(FOptionalElements, deProjectUrl); if package.ReportUrl <> '' then Include(FOptionalElements, deReportUrl); if package.Tags <> '' then Include(FOptionalElements, deTags); end; UpdateLayout; Invalidate; end; procedure TPackageDetailsPanel.UpdateLayout; begin //We need this because Resize calls updatelayout which can trigger resize if FUpdating then exit; FUpdating := true; try if HandleAllocated then FLayout.Update(Self.Canvas, Self, FPackage, FOptionalElements); finally FUpdating := False; end; if HandleAllocated then if FLayout.LayoutHeight <> ClientHeight then begin Self.ClientHeight := FLayout.LayoutHeight; Invalidate; end; end; procedure TPackageDetailsPanel.WMEraseBkgnd(var Message : TWmEraseBkgnd); begin message.Result := 1; end; { TDetailsLayout } procedure TDetailsLayout.ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND}); begin VersionPadding := MulDiv(VersionPadding, M, D); PaddingX := MulDiv(PaddingX, M, D); PaddingY := MulDiv(PaddingY, M, D); LineSpacing := MulDiv(LineSpacing, M, D); DescriptionHeight := MulDiv(DescriptionHeight, M, D); end; constructor TDetailsLayout.Create(dummy: integer); begin VersionPadding := 6; PaddingX := 6; PaddingY := 4; LineSpacing := 6; DescriptionHeight := 5000; end; procedure TDetailsLayout.Update(const ACanvas : TCanvas; const AControl : TPackageDetailsPanel; const package : IPackageSearchResultItem; const optionalElements : TDetailElements); var textSize : TSize; clientRect : TRect; bottom : integer; count : integer; tagsArr : TArray<string>; i : integer; begin if package = nil then exit; clientRect := AControl.ClientRect; InflateRect(clientRect, -PaddingX, -PaddingY); //we are going to calc this anyway clientRect.Height := 1000; //widest label ACanvas.Font.Style := []; textSize := ACanvas.TextExtent('Date published : '); ACanvas.Font.Style := []; DescriptionLabelRect := clientRect; DescriptionLabelRect.Height := textSize.cy; DescriptionRect := clientRect; DescriptionRect.Top := DescriptionLabelRect.Bottom + textSize.cy; DescriptionRect.Bottom := DescriptionRect.Top + DescriptionHeight; DrawText(ACanvas.Handle, package.Description, Length(package.Description), DescriptionRect, DT_LEFT + DT_CALCRECT + DT_WORDBREAK); VersionLabelRect.Top := DescriptionRect.Bottom + LineSpacing; VersionLabelRect.Left := ClientRect.Left; VersionLabelRect.Width := textSize.cx; VersionLabelRect.Height := textSize.cy; VersionRect.Top := VersionLabelRect.Top; VersionRect.Left := VersionLabelRect.Right + VersionPadding; VersionRect.Right := clientRect.Right; VersionRect.Height := textSize.cy; DrawText(ACanvas.Handle, package.Version.ToStringNoMeta, Length(package.Version.ToStringNoMeta), VersionRect, DT_LEFT + DT_CALCRECT + DT_WORDBREAK); AuthorsLabelRect.Top := VersionRect.Bottom + LineSpacing; AuthorsLabelRect.Left := clientRect.Left; AuthorsLabelRect.Width := textSize.cx; AuthorsLabelRect.Height := textSize.cy; AuthorsRect.Top := AuthorsLabelRect.Top; AuthorsRect.Left := VersionRect.Left; AuthorsRect.Right := clientRect.Right; AuthorsRect.Height := textSize.cy; DrawText(ACanvas.Handle, package.Authors, Length(package.Authors), AuthorsRect, DT_LEFT + DT_CALCRECT + DT_WORDBREAK); bottom := AuthorsRect.Bottom; if (deLicense in optionalElements) then begin LicenseLabelRect.Top := bottom + LineSpacing; LicenseLabelRect.Left := clientRect.Left; LicenseLabelRect.Width := textSize.cx; LicenseLabelRect.Height := textSize.cy; LicenseRect.Top := LicenseLabelRect.Top; LicenseRect.Left := VersionRect.Left; LicenseRect.Right := clientRect.Right; LicenseRect.Height := textSize.cy; DrawText(ACanvas.Handle, package.License, Length(package.License), LicenseRect, DT_LEFT + DT_CALCRECT + DT_WORDBREAK); bottom := LicenseRect.Bottom; end; PublishDateLabelRect.Top := bottom + LineSpacing; PublishDateLabelRect.Left := clientRect.Left; PublishDateLabelRect.Width := textSize.cx; PublishDateLabelRect.Height := textSize.cy; PublishDateRect.Top := PublishDateLabelRect.Top; PublishDateRect.Left := VersionRect.Left; PublishDateRect.Right := clientRect.Right; PublishDateRect.Height := textSize.cy; bottom := PublishDateRect.Bottom; if (deProjectUrl in optionalElements) then begin ProjectUrlLabelRect.Top := bottom + LineSpacing; ProjectUrlLabelRect.Left := clientRect.Left; ProjectUrlLabelRect.Width := textSize.cx; ProjectUrlLabelRect.Height := textSize.cy; ProjectUrlRect.Top := ProjectUrlLabelRect.Top; ProjectUrlRect.Left := VersionRect.Left; ProjectUrlRect.Right := clientRect.Right; ProjectUrlRect.Height := textSize.cy; //drawtext doesn't wrap text without breaks and the windows api does not have any such functionalty; //TODO : Write a function to calc and split into lines DrawText(ACanvas.Handle, package.ProjectUrl, Length(package.ProjectUrl), ProjectUrlRect, DT_LEFT + DT_CALCRECT); bottom := ProjectUrlRect.Bottom; end; if (deReportUrl in optionalElements) then begin ReportUrlLabelRect.Top := bottom + LineSpacing; ReportUrlLabelRect.Left := clientRect.Left; ReportUrlLabelRect.Width := textSize.cx; ReportUrlLabelRect.Height := textSize.cy; ReportUrlRect.Top := ReportUrlLabelRect.Top; ReportUrlRect.Left := VersionRect.Left; ReportUrlRect.Right := clientRect.Right; ReportUrlRect.Height := textSize.cy; //drawtext doesn't wrap text without breaks and the windows api does not have any such functionalty; //TODO : Write a function to calc and split into lines //TODO : We need reporturl on the searchresultitem DrawText(ACanvas.Handle, package.ReportUrl, Length(package.ReportUrl), ReportUrlRect, DT_LEFT + DT_CALCRECT); bottom := ReportUrlRect.Bottom; end; if (deRepositoryUrl in optionalElements) then begin RepositoryUrlLabelRect.Top := bottom + LineSpacing; RepositoryUrlLabelRect.Left := clientRect.Left; RepositoryUrlLabelRect.Width := textSize.cx; RepositoryUrlLabelRect.Height := textSize.cy; RepositoryUrlRect.Top := RepositoryUrlLabelRect.Top; RepositoryUrlRect.Left := VersionRect.Left; RepositoryUrlRect.Right := clientRect.Right; ReportUrlRect.Height := textSize.cy; //RepositoryUrlRect doesn't wrap text without breaks and the windows api does not have any such functionalty; //TODO : Write a function to calc and split into lines //TODO : We need reporturl on the searchresultitem DrawText(ACanvas.Handle, package.RepositoryUrl, Length(package.RepositoryUrl), RepositoryUrlRect, DT_LEFT + DT_CALCRECT); bottom := RepositoryUrlRect.Bottom; end; if (deTags in optionalElements) then begin TagsLabelRect.Top := bottom + LineSpacing; TagsLabelRect.Left := clientRect.Left; TagsLabelRect.Width := textSize.cx; TagsLabelRect.Height := textSize.cy; TagsRect.Top := TagsLabelRect.Top; TagsRect.Left := VersionRect.Left; TagsRect.Right := clientRect.Right; TagsRect.Height := textSize.cy; //drawtext doesn't wrap text without breaks and the windows api does not have any such functionalty; //TODO : Write a function to calc and split into lines Tags := ''; tagsArr := TStringUtils.SplitStr(package.Tags, ' ', TSplitStringOptions.ExcludeEmpty); for i := 0 to Length(tagsArr) -1 do begin if Tags <> '' then Tags := Tags + ', ' ; Tags := Tags + tagsArr[i]; end; DrawText(ACanvas.Handle, Tags, Length(Tags), TagsRect, DT_LEFT + DT_CALCRECT); bottom := TagsRect.Bottom; end; DependLabelRect.Top := bottom + LineSpacing; DependLabelRect.Left := clientRect.Left; DependLabelRect.Width := textSize.cx; DependLabelRect.Height := textSize.cy; if package.Dependencies.Any then begin DependRect.Top := DependLabelRect.Bottom + LineSpacing; DependRect.Left := DependLabelRect.Left; DependRect.Right := clientRect.Right; count := 0; //work out the height; Inc(count, PaddingY div 2); Inc(count, package.Dependencies.Count * 2); DependRect.Height := count * textSize.cy; end else begin //single line, no dependencies DependRect.Top := DependLabelRect.Bottom + LineSpacing; DependRect.Left := DependLabelRect.Left; DependRect.Right := clientRect.Right; DependRect.Height := textSize.cy; end; bottom := DependRect.Bottom; //Change this as we add more fields LayoutHeight := bottom - clientRect.Top + textSize.cy * 2; end; end.
unit MT5.Position; interface uses System.SysUtils, System.JSON, REST.JSON, System.Generics.Collections, MT5.Connect, MT5.RetCode; type TMTPositionProtocol = class; TMTPosition = class; TMTPositionTotalAnswer = class; TMTPositionPageAnswer = class; TMTPositionAnswer = class; TMTPositionJson = class; TMTPositionProtocol = class private { private declarations } FMTConnect: TMTConnect; protected { protected declarations } function ParsePosition(ACommand: string; AAnswer: string; out APositionAnswer: TMTPositionAnswer): TMTRetCodeType; function ParsePositionPage(AAnswer: string; out APositionPageAnswer: TMTPositionPageAnswer): TMTRetCodeType; function ParsePositionTotal(AAnswer: string; out APositionTotalAnswer: TMTPositionTotalAnswer): TMTRetCodeType; public { public declarations } constructor Create(AConnect: TMTConnect); function PositionGet(ALogin: Integer; ASymbol: string; out APosition: TMTPosition): TMTRetCodeType; function PositionGetPage(ALogin, AOffset, ATotal: Integer; out APositionsCollection: TArray<TMTPosition>): TMTRetCodeType; function PositionGetTotal(ALogin: Integer; out ATotal: Integer): TMTRetCodeType; end; TMTEnPositionAction = ( POSITION_BUY = 0, // buy POSITION_SELL = 1, // sell // --- enumeration borders POSITION_FIRST = TMTEnPositionAction.POSITION_BUY, POSITION_LAST = TMTEnPositionAction.POSITION_SELL ); TMTEnActivation = ( ACTIVATION_NONE = 0, // none ACTIVATION_SL = 1, // SL activated ACTIVATION_TP = 2, // TP activated ACTIVATION_STOPOUT = 3, // Stop-Out activated // --- enumeration borders ACTIVATION_FIRST = TMTEnActivation.ACTIVATION_NONE, ACTIVATION_LAST = TMTEnActivation.ACTIVATION_STOPOUT ); TMTEnPositionTradeActivationFlags = ( ACTIV_FLAGS_NO_LIMIT = $01, ACTIV_FLAGS_NO_STOP = $02, ACTIV_FLAGS_NO_SLIMIT = $04, ACTIV_FLAGS_NO_SL = $08, ACTIV_FLAGS_NO_TP = $10, ACTIV_FLAGS_NO_SO = $20, ACTIV_FLAGS_NO_EXPIRATION = $40, // --- ACTIV_FLAGS_NONE = $00, ACTIV_FLAGS_ALL = $7F ); TMTEnPositionReason = ( POSITION_REASON_CLIENT = 0, // position placed manually POSITION_REASON_EXPERT = 1, // position placed by expert POSITION_REASON_DEALER = 2, // position placed by dealer POSITION_REASON_SL = 3, // position placed due SL POSITION_REASON_TP = 4, // position placed due TP POSITION_REASON_SO = 5, // position placed due Stop-Out POSITION_REASON_ROLLOVER = 6, // position placed due rollover POSITION_REASON_EXTERNAL_CLIENT = 7, // position placed from the external system by client POSITION_REASON_VMARGIN = 8, // position placed due variation margin POSITION_REASON_GATEWAY = 9, // position placed by gateway POSITION_REASON_SIGNAL = 10, // position placed by signal service POSITION_REASON_SETTLEMENT = 11, // position placed due settlement POSITION_REASON_TRANSFER = 12, // position placed due position transfer POSITION_REASON_SYNC = 13, // position placed due position synchronization POSITION_REASON_EXTERNAL_SERVICE = 14, // position placed from the external system due service issues POSITION_REASON_MIGRATION = 15, // position placed due migration POSITION_REASON_MOBILE = 16, // position placed by mobile terminal POSITION_REASON_WEB = 17, // position placed by web terminal POSITION_REASON_SPLIT = 18, // position placed due split // --- enumeration borders POSITION_REASON_FIRST = TMTEnPositionReason.POSITION_REASON_CLIENT, POSITION_REASON_LAST = TMTEnPositionReason.POSITION_REASON_SPLIT ); TMTPositionEnTradeModifyFlags = ( MODIFY_FLAGS_ADMIN = $01, MODIFY_FLAGS_MANAGER = $02, MODIFY_FLAGS_POSITION = $04, MODIFY_FLAGS_RESTORE = $08, MODIFY_FLAGS_API_ADMIN = $10, MODIFY_FLAGS_API_MANAGER = $20, MODIFY_FLAGS_API_SERVER = $40, MODIFY_FLAGS_API_GATEWAY = $80, // --- enumeration borders MODIFY_FLAGS_NONE = $00, MODIFY_FLAGS_ALL = $FF ); TMTPosition = class private FSymbol: string; FActivationMode: TMTEnActivation; FExternalID: string; FActivationPrice: Single; FRateMargin: Single; FPriceSL: Single; FComment: string; FExpertPositionID: Int64; FExpertID: Int64; FContractSize: Single; FRateProfit: Single; FPriceCurrent: Single; FTimeUpdate: Int64; FReason: TMTEnPositionReason; FActivationTime: Int64; FDealer: Int64; FDigitsCurrency: Int64; FVolumeExt: Int64; FDigits: Int64; FStorage: Single; FModifyFlags: TMTPositionEnTradeModifyFlags; FTimeCreate: Int64; FVolume: Int64; FPriceOpen: Single; FAction: Int64; FActivationFlags: TMTEnPositionTradeActivationFlags; FLogin: Int64; FPosition: Int64; FProfit: Single; FPriceTP: Single; FOriginalJSON: TJSONObject; procedure SetAction(const Value: Int64); procedure SetActivationFlags(const Value: TMTEnPositionTradeActivationFlags); procedure SetActivationMode(const Value: TMTEnActivation); procedure SetActivationPrice(const Value: Single); procedure SetActivationTime(const Value: Int64); procedure SetComment(const Value: string); procedure SetContractSize(const Value: Single); procedure SetDealer(const Value: Int64); procedure SetDigits(const Value: Int64); procedure SetDigitsCurrency(const Value: Int64); procedure SetExpertID(const Value: Int64); procedure SetExpertPositionID(const Value: Int64); procedure SetExternalID(const Value: string); procedure SetLogin(const Value: Int64); procedure SetModifyFlags(const Value: TMTPositionEnTradeModifyFlags); procedure SetPosition(const Value: Int64); procedure SetPriceCurrent(const Value: Single); procedure SetPriceOpen(const Value: Single); procedure SetPriceSL(const Value: Single); procedure SetPriceTP(const Value: Single); procedure SetProfit(const Value: Single); procedure SetRateMargin(const Value: Single); procedure SetRateProfit(const Value: Single); procedure SetReason(const Value: TMTEnPositionReason); procedure SetStorage(const Value: Single); procedure SetSymbol(const Value: string); procedure SetTimeCreate(const Value: Int64); procedure SetTimeUpdate(const Value: Int64); procedure SetVolume(const Value: Int64); procedure SetVolumeExt(const Value: Int64); { private declarations } protected { protected declarations } procedure SetOriginalJSON(AValue: TJSONObject); public { public declarations } destructor Destroy; override; // --- position ticket property Position: Int64 read FPosition write SetPosition; // --- position ticket in external system (exchange, ECN, etc) property ExternalID: string read FExternalID write SetExternalID; // --- owner client login property Login: Int64 read FLogin write SetLogin; // --- processed dealer login (0-means auto) (first position deal dealer) property Dealer: Int64 read FDealer write SetDealer; // --- position symbol property Symbol: string read FSymbol write SetSymbol; // --- MTEnPositionAction property Action: Int64 read FAction write SetAction; // --- price digits property Digits: Int64 read FDigits write SetDigits; // --- currency digits property DigitsCurrency: Int64 read FDigitsCurrency write SetDigitsCurrency; // --- position reason (type is MTEnPositionReason) property Reason: TMTEnPositionReason read FReason write SetReason; // --- symbol contract size property ContractSize: Single read FContractSize write SetContractSize; // --- position create time property TimeCreate: Int64 read FTimeCreate write SetTimeCreate; // --- position last update time property TimeUpdate: Int64 read FTimeUpdate write SetTimeUpdate; // --- modification flags (type is MTPositionEnTradeModifyFlags) property ModifyFlags: TMTPositionEnTradeModifyFlags read FModifyFlags write SetModifyFlags; // --- position weighted average open price property PriceOpen: Single read FPriceOpen write SetPriceOpen; // --- position current price property PriceCurrent: Single read FPriceCurrent write SetPriceCurrent; // --- position SL price property PriceSL: Single read FPriceSL write SetPriceSL; // --- position TP price property PriceTP: Single read FPriceTP write SetPriceTP; // --- position volume property Volume: Int64 read FVolume write SetVolume; // --- position volume property VolumeExt: Int64 read FVolumeExt write SetVolumeExt; // --- position floating profit property Profit: Single read FProfit write SetProfit; // --- position accumulated swaps property Storage: Single read FStorage write SetStorage; // --- profit conversion rate (from symbol profit currency to deposit currency) property RateProfit: Single read FRateProfit write SetRateProfit; // --- margin conversion rate (from symbol margin currency to deposit currency) property RateMargin: Single read FRateMargin write SetRateMargin; // --- expert id (filled by expert advisor) property ExpertID: Int64 read FExpertID write SetExpertID; // --- expert position id (filled by expert advisor) property ExpertPositionID: Int64 read FExpertPositionID write SetExpertPositionID; // --- comment property Comment: string read FComment write SetComment; // --- order activation state (type is MTEnActivation) property ActivationMode: TMTEnActivation read FActivationMode write SetActivationMode; // --- order activation time property ActivationTime: Int64 read FActivationTime write SetActivationTime; // --- order activation price property ActivationPrice: Single read FActivationPrice write SetActivationPrice; // --- order activation flags (type is MTEnPositionTradeActivationFlags) property ActivationFlags: TMTEnPositionTradeActivationFlags read FActivationFlags write SetActivationFlags; function ToOriginalJSON: TJSONObject; end; TMTPositionTotalAnswer = class private FRetCode: string; FTotal: Integer; procedure SetRetCode(const Value: string); procedure SetTotal(const Value: Integer); { private declarations } protected { protected declarations } public { public declarations } constructor Create; virtual; property RetCode: string read FRetCode write SetRetCode; property Total: Integer read FTotal write SetTotal; end; TMTPositionPageAnswer = class private FRetCode: string; FConfigJson: string; procedure SetRetCode(const Value: string); procedure SetConfigJson(const Value: string); { private declarations } protected { protected declarations } public { public declarations } constructor Create; virtual; property RetCode: string read FRetCode write SetRetCode; property ConfigJson: string read FConfigJson write SetConfigJson; function GetArrayFromJson: TArray<TMTPosition>; end; TMTPositionAnswer = class private FConfigJson: string; FRetCode: string; procedure SetConfigJson(const Value: string); procedure SetRetCode(const Value: string); { private declarations } protected { protected declarations } public { public declarations } constructor Create; virtual; property RetCode: string read FRetCode write SetRetCode; property ConfigJson: string read FConfigJson write SetConfigJson; function GetFromJson: TMTPosition; end; TMTPositionJson = class private { private declarations } protected { protected declarations } public { public declarations } class function GetFromJson(AJsonObject: TJSONObject): TMTPosition; end; implementation uses MT5.Types, MT5.Protocol, MT5.Utils, MT5.BaseAnswer, MT5.ParseProtocol; { TMTPositionProtocol } constructor TMTPositionProtocol.Create(AConnect: TMTConnect); begin FMTConnect := AConnect; end; function TMTPositionProtocol.ParsePosition(ACommand, AAnswer: string; out APositionAnswer: TMTPositionAnswer): TMTRetCodeType; var LPos: Integer; LPosEnd: Integer; LCommandReal: string; LParam: TMTAnswerParam; LRetCodeType: TMTRetCodeType; LJsonDataString: string; begin LPos := 0; APositionAnswer := nil; LCommandReal := TMTParseProtocol.GetCommand(AAnswer, LPos); if (LCommandReal <> ACommand) then Exit(TMTRetCodeType.MT_RET_ERR_DATA); APositionAnswer := TMTPositionAnswer.Create; LPosEnd := -1; LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd); try while LParam <> nil do begin if LParam.Name = TMTProtocolConsts.WEB_PARAM_RETCODE then begin APositionAnswer.RetCode := LParam.Value; Break; end; FreeAndNil(LParam); LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd); end; finally LParam.Free; end; LRetCodeType := TMTParseProtocol.GetRetCode(APositionAnswer.RetCode); if LRetCodeType <> TMTRetCodeType.MT_RET_OK then Exit(LRetCodeType); LJsonDataString := TMTParseProtocol.GetJson(AAnswer, LPosEnd); if LJsonDataString = EmptyStr then Exit(TMTRetCodeType.MT_RET_REPORT_NODATA); APositionAnswer.ConfigJson := LJsonDataString; Exit(TMTRetCodeType.MT_RET_OK); end; function TMTPositionProtocol.ParsePositionPage(AAnswer: string; out APositionPageAnswer: TMTPositionPageAnswer): TMTRetCodeType; var LPos: Integer; LPosEnd: Integer; LCommandReal: string; LParam: TMTAnswerParam; LRetCodeType: TMTRetCodeType; LJsonDataString: string; begin LPos := 0; APositionPageAnswer := nil; LCommandReal := TMTParseProtocol.GetCommand(AAnswer, LPos); if (LCommandReal <> TMTProtocolConsts.WEB_CMD_POSITION_GET_PAGE) then Exit(TMTRetCodeType.MT_RET_ERR_DATA); APositionPageAnswer := TMTPositionPageAnswer.Create; LPosEnd := -1; LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd); try while LParam <> nil do begin if LParam.Name = TMTProtocolConsts.WEB_PARAM_RETCODE then begin APositionPageAnswer.RetCode := LParam.Value; Break; end; FreeAndNil(LParam); LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd); end; finally LParam.Free; end; LRetCodeType := TMTParseProtocol.GetRetCode(APositionPageAnswer.RetCode); if LRetCodeType <> TMTRetCodeType.MT_RET_OK then Exit(LRetCodeType); LJsonDataString := TMTParseProtocol.GetJson(AAnswer, LPosEnd); if LJsonDataString = EmptyStr then Exit(TMTRetCodeType.MT_RET_REPORT_NODATA); APositionPageAnswer.ConfigJson := LJsonDataString; Exit(TMTRetCodeType.MT_RET_OK); end; function TMTPositionProtocol.ParsePositionTotal(AAnswer: string; out APositionTotalAnswer: TMTPositionTotalAnswer): TMTRetCodeType; var LPos: Integer; LPosEnd: Integer; LCommandReal: string; LParam: TMTAnswerParam; LRetCodeType: TMTRetCodeType; begin LPos := 0; APositionTotalAnswer := nil; LCommandReal := TMTParseProtocol.GetCommand(AAnswer, LPos); if (LCommandReal <> TMTProtocolConsts.WEB_CMD_POSITION_GET_TOTAL) then Exit(TMTRetCodeType.MT_RET_ERR_DATA); APositionTotalAnswer := TMTPositionTotalAnswer.Create; LPosEnd := -1; LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd); try while LParam <> nil do begin if LParam.Name = TMTProtocolConsts.WEB_PARAM_RETCODE then APositionTotalAnswer.RetCode := LParam.Value; if LParam.Name = TMTProtocolConsts.WEB_PARAM_TOTAL then APositionTotalAnswer.Total := LParam.Value.ToInteger; FreeAndNil(LParam); LParam := TMTParseProtocol.GetNextParam(AAnswer, LPos, LPosEnd); end; finally LParam.Free; end; LRetCodeType := TMTParseProtocol.GetRetCode(APositionTotalAnswer.RetCode); if LRetCodeType <> TMTRetCodeType.MT_RET_OK then Exit(LRetCodeType); Exit(TMTRetCodeType.MT_RET_OK); end; function TMTPositionProtocol.PositionGet(ALogin: Integer; ASymbol: string; out APosition: TMTPosition): TMTRetCodeType; var LData: TArray<TMTQuery>; LAnswer: TArray<Byte>; LAnswerString: string; LRetCodeType: TMTRetCodeType; LPositionAnswer: TMTPositionAnswer; begin LData := [ TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_LOGIN, ALogin.ToString), TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_SYMBOL, ASymbol) ]; if not FMTConnect.Send(TMTProtocolConsts.WEB_CMD_POSITION_GET, LData) then Exit(TMTRetCodeType.MT_RET_ERR_NETWORK); LAnswer := FMTConnect.Read(True); if Length(LAnswer) = 0 then Exit(TMTRetCodeType.MT_RET_ERR_NETWORK); LAnswerString := TMTUtils.GetString(LAnswer); LRetCodeType := ParsePosition(TMTProtocolConsts.WEB_CMD_POSITION_GET, LAnswerString, LPositionAnswer); try if LRetCodeType <> TMTRetCodeType.MT_RET_OK then Exit(LRetCodeType); APosition := LPositionAnswer.GetFromJson; Exit(TMTRetCodeType.MT_RET_OK); finally LPositionAnswer.Free; end; end; function TMTPositionProtocol.PositionGetPage(ALogin, AOffset, ATotal: Integer; out APositionsCollection: TArray<TMTPosition>): TMTRetCodeType; var LData: TArray<TMTQuery>; LAnswer: TArray<Byte>; LAnswerString: string; LRetCodeType: TMTRetCodeType; LPositionPageAnswer: TMTPositionPageAnswer; begin LData := [ TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_LOGIN, ALogin.ToString), TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_OFFSET, AOffset.ToString), TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_TOTAL, AOffset.ToString) ]; if not FMTConnect.Send(TMTProtocolConsts.WEB_CMD_POSITION_GET_PAGE, LData) then Exit(TMTRetCodeType.MT_RET_ERR_NETWORK); LAnswer := FMTConnect.Read(True); if Length(LAnswer) = 0 then Exit(TMTRetCodeType.MT_RET_ERR_NETWORK); LAnswerString := TMTUtils.GetString(LAnswer); LRetCodeType := ParsePositionPage(LAnswerString, LPositionPageAnswer); try if LRetCodeType <> TMTRetCodeType.MT_RET_OK then Exit(LRetCodeType); APositionsCollection := LPositionPageAnswer.GetArrayFromJson; Exit(TMTRetCodeType.MT_RET_OK); finally LPositionPageAnswer.Free; end; end; function TMTPositionProtocol.PositionGetTotal(ALogin: Integer; out ATotal: Integer): TMTRetCodeType; var LData: TArray<TMTQuery>; LAnswer: TArray<Byte>; LAnswerString: string; LRetCodeType: TMTRetCodeType; LPositionTotalAnswer: TMTPositionTotalAnswer; begin ATotal := 0; LData := [ TMTQuery.Create(TMTProtocolConsts.WEB_PARAM_LOGIN, ALogin.ToString) ]; if not FMTConnect.Send(TMTProtocolConsts.WEB_CMD_POSITION_GET_TOTAL, LData) then Exit(TMTRetCodeType.MT_RET_ERR_NETWORK); LAnswer := FMTConnect.Read(True); if Length(LAnswer) = 0 then Exit(TMTRetCodeType.MT_RET_ERR_NETWORK); LAnswerString := TMTUtils.GetString(LAnswer); LRetCodeType := ParsePositionTotal(LAnswerString, LPositionTotalAnswer); try if LRetCodeType <> TMTRetCodeType.MT_RET_OK then Exit(LRetCodeType); ATotal := LPositionTotalAnswer.Total; Exit(TMTRetCodeType.MT_RET_OK); finally LPositionTotalAnswer.Free; end; end; { TMTPosition } destructor TMTPosition.Destroy; begin FOriginalJSON.Free; inherited; end; procedure TMTPosition.SetAction(const Value: Int64); begin FAction := Value; end; procedure TMTPosition.SetActivationFlags(const Value: TMTEnPositionTradeActivationFlags); begin FActivationFlags := Value; end; procedure TMTPosition.SetActivationMode(const Value: TMTEnActivation); begin FActivationMode := Value; end; procedure TMTPosition.SetActivationPrice(const Value: Single); begin FActivationPrice := Value; end; procedure TMTPosition.SetActivationTime(const Value: Int64); begin FActivationTime := Value; end; procedure TMTPosition.SetComment(const Value: string); begin FComment := Value; end; procedure TMTPosition.SetContractSize(const Value: Single); begin FContractSize := Value; end; procedure TMTPosition.SetDealer(const Value: Int64); begin FDealer := Value; end; procedure TMTPosition.SetDigits(const Value: Int64); begin FDigits := Value; end; procedure TMTPosition.SetDigitsCurrency(const Value: Int64); begin FDigitsCurrency := Value; end; procedure TMTPosition.SetExpertID(const Value: Int64); begin FExpertID := Value; end; procedure TMTPosition.SetExpertPositionID(const Value: Int64); begin FExpertPositionID := Value; end; procedure TMTPosition.SetExternalID(const Value: string); begin FExternalID := Value; end; procedure TMTPosition.SetLogin(const Value: Int64); begin FLogin := Value; end; procedure TMTPosition.SetModifyFlags(const Value: TMTPositionEnTradeModifyFlags); begin FModifyFlags := Value; end; procedure TMTPosition.SetOriginalJSON(AValue: TJSONObject); begin FOriginalJSON := AValue; end; procedure TMTPosition.SetPosition(const Value: Int64); begin FPosition := Value; end; procedure TMTPosition.SetPriceCurrent(const Value: Single); begin FPriceCurrent := Value; end; procedure TMTPosition.SetPriceOpen(const Value: Single); begin FPriceOpen := Value; end; procedure TMTPosition.SetPriceSL(const Value: Single); begin FPriceSL := Value; end; procedure TMTPosition.SetPriceTP(const Value: Single); begin FPriceTP := Value; end; procedure TMTPosition.SetProfit(const Value: Single); begin FProfit := Value; end; procedure TMTPosition.SetRateMargin(const Value: Single); begin FRateMargin := Value; end; procedure TMTPosition.SetRateProfit(const Value: Single); begin FRateProfit := Value; end; procedure TMTPosition.SetReason(const Value: TMTEnPositionReason); begin FReason := Value; end; procedure TMTPosition.SetStorage(const Value: Single); begin FStorage := Value; end; procedure TMTPosition.SetSymbol(const Value: string); begin FSymbol := Value; end; procedure TMTPosition.SetTimeCreate(const Value: Int64); begin FTimeCreate := Value; end; procedure TMTPosition.SetTimeUpdate(const Value: Int64); begin FTimeUpdate := Value; end; procedure TMTPosition.SetVolume(const Value: Int64); begin FVolume := Value; end; procedure TMTPosition.SetVolumeExt(const Value: Int64); begin FVolumeExt := Value; end; function TMTPosition.ToOriginalJSON: TJSONObject; begin Result := FOriginalJSON; end; { TMTPositionTotalAnswer } constructor TMTPositionTotalAnswer.Create; begin FRetCode := '-1'; FTotal := 0; end; procedure TMTPositionTotalAnswer.SetRetCode(const Value: string); begin FRetCode := Value; end; procedure TMTPositionTotalAnswer.SetTotal(const Value: Integer); begin FTotal := Value; end; { TMTPositionPageAnswer } constructor TMTPositionPageAnswer.Create; begin FRetCode := '-1'; FConfigJson := ''; end; function TMTPositionPageAnswer.GetArrayFromJson: TArray<TMTPosition>; var LPositionsJsonArray: TJsonArray; I: Integer; begin LPositionsJsonArray := TJSONObject.ParseJSONValue(ConfigJson) as TJsonArray; try for I := 0 to LPositionsJsonArray.Count - 1 do Result := Result + [TMTPositionJson.GetFromJson(TJSONObject(LPositionsJsonArray.Items[I]))]; finally LPositionsJsonArray.Free; end; end; procedure TMTPositionPageAnswer.SetConfigJson(const Value: string); begin FConfigJson := Value; end; procedure TMTPositionPageAnswer.SetRetCode(const Value: string); begin FRetCode := Value; end; { TMTPositionAnswer } constructor TMTPositionAnswer.Create; begin FConfigJson := ''; FRetCode := '-1'; end; function TMTPositionAnswer.GetFromJson: TMTPosition; begin Result := TMTPositionJson.GetFromJson(TJSONObject.ParseJSONValue(ConfigJson) as TJSONObject); end; procedure TMTPositionAnswer.SetConfigJson(const Value: string); begin FConfigJson := Value; end; procedure TMTPositionAnswer.SetRetCode(const Value: string); begin FRetCode := Value; end; { TMTPositionJson } class function TMTPositionJson.GetFromJson(AJsonObject: TJSONObject): TMTPosition; var LPosition: TMTPosition; LVolumeExt: Int64; begin LPosition := TMTPosition.Create; Result := LPosition; LPosition.Position := AJsonObject.GetValue<Integer>('Position'); LPosition.ExternalID := AJsonObject.GetValue<string>('ExternalID'); LPosition.Login := AJsonObject.GetValue<Integer>('Login'); LPosition.Dealer := AJsonObject.GetValue<Integer>('Dealer'); LPosition.Symbol := AJsonObject.GetValue<string>('Symbol'); LPosition.Action := AJsonObject.GetValue<Integer>('Action'); LPosition.Digits := AJsonObject.GetValue<Integer>('Digits'); LPosition.DigitsCurrency := AJsonObject.GetValue<Integer>('DigitsCurrency'); LPosition.Reason := TMTEnPositionReason(AJsonObject.GetValue<Integer>('Reason')); LPosition.ContractSize := AJsonObject.GetValue<Single>('ContractSize'); LPosition.TimeCreate := AJsonObject.GetValue<Integer>('TimeCreate'); LPosition.TimeUpdate := AJsonObject.GetValue<Integer>('TimeUpdate'); LPosition.ModifyFlags := TMTPositionEnTradeModifyFlags(AJsonObject.GetValue<Integer>('ModifyFlags')); LPosition.PriceOpen := AJsonObject.GetValue<Single>('PriceOpen'); LPosition.PriceCurrent := AJsonObject.GetValue<Single>('PriceCurrent'); LPosition.PriceSL := AJsonObject.GetValue<Single>('PriceSL'); LPosition.PriceTP := AJsonObject.GetValue<Single>('PriceTP'); LPosition.Volume := AJsonObject.GetValue<Int64>('Volume'); if AJsonObject.TryGetValue('VolumeExt', LVolumeExt) then LPosition.VolumeExt := AJsonObject.GetValue<Int64>('VolumeExt') else LPosition.VolumeExt := TMTUtils.ToNewVolume(LPosition.Volume); LPosition.Profit := AJsonObject.GetValue<Single>('Profit'); LPosition.Storage := AJsonObject.GetValue<Single>('Storage'); LPosition.RateProfit := AJsonObject.GetValue<Single>('RateProfit'); LPosition.RateMargin := AJsonObject.GetValue<Single>('RateMargin'); LPosition.ExpertID := AJsonObject.GetValue<Int64>('ExpertID'); LPosition.ExpertPositionID := AJsonObject.GetValue<Int64>('ExpertPositionID'); LPosition.Comment := AJsonObject.GetValue<string>('Comment'); LPosition.ActivationMode := TMTEnActivation(AJsonObject.GetValue<Integer>('ActivationMode')); LPosition.ActivationTime := AJsonObject.GetValue<Integer>('ActivationTime'); LPosition.ActivationPrice := AJsonObject.GetValue<Single>('ActivationPrice'); LPosition.ActivationFlags := TMTEnPositionTradeActivationFlags(AJsonObject.GetValue<Integer>('ActivationFlags')); LPosition.SetOriginalJSON(AJsonObject.Clone as TJSONObject); end; end.
unit uVCLHelpers; interface uses System.Types, System.SysUtils, System.Classes, Winapi.Windows, Winapi.Dwmapi, Winapi.Commctrl, Vcl.ExtCtrls, Vcl.Forms, Vcl.Controls, Vcl.Graphics, Vcl.Menus, Vcl.Themes, Vcl.ActnPopup, Vcl.StdCtrls, Vcl.ImgList, Vcl.ComCtrls, Dmitry.Utils.Files, uRuntime, uMemory, uConstants, uLogger, uIDBForm, uSettings, uConfiguration; type TTimerHelper = class helper for TTimer public procedure Restart(NewInterval: Integer = 0); end; type TButtonHelper = class helper for TButton public procedure AdjustButtonWidth; procedure SetEnabledEx(Value: Boolean); procedure AdjustButtonHeight; end; type TComboBoxHelper = class helper for TComboBox private function GetValue: string; procedure SetValue(const Value: string); public property Value: string read GetValue write SetValue; end; type TCheckBoxHelper = class helper for TCheckBox public procedure AdjustWidth(AdditionalWidth: Integer = 0); end; type TMenuItemHelper = class helper for TMenuItem public procedure ExSetDefault(Value: Boolean); function ExGetDefault: Boolean; end; type TPopupActionBarHelper = class helper for TPopupActionBar public procedure DoPopupEx(X, Y: Integer); end; TWinControlHelper = class helper for TWinControl private function GetBoundsRectScreen: TRect; public function FindChildByName<T: TControl>(Name: string): T; function FindChildByTag<T: TControl>(Tag: NativeInt): T; function FindChildByType<T: TControl>: T; function HasHandle(Handle: THandle): Boolean; property BoundsRectScreen: TRect read GetBoundsRectScreen; end; TControlHelper = class helper for TControl function AfterTop(Padding: Integer): Integer; function AfterRight(Padding: Integer): Integer; procedure BeforeLeft(Control: TControl; Padding: Integer); procedure BeforeRight(Control: TControl); function FormBounds: TRect; function ScreenBelow: TPoint; function OwnerForm: TForm; end; TCustomImageListHelper = class helper for TCustomImageList public function LoadFromCache(CacheFileName: string): Boolean; procedure SaveToCache(CacheFileName: string); end; TPictureHelper = class helper for TPicture public procedure SetGraphicEx(Value: TGraphic); end; type TPictureX = class(TInterfacedPersistent, IStreamPersist) private FGraphic: TGraphic; public procedure LoadFromStream(Stream: TStream); procedure SaveToStream(Stream: TStream); end; TListBoxHelper = class helper for TListBox private function GetSelectedIndex: Integer; public property SelectedIndex: Integer read GetSelectedIndex; end; TToolBarHelper = class helper for TToolBar public procedure DisableToolBarForButtons; procedure EnableToolBarForButtons; end; TStatusBarHelper = class helper for TStatusBar function CreateProgressBar(Index: Integer): TProgressBar; end; TScreenHelper = class helper for TScreen function ActiveFormHandle: THandle; function CurrentImageFileName: string; end; type TNotifyEventRef = reference to procedure(Sender: TObject); TKeyEventRef = reference to procedure(Sender: TObject; var Key: Word; Shift: TShiftState); TMessageEventRef = reference to procedure(var Msg: TMsg; var Handled: Boolean); function MakeNotifyEvent(const ANotifyRef: TNotifyEventRef): TNotifyEvent; function MakeKeyEvent(const ANotifyRef: TKeyEventRef): TKeyEvent; function MakMessageEvent(const ANotifyRef: TMessageEventRef): TMessageEvent; function IsPopupMenuActive: Boolean; implementation function IsPopupMenuActive: Boolean; begin //todo: review functionality if possible Result := BlockClosingOfWindows; end; procedure MethRefToMethPtr(const MethRef; var MethPtr); type TVtable = array[0..3] of Pointer; PVtable = ^TVtable; PPVtable = ^PVtable; begin // 3 is offset of Invoke, after QI, AddRef, Release TMethod(MethPtr).Code := PPVtable(MethRef)^^[3]; TMethod(MethPtr).Data := Pointer(MethRef); end; function MakeNotifyEvent(const ANotifyRef: TNotifyEventRef): TNotifyEvent; begin MethRefToMethPtr(ANotifyRef, Result); end; function MakeKeyEvent(const ANotifyRef: TKeyEventRef): TKeyEvent; begin MethRefToMethPtr(ANotifyRef, Result); end; function MakMessageEvent(const ANotifyRef: TMessageEventRef): TMessageEvent; begin MethRefToMethPtr(ANotifyRef, Result); end; type TCustomButtonEx = class(TButton); procedure TButtonHelper.AdjustButtonHeight; const PaddingLeft = 40; PaddingTop = 15; var DrawRect: TRect; TextRect: TRect; Surface: TBitmap; ACanvas: TCanvas; DrawOptions, CaptionHeight: Integer; begin DrawRect := Self.ClientRect; Surface := TBitmap.Create; try ACanvas := Surface.Canvas; DrawRect := Rect(0, 0, 0, 0); if (GetWindowLong(Self.Handle, GWL_STYLE) and BS_COMMANDLINK) = BS_COMMANDLINK then begin TextRect := Self.ClientRect; Dec(TextRect.Right, PaddingLeft + 15); Dec(TextRect.Bottom, PaddingTop + 15); TextRect.Bottom := MaxInt; ACanvas.Font := TCustomButtonEx(Self).Font; ACanvas.Font.Style := []; ACanvas.Font.Size := 12; DrawText(ACanvas.Handle, PChar(Self.Caption), Length(Self.Caption), TextRect, DT_LEFT or DT_SINGLELINE or DT_CALCRECT); CaptionHeight := TextRect.Height + 2; OffsetRect(TextRect, PaddingLeft, PaddingTop); UnionRect(DrawRect, DrawRect, TextRect); ACanvas.Font.Size := 8; TextRect := Self.ClientRect; Dec(TextRect.Right, PaddingLeft); Dec(TextRect.Bottom, PaddingTop); TextRect.Bottom := MaxInt; DrawText(ACanvas.Handle, PChar(Self.CommandLinkHint), Length(Self.CommandLinkHint), TextRect, DT_LEFT or DT_WORDBREAK or DT_CALCRECT); OffsetRect(TextRect, PaddingLeft, PaddingTop + CaptionHeight); UnionRect(DrawRect, DrawRect, TextRect); Self.SetBounds(Self.Left, Self.Top, Self.Width, DrawRect.Height + PaddingTop + 15); end else begin TextRect := Self.ClientRect; DrawOptions := DT_LEFT or DT_CALCRECT; if TCustomButtonEx(Self).WordWrap then DrawOptions := DrawOptions or DT_WORDBREAK; DrawText(ACanvas.Handle, PChar(Self.Caption), Length(Self.Caption), TextRect, DrawOptions); Self.SetBounds(Self.Left, Self.Top, Self.Width, TextRect.Height + 10); end; finally Surface.Free; end; end; procedure TButtonHelper.AdjustButtonWidth; var TextSize: TSize; ADC: HDC; begin aDC := GetDC(Handle); try SelectObject(ADC, Font.Handle); GetTextExtentPoint32(ADC, PChar(Caption), Length(Caption), TextSize); Width := TextSize.Cx + 10; finally ReleaseDc(Handle, ADC); end; end; { TTimerHelper } procedure TTimerHelper.Restart(NewInterval: Integer = 0); begin if NewInterval <> 0 then Interval := NewInterval; Enabled := False; Enabled := True; end; { TComboBoxHelper } function TComboBoxHelper.GetValue: string; begin Result := ''; if ItemIndex > -1 then Result := Items[ItemIndex]; end; procedure TComboBoxHelper.SetValue(const Value: string); var I: Integer; begin if Items.Count > 0 then ItemIndex := 0; for I := 0 to Items.Count - 1 do if Items[I] = Value then begin ItemIndex := I; Break; end; end; { TCheckBoxHelper } procedure TCheckBoxHelper.AdjustWidth(AdditionalWidth: Integer = 0); var TextSize: TSize; ADC: HDC; begin aDC := GetDC(Handle); try SelectObject(ADC, Font.Handle); GetTextExtentPoint32(ADC, PChar(Caption), Length(Caption), TextSize); Width := TextSize.Cx + GetSystemMetrics(SM_CXMENUCHECK) + GetSystemMetrics(SM_CXEDGE) * 2 + AdditionalWidth; finally ReleaseDc(Handle, ADC); end; end; { TMenuItemHelper } function TMenuItemHelper.ExGetDefault: Boolean; begin if TStyleManager.Enabled and TStyleManager.IsCustomStyleActive then Result := Checked else Result := Default; end; procedure TMenuItemHelper.ExSetDefault(Value: Boolean); var I: Integer; function IsStyledItem: Boolean; begin Result := TStyleManager.Enabled; if GetParentMenu is TMainMenu then Result := False; if (Owner is TMenuItem) then if (Owner as TMenuItem).GetParentMenu is TMainMenu then Result := False; end; begin if not Value then begin if IsStyledItem then Self.Checked := False else Self.Default := False; Exit; end; if IsStyledItem then begin Self.Checked := True; if Parent <> nil then begin for I := 0 to Parent.Count - 1 do begin if Parent.Items[I] <> Self then Parent.Items[I].Checked := False; end; end; end else begin Self.Default := True; end; end; { TPopupActionBarHelper } procedure TPopupActionBarHelper.DoPopupEx(X, Y: Integer); begin BlockClosingOfWindows := True; try Popup(X, Y); finally BlockClosingOfWindows := False; end; end; { TWinControlHelper } function TWinControlHelper.FindChildByName<T>(Name: string): T; var I: Integer; begin Result := default(T); for I := 0 to ControlCount - 1 do begin if Controls[I].Name = Name then begin Result := Controls[I] as T; Exit; end; end; end; function TWinControlHelper.FindChildByTag<T>(Tag: NativeInt): T; var I: Integer; begin Result := default(T); for I := 0 to ControlCount - 1 do begin if Controls[I].Tag = Tag then begin Result := Controls[I] as T; Exit; end; end; end; function TWinControlHelper.FindChildByType<T>: T; var I: Integer; begin Result := default(T); for I := 0 to ControlCount - 1 do begin if Controls[I] is T then begin Result := Controls[I] as T; Exit; end; end; end; function TWinControlHelper.GetBoundsRectScreen: TRect; var P1, P2: TPoint; begin P1 := BoundsRect.TopLeft; P2 := BoundsRect.BottomRight; P1 := ClientToScreen(P1); P2 := ClientToScreen(P2); Result := Rect(P1, P2); end; function TWinControlHelper.HasHandle(Handle: THandle): Boolean; var Control: TControl; I: Integer; begin if Self.Handle = Handle then Exit(True); for I := 0 to ControlCount - 1 do begin Control := Controls[I]; if Control is TWinControl then if TWinControl(Control).HasHandle(Handle) then Exit(True); end; Exit(False); end; procedure TButtonHelper.SetEnabledEx(Value: Boolean); begin Enabled := Value; if not Value then Perform(CM_RECREATEWND, 0, 0); end; { TCustomImageListHelper } type TCustomImageListEx = class(TCustomImageList); function TCustomImageListHelper.LoadFromCache(CacheFileName: string): Boolean; var FileName: string; FS: TFileStream; procedure ReadData(Stream: TFileStream); var LAdapter: TStreamAdapter; begin LAdapter := TStreamAdapter.Create(Stream); try Handle := ImageList_Read(LAdapter); finally LAdapter.Free; end; ImageList_SetImageCount(Handle, ImageList_GetImageCount(Handle)); end; begin Result := True; FileName := GetAppDataDirectoryFromSettings + CommonCacheDirectory + CacheFileName + '.imlist'; FS := nil; try try FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); ReadData(FS); //TCustomImageListEx(Self).ReadData(FS); except on e: Exception do begin EventLog(e); Result := False; end; end; finally F(FS); end; end; procedure TCustomImageListHelper.SaveToCache(CacheFileName: string); var Directory, FileName: string; FS: TFileStream; begin Directory := GetAppDataDirectoryFromSettings + CommonCacheDirectory; CreateDirA(Directory); FileName := Directory + CacheFileName + '.imlist'; FS := nil; try try FS := TFileStream.Create(FileName, fmCreate); TCustomImageListEx(Self).WriteData(FS); except on e: Exception do EventLog(e); end; finally F(FS); end; end; { TPictureHelper } procedure TPictureHelper.SetGraphicEx(Value: TGraphic); begin if TPictureX(Self).FGraphic <> nil then TPictureX(Self).FGraphic.Free; TPictureX(Self).FGraphic := Value; end; { TPictureX } procedure TPictureX.LoadFromStream(Stream: TStream); begin end; procedure TPictureX.SaveToStream(Stream: TStream); begin end; { TListBoxHelper } function TListBoxHelper.GetSelectedIndex: Integer; var I: Integer; begin Result := -1; for I := 0 to Self.Items.Count - 1 do begin if Self.Selected[I] then begin Result := I; Break; end; end; end; { TControlHelper } function TControlHelper.AfterRight(Padding: Integer): Integer; begin Result := Left + Width + Padding; end; function TControlHelper.AfterTop(Padding: Integer): Integer; begin Result := Top + Height + Padding; end; procedure TControlHelper.BeforeLeft(Control: TControl; Padding: Integer); begin Left := Control.Left - Width - Padding; end; procedure TControlHelper.BeforeRight(Control: TControl); var W: Integer; begin if Control is TForm then begin W := Control.ClientWidth; if (TForm(Control).BorderStyle = bsSingle) and DwmCompositionEnabled then W := W - GetSystemMetrics(SM_CXSIZEFRAME); end else W := Control.Width; Left := Control.Left + W - Width; end; function TControlHelper.FormBounds: TRect; var Control: TControl; X, Y: Integer; begin Control := Self; X := 0; Y := 0; while (Control <> nil) and not (Control is TForm) do begin Inc(X, Control.Left); Inc(Y, Control.Top); Control := Control.Parent; end; Result := Rect(X, Y, X + Width, Y + Height); end; function TControlHelper.OwnerForm: TForm; var Owner: TComponent; begin Owner := Self.Owner; while (Owner.Owner <> nil) and not (Owner is TForm) do Owner := Owner.Owner; Result := Owner as TForm; end; function TControlHelper.ScreenBelow: TPoint; begin Result := Point(Left, BoundsRect.Bottom); Result := Parent.ClientToScreen(Result); end; { TToolBarHelper } type TToolBarButtonEx = class(TToolButton); procedure TToolBarHelper.DisableToolBarForButtons; var I: Integer; begin for I := 0 to Self.ButtonCount - 1 do TToolBarButtonEx(Self.Buttons[I]).FToolBar := nil; end; procedure TToolBarHelper.EnableToolBarForButtons; var I: Integer; begin for I := 0 to Self.ButtonCount - 1 do begin TToolBarButtonEx(Self.Buttons[I]).FToolBar := Self; Perform(TB_CHANGEBITMAP, Buttons[I].Index, LPARAM(Buttons[I].ImageIndex)); end; end; { TStatusBarHelper } function TStatusBarHelper.CreateProgressBar(Index: Integer): TProgressBar; var Findleft: Integer; I: Integer; begin Result := TProgressBar.Create(Self); Result.Parent := Self; Result.Visible := True; Result.Top := 2; FindLeft := 0; for I := 0 to index - 1 do FindLeft := FindLeft + Self.Panels[I].Width + 1; Result.Left := Findleft; Result.Width := Self.Panels[index].Width - 4; Result.Height := Self.Height - 2; end; { TScreenHelper } function TScreenHelper.ActiveFormHandle: THandle; begin if Self.ActiveForm <> nil then Result := Self.ActiveForm.Handle else Result := 0; end; function TScreenHelper.CurrentImageFileName: string; var I: Integer; Form: IDBForm; Source: ICurrentImageSource; begin Result := ''; for I := 0 to FormCount - 1 do begin if not Supports(Forms[I], IDBForm, Form) then Continue; if Form.QueryInterfaceEx(ICurrentImageSource, Source) = S_OK then begin Result := Source.GetCurrentImageFileName; if Result <> '' then Break; end; end; end; end.
namespace LinqToObjects; interface uses System.Collections.Generic, System.Linq, System.Text; type Words = public class private words : Array of String := ['hello', 'Oxygene', 'wonderful', 'linq', 'beautiful', 'world' ]; public method SimpleSelect; method ComplexSelect; end; implementation method Words.SimpleSelect; begin var shortwords := From word in words Where word.Length <= 5 Select word; Console.WriteLine('Simple select statment'); Console.WriteLine; for each word in shortwords do begin Console.WriteLine(word); end; end; method Words.ComplexSelect; begin var groups := From word in words Order by word asc group word by word.Length into lengthGroups Order by lengthGroups.Key desc select new class (Length:=lengthGroups.Key,Words:=lengthGroups); Console.WriteLine('Complex query using group and order'); Console.WriteLine; for each grupo in groups do begin Console.WriteLine('Words of length ' + grupo.Length); for each word in grupo.Words do Console.WriteLine(' ' + word); end; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0105.PAS Description: Simpson's Approximation Author: DAVID PINCH Date: 02-21-96 21:04 *) { This simple Pascal program computes a definite integral using Simpson's approximation. Efficiency has been sacrificed for clarity, so it should be easy to follow the logic of the program. - DJP } Var { Declare variables } a : Integer; { Left point } b : Integer; { Right point } d : Real; { Delta x } i : Integer; { Iteration } n : Integer; { No. of intervals } SubTotal : Real; Function y(x:real):Real; { Define your function here } Begin y:=1/x End; Function Coefficient(i:Integer):Integer; Begin If (i=0) or (i=n) Then Coefficient:=1 Else Coefficient:=(i Mod 2)*2+2 { Notes: The MOD operater returns the remainder of a division. This allows us to determine if the partition is odd or even. <even> MOD 2 = 0 <odd> MOD 2 = 1 An examination of the coefficients of a typical approximation sum shows an interesting pattern: Odd partitions have 4 as a coefficient and even partitions have 2 as a coefficient. The first and last partitions are exceptions to this rule. This pattern is used as a basis for calculating the coefficient of a given partition. } End; Function xi(i:Integer):Real; Begin xi:=a+i*d End; Begin a:=1; b:=2; SubTotal:=0; Repeat Write('Subintervals? '); ReadLn(n); Until (n Mod 2)=0; { Even number required } d:=(b-1)/n; WriteLn; WriteLn(' n xi f(xi) c cf(xi)'); WriteLn('-------------------------------'); For i:=0 to n Do Begin WriteLn(i:3, xi(i):8:3, y(xi(i)):8:3, Coefficient(i):4, Coefficient(i)*y(xi(i)):8:3); SubTotal:=SubTotal+Coefficient(i)*y(xi(i)) End; WriteLn; WriteLn('SubTotal',SubTotal:23:3); WriteLn('Result = ', (d/3)*SubTotal:0:50) End. { Quick Optimizations: a. Remove the WriteLn statement in the For loop. b. Turn on 80x87 support. c. Consolidate some of the procedures. peace/dp }
unit Coche.Interfaces; interface uses System.SysUtils, System.Rtti, System.Classes, Data.DB, Spring, MVVM.Interfaces, MVVM.Interfaces.Architectural, MVVM.Bindings, MVVM.Types, Coche.Types, DataSet.Model; type ICoches_ViewModel = Interface(IViewModel) ['{6AAA74B3-325A-4986-8556-3D703B090364}'] function GetDataSet: TDataSet; function GetProcMakeGetRows: TExecuteMethod; function GetProcDeleteActiveRow: TExecuteMethod; function GetProcMakeAppend: TExecuteMethod; function GetProcMakeUpdate: TExecuteMethod; function GetIsOpen: TCanExecuteMethod; function GetActiveRow: RCoche; procedure AppendRow(const AData: RCoche); procedure UpdateActiveRow(const AData: RCoche); property DataSet: TDataSet read GetDataSet; property IsOpen: TCanExecuteMethod read GetIsOpen; property DoMakeGetRows: TExecuteMethod read GetProcMakeGetRows; property DoDeleteActiveRow: TExecuteMethod read GetProcDeleteActiveRow; property DoMakeAppend: TExecuteMethod read GetProcMakeAppend; property DoMakeUpdate: TExecuteMethod read GetProcMakeUpdate; end; INewCoche_ViewModel = Interface(IViewModel) ['{DECCB720-73A7-4F02-ABD9-5CD6F7995428}'] function GetSetData: TExecuteMethod<RCoche>; procedure SetData(const AData: RCoche); function GetOnDataSelected: IEvent<TNotify_Coche>; property OnDataSelected: IEvent<TNotify_Coche> read GetOnDataSelected; property DoSetData: TExecuteMethod<RCoche> read GetSetData; end; IUpdateCoche_ViewModel = Interface(IViewModel) ['{2F6ADB68-A4E0-43E2-8C0A-1BBE2FE1C1C7}'] function GetSetData: TExecuteMethod<RCoche>; function GetData: RCoche; procedure SetData(const AData: RCoche); function GetOnDataSelected: IEvent<TNotify_Coche>; property OnDataSelected: IEvent<TNotify_Coche> read GetOnDataSelected; property DoSetData: TExecuteMethod<RCoche> read GetSetData; property Data: RCoche read GetData write SetData; end; implementation end.
unit MailQueries; interface uses {RTL/VCL} Contnrs, {Project} MailBox, QueryBase, {3rd Party} ZSqlUpdate ; type //------------------------------------------------------------------------------ //TMailQueries CLASS //------------------------------------------------------------------------------ TMailQueries = class(TQuerybase) protected public procedure LoadMails( const AMailList : TObjectList; const CharID : LongWord; var AMails,ANewmails :Byte ); function Get( const CharID : LongWord; const MailID : LongWord ):TMail;overload; function Get( const MailID : LongWord ):TMail;overload; function Delete( const CharID : LongWord; const MailID : LongWord ):Boolean; procedure Add( const Mail : TMail ); end; implementation uses ZDataset, DB ; //------------------------------------------------------------------------------ //LoadMails PROCEDURE //------------------------------------------------------------------------------ // What it does- // Load mail list // // Changes - // [2008/06/11] Aeomin - Created // //------------------------------------------------------------------------------ procedure TMailQueries.LoadMails( const AMailList : TObjectList; const CharID : LongWord; var AMails,ANewmails :Byte ); const AQuery = 'SELECT * FROM mailbox WHERE `receiver_id`=:ID ORDER BY `time` DESC;'; var ADataSet : TZQuery; AParam : TParam; Mail : TMail; begin {Reset First} AMails := 0; ANewmails := 0; if AMailList.Count >0 then AMailList.Clear; ADataSet := TZQuery.Create(nil); //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := CharID; ADataSet.Params.AddParam( AParam ); try Query(ADataSet, AQuery); ADataSet.First; while NOT ADataSet.Eof do begin Mail := TMail.Create; Mail.ID := ADataSet.Fields[0].AsInteger; Mail.SenderID := ADataSet.Fields[1].AsInteger; Mail.SenderName := ADataSet.Fields[2].AsString; Mail.ReceiverID := ADataSet.Fields[3].AsInteger; Mail.ReceiverName := ADataSet.Fields[4].AsString; Mail.Title := ADataSet.Fields[5].AsString; Mail.SendTime := ADataSet.Fields[7].AsInteger; Mail.Read := Boolean(ADataSet.Fields[8].AsInteger); if not Mail.Read then Inc(ANewMails); AMailList.Add(Mail); ADataSet.Next; end; AMails := AMailList.Count; finally ADataSet.Free; end; end;{LoadMails} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Get PROCEDURE //------------------------------------------------------------------------------ // What it does- // Get a mail // // Changes - // [2008/06/12] Aeomin - Created // //------------------------------------------------------------------------------ function TMailQueries.Get( const CharID : LongWord; const MailID : LongWord ):TMail; const AQuery = 'SELECT * FROM mailbox WHERE `id`=:ID AND `receiver_id`=:CID'; AUpdateQuery = 'UPDATE mailbox SET `read`=1 WHERE `id`=:ID AND `receiver_id`=:CID;'; var ADataSet : TZQuery; ADataSet2 : TZQuery; AParam : TParam; begin Result := nil; ADataSet := TZQuery.Create(nil); ADataSet2 := TZQuery.Create(nil); //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := MailID; ADataSet.Params.AddParam( AParam ); AParam := ADataset2.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := MailID; ADataSet2.Params.AddParam( AParam ); //CID AParam := ADataset.Params.CreateParam(ftInteger, 'CID', ptInput); AParam.AsInteger := CharID; ADataSet.Params.AddParam( AParam ); AParam := ADataset2.Params.CreateParam(ftInteger, 'CID', ptInput); AParam.AsInteger := CharID; ADataSet2.Params.AddParam( AParam ); try Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin Result := TMail.Create; Result.ID := ADataSet.Fields[0].AsInteger; Result.SenderID := ADataSet.Fields[1].AsInteger; Result.SenderName := ADataSet.Fields[2].AsString; Result.ReceiverID := ADataSet.Fields[3].AsInteger; Result.ReceiverName := ADataSet.Fields[4].AsString; Result.Title := ADataSet.Fields[5].AsString; Result.Content := ADataSet.Fields[6].AsString; Result.SendTime := ADataSet.Fields[7].AsInteger; Result.Read := Boolean(ADataSet.Fields[8].AsInteger); QueryNoResult(ADataSet2, AUpdateQuery); end; finally ADataSet.Free; ADataSet2.Free; end; end;{Get} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Get PROCEDURE //------------------------------------------------------------------------------ // What it does- // Get an mail, w/o modify 'read' // // Changes - // [2008/08/11] Aeomin - Created // //------------------------------------------------------------------------------ function TMailQueries.Get( const MailID : LongWord ):TMail; const AQuery = 'SELECT * FROM mailbox WHERE `id`=:ID;'; var ADataSet : TZQuery; AParam : TParam; begin Result := nil; ADataSet := TZQuery.Create(nil); //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := MailID; ADataSet.Params.AddParam( AParam ); try Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin Result := TMail.Create; Result.ID := ADataSet.Fields[0].AsInteger; Result.SenderID := ADataSet.Fields[1].AsInteger; Result.SenderName := ADataSet.Fields[2].AsString; Result.ReceiverID := ADataSet.Fields[3].AsInteger; Result.ReceiverName := ADataSet.Fields[4].AsString; Result.Title := ADataSet.Fields[5].AsString; Result.Content := ADataSet.Fields[6].AsString; Result.SendTime := ADataSet.Fields[7].AsInteger; Result.Read := Boolean(ADataSet.Fields[8].AsInteger); end; finally ADataSet.Free; end; end;{Get} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Delete PROCEDURE //------------------------------------------------------------------------------ // What it does- // Delete a mail. // // Changes - // [2008/08/09] Aeomin - Created // //------------------------------------------------------------------------------ function TMailQueries.Delete( const CharID : LongWord; const MailID : LongWord ):Boolean; const AQuery = 'SELECT `id` FROM mailbox WHERE `id`=:ID AND `receiver_id`=:CID'; ADeleteQuery = 'DELETE FROM mailbox WHERE `id`=:ID AND `receiver_id`=:CID'; var ADataSet : TZQuery; ADataSet2 : TZQuery; AParam : TParam; begin Result := False; ADataSet := TZQuery.Create(nil); ADataSet2 := TZQuery.Create(nil); //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := MailID; ADataSet.Params.AddParam( AParam ); AParam := ADataset2.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := MailID; ADataSet2.Params.AddParam( AParam ); //CID AParam := ADataset.Params.CreateParam(ftInteger, 'CID', ptInput); AParam.AsInteger := CharID; ADataSet.Params.AddParam( AParam ); AParam := ADataset2.Params.CreateParam(ftInteger, 'CID', ptInput); AParam.AsInteger := CharID; ADataSet2.Params.AddParam( AParam ); try Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin QueryNoResult(ADataSet2, ADeleteQuery); Result := True; end; finally ADataSet.Free; ADataSet2.Free; end; end;{Delete} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Add PROCEDURE //------------------------------------------------------------------------------ // What it does- // Add a mail // // Changes - // [2008/08/09] Aeomin - Created // //------------------------------------------------------------------------------ procedure TMailQueries.Add( const Mail : TMail ); const AQuery = 'INSERT INTO mailbox (`sender_id`,`sender_name`,`receiver_id`,`receiver_name`,`title`,`message`,`time`) VALUES '+ '(:SenderID,:SenderName,:ReceiverID,:ReceiverName,:Title,:Message,:Time);'; ALastID = 'SELECT MAX(id) as id FROM mailbox WHERE `receiver_id`=:ReceiverID;'; var ADataSet : TZQuery; ADataSet2 : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); ADataSet2 := TZQuery.Create(nil); //SenderID AParam := ADataset.Params.CreateParam(ftInteger, 'SenderID', ptInput); AParam.AsInteger := Mail.SenderID; ADataSet.Params.AddParam( AParam ); //SenderName AParam := ADataset.Params.CreateParam(ftString, 'SenderName', ptInput); AParam.AsString := Mail.SenderName; ADataSet.Params.AddParam( AParam ); //ReceiverID AParam := ADataset.Params.CreateParam(ftInteger, 'ReceiverID', ptInput); AParam.AsInteger := Mail.ReceiverID; ADataSet.Params.AddParam( AParam ); AParam := ADataset2.Params.CreateParam(ftInteger, 'ReceiverID', ptInput); AParam.AsInteger := Mail.ReceiverID; ADataSet2.Params.AddParam( AParam ); //ReceiverName AParam := ADataset.Params.CreateParam(ftString, 'ReceiverName', ptInput); AParam.AsString := Mail.ReceiverName; ADataSet.Params.AddParam( AParam ); //Title AParam := ADataset.Params.CreateParam(ftString, 'Title', ptInput); AParam.AsString := Mail.Title; ADataSet.Params.AddParam( AParam ); //Content AParam := ADataset.Params.CreateParam(ftString, 'Message', ptInput); AParam.AsString := Mail.Content; ADataSet.Params.AddParam( AParam ); //Time AParam := ADataset.Params.CreateParam(ftInteger, 'Time', ptInput); AParam.AsInteger := Mail.SendTime; ADataSet.Params.AddParam( AParam ); try QueryNoResult(ADataSet, AQuery); Query(ADataSet2, ALastID); ADataSet2.First; if NOT ADataSet2.Eof then begin Mail.ID := ADataSet2.Fields[0].AsInteger; end; finally ADataSet.Free; ADataSet2.Free; end; end;{Add} //------------------------------------------------------------------------------ end.
unit Gdos; { Version DELPHI } INTERFACE {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses classes,sysutils,util1,debug0; procedure Fsplit(st:AnsiString;var chemin:AnsiString; var nom:AnsiString; var ext:AnsiString); function NomDuFichier(st:AnsiString):AnsiString; function NomDuFichier1(st:AnsiString):AnsiString; function NouvelleExtension(st:AnsiString;ext:AnsiString):AnsiString; function cheminDuFichier(st:AnsiString):AnsiString; function ExtensionDuFichier(st:AnsiString):AnsiString; function RepertoireExiste(st:AnsiString):boolean; function FichierExiste(st:AnsiString):boolean; function TrouverChemin(nom:AnsiString):AnsiString; { Cherche le chemin d'accès au fichier -dans le répertoire courant -dans le répertoire du programme exécuté Nom contient nom+extension ( 12 caractŠres ). le nom complet est TrouverChemin(nom)+nom. Si le chemin n'est pas trouvé, TrouverChemin='!' } function TrouverFichier(nom,parent:AnsiString):AnsiString; { si Nom existe, alors TrouverFichier=nom sinon on cherche dans le répertoire de parent. Si on ne trouve pas, on appelle TrouverChemin. Enfin, si on ne trouve pas du tout, TrouverChemin=''. La valeur renvoyée est un nom de fichier complet. Le PATH n'est plus utilisé dans les deux fonctions précédentes } function espaceDisque(st:AnsiString):intG; { st est un fichier que l'on souhaite ‚crire ou bien le d‚but du chemin d'accŠs. La fonction renvoie l'espace disponible sur le disque } function EffacerFichier(st:AnsiString):boolean; function RenommerFichier(st1,st2:AnsiString):boolean; function copierFichier(st1,st2:AnsiString):boolean; procedure DecomposerNomFichier( st:AnsiString;var chemin:AnsiString; var nom,numero:AnsiString; var extension:AnsiString); function fichierSuivant(st1:AnsiString):AnsiString; function fichierPrecedent(st1:AnsiString):AnsiString; function PremierNomDisponible(st:AnsiString):AnsiString; function getTMPname(stg:AnsiString):AnsiString; procedure resetTMPfiles(stg:AnsiString); function GfileDateTime(stf:AnsiString):TdateTime; function FonctionFileAge(st: AnsiString):TdateTime;pascal; function FonctionFileAge_1(st: AnsiString; mode:integer):TdateTime;pascal; procedure proSplitFileName( st:AnsiString; var chemin:AnsiString;var nom:AnsiString;var extension:AnsiString);pascal; procedure proSplitFileName_1( st:AnsiString; var chemin:PgString;sz1:integer; var nom:PgString; sz2:integer; var extension:PgString;sz4:integer);pascal; procedure proSplitFileNameEx( st:AnsiString;var chemin,nom:AnsiString;var numero:integer;var extension:AnsiString);pascal; procedure proSplitFileNameEx_1( st:AnsiString; var chemin:PgString;sz1:integer; var nom:PgString; sz2:integer; var numero:integer; var extension:PgString;sz4:integer);pascal; function fonctionNextFileEx(st:AnsiString):AnsiString;pascal; function fonctionPreviousFileEx(st:AnsiString):AnsiString;pascal; function compareFiles(st1,st2:AnsiString):integer; { Compare deux fichiers de petite taille: ils doivent tenir en mémoire Renvoie 0 si les fichiers sont identiques -1 si leurs tailles sont différentes n si le premier octet différent est à l'indice n -2 si erreur } IMPLEMENTATION uses ncdef2; procedure Fsplit(st:AnsiString;var chemin:AnsiString; var nom:AnsiString; var ext:AnsiString); var k:integer; begin ext:=extractFileExt(st); chemin:=extractFilePath(st); nom:=extractFileName(st); k:=length(nom)-length(ext)+1; if k>0 then delete(nom,k,100); end; function RepertoireExiste(st:AnsiString):boolean; begin result:=DirectoryExists(st); end; function FichierExiste(st:AnsiString):boolean; begin result:=fileExists(st); end; function NomDuFichier(st:AnsiString):AnsiString; begin result:=extractFileName(st); end; function NomDuFichier1(st:AnsiString):AnsiString; begin result:=extractFileName(st); if pos('.',result)>0 then delete(result,pos('.',result),20); end; function cheminDuFichier(st:AnsiString):AnsiString; begin result:=extractFilePath(st); end; function ExtensionDuFichier(st:AnsiString):AnsiString; begin result:=extractFileExt(st); end; function TrouverChemin(nom:AnsiString):AnsiString; var rep1:AnsiString; name1:AnsiString; ext1:AnsiString; begin trouverChemin:=''; if fichierExiste(nom) then exit; Fsplit(paramstr(0),rep1,name1,ext1); if fichierExiste(rep1+nom) then begin trouverChemin:=rep1; exit; end; trouverChemin:='!'; end; function TrouverFichier(nom,parent:AnsiString):AnsiString; var st:AnsiString; begin if not fichierExiste(nom) then begin st:=cheminDuFichier(parent)+nomDufichier(nom); if fichierExiste(st) then begin trouverFichier:=st; exit; end end else trouverFichier:=nom; end; function espaceDisque(st:AnsiString):intG; var vol:byte; begin st:=Fmaj(st); if st[2]=':' then vol:=ord(st[1])-ord('A')+1 else vol:=0; EspaceDisque:=diskfree(vol); end; function EffacerFichier(st:AnsiString):boolean; begin result:=deleteFile(st); end; function RenommerFichier(st1,st2:AnsiString):boolean; begin result:=renameFile(st1,st2); end; function NouvelleExtension(st:AnsiString;ext:AnsiString):AnsiString; var st1:AnsiString; k:integer; begin st1:=extractFileExt(st); k:=length(st)-length(st1)+1; if k>0 then delete(st,k,100); // le point est aussi supprimé if (length(ext)>0) and (ext[1]<>'.') then ext:='.'+ext; result:=st+ext; end; function copierFichier(st1,st2:AnsiString):boolean; var f1,f2: TfileStream; begin result:=false; f1:=nil; f2:=nil; try f1:=TfileStream.create(st1,fmOpenRead); f2:=TfileStream.create(st2,fmCreate); f2.CopyFrom(f1,f1.size); f2.Free; f2:=nil; f1.Free; result:=true; except f2.free; f1.Free; end; end; procedure DecomposerNomFichier( st:AnsiString;var chemin:AnsiString; var nom,numero:AnsiString; var extension:AnsiString); var i:smallint; nom0:AnsiString; begin {supespace(st);} st:=Fmaj(st); Fsplit(st,chemin,nom0,extension); i:=length(nom0); while (i>0) and (nom0[i] in ['0'..'9']) do dec(i); if i>0 then nom:=copy(nom0,1,i) else nom:=''; if i<length(nom0) then numero:=copy(nom0,i+1,length(nom0)-i) else numero:=''; end; function fichierSuivant(st1:AnsiString):AnsiString; var code:integer; n0,n1,n2:longint; chemin1:AnsiString; nom1,num1:AnsiString; ext1:AnsiString; num2,num0:AnsiString; dirInfo:TsearchRec; doserror:smallint; nom,nomEnt:AnsiString; begin st1:=Fmaj(st1); fichierSuivant:=st1; decomposerNomFichier(st1,chemin1,nom1,num1,ext1); if num1='' then exit; val(num1,n1,code); dosError:=findfirst(chemin1+nom1+'*'+ext1,faarchive+fareadOnly,dirinfo); n0:=maxEntierLong; while doserror=0 do begin nom:=DirInfo.name; num2:=copy(nom,length(nom1)+1, length(nom) -length(nom1)-length(ext1)); val(num2,n2,code); if (code=0) AND ( (n2>n1) or (n2=n1) AND (num2>num1) ) AND ( (n2<n0) or (n2=n0) AND (num2<num0) ) then begin num0:=num2; n0:=n2; nomEnt:=nom; end; dosError:=findNext(dirinfo); end; if n0<maxEntierLong then fichierSuivant:=chemin1+nomEnt; findClose(dirinfo); end; function fichierPrecedent(st1:AnsiString):AnsiString; var code:integer; n0,n1,n2:longint; chemin1:AnsiString; nom1,num1:AnsiString; ext1:AnsiString; num2,num0:AnsiString; nom,nomEnt:AnsiString; dirInfo:TsearchRec; doserror:smallint; begin st1:=Fmaj(st1); fichierPrecedent:=st1; decomposerNomFichier(st1,chemin1,nom1,num1,ext1); if num1='' then exit; val(num1,n1,code); n0:=0; dosError:=findfirst(chemin1+nom1+'*'+ext1,faarchive+fareadOnly,dirinfo); while DosError=0 do begin nom:=DirInfo.name; num2:=copy(nom,length(nom1)+1, length(nom) -length(nom1)-length(ext1)); val(num2,n2,code); if (code=0) AND ( (n2<n1) or (n2=n1) AND (num2<num1) ) AND ( (n2>n0) or (n2=n0) AND (num2>num0) ) then begin n0:=n2; num0:=num2; nomEnt:=nom; end; doserror:=findNext(dirInfo); end; if n0>0 then fichierPrecedent:=chemin1+nomEnt; findClose(dirinfo); end; function PremierNomDisponible(st:AnsiString):AnsiString; var chemin:AnsiString; nom,num,nom1:AnsiString; ext:AnsiString; n:longint; code:integer; i:integer; begin st:=Fmaj(st); premierNomDisponible:=''; decomposerNomFichier(st,chemin,nom,num,ext); nom1:=nom; for i:=1 to 4 do nom1:=nom1+'9'; if fichierExiste(chemin+nom1+ext) then exit; st:=fichierPrecedent(chemin+nom1+ext); if st=chemin+nom1+ext then premierNomDisponible:=chemin+nom+'1'+ext else begin DecomposerNomFichier(st,chemin,nom,num,ext); val(num,n,code); inc(n); str(n,num); premierNomDisponible:=chemin+nom+num+ext; end; end; function getTMPname(stg:AnsiString):AnsiString; begin getTMPname:=premierNomDisponible(AppData+stg+'.TMP'); {messageCentral('Creer '+result);} end; procedure resetTMPfiles(stg:AnsiString); var st,st1:AnsiString; begin st1:=fichierSuivant(AppData+stg+'0.TMP'); if not fichierExiste(st1) then exit; repeat st:=st1; effacerFichier(st); {affdebug('Effacer '+st);} st1:=fichierSuivant(st); until st1=st; end; function GfileDateTime(stf:AnsiString):TdateTime; begin if fichierExiste(stf) then result:=FileDateToDateTime(FileAge(stf)) else result:=0; end; function FonctionFileAge_1(st: AnsiString; mode:integer):TdateTime; begin if not fileExists(st) then sortieErreur('File not found'); result:=FileDateToDateTime(UfileAge(st,mode)); end; function FonctionFileAge(st: AnsiString):TdateTime; begin result:=FonctionFileAge_1(st,1); end; procedure proSplitFileName( st:AnsiString; var chemin:AnsiString;var nom:AnsiString;var extension:AnsiString); begin Fsplit(st,chemin,nom,extension); end; procedure proSplitFileName_1( st:AnsiString; var chemin:PgString;sz1:integer; var nom:PgString; sz2:integer; var extension:PgString;sz4:integer); var Xchemin:shortString absolute chemin; Xnom:shortString absolute nom; Xext:shortString absolute extension; chemin1,nom1,ext1:AnsiString; begin Fsplit(st,chemin1,nom1,ext1); Xchemin:=copy(chemin1,1,sz1-1); Xnom:=copy(nom1,1,sz2-1); Xext:=copy(ext1,1,sz4-1); end; procedure proSplitFileNameEx( st:AnsiString;var chemin,nom:AnsiString;var numero:integer;var extension:AnsiString); var num1:AnsiString; code:integer; begin decomposerNomFichier(st,chemin,nom,num1,extension); val(num1,numero,code); if code<>0 then numero:=-1; end; procedure proSplitFileNameEx_1( st:AnsiString; var chemin:PgString;sz1:integer; var nom:PgString; sz2:integer; var numero:integer; var extension:PgString;sz4:integer); var Xchemin:shortString absolute chemin; Xnom:shortString absolute nom; Xext:shortString absolute extension; chemin1,nom1,num1,ext1:AnsiString; code:integer; begin decomposerNomFichier(st,chemin1,nom1,num1,ext1); Xchemin:=copy(chemin1,1,sz1-1); Xnom:=copy(nom1,1,sz2-1); Xext:=copy(ext1,1,sz4-1); val(num1,numero,code); if code<>0 then numero:=-1; end; function fonctionNextFileEx(st:AnsiString):AnsiString; begin result:=fichierSuivant(st); if Fmaj(st)=Fmaj(result) then result:=''; end; function fonctionPreviousFileEx(st:AnsiString):AnsiString; begin result:=fichierPrecedent(st); if Fmaj(st)=Fmaj(result) then result:=''; end; function compareFiles(st1,st2:AnsiString):integer; var f:TfileStream; sz1,sz2,res:integer; i:integer; p1,p2:PtabOctet; begin result:=-2; p1:=nil; p2:=nil; f:=nil; try f:=TfileStream.create(st1,fmOpenRead); sz1:=f.size; getmem(p1,sz1); f.read(p1^,sz1); f.free; f:=nil; f:=TfileStream.create(st2,fmOpenRead); sz2:=f.size; getmem(p2,sz2); f.read(p2^,sz2); f.free; f:=nil; if sz1<>sz2 then result:=-1 else result:=0; if result=0 then for i:=0 to sz1-1 do if p1^[i]<>p2^[i] then begin result:=i; break; end; freemem(p1); p1:=nil; freemem(p2); p2:=nil; except freemem(p1); freemem(p2); f.free; end; end; Initialization AffDebug('Initialization Gdos',0); AppDir:= extractFilePath(paramstr(0)); if DirectoryExists(AppDir+'AppData') then AppData:=AppDir+'AppData\' else AppData:=AppDir; end.
unit uFaceRecognizer; interface uses Winapi.Windows, Generics.Defaults, Generics.Collections, System.Math, System.Classes, System.SysUtils, System.SyncObjs, System.IOUtils, System.Types, Vcl.Graphics, Xml.xmldom, OpenCV.Core, OpenCV.Utils, OpenCV.ImgProc, OpenCV.Legacy, OpenCV.HighGUI, Dmitry.Utils.System, Dmitry.Utils.Files, uMemory, uGuidUtils, uLogger; type TFaceRecognitionResult = class private FFace: TBitmap; function GetPercent: Double; function GetIsValid: Boolean; public PersonId: Integer; Index: Integer; FaceId: Integer; HasNegative: Boolean; Distance: Double; Threshold: Double; constructor Create; destructor Destroy; override; procedure SetFace(Face: TBitmap); function ExtractBitmap: TBitmap; property Percents: Double read GetPercent; property IsValid: Boolean read GetIsValid; end; TFaceRecognitionResults = class private FData: TList<TFaceRecognitionResult>; function GetCount: Integer; function GetItemByIndex(Index: Integer): TFaceRecognitionResult; public constructor Create; destructor Destroy; override; procedure Add(Item: TFaceRecognitionResult); property Count: Integer read GetCount; property Items[Index: Integer]: TFaceRecognitionResult read GetItemByIndex; default; end; TEigenThresholdFunction = reference to function(CountOfFaces: Integer): Double; IFaceRecognizer = Interface ['{4084C125-FB9B-4DED-9732-EE6B7B90D0FA}'] function SaveState(Path: string): Boolean; function LoadState(Path: string): Boolean; function Train: Boolean; //simple add face to detection collection function HasPerson(PersonId: Integer): Boolean; function HasFace(FaceId: Integer): Boolean; function RemoveFaceById(FaceId: Integer): Boolean; function MoveFaceToAnotherPerson(FaceId: Integer; PersonId: Integer): Boolean; function TrainFace(Face: TBitmap; Image: TBitmap; PersonId: Integer; FaceId: Integer; Quality: Byte): Boolean; overload; function TrainFace(Face: pIplImage; Image: TBitmap; PersonId: Integer; FaceId: Integer; Quality: Byte): Boolean; overload; //resolve person by image function RecognizeFace(Face: TBitmap; PersonsToSearch: Integer): TFaceRecognitionResults; overload; function RecognizeFace(Face: TBitmap): Integer; overload; function RecognizeFace(Face: pIplImage): Integer; overload; function GetFacesCount: Integer; end; TPersonFaces = class; TPersonFace = class private FFaceImage: pIplImage; FSuccessCount: Integer; FFailedCound: Integer; FFaces: TPersonFaces; FQuality: Byte; FImageId: Integer; FFaceId: Integer; FAreaRect: TRect; FUID: TGUID; FLastUsedDate: TDateTime; FImage: TBitmap; function GetScore: Double; public destructor Destroy; override; constructor Create(FaceImage: pIplImage; Image: TBitmap; FaceId: Integer; Quality: Byte; Faces: TPersonFaces); constructor CreateFromFile(XmlFileName: string); procedure SaveToFile(XmlFileName: string); procedure IncSuccess; procedure IncFail; property Face: pIplImage read FFaceImage; property Person: TPersonFaces read FFaces; property Quality: Byte read FQuality; property Score: Double read GetScore; property UID: TGUID read FUID; end; TPersonFaces = class private FPersonId: Integer; FFaces: TList<TPersonFace>; FCapacity: Integer; function GetFacesCount: Integer; function GetFace(Index: Integer): TPersonFace; function GetMinQuality: Byte; public constructor Create(PersonId: Integer; Capacity: Integer); destructor Destroy; override; function AddFace(Face: pIplImage; Image: TBitmap; FaceId: Integer; Quality: Byte): TPersonFace; procedure Add(Face: TPersonFace); function AddNotFoundFace(Face: pIplImage; Image: TBitmap; FaceId: Integer; Quality: Byte): TPersonFace; procedure CleanUp; procedure IncFail; property Id: Integer read FPersonId; property FacesCount: Integer read GetFacesCount; property Faces[Index: Integer]: TPersonFace read GetFace; property MinQuality: Byte read GetMinQuality; end; TFaceRecognitionInternalResult = record PersonId: Integer; Index: Integer; Distance: Double; HasNegative: Boolean; Face: TPersonFace; end; TFaceRecognitionInternalResults = array of TFaceRecognitionInternalResult; TFaceEigenRecognizer = class(TInterfacedObject, IFaceRecognizer) private FSync: TCriticalSection; FSize: TCvSize; FMaxFacesPerPerson: Integer; FMaxFaces: Integer; FPersons: TList<TPersonFaces>; FTrainedFacesCount: Integer; FTrainedFaces: array of TPersonFace; FIsTrained: Boolean; FEigImg: array[0..255] of pIplImage; FMeanImg: pIplImage; // Average face (float point) FCoeffs: array[0..255] of array[0..255] of Float; FEigenVals: pCvMat; FThresholdFunc: TEigenThresholdFunction; FLoadedPath: string; SamplesArray: array[0..255] of pIplImage; procedure ClearTrainingMemory; function FindFaces(FaceImage: pIplImage; MaxItems: Integer): TFaceRecognitionInternalResults; function FindFace(FaceImage: pIplImage): TPersonFace; function FindPerson(PersonId: Integer): TPersonFaces; function AddPerson(FaceImage: pIplImage; Image: TBitmap; Quality: Byte; PersonId, FaceId: Integer): TPersonFaces; overload; function AddPerson(PersonId: Integer; Face: TPersonFace): TPersonFaces; overload; procedure CleanUp1Face; function Train: Boolean; public constructor Create(Width, Height: Integer; MaxFacesPerPerson, MaxFaces: Integer; ThresholdFunc: TEigenThresholdFunction = nil); destructor Destroy; override; function SaveState(Path: string): Boolean; function LoadState(Path: string): Boolean; function HasPerson(PersonId: Integer): Boolean; function HasFace(FaceId: Integer): Boolean; function RemoveFaceById(FaceId: Integer): Boolean; function MoveFaceToAnotherPerson(FaceId: Integer; PersonId: Integer): Boolean; function TrainFace(Face: TBitmap; Image: TBitmap; PersonId: Integer; FaceId: Integer; Quality: Byte): Boolean; overload; function TrainFace(Face: pIplImage; Image: TBitmap; PersonId: Integer; FaceId: Integer; Quality: Byte): Boolean; overload; function RecognizeFace(Face: TBitmap): Integer; overload; function RecognizeFace(Face: pIplImage): Integer; overload; function RecognizeFace(Face: TBitmap; PersonsToSearch: Integer): TFaceRecognitionResults; overload; function GetFacesCount: Integer; end; implementation { TPersonFace } constructor TPersonFace.Create(FaceImage: pIplImage; Image: TBitmap; FaceId: Integer; Quality: Byte; Faces: TPersonFaces); begin FFaceImage := cvCreateImage(CvSize(FaceImage.width, FaceImage.height), FaceImage.depth, FaceImage.nChannels); cvSplit(FaceImage, FFaceImage, nil, nil, nil); FUID := GetGUID; FQuality := Quality; FSuccessCount := 0; FFailedCound := 0; FFaces := Faces; FLastUsedDate := Now; FFaceId := FaceId; FImage := Image; end; constructor TPersonFace.CreateFromFile(XmlFileName: string); var Doc: IDOMDocument; DocumentElement: IDOMElement; ImageFileName: string; B: TBitmap; Size: TCvSize; begin Doc := GetDOM.createDocument('', '', nil); try (Doc as IDOMPersist).load(XmlFileName); DocumentElement := Doc.documentElement; FSuccessCount := StrToInt(DocumentElement.attributes.getNamedItem('SuccessCount').nodeValue); FFailedCound := StrToInt(DocumentElement.attributes.getNamedItem('FailedCound').nodeValue); FQuality := StrToInt(DocumentElement.attributes.getNamedItem('Quality').nodeValue); FImageId := StrToInt(DocumentElement.attributes.getNamedItem('ImageId').nodeValue); FFaceId := StrToInt(DocumentElement.attributes.getNamedItem('FaceId').nodeValue); FUID := StringToGUID(DocumentElement.attributes.getNamedItem('UID').nodeValue); FAreaRect := Rect( StrToInt(DocumentElement.attributes.getNamedItem('Left').nodeValue), StrToInt(DocumentElement.attributes.getNamedItem('Top').nodeValue), StrToInt(DocumentElement.attributes.getNamedItem('Right').nodeValue), StrToInt(DocumentElement.attributes.getNamedItem('Bottom').nodeValue) ); ImageFileName := ExtractFilePath(XmlFileName) + GUIDToString(FUID) + '_face.bmp'; B := TBitmap.Create; try B.LoadFromFile(ImageFileName); Size := CvSize(B.Width, B.Height); FFaceImage := cvCreateImage(Size, IPL_DEPTH_8U, 1); Bitmap2IplImage(FFaceImage, B); finally F(B); end; ImageFileName := ExtractFilePath(XmlFileName) + GUIDToString(FUID) + '_image.bmp'; FImage := TBitmap.Create; FImage.LoadFromFile(ImageFileName); except on e: Exception do EventLog(e); end; end; procedure TPersonFace.SaveToFile(XmlFileName: string); var Doc: IDOMDocument; DocumentElement: IDOMElement; FaceNode: IDOMNode; ImageFileName: string; FaceImage: TBitmap; procedure AddXmlProperty(Name: string; Value: string); var Attr: IDOMAttr; begin Attr := Doc.createAttribute(Name); Attr.value := Value; FaceNode.attributes.setNamedItem(Attr); end; begin Doc := GetDOM.createDocument('', '', nil); try DocumentElement := Doc.createElement('faces'); Doc.documentElement := DocumentElement; FaceNode := DocumentElement; AddXmlProperty('SuccessCount', IntToStr(FSuccessCount)); AddXmlProperty('FailedCound', IntToStr(FFailedCound)); AddXmlProperty('Quality', IntToStr(FQuality)); AddXmlProperty('ImageId', IntToStr(FImageId)); AddXmlProperty('FaceId', IntToStr(FFaceId)); AddXmlProperty('UID', GUIDToString(FUID)); AddXmlProperty('Left', IntToStr(FAreaRect.Left)); AddXmlProperty('Top', IntToStr(FAreaRect.Top)); AddXmlProperty('Right', IntToStr(FAreaRect.Right)); AddXmlProperty('Bottom', IntToStr(FAreaRect.Bottom)); (Doc as IDOMPersist).save(XmlFileName); FaceImage := TBitmap.Create; try FaceImage.PixelFormat := pf24Bit; IplImage2Bitmap(FFaceImage, FaceImage); ImageFileName := ChangeFileExt(ExtractFilePath(XmlFileName) + GUIDToString(FUID), '_face.bmp'); FaceImage.SaveToFile(ImageFileName); if (FImage <> nil) and not FImage.Empty then begin ImageFileName := ChangeFileExt(ExtractFilePath(XmlFileName) + GUIDToString(FUID), '_image.bmp'); FImage.SaveToFile(ImageFileName); end; finally F(FaceImage); end; except on e: Exception do EventLog(e); end; end; destructor TPersonFace.Destroy; begin cvReleaseImage(FFaceImage); F(FImage); inherited; end; function TPersonFace.GetScore: Double; begin if FFailedCound > 0 then Result := (FSuccessCount / (1.1 - (Quality / 100)) - FFailedCound) / FFailedCound else Result := FSuccessCount / (1.1 - (Quality / 100)); end; procedure TPersonFace.IncFail; begin Inc(FFailedCound); end; procedure TPersonFace.IncSuccess; begin Inc(FSuccessCount); FLastUsedDate := Now; end; { TPersonFaces } procedure TPersonFaces.Add(Face: TPersonFace); begin Face.FFaces := Self; FFaces.Add(Face); end; function TPersonFaces.AddFace(Face: pIplImage; Image: TBitmap; FaceId: Integer; Quality: Byte): TPersonFace; begin Result := TPersonFace.Create(Face, Image, FaceId, Quality, Self); Result.IncSuccess; FFaces.Add(Result); CleanUp(); end; function TPersonFaces.AddNotFoundFace(Face: pIplImage; Image: TBitmap; FaceId: Integer; Quality: Byte): TPersonFace; begin IncFail; Result := TPersonFace.Create(Face, Image, FaceId, Quality, Self); Result.IncSuccess; FFaces.Add(Result); CleanUp(); end; procedure TPersonFaces.IncFail; var I: Integer; begin for I := 0 to FacesCount - 1 do Faces[I].IncFail; CleanUp; end; procedure TPersonFaces.CleanUp; var I: Integer; MinScore, Score: Double; FaceToRemove: TPersonFace; begin if FacesCount <= FCapacity then Exit; MinScore := MaxDouble; FaceToRemove := nil; for I := 0 to FacesCount - 1 do begin Score := Faces[I].Score; if Score < MinScore then begin FaceToRemove := Faces[I]; MinScore := Score; end; end; if FaceToRemove <> nil then begin FFaces.Remove(FaceToRemove); F(FaceToRemove); end; end; constructor TPersonFaces.Create(PersonId: Integer; Capacity: Integer); begin FPersonId := PersonId; FCapacity := Capacity; FFaces := TList<TPersonFace>.Create; end; destructor TPersonFaces.Destroy; begin FreeList(FFaces); inherited; end; function TPersonFaces.GetFace(Index: Integer): TPersonFace; begin Result := FFaces[Index]; end; function TPersonFaces.GetFacesCount: Integer; begin Result := FFaces.Count; end; function TPersonFaces.GetMinQuality: Byte; var I: Integer; begin Result := 255; for I := 0 to FacesCount - 1 do if Faces[I].Quality < Result then Result := Faces[I].Quality; end; { TFaceDetector } constructor TFaceEigenRecognizer.Create(Width, Height: Integer; MaxFacesPerPerson, MaxFaces: Integer; ThresholdFunc: TEigenThresholdFunction = nil); begin FSize.width := Width; FSize.height := Height; FMaxFacesPerPerson := MaxFacesPerPerson; FMaxFaces := MaxFaces; FSync := TCriticalSection.Create; FPersons := TList<TPersonFaces>.Create; FTrainedFacesCount := 0; FIsTrained := False; FThresholdFunc := ThresholdFunc; if not Assigned(FThresholdFunc) then FThresholdFunc := function(N: Integer): Double begin //Result := LogN(9, N - 1) / 2.2; Result := LogN(3.9, N - 1) / 3; //2% Fail Result := LogN(3, N - 1) / 7.2; end; FillChar(FEigImg, SizeOf(FEigImg), 0); SetLength(FTrainedFaces, 0); FMeanImg := nil; // Average face (float point) FEigenVals := nil; end; destructor TFaceEigenRecognizer.Destroy; begin ClearTrainingMemory; FreeList(FPersons); F(FSync); inherited; end; function TFaceEigenRecognizer.AddPerson(PersonId: Integer; Face: TPersonFace): TPersonFaces; begin FIsTrained := False; Result := TPersonFaces.Create(PersonId, FMaxFacesPerPerson); Result.Add(Face); FPersons.Add(Result); end; function TFaceEigenRecognizer.AddPerson(FaceImage: pIplImage; Image: TBitmap; Quality: Byte; PersonId, FaceId: Integer): TPersonFaces; begin FIsTrained := False; Result := TPersonFaces.Create(PersonId, FMaxFacesPerPerson); Result.AddFace(FaceImage, Image, FaceId, Quality); FPersons.Add(Result); end; function TFaceEigenRecognizer.FindPerson(PersonId: Integer): TPersonFaces; var I: Integer; begin Result := nil; for I := 0 to FPersons.Count - 1 do if FPersons[I].Id = PersonId then Exit(FPersons[I]); end; function TFaceEigenRecognizer.GetFacesCount: Integer; var I: Integer; begin Result := 0; for I := 0 to FPersons.Count - 1 do Inc(Result, FPersons[I].FacesCount); end; function TFaceEigenRecognizer.HasFace(FaceId: Integer): Boolean; var I, J: Integer; begin Result := False; for I := 0 to FPersons.Count - 1 do for J := 0 to FPersons[I].FacesCount - 1 do if FPersons[I].Faces[J].FFaceId = FaceId then Exit(True); end; function TFaceEigenRecognizer.HasPerson(PersonId: Integer): Boolean; begin Result := FindPerson(PersonId) <> nil; end; function TFaceEigenRecognizer.RecognizeFace(Face: TBitmap; PersonsToSearch: Integer): TFaceRecognitionResults; var Results: TFaceRecognitionInternalResults; MaxDistance: Double; I: Integer; CvFaceImage, CvTestImage: pIplImage; ResultItem: TFaceRecognitionResult; begin Result := TFaceRecognitionResults.Create; FSync.Enter; try CvFaceImage := cvCreateImage(FSize, IPL_DEPTH_8U, 3); try Bitmap2IplImage(CvFaceImage, Face); CvTestImage := cvCreateImage(FSize, IPL_DEPTH_8U, 1); try cvCvtColor(CvFaceImage, CvTestImage, CV_BGR2GRAY ); cvEqualizeHist(CvTestImage, CvTestImage); Results := FindFaces(CvTestImage, PersonsToSearch); MaxDistance := FThresholdFunc(GetFacesCount); for I := 0 to Length(Results) - 1 do begin ResultItem := TFaceRecognitionResult.Create; Result.Add(ResultItem); ResultItem.PersonId := Results[I].PersonId; ResultItem.Index := Results[I].Index; ResultItem.Threshold := MaxDistance; ResultItem.Distance := Results[I].Distance; ResultItem.HasNegative := Results[I].HasNegative; ResultItem.SetFace(Results[I].Face.FImage); end; finally cvReleaseImage(CvTestImage); end; finally cvReleaseImage(CvFaceImage); end; finally FSync.Leave; end; end; function TFaceEigenRecognizer.RecognizeFace(Face: pIplImage): Integer; var Results: TFaceRecognitionInternalResults; begin Result := 0; FSync.Enter; try Results := FindFaces(Face, 1); if Length(Results) > 0 then Exit(Results[0].PersonId); finally FSync.Leave; end; end; function TFaceEigenRecognizer.RecognizeFace(Face: TBitmap): Integer; var CvFaceImage, CvTestImage: pIplImage; begin CvFaceImage := cvCreateImage(FSize, IPL_DEPTH_8U, 3); try Bitmap2IplImage(CvFaceImage, Face); CvTestImage := cvCreateImage(FSize, IPL_DEPTH_8U, 1); try cvCvtColor(CvFaceImage, CvTestImage, CV_BGR2GRAY ); cvEqualizeHist(CvTestImage, CvTestImage); Result := RecognizeFace(CvTestImage); finally cvReleaseImage(CvTestImage); end; finally cvReleaseImage(CvFaceImage); end; end; procedure TFaceEigenRecognizer.CleanUp1Face; var I, J: Integer; MinScore: Double; FMinPerson: TPersonFaces; FMinFace: TPersonFace; begin MinScore := MaxDouble; FMinPerson := nil; FMinFace := nil; for I := 0 to FPersons.Count - 1 do begin for J := 0 to FPersons[I].FacesCount - 1 do begin if MinScore > FPersons[I].Faces[J].Score then begin MinScore := FPersons[I].Faces[J].Score; FMinPerson := FPersons[I]; FMinFace := FPersons[I].Faces[J]; end; end; end; if FMinPerson <> nil then begin FMinPerson.FFaces.Remove(FMinFace); F(FMinFace); FIsTrained := False; end; end; procedure TFaceEigenRecognizer.ClearTrainingMemory; var I: Integer; Image: pIplImage; begin if Assigned(FEigenVals) then begin cvReleaseMat(FEigenVals); FEigenVals := nil; end; if Assigned(FMeanImg) then begin cvReleaseImage(FMeanImg); FMeanImg := nil; end; for I := Low(FEigImg) to High(FEigImg) do begin if Assigned(FEigImg[I]) then begin Image := FEigImg[I]; cvReleaseImage(Image); end; end; FillChar(FEigImg, SizeOf(FEigImg), 0); SetLength(FTrainedFaces, 0); end; function TFaceEigenRecognizer.SaveState(Path: string): Boolean; var I, J: Integer; P: TPersonFaces; Face: TPersonFace; PersonDirectory, FaceXmlFileName: string; begin Result := True; DeleteDirectoryWithFiles(Path); CreateDir(Path); FSync.Enter; try for I := 0 to FPersons.Count - 1 do begin P := FPersons[I]; PersonDirectory := IncludeTrailingBackslash(Path) + IntToStr(P.FPersonId); CreateDir(PersonDirectory); for J := 0 to P.FacesCount - 1 do begin Face := P.Faces[J]; FaceXmlFileName := IncludeTrailingBackslash(PersonDirectory) + GUIDToString(Face.UID) + '.xml'; Face.SaveToFile(FaceXmlFileName); end; end; finally FSync.Leave; end; end; function TFaceEigenRecognizer.LoadState(Path: string): Boolean; var PersonId: Integer; P: TPersonFaces; Face: TPersonFace; PersonDir, FaceFileName: string; begin Result := True; FSync.Enter; try if TDirectory.Exists(Path) then for PersonDir in TDirectory.GetDirectories(Path) do begin P := nil; PersonId := StrToIntDef(ExtractFileName(PersonDir), 0); if PersonId > 0 then begin for FaceFileName in TDirectory.GetFiles(PersonDir, '*.xml') do begin if GetFacesCount > FMaxFaces then CleanUp1Face; Face := TPersonFace.CreateFromFile(FaceFileName); if Face.FFaceImage <> nil then begin if P = nil then begin P := TPersonFaces.Create(PersonId, FMaxFacesPerPerson); FPersons.Add(P); end; P.Add(Face); end else F(Face); end; end; end; FLoadedPath := Path; finally FSync.Leave; end; end; function TFaceEigenRecognizer.MoveFaceToAnotherPerson(FaceId, PersonId: Integer): Boolean; var I, J: Integer; Face: TPersonFace; Person: TPersonFaces; begin Result := False; FSync.Enter; try for I := 0 to FPersons.Count - 1 do begin for J := FPersons[I].FacesCount - 1 downto 0 do if FPersons[I].Faces[J].FFaceId = FaceId then begin Face := FPersons[I].Faces[J]; FPersons[I].FFaces.Remove(Face); Person := FindPerson(PersonId); if Person <> nil then Person.Add(Face) else AddPerson(PersonId, Face); FIsTrained := False; Result := True; end; end; finally FSync.Leave; end; end; function TFaceEigenRecognizer.RemoveFaceById(FaceId: Integer): Boolean; var I, J: Integer; Face: TPersonFace; begin Result := False; FSync.Enter; try for I := 0 to FPersons.Count - 1 do begin for J := FPersons[I].FacesCount - 1 downto 0 do if FPersons[I].Faces[J].FFaceId = FaceId then begin Face := FPersons[I].Faces[J]; FPersons[I].FFaces.Remove(Face); F(Face); FIsTrained := False; Result := True; end; end; finally FSync.Leave; end; end; function TFaceEigenRecognizer.Train: Boolean; var I, J: Integer; Tc: TCvTermCriteria; NEigens: Integer; Person: TPersonFaces; begin ClearTrainingMemory; if GetFacesCount < 2 then Exit(False); FillChar(SamplesArray, SizeOf(SamplesArray), 0); FTrainedFacesCount := 0; for I := 0 to FPersons.Count - 1 do begin Person := FPersons[I]; for J := 0 to Person.FacesCount - 1 do begin SamplesArray[FTrainedFacesCount] := Person.Faces[J].Face; SetLength(FTrainedFaces, Length(FTrainedFaces) + 1); FTrainedFaces[Length(FTrainedFaces) - 1] := Person.Faces[J]; Inc(FTrainedFacesCount); {$IFDEF DEBUG} //SavePIplImageAsBitmap(FTrainedFaces[Length(FTrainedFaces) - 1].Face, 'd:\trainset\' + IntToStr(Length(FTrainedFaces) - 1) + '.bmp'); {$ENDIF} end; end; SaveState(FLoadedPath); FMeanImg := cvCreateImage(FSize, IPL_DEPTH_32F, 1); // ----------------------------------------------------- // Cound of basis vectors = #images - 1 // ----------------------------------------------------- NEigens := FTrainedFacesCount - 1; // ----------------------------------- // Set criteria to terminate process // ----------------------------------- Tc.cType := CV_TERMCRIT_NUMBER; Tc.max_iter := NEigens; Tc.epsilon := 0; // This is a basis FillChar(FEigImg, SizeOf(FEigImg), 0); FEigenVals := cvCreateMat(1, NEigens, CV_32FC1); // Get memory for basis for I := 0 to NEigens - 1 do FEigImg[I] := cvCreateImage(FSize, IPL_DEPTH_32F, 1); // Calculate basis cvCalcEigenObjects( FTrainedFacesCount, @SamplesArray, @FEigImg, CV_EIGOBJ_NO_CALLBACK, 0, nil, @Tc, FMeanImg, pFloat(FEigenVals.Data)); // ----------------------------------------------------------- // Разложение тестируемого изображения по полученному базису // ----------------------------------------------------------- for I := 0 to FTrainedFacesCount - 1 do begin cvEigenDecomposite( SamplesArray[I], NEigens, @FEigImg, CV_EIGOBJ_NO_CALLBACK, nil, FMeanImg, @FCoeffs[I]); end; FIsTrained := True; Result := True; end; function TFaceEigenRecognizer.TrainFace(Face: TBitmap; Image: TBitmap; PersonId: Integer; FaceId: Integer; Quality: Byte): Boolean; var CvFace, CvSampleFace: pIplImage; begin CvFace := cvCreateImage(FSize, IPL_DEPTH_8U, 3); Bitmap2IplImage(CvFace, Face); CvSampleFace := cvCreateImage(FSize, IPL_DEPTH_8U, 1); cvCvtColor(CvFace, CvSampleFace, CV_BGR2GRAY ); cvEqualizeHist(CvSampleFace, CvSampleFace); Result := TrainFace(CvSampleFace, Image, PersonId, FaceId, Quality); cvReleaseImage(CvFace); cvReleaseImage(CvSampleFace); end; function TFaceEigenRecognizer.TrainFace(Face: pIplImage; Image: TBitmap; PersonId: Integer; FaceId: Integer; Quality: Byte): Boolean; var Person: TPersonFaces; FaceItem: TPersonFace; begin Result := FTrainedFacesCount > 2; FSync.Enter; try if GetFacesCount > FMaxFaces then CleanUp1Face; FaceItem := FindFace(Face); if FaceItem = nil then begin Person := FindPerson(PersonId); if Person = nil then AddPerson(Face, Image, Quality, PersonId, FaceId) else begin Person.AddNotFoundFace(Face, Image, FaceId, Quality); FIsTrained := False; end; Exit; end; Person := FaceItem.Person; if FaceItem.Person.Id = PersonId then begin FaceItem.IncSuccess; if Quality > Person.MinQuality then begin FIsTrained := False; Person.AddFace(Face, Image, FaceId, Quality); end else F(Image); Exit; end; FaceItem.IncFail; Person := FindPerson(PersonId); if Person = nil then begin FIsTrained := False; AddPerson(Face, Image, Quality, PersonId, FaceId); Exit; end; FIsTrained := False; Person.AddNotFoundFace(Face, Image, FaceId, Quality); finally FSync.Leave; end; end; function TFaceEigenRecognizer.FindFace(FaceImage: pIplImage): TPersonFace; var Results: TFaceRecognitionInternalResults; MaxDistance: Double; begin Result := nil; MaxDistance := FThresholdFunc(GetFacesCount); Results := FindFaces(FaceImage, 1); if (Length(Results) > 0) and (MaxDistance > Results[0].Distance) then Result := Results[0].Face; end; function TFaceEigenRecognizer.FindFaces(FaceImage: pIplImage; MaxItems: Integer): TFaceRecognitionInternalResults; type TFaceDistance = record Face: TPersonFace; Distance: Double; Index: Integer; end; var ProjectedTestFaces: array[0..255] of Float; FL: Float; I, NEigens, ITrain: Integer; DI, DistSq: Float; FD: TFaceDistance; FaceDistances: TList<TFaceDistance>; HasNegative: Boolean; function PersonExistsInResults(Res: TFaceRecognitionInternalResults; PersonId: Integer): Boolean; var I: Integer; begin Result := False; for I := 0 to Length(Res) - 1 do if Res[I].PersonId = PersonId then Exit(True); end; begin SetLength(Result, 0); if not FIsTrained and not Train then Exit; HasNegative := False; FillChar(ProjectedTestFaces, SizeOf(ProjectedTestFaces), 0); // ----------------------------------------------------------- // Load test image // ----------------------------------------------------------- cvEigenDecomposite( FaceImage, FTrainedFacesCount - 1, @FEigImg, CV_EIGOBJ_NO_CALLBACK, nil, FMeanImg, @ProjectedTestFaces); // ----------------------------------------------------------- FaceDistances := TList<TFaceDistance>.Create; try NEigens := FTrainedFacesCount - 1; for ITrain := 0 to FTrainedFacesCount - 1 do begin DistSq := 0; for I := 0 to NEigens - 1 do begin DI := ProjectedTestFaces[I] - FCoeffs[ITrain][I]; FL := pFloat(FEigenVals.Data)[I]; if FL < 0 then begin HasNegative := True; FL := Abs(FL); end; if IsNan(FL) or (FL = 0) then DistSq := DBL_MAX else DistSq := DistSq + DI * DI / FL; end; FD.Face := FTrainedFaces[ITrain]; FD.Distance := DistSq; FD.Index := ITrain; FaceDistances.Add(FD); end; FaceDistances.Sort(TComparer<TFaceDistance>.Construct( function (const L, R: TFaceDistance): Integer begin if L.Distance = R.Distance then Exit(0); Result := IIF(Abs(L.Distance) - Abs(R.Distance) < 0, -1, 1); end )); if (FaceDistances.Count > 0) then begin for I := 0 to FaceDistances.Count - 1 do begin if not PersonExistsInResults(Result, FaceDistances[I].Face.Person.FPersonId) then begin SetLength(Result, Length(Result) + 1); Result[Length(Result) - 1].PersonId := FaceDistances[I].Face.Person.FPersonId; Result[Length(Result) - 1].Distance := FaceDistances[I].Distance; Result[Length(Result) - 1].Index := I; Result[Length(Result) - 1].HasNegative := HasNegative; Result[Length(Result) - 1].Face := FaceDistances[I].Face; if Length(Result) = MaxItems then Break; end; {$IFDEF DEBUG} (*if I = 0 then begin cvNamedWindow('SearchFor', 0); cvNamedWindow('Found', 0); cvShowImage('SearchFor', FaceImage); cvShowImage('Found', FaceDistances[I].Face.FFaceImage); cvWaitKey(10); end;*) {$ENDIF} end; end; finally F(FaceDistances); end; end; { TFaceRecognitionResults } procedure TFaceRecognitionResults.Add(Item: TFaceRecognitionResult); begin FData.Add(Item); end; constructor TFaceRecognitionResults.Create; begin FData := TList<TFaceRecognitionResult>.Create; end; destructor TFaceRecognitionResults.Destroy; begin FreeList(FData); inherited; end; function TFaceRecognitionResults.GetCount: Integer; begin Result := FData.Count; end; function TFaceRecognitionResults.GetItemByIndex(Index: Integer): TFaceRecognitionResult; begin Result := FData[Index]; end; { TFaceRecognitionResult } constructor TFaceRecognitionResult.Create; begin FFace := nil; end; destructor TFaceRecognitionResult.Destroy; begin F(FFace); inherited; end; function TFaceRecognitionResult.ExtractBitmap: TBitmap; begin Result := FFace; FFace := nil; end; function TFaceRecognitionResult.GetIsValid: Boolean; begin Result := Percents > 0; end; function TFaceRecognitionResult.GetPercent: Double; begin Result := 100 * (Threshold - Distance) / Threshold; if Result < 0 then Result := 0; end; procedure TFaceRecognitionResult.SetFace(Face: TBitmap); begin if (Face <> nil) and not Face.Empty then begin FFace := TBitmap.Create; FFace.Assign(Face); Exit; end; FFace := nil; end; end.
{ Sa se scrie un program care determina fluxul maxim intr-o retea de transport folosind algoritmul lui Ford-Fulkerson. } uses crt; const maxvirf=20; type matrad=array [1..maxvirf,1..maxvirf] of integer; { matrice de adiacenta } drum=array [1..maxvirf] of integer; { drum intre doua virfuri } var n:integer; { numarul de virfuri in graf } m:integer; { numarul arcelor in graf } c:matrad; { graful capacitatilor } s,d:integer; { sursa si destinatia } fi:array [1..maxvirf,1..maxvirf] of integer; { fluxul maxim in graf } ft:integer; { fluxul total in graf } i,j,k,l,cod:integer; f:text; procedure CautaDrum(n:integer;var a:matrad;s,d:integer; var k:integer;var dr:drum); { Cauta un drum in graful cu n virfuri si matricea de adiacenta a intre s si d. Returneaza in k numarul virfurilor prin care trece drumul gasit si in dr aceste virfuri in ordine inversa. (alg. Moore-Dijkstra) } var V1,V2,V3:set of byte; landa:array [1..maxvirf] of integer; i,j,l:integer; begin l:=0;V1:=[s];V2:=[s]; for i:=1 to n do landa[i]:=32767; landa[s]:=0; repeat V3:=[]; for i:=1 to n do if i in V1 then for j:=1 to n do if (a[i,j]<>0) then begin if not(j in V2) then begin V3:=V3+[j];landa[j]:=l+1 end; if j=d then begin k:=1;dr[k]:=d; while landa[j]>0 do begin i:=1; while not((a[i,j]<>0) and (landa[i]=landa[j]-1)) do i:=i+1; j:=i;k:=k+1;dr[k]:=j; end; exit; end; end; V1:=V3; V2:=V2+V1; l:=l+1; until V1=[]; k:=0; end; procedure FordFulkerson; { Calcularea fluxului maxim in graf folosind algoritmul lui Ford-Fulkerson } var i,j,k:integer; ge:matrad; { graful ecarturilor } dr:drum; eps:integer; begin for i:=1 to n do for j:=1 to n do fi[i,j]:=0; ft:=0; while True do begin { construim graful ecarturilor } for i:=1 to n do for j:=1 to n do ge[i,j]:=0; for i:=1 to n do for j:=1 to n do if c[i,j]>0 then begin if fi[i,j]<c[i,j] then ge[i,j]:=c[i,j]-fi[i,j]; if fi[i,j]>0 then ge[j,i]:=-fi[i,j]; end; CautaDrum(n,ge,s,d,k,dr); if k<2 then exit; { determinam capacitatea reziduala a drumului gasit } eps:=32767; for i:=k-1 downto 1 do if abs(ge[dr[i+1],dr[i]])<eps then eps:=abs(ge[dr[i+1],dr[i]]); { calculam fluxul nou obtinut } ft:=ft+eps; for i:=k-1 downto 1 do if ge[dr[i+1],dr[i]]>0 then Inc(fi[dr[i+1],dr[i]],eps) else Dec(fi[dr[i+1],dr[i]],eps); end; end; begin Clrscr; Writeln('Determinarea fluxului maxim intr-o retea de transport:'); Writeln; { Citirea datelor de intrare } if ParamCount=0 then cod:=1 else begin Assign(f,ParamStr(1)); {$I-} Reset(f); {$I+} if IOResult<>0 then cod:=1 else cod:=0; end; for i:=1 to maxvirf do for j:=1 to maxvirf do c[i,j]:=0; if cod=1 then begin Write('Nr de virfuri: ');Readln(n); Write('Nr de arce: ');Readln(m); Writeln('Arcele grafului:'); for l:=1 to m do begin Write(' ');Readln(i,j,k); c[i,j]:=k; end; Write('Sursa: ');Readln(s); Write('Destinatia: ');Readln(d); Writeln; end else begin Readln(f,n); Readln(f,m); for l:=1 to m do begin Readln(f,i,j,k); c[i,j]:=k; end; Readln(f,s); Readln(f,d); Close(f); end; { Aplicarea algoritmului Ford-Fulkerson } FordFulkerson; { Tiparirea fluxului maxim } Writeln('Fluxul maxim este:'); for i:=1 to n do for j:=1 to n do if fi[i,j]>0 then Writeln(' (',i,',',j,') - ',fi[i,j]); Writeln('Fluxul total este: ',ft); repeat until keypressed; end.
unit ACMConvertor; interface uses Windows, Messages, MSACM, MMSystem; type TNotifyEvent = procedure(Sender: TObject) of object; TSeekOrigin = (soBeginning, soCurrent, soEnd); TStream = class(TObject) private function GetPosition: Int64; procedure SetPosition(const Pos: Int64); function GetSize: Int64; procedure SetSize64(const NewSize: Int64); protected procedure SetSize(NewSize: Longint); overload; virtual; procedure SetSize(const NewSize: Int64); overload; virtual; public function Read(var Buffer; Count: Longint): Longint; virtual; abstract; function Write(const Buffer; Count: Longint): Longint; virtual; abstract; function Seek(Offset: Longint; Origin: Word): Longint; overload; virtual; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; virtual; procedure ReadBuffer(var Buffer; Count: Longint); procedure WriteBuffer(const Buffer; Count: Longint); function CopyFrom(Source: TStream; Count: Int64): Int64; property Position: Int64 read GetPosition write SetPosition; property Size: Int64 read GetSize write SetSize64; end; TACMWaveFormat = packed record case integer of 0: (Format: TWaveFormatEx); 1: (RawData: Array[0..128] of byte); end; TACMConvertor = Class(TObject) private FChooseData: TACMFORMATCHOOSEA; FActive: Boolean; FBufferIn: Pointer; FBufferOut: Pointer; FInputBufferSize: DWord; FOutputBufferSize: DWord; FStartOfStream: Boolean; FStreamHandle: HACMStream; FStreamHeader: TACMStreamHeader; procedure SetActive(const Value: Boolean); procedure SetInputBufferSize(const Value: DWord); protected procedure CloseStream; procedure OpenStream; procedure ReadFormat(var Format: TACMWaveFormat; Stream: TStream); procedure WriteFormat(var Format: TACMWaveFormat; Stream: TStream); public FormatIn, FormatOut: TACMWaveFormat; constructor Create; destructor Destroy; override; function ChooseFormat(var Format: TACMWaveFormat; const UseDefault: Boolean): Boolean; function ChooseFormatIn(const UseDefault: Boolean): Boolean; function ChooseFormatOut(const UseDefault: Boolean): Boolean; function Convert: DWord; function SuggestFormat(Format: TACMWaveFormat): TACMWaveFormat; property Active: Boolean read FActive write SetActive; property BufferIn: Pointer read FBufferIn; property BufferOut: Pointer read FBufferOut; property OutputBufferSize: DWord read FOutputBufferSize; published property InputBufferSize: DWord read FInputBufferSize write SetInputBufferSize; end; implementation {TStream} function TStream.GetPosition: Int64; begin Result := Seek(0, soCurrent); end; procedure TStream.SetPosition(const Pos: Int64); begin Seek(Pos, soBeginning); end; function TStream.GetSize: Int64; var Pos: Int64; begin Pos := Seek(0, soCurrent); Result := Seek(0, soEnd); Seek(Pos, soBeginning); end; procedure TStream.SetSize(NewSize: Longint); begin WriteLn(NewSize); end; procedure TStream.SetSize64(const NewSize: Int64); begin SetSize(NewSize); end; procedure TStream.SetSize(const NewSize: Int64); begin if (NewSize < Low(Longint)) or (NewSize > High(Longint)) then Exit; SetSize(Longint(NewSize)); end; function TStream.Seek(Offset: Longint; Origin: Word): Longint; type TSeek64 = function (const Offset: Int64; Origin: TSeekOrigin): Int64 of object; var Impl: TSeek64; Base: TSeek64; ClassTStream: TClass; begin Impl := Seek; ClassTStream := Self.ClassType; while (ClassTStream <> nil) and (ClassTStream <> TStream) do ClassTStream := ClassTStream.ClassParent; Base := TStream(@ClassTStream).Seek; Result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; function TStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result := 0; if (Offset < Low(Longint)) or (Offset > High(Longint)) then Exit; Result := Seek(Longint(Offset), Ord(Origin)); end; procedure TStream.ReadBuffer(var Buffer; Count: Longint); begin if (Count <> 0) and (Read(Buffer, Count) <> Count) then Exit; end; procedure TStream.WriteBuffer(const Buffer; Count: Longint); begin if (Count <> 0) and (Write(Buffer, Count) <> Count) then Exit; end; function TStream.CopyFrom(Source: TStream; Count: Int64): Int64; const MaxBufSize = $F000; var BufSize, N: Integer; Buffer: PChar; begin if Count = 0 then begin Source.Position := 0; Count := Source.Size; end; Result := Count; if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count; GetMem(Buffer, BufSize); try while Count <> 0 do begin if Count > BufSize then N := BufSize else N := Count; Source.ReadBuffer(Buffer^, N); WriteBuffer(Buffer^, N); Dec(Count, N); end; finally FreeMem(Buffer, BufSize); end; end; {TACMConvertor} function TACMConvertor.ChooseFormat(var Format: TACMWaveFormat; const UseDefault: Boolean): Boolean; var OriginalFormat: PWaveFormatEX; FormatSelection: Longint; begin Result := False; GetMem(OriginalFormat, Sizeof(TACMWaveFormat)); try if UseDefault then begin Move(Format, OriginalFormat^, SizeOf(TACMWaveFormat)) end else begin with OriginalFormat^ do begin wFormatTag := 49; nChannels := 1; nSamplesPerSec := 8000; nAvgBytesPerSec:= 8000; nBlockAlign:=1; wbitspersample := 8; cbSize := SizeOf(TACMWaveFormat); end; end; with FChooseData do begin pwfx := OriginalFormat; cbStruct := SizeOf(FChooseData); cbwfx := SizeOf(TACMWaveFormat); fdwStyle := ACMFORMATCHOOSE_STYLEF_INITTOWFXSTRUCT end; FormatSelection := ACMFormatChoose(FChooseData); if FormatSelection = MMSYSERR_NOERROR then begin Move(FChooseData.pwfx^, Format, SizeOf(TACMWaveFormat)); Result := True; end; finally FreeMem(OriginalFormat); end; end; function TACMConvertor.ChooseFormatIn(const UseDefault: Boolean): Boolean; begin Result := ChooseFormat(FormatIn, UseDefault); end; function TACMConvertor.ChooseFormatOut(const UseDefault: Boolean): Boolean; begin Result := ChooseFormat(FormatOut, UseDefault); end; procedure TACMConvertor.CloseStream; begin ACMStreamUnPrepareHeader(FStreamHandle, FStreamHeader, 0); ACMStreamClose(FStreamHandle, 0); FreeMem(FBufferIn); FreeMem(FBufferOut); FActive := False; FStartOfStream := False; end; function TACMConvertor.Convert: dword; var Start: dword; begin if FStartOfStream then begin Start := ACM_STREAMCONVERTF_BLOCKALIGN end else begin Start := 0; end; ZeroMemory(BufferOut, OutputBufferSize); ACMStreamConvert(FStreamHandle, FStreamHeader, ACM_STREAMCONVERTF_BLOCKALIGN or Start); ACMStreamReset(FStreamHandle,0); Result := FStreamHeader.cbDstLengthUsed; FStartOfStream := False; end; constructor TACMConvertor.Create; begin inherited; FStreamHandle := nil; InputBufferSize := 2048; with FormatIn.Format do begin wFormatTag := 1; nChannels := 1; nSamplesPerSec := 22050; nAvgBytesPerSec:= 22050; nBlockAlign:=1; wbitspersample := 8; cbSize := SizeOf(TACMWaveFormat); end; with FormatOut.Format do begin wFormatTag := 1; nChannels := 1; nSamplesPerSec := 22050; nAvgBytesPerSec:= 22050; nBlockAlign:=1; wbitspersample := 8; cbSize := SizeOf(TACMWaveFormat); end; end; destructor TACMConvertor.Destroy; begin Active := False; inherited; end; procedure TACMConvertor.OpenStream; procedure BuildHeader; begin with FStreamHeader do begin cbStruct := SizeOf(TACMStreamHeader); fdwStatus := 0; dwUser := 0; pbSrc := FBufferIn; cbSrcLength := InputBufferSize; cbSrcLengthUsed := 0; dwSrcUser := 0; pbDst := FBufferOut; cbDstLength := OutputBufferSize; cbDstLengthUsed := 0; dwDstUser := 0; end; end; begin FStartOfStream := True; ACMStreamOpen(FStreamhandle, nil, FormatIn.Format, FormatOut.Format, nil, 0, 0, 0); ACMStreamSize(FStreamHandle, InputBufferSize, FOutputBufferSize, ACM_STREAMSIZEF_SOURCE); GetMem(FBufferIn, InputBufferSize); Getmem(FBufferOut, OutputBufferSize); try BuildHeader; ACMStreamPrepareHeader(FStreamHandle, FStreamHeader, 0); except Freemem(FBufferIn); Freemem(FBufferOut); Exit; end; FActive := True; end; procedure TACMConvertor.ReadFormat(var Format: TACMWaveFormat; Stream: TStream); var Size: integer; begin Stream.Read(Size, SizeOf(integer)); Stream.Read(Format, Size); end; procedure TACMConvertor.SetActive(const Value: Boolean); begin if Value = FActive then Exit; if Value then begin OpenStream end else begin CloseStream; end; end; procedure TACMConvertor.SetInputBufferSize(const Value: DWord); begin if Active then Exit; FInputBufferSize := Value; end; function TACMConvertor.SuggestFormat(Format: TACMWaveFormat): TACMWaveFormat; var WaveFormatEx: TWaveFormatEx; ValidItems: dword; begin ValidItems := 0; if ACMFormatSuggest(nil, Format.Format, WaveFormatEx, SizeOf(TACMWaveFormat), ValidItems) = 0 then Exit; Move(WaveFormatEx, Result, SizeOf(TACMWaveFormat)); end; procedure TACMConvertor.WriteFormat(var Format: TACMWaveFormat; Stream: TStream); var Size: integer; begin Size := SizeOf(Format); Stream.Write(Size, SizeOf(integer)); Stream.Write(Format, Size); end; end.
//*****************************************// // Carlo Pasolini // // http://pasotech.altervista.org // // email: cdpasop@hotmail.it // //*****************************************// unit uUtils; interface function DumpData(Buffer: Pointer; BufLen: Cardinal): String; function PidProcesso(NomeProcesso: string): Cardinal; implementation uses Windows, TlHelp32, uDecls; (*function FileTimeToDateTime(const FileTime: FILETIME): TDateTime; const FileTimeBase = -109205.0; FileTimeStep: Extended = 24.0 * 60.0 * 60.0 * 1000.0 * 1000.0 * 10.0; // 100 nSek per Day begin Result := Int64(FileTime) / FileTimeStep; Result := Result + FileTimeBase; end;*) function IntToHex(dwValue, dwDigits: Cardinal): String; stdcall; const hex: array[0..$F] of char = ('0','1','2','3','4','5','6','7', '8','9','A','B','C','D','E','F'); begin if (dwDigits > 8) then dwDigits := 8; Result := Copy( hex[(dwValue and $F0000000) shr 28]+ hex[(dwValue and $0F000000) shr 24]+ hex[(dwValue and $00F00000) shr 20]+ hex[(dwValue and $000F0000) shr 16]+ hex[(dwValue and $0000F000) shr 12]+ hex[(dwValue and $00000F00) shr 8]+ hex[(dwValue and $000000F0) shr 4]+ hex[(dwValue and $0000000F) shr 0],9-dwDigits,dwDigits); end; function ConvertDataToAscii(Buffer: pointer; Length: Word): string; var Iterator: integer; AsciiBuffer: string; begin AsciiBuffer := ''; for Iterator := 0 to Length - 1 do begin if char(pointer(integer(Buffer) + Iterator)^) in [#32..#127] then AsciiBuffer := AsciiBuffer + '' + char(pointer(integer(Buffer) + Iterator)^) + '' else AsciiBuffer := AsciiBuffer + '.'; end; Result := AsciiBuffer; end; function ConvertDataToHex(Buffer: pointer; Length: Word): string; var Iterator: integer; HexBuffer: string; begin HexBuffer := ''; for Iterator := 0 to Length - 1 do begin HexBuffer := HexBuffer + IntToHex(Ord(char(pointer(integer(Buffer) + Iterator)^)), 2) + ' '; end; Result := HexBuffer; end; {function DumpData(Buffer: Pointer; BufLen: Cardinal): String; var i, j, c: Integer; begin c := 0; Result := ''; for i := 1 to BufLen div 16 do //vado a blocchi di 16 alla volta begin Result := Result + IntToHex((i-1)*16, 4) + ' ' + ConvertDataToHex(Pointer(Integer(Buffer) + c), 16) + ' '; Result := Result + ConvertDataToAscii(Pointer(Integer(Buffer) + c), 16) + #13#10; c := c + 16; end; if BufLen mod 16 <> 0 then begin Result := Result + IntToHex((i-1)*16, 4) + ' ' + ConvertDataToHex(Pointer(Integer(Buffer) + Integer(BufLen) - (BufLen mod 16)), (BufLen mod 16)); for j := ((BufLen mod 16) + 1) to 16 do begin Result := Result + ' ' + ' '; end; Result := Result + ' '; Result := Result + ConvertDataToAscii(Pointer(Integer(Buffer) + Integer(BufLen) - (BufLen mod 16)), (BufLen mod 16)); end; end; } function DumpData(Buffer: Pointer; BufLen: DWord): String; var i, j, c: Integer; begin c := 0; Result := ''; for i := 1 to BufLen div 16 do begin for j := c to c + 15 do if (PByte(Integer(Buffer) + j)^ < $20) or (PByte(Integer(Buffer) + j)^ > $FA) then Result := Result else Result := Result + PChar(Integer(Buffer) + j)^; c := c + 16; end; if BufLen mod 16 <> 0 then begin for i := BufLen mod 16 downto 1 do begin if (PByte(Integer(Buffer) + Integer(BufLen) - i)^ < $20) or (PByte(Integer(Buffer) + Integer(BufLen) - i)^ > $FA) then Result := Result else Result := Result + PChar(Integer(Buffer) + Integer(BufLen) - i)^; end; end; end; function PidProcesso(NomeProcesso: string): Cardinal; var pe: TProcessEntry32; hSnap: THandle; n1,n2: string; begin Result := 0; hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); pe.dwSize := sizeof(TProcessEntry32); //Prelevo informazioni sul primo processo nello snapshot di sistema Process32First(hSnap, pe); repeat //loop sui processi //messagebox(0,pchar(CharUpper(pe.szExeFile) + #13#10 + CharUpper(pchar(NomeProcesso))),'',0); n1 := CharUpper(pe.szExeFile); n2 := CharUpper(pchar(NomeProcesso)); if n1 = n2 then begin Result := pe.th32ProcessID; break; end; until (not (Process32Next(hSnap, pe)) ) ; CloseHandle(hSnap); end; end.
{$I texel.inc} unit txcollec; { 1998-07-15 } interface uses Objects; type PVariableCollection = ^TVariableCollection; TVariableCollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; PParameterCollection = ^TParameterCollection; TParameterCollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; PFontCollection = ^TFontCollection; TFontCollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; PFunctionCollection = ^TFunctionCollection; TFunctionCollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; PCategoryCollection = ^TCategoryCollection; TCategoryCollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; PFormatCollection = ^TFormatCollection; TFormatCollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; POLECollection = ^TOLECollection; TOLECollection = object(TStringCollection) function KeyOf(Item: pointer): pointer; virtual; procedure FreeItem(Item: pointer); virtual; end; implementation uses OProcs,txtypes; function TParameterCollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=PParameter(Item)^.ListName end; procedure TParameterCollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(PParameter(Item)^.Name); DisposeStr(PParameter(Item)^.ListName); DisposeStr(PParameter(Item)^.Txt); DisposeStr(PParameter(Item)^.Descr); dispose(PParameter(Item)) end end; function TFontCollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=PFont(Item)^.Name end; procedure TFontCollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(PFont(Item)^.Name); if PFont(Item)^.SizeCount>0 then freemem(PFont(Item)^.Sizes,PFont(Item)^.SizeCount shl 1); Dispose(PFont(Item)) end end; function TFunctionCollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=PFunction(Item)^.Name end; procedure TFunctionCollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(PFunction(Item)^.Name); DisposeStr(PFunction(Item)^.Descr1); DisposeStr(PFunction(Item)^.Descr2); dispose(PFunction(Item)) end end; function TCategoryCollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=PCategory(Item)^.Name end; procedure TCategoryCollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(PCategory(Item)^.Name); dispose(PCategory(Item)) end end; function TFormatCollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=PFormat(Item)^.Name end; procedure TFormatCollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(PFormat(Item)^.Name); dispose(PFormat(Item)) end end; function TOLECollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=POLEType(Item)^.Descr end; procedure TOLECollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(POLEType(Item)^.Descr); dispose(POLEType(Item)) end end; function TVariableCollection.KeyOf(Item: pointer): pointer; begin if Item=nil then KeyOf:=nil else KeyOf:=PVariable(Item)^.Name end; procedure TVariableCollection.FreeItem(Item: pointer); begin if Item<>nil then begin DisposeStr(PVariable(Item)^.Name); dispose(PVariable(Item)) end end; end.
unit SDUFrames; // Description: Base frame // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, Controls, Dialogs, Forms, Graphics, Messages, SysUtils, Variants, Windows; type TSDUFrame = class (TFrame) PRIVATE FOnLoaded: TNotifyEvent; FOnHide: TNotifyEvent; FOnShow: TNotifyEvent; procedure CMShowingChanged(var Message: TMessage); MESSAGE CM_SHOWINGCHANGED; PROTECTED procedure Loaded(); OVERRIDE; procedure DoLoaded(); procedure DoHide(); DYNAMIC; procedure DoShow(); DYNAMIC; PUBLISHED property OnLoaded: TNotifyEvent Read FOnLoaded Write FOnLoaded; property OnShow: TNotifyEvent Read FOnShow Write FOnShow; property OnHide: TNotifyEvent Read FOnHide Write FOnHide; end; implementation {$R *.dfm} procedure TSDUFrame.Loaded(); begin inherited; if not (csDesigning in ComponentState) then DoLoaded(); end; procedure TSDUFrame.CMShowingChanged(var Message: TMessage); begin inherited; if not (csDesigning in ComponentState) then begin if Showing then begin try DoShow; except Application.HandleException(Self); end; end; end else begin try DoHide; except Application.HandleException(Self); end; end; end; procedure TSDUFrame.DoLoaded(); begin if Assigned(FOnLoaded) then FOnLoaded(Self); end; procedure TSDUFrame.DoHide(); begin if Assigned(FOnHide) then FOnHide(Self); end; procedure TSDUFrame.DoShow(); begin if Assigned(FOnShow) then FOnShow(Self); end; end.
unit uFrmSizeColorGrid; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, DB, Grids; const COL_SPACE = 10; type TFrmSizeColorGrid = class(TForm) pnlBotton: TPanel; imgBotton: TImage; btnClose: TBitBtn; sgGrid: TStringGrid; pnlValues: TPanel; rdQtd: TRadioButton; rbSalePrice: TRadioButton; edtValue: TEdit; btnApplyLine: TButton; btnApplyColumn: TButton; btCreateGrid: TButton; Label2: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCloseClick(Sender: TObject); procedure rdQtdClick(Sender: TObject); procedure sgGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure edtValueExit(Sender: TObject); procedure edtValueKeyPress(Sender: TObject; var Key: Char); procedure btnApplyLineClick(Sender: TObject); procedure btnApplyColumnClick(Sender: TObject); procedure btCreateGridClick(Sender: TObject); private FRow, FCol : Integer; FModel : String; procedure GridPaint(Column : String); procedure UpdateValue(Row, Col : Integer; Value : String); procedure RefreshOption; public function Start(Model : String): Boolean; end; implementation uses uDMExport, DBClient, uCharFunctions, uMsgBox, uFrmBuildGrid; {$R *.dfm} { TFrmSizeColorGrid } function TFrmSizeColorGrid.Start(Model : String): Boolean; begin FModel := Model; with DMExport.cdsGrid do begin Filtered := False; Filter := 'Model = ' + QuotedStr(FModel); Filtered := True; end; GridPaint('Qty'); Caption := DMExport.cdsGrid.FieldByName('Model').AsString; ShowModal; DMExport.cdsGrid.Filtered := False; DMExport.cdsGrid.Filter := ''; Result := True; end; procedure TFrmSizeColorGrid.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmSizeColorGrid.btnCloseClick(Sender: TObject); begin Close; end; procedure TFrmSizeColorGrid.GridPaint(Column : String); var slColor, slSize: TStringList; iMaxSizeWidth, iMaxColorWidth: integer; i, j: integer; CelValue : String; // ---------------------- // Sub // ---------------------- function IndexOfColor(sColor: String): integer; begin Result := slColor.IndexOf(sColor); if Result = -1 then begin Result := slColor.Add(sColor); sgGrid.RowCount := slColor.Count + 1; end; Result := Result + 1; end; function IndexOfSize(sSize: String): integer; begin Result := slSize.IndexOf(sSize); if Result = -1 then begin Result := slSize.Add(sSize); sgGrid.ColCount := slSize.Count + 1; end; Result := Result + 1; end; // ---------------------- // Main // ---------------------- begin // Utilizo dois StringList para incluir e recuperar os Index slColor := TStringList.Create; slSize := TStringList.Create; iMaxSizeWidth := 0; iMaxColorWidth := 0; try with sgGrid do begin ColCount := 0; RowCount := 0; DMExport.cdsGrid.First; while not DMExport.cdsGrid.EOF do begin if rdQtd.Checked then CelValue := DMExport.cdsGrid.FieldByName(Column).AsString else CelValue := FormatFloat('#,##0.00', DMExport.cdsGrid.FieldByName(Column).AsFloat); Cells[ IndexOfSize(DMExport.cdsGrid.FieldByName('MSize').AsString), IndexOfColor(DMExport.cdsGrid.FieldByName('MColor').AsString) ] := CelValue; DMExport.cdsGrid.Next; end; // Ajusto as Larguras das cell for i := 0 to slColor.Count-1 do begin j := Canvas.TextWidth(slColor[i]); if iMaxColorWidth < j then iMaxColorWidth := j; end; ColWidths[0] := iMaxColorWidth + COL_SPACE; for i := 0 to slSize.Count-1 do begin j := Canvas.TextWidth(slSize[i]); if iMaxSizeWidth < j then iMaxSizeWidth := j; end; if iMaxSizeWidth < 30 then iMaxSizeWidth := iMaxSizeWidth + 30; for i := 1 to ColCount-1 do ColWidths[i] := iMaxSizeWidth + COL_SPACE; // Pinto os titulos das colunas e das linhas if ColCount > 1 then FixedCols := 1; if RowCount > 1 then FixedRows := 1; for i := 0 to slColor.Count-1 do Cells[0, i+1] := slColor[i]; for i := 0 to slSize.Count-1 do Cells[i+1, 0] := slSize[i]; end; finally slColor.Free; slSize.Free; end; end; procedure TFrmSizeColorGrid.rdQtdClick(Sender: TObject); begin RefreshOption; end; procedure TFrmSizeColorGrid.sgGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var R: TRect; begin //Somente na Coluna desejada if ((ACol <> 0) AND (ARow <> 0)) then begin FRow := ARow; FCol := ACol; {Size and position the combo box to fit the cell} R := sgGrid.CellRect(ACol, ARow); R.Left := R.Left + sgGrid.Left; R.Right := R.Right + sgGrid.Left; R.Top := R.Top + sgGrid.Top; R.Bottom := R.Bottom + sgGrid.Top; edtValue.Left := R.Left + 1; edtValue.Top := R.Top + 1; edtValue.Width := (R.Right + 1) - R.Left; edtValue.Height := (R.Bottom + 1) - R.Top; {Show the combobox} edtValue.Text := sgGrid.Cells[ACol, ARow]; edtValue.Visible := True; edtValue.SetFocus; end; CanSelect := True; end; procedure TFrmSizeColorGrid.UpdateValue(Row, Col: Integer; Value: String); var Qty: Double; Sale : Currency; begin if Trim(Value) <> '' then begin Qty := 0; Sale := 0; if rdQtd.Checked then Qty := StrToFloat(Trim(Value)) else Sale := StrToCurr(Trim(Value)); with DMExport.cdsGrid do if Locate('MColor;MSize', VarArrayOf([sgGrid.Cells[0, Row], sgGrid.Cells[Col, 0]]), []) then begin Edit; if rdQtd.Checked then FieldByName('Qty').AsFloat := Qty else FieldByName('SalePrice').AsFloat := Sale; Post; end; end; end; procedure TFrmSizeColorGrid.edtValueExit(Sender: TObject); begin edtValue.Visible := False; if (edtValue.Text <> '') and (sgGrid.Cells[FCol, FRow] <> edtValue.Text) then begin if rdQtd.Checked then sgGrid.Cells[FCol, FRow] := edtValue.Text else sgGrid.Cells[FCol, FRow] := FormatFloat('##0.00', StrToCurr(edtValue.Text)); UpdateValue(FRow, FCol, edtValue.Text); end; end; procedure TFrmSizeColorGrid.edtValueKeyPress(Sender: TObject; var Key: Char); begin if key <> #13 then Key := ValidatePositiveCurrency(Key) else sgGrid.SetFocus; end; procedure TFrmSizeColorGrid.btnApplyLineClick(Sender: TObject); var Value : Double; Col, i : integer; begin Col := sgGrid.Col; Value := StrToFloatDef(sgGrid.Cells[Col, sgGrid.Row],0); if (Value <> 0) then if MsgBox(Format('Aplicar %f para os itens da mesma linha?', [Value]), vbYesNo + vbQuestion) = vbYes then begin for i := 0 to sgGrid.ColCount-1 do if (i <> Col) then UpdateValue(sgGrid.Row, i, FloatToStr(Value)); RefreshOption; end; end; procedure TFrmSizeColorGrid.RefreshOption; begin if rdQtd.Checked then GridPaint('Qty') else GridPaint('SalePrice'); end; procedure TFrmSizeColorGrid.btnApplyColumnClick(Sender: TObject); var Value : Double; Row, i : integer; begin Row := sgGrid.Row; Value := StrToFloatDef(sgGrid.Cells[sgGrid.Col, Row], 0); if (Value <> 0) then if MsgBox(Format('Aplicar %f para os itens da mesma coluna?', [Value]), vbYesNo + vbQuestion) = vbYes then begin for i := 0 to sgGrid.RowCount-1 do if (i <> Row) then UpdateValue(i, sgGrid.Col, FloatToStr(Value)); RefreshOption; end; end; procedure TFrmSizeColorGrid.btCreateGridClick(Sender: TObject); begin with TFrmBuildGrid.Create(Self) do if Start(FModel) then RefreshOption; end; end.
unit ZcxFilterBar; interface uses SysUtils, Classes, Forms, dxBar, pFIBDataSet,DB, Unit_ZGlobal_Consts, ZProc, Menus, Z_Images_DM, dxBarExtItems, Dates, ZMessages, Dialogs; type TzFilterBarPeriods = class protected procedure fOnYear1SpinEditCurChange(Sender:TObject); procedure fOnYear2SpinEditCurChange(Sender:TObject); private pBar:TdxBar; pBarManager:TdxBarManager; pFilterBtn:TdxBarButton; pYear1SpinEdit:TdxBarSpinEdit; pYear2SpinEdit:TdxBarSpinEdit; pMonth1Combo:TdxBarCombo; pMonth2Combo:TdxBarCombo; pSeparatorStatic:TdxBarStatic; pDMImage:TDMImages; pLanguageIndex:Byte; procedure SetKodSetup1(KodSetup:Integer); procedure SetKodSetup2(KodSetup:Integer); function GetKodSetup1:Integer; function GetKodSetup2:Integer; procedure SetKodSetup2Visible(AVisible:TdxBarItemVisible); function GetKodSetup2Visible:TdxBarItemVisible; public constructor Create(ABarManager:TdxBarManager;ABar:TdxBar=nil); destructor Destroy;override; property Bar:TdxBar read pBar; property BarManager:TdxBarManager read PBarManager; property FilterBtn:TdxBarButton read pFilterBtn; property KodSetupBeg:Integer read GetKodSetup1 write SetKodSetup1; property KodSetupEnd:Integer read GetKodSetup2 write SetKodSetup2; property KodSetup2Visible:TdxBarItemVisible read GetKodSetup2Visible write SetKodSetup2Visible; end; implementation constructor TzFilterBarPeriods.Create(ABarManager:TdxBarManager;ABar:TdxBar=nil); begin inherited Create; PLanguageIndex:=LanguageIndex; PBarManager := ABarManager; if PBarManager.Images=nil then begin PDMImage:=TDMImages.Create(ABarManager.Owner as TForm); PBarManager.Images := PDMImage.Images; end; if ABar=nil then pBar := PBarManager.Bars.Add else pBar:=ABar; with pBar do begin Name := 'zBarFilter'; caption := FilterBtn_Caption[pLanguageIndex]; DockingStyle := dsBottom; AllowClose := False; AllowCustomizing := False; AllowQuickCustomizing := False; AllowReset := False; NotDocking := [dsNone,dsLeft,dsTop,dsRight,dsBottom]; MultiLine := True; UseRestSpace := True; Visible := True; end; pMonth1Combo := TdxBarCombo.Create(PBarManager); pYear1SpinEdit := TdxBarSpinEdit.Create(PBarManager); pMonth2Combo := TdxBarCombo.Create(PBarManager); pYear2SpinEdit := TdxBarSpinEdit.Create(PBarManager); pFilterBtn := TdxBarButton.Create(PBarManager); pSeparatorStatic := TdxBarStatic.Create(pBarManager); with pMonth1Combo do begin Name := 'pMonth1Combo'; Caption := LabelMonth_Caption[pLanguageIndex]; Hint := Caption; Visible := ivAlways; ShowCaption := False; Items.Text := MonthesList_Text[pLanguageIndex]; DropDownCount := 12; ShowEditor := False; // ReadOnly := True; end; with pMonth2Combo do begin Name := 'pMonth2Combo'; Caption := LabelMonth_Caption[pLanguageIndex]; Hint := Caption; Visible := ivAlways; ShowCaption := False; Items.Text := MonthesList_Text[pLanguageIndex]; DropDownCount := 12; ShowEditor := False; // ReadOnly := True; end; with pSeparatorStatic do begin Name := 'pSeparatorStatic'; Caption := ' - '; Hint := ''; Visible := ivAlways; ShowCaption := True; AllowClick := True; end; with pYear1SpinEdit do begin Name := 'pYear1SpinEdit'; Caption := LabelYear_Caption[pLanguageIndex]; Hint := Caption; Visible := ivAlways; ShowCaption := False; MinValue := 2000; MaxValue := 2100; OnCurChange := fOnYear1SpinEditCurChange; end; with pYear2SpinEdit do begin Name := 'pYear2SpinEdit'; Caption := LabelYear_Caption[pLanguageIndex]; Hint := Caption; Visible := ivAlways; ShowCaption := False; MinValue := 2000; MaxValue := 2100; OnCurChange := fOnYear2SpinEditCurChange; end; with pFilterBtn do begin Name := 'pFilterBtn'; Caption := FilterBtn_Caption[pLanguageIndex]; Hint := Caption; ButtonStyle := bsDefault; PaintStyle := psCaptionGlyph; UnclickAfterDoing := True; Visible := ivAlways; ShortCut:=119; //F8 ImageIndex := PDMImage.ImageIndexByName(zbiFilter); end; with Bar, ItemLinks do begin LockUpdate := True; with Add do begin Item := pMonth1Combo; Index := AvailableItemCount - 1; BringToTopInRecentList(False); end; with Add do begin Item := pYear1SpinEdit; Index := AvailableItemCount - 1; BringToTopInRecentList(False); end; with Add do begin Item := pSeparatorStatic; Index := AvailableItemCount - 1; BringToTopInRecentList(False); end; with Add do begin Item := pMonth2Combo; Index := AvailableItemCount - 1; BringToTopInRecentList(False); end; with Add do begin Item := pYear2SpinEdit; Index := AvailableItemCount - 1; BringToTopInRecentList(False); end; with Add do begin Item := pFilterBtn; Index := AvailableItemCount - 1; BeginGroup := True; BringToTopInRecentList(False); end; LockUpdate := False; end; end; destructor TzFilterBarPeriods.Destroy; begin pFilterBtn.Destroy; pYear1SpinEdit.Destroy; pYear2SpinEdit.Destroy; pMonth1Combo.Destroy; pMonth2Combo.Destroy; inherited Destroy; end; procedure TzFilterBarPeriods.SetKodSetup1(KodSetup:Integer); begin pYear1SpinEdit.IntValue := YearMonthFromKodSetup(KodSetup); pMonth1Combo.ItemIndex := YearMonthFromKodSetup(KodSetup,False)-1; end; procedure TzFilterBarPeriods.SetKodSetup2(KodSetup:Integer); begin pYear2SpinEdit.IntValue := YearMonthFromKodSetup(KodSetup); pMonth2Combo.ItemIndex := YearMonthFromKodSetup(KodSetup,False)-1; end; function TzFilterBarPeriods.GetKodSetup1:Integer; begin Result:=PeriodToKodSetup(pYear1SpinEdit.IntValue,pMonth1Combo.ItemIndex+1); end; function TzFilterBarPeriods.GetKodSetup2:Integer; begin Result:=PeriodToKodSetup(pYear2SpinEdit.IntValue,pMonth2Combo.ItemIndex+1); end; procedure TzFilterBarPeriods.fOnYear1SpinEditCurChange(Sender:TObject); begin pYear1SpinEdit.Value := pYear1SpinEdit.CurValue; end; procedure TzFilterBarPeriods.fOnYear2SpinEditCurChange(Sender:TObject); begin pYear2SpinEdit.Value := pYear2SpinEdit.CurValue; end; procedure TzFilterBarPeriods.SetKodSetup2Visible(AVisible:TdxBarItemVisible); begin pSeparatorStatic.Visible := AVisible; pYear2SpinEdit.Visible := AVisible; pMonth2Combo.Visible := AVisible; end; function TzFilterBarPeriods.GetKodSetup2Visible:TdxBarItemVisible; begin Result := pSeparatorStatic.Visible; end; end.
unit Localization; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TLocale = class protected FAdviceSystem32Processor32: string; FAdviceProcessor64RamEnough: string; FAdviceProcessor64RamEnoughSystem64: string; FAdviceProcessor64RamLittleSystem32: string; FAdviceProcessor64RamLittleSystem64: string; FAdviceDefault: string; FBbClose: string; FFmMainScreen: string; FGbAdvice: string; FGbMemory: string; FGbOperatingSystem: string; FGbProcessor: string; FLeOperatingSystemArchitecture: string; FLeOperatingSystemProductName: string; FLeProcessorArchitecture: string; FLeProcessorModel: string; FLeRam: string; FMeAdvice: string; FOperatingSystemArchitecture32bit: string; FOperatingSystemArchitecture64bit: string; FOperatingSystemArchitectureUnknown: string; FOperatingSystemArchitectureBit: string; FProcessorArchitecture32bit: string; FProcessorArchitecture64bit: string; FProcessorArchitectureUnknown: string; FProcessorArchitectureBit: string; public constructor Create(); property AdviceSystem32Processor32: string read FAdviceSystem32Processor32; property AdviceProcessor64RamEnough: string read FAdviceProcessor64RamEnough; property AdviceProcessor64RamEnoughSystem64: string read FAdviceProcessor64RamEnoughSystem64; property AdviceProcessor64RamLittleSystem32: string read FAdviceProcessor64RamLittleSystem32; property AdviceProcessor64RamLittleSystem64: string read FAdviceProcessor64RamLittleSystem64; property AdviceDefault: string read FAdviceDefault; property BbClose: string read FBbClose; property FmMainScreen: string read FFmMainScreen; property GbAdvice: string read FGbAdvice; property GbMemory: string read FGbMemory; property GbOperatingSystem: string read FGbOperatingSystem; property GbProcessor: string read FGbProcessor; property LeOperatingSystemArchitecture: string read FLeOperatingSystemArchitecture; property LeOperatingSystemProductName: string read FLeOperatingSystemProductName; property LeProcessorArchitecture: string read FLeProcessorArchitecture; property LeProcessorModel: string read FLeProcessorModel; property LeRam: string read FLeRam; property MeAdvice: string read FMeAdvice; property OperatingSystemArchitecture32bit: string read FOperatingSystemArchitecture32bit; property OperatingSystemArchitecture64bit: string read FOperatingSystemArchitecture64bit; property OperatingSystemArchitectureUnknown: string read FOperatingSystemArchitectureUnknown; property OperatingSystemArchitectureBit: string read FOperatingSystemArchitectureBit; property ProcessorArchitecture32bit: string read FProcessorArchitecture32bit; property ProcessorArchitecture64bit: string read FProcessorArchitecture64bit; property ProcessorArchitectureUnknown: string read FProcessorArchitectureUnknown; property ProcessorArchitectureBit: string read FProcessorArchitectureBit; end; TPortugueseBrazilianLocale = class(TLocale) public constructor Create(); end; var Locale: TLocale; function GetSystemLanguage(): string; implementation uses GetText; function GetSystemLanguage(): string; var Lang, FallbackLang: string; begin GetLanguageIDs(Lang, FallbackLang); Result := FallbackLang; end; constructor TLocale.Create(); begin FAdviceSystem32Processor32 := 'Your computer supports 32-bit operating ' + 'systems only.'; FAdviceProcessor64RamEnough := 'Since your computer supports 64-bit ' + 'operating systems and it has enough RAM (>= 2GB), you should use a ' + '64-bit system.'; FAdviceProcessor64RamEnoughSystem64 := 'At the moment, you are using a ' + '64-bit system.'; FAdviceProcessor64RamLittleSystem32 := 'Your computer supports 64-bit ' + 'operating systems, but it does not have much RAM (< 2GB). At the ' + 'moment, you are using a 32-bit system. If its performance is good, you ' + 'should use a 32-bit system.'; FAdviceProcessor64RamLittleSystem64 := 'Your computer supports 64-bit ' + 'operating systems, but it does not have much RAM (< 2GB). At the ' + 'moment, you are using a 64-bit system. If its performance is not ' + 'satisfying, you should consider using a 32-bit system.'; FAdviceDefault := 'You should use a system that matches your processor''s ' + 'architecture.'; FBbClose := '&Close'; FFmMainScreen := 'Should I go 32 or 64-bit?'; FGbAdvice := 'Advice'; FGbMemory := 'Memory'; FGbOperatingSystem := 'Operating system'; FGbProcessor := 'Processor'; FLeOperatingSystemArchitecture := 'System architecture'; FLeOperatingSystemProductName := 'Product name'; FLeProcessorArchitecture := 'Processor architecture'; FLeProcessorModel := 'Processor model'; FLeRam := 'RAM'; FOperatingSystemArchitecture32bit := '32-bit'; FOperatingSystemArchitecture64bit := '64-bit'; FOperatingSystemArchitectureUnknown := 'Unknown'; FOperatingSystemArchitectureBit := '-bit'; FProcessorArchitecture32bit := 'Legacy 32-bit PC'; FProcessorArchitecture64bit := '64-bit PC'; FProcessorArchitectureUnknown := 'Unknown'; FProcessorArchitectureBit := '-bit'; end; constructor TPortugueseBrazilianLocale.Create(); begin FAdviceSystem32Processor32 := 'Seu computador suporta apenas sistemas ' + 'operacionais de 32 bits.'; FAdviceProcessor64RamEnough := 'Como seu computador suporta sistemas ' + 'operacionais de 64 bits e dispõe de memória RAM suficiente (>= 2GB), ' + 'você deve usar um sistema de 64 bits.'; FAdviceProcessor64RamEnoughSystem64 := 'No momento, você está usando um ' + 'sistema de 64 bits.'; FAdviceProcessor64RamLittleSystem32 := 'Seu computador suporta sistemas ' + 'operacionais de 64 bits, mas ele não dispõe de memória RAM suficiente ' + '(< 2 GB). No momento, você está usando um sistema de 32 bits. Se o ' + 'desempenho dele é bom, você deve usar um sistema de 32 bits.'; FAdviceProcessor64RamLittleSystem64 := 'Seu computador suporta sistemas ' + 'operacionais de 64 bits, mas ele não dispõe de memória RAM suficiente ' + '(< 2 GB). No momento, você está usando um sistema de 64 bits. Se o ' + 'desempenho dele não é satisfatório, considere usar um sistema de 32 bits.'; FAdviceDefault := 'Você deve usar um sistema operacional com a mesma ' + 'arquitetura do seu processador.'; FBbClose := '&Fechar'; FFmMainScreen := 'Qual devo usar: 32 ou 64 bits?'; FGbAdvice := 'Conselho'; FGbMemory := 'Memória'; FGbOperatingSystem := 'Sistema operacional'; FGbProcessor := 'Processador'; FLeOperatingSystemArchitecture := 'Arquitetura do sistema'; FLeOperatingSystemProductName := 'Nome do produto'; FLeProcessorArchitecture := 'Arquitetura do processador'; FLeProcessorModel := 'Modelo do processador'; FLeRam := 'RAM'; FOperatingSystemArchitecture32bit := '32 bits'; FOperatingSystemArchitecture64bit := '64 bits'; FOperatingSystemArchitectureUnknown := 'Não identificada'; FOperatingSystemArchitectureBit := ' bits'; FProcessorArchitecture32bit := 'PC de 32 bits (antigo)'; FProcessorArchitecture64bit := 'PC de 64 bits'; FProcessorArchitectureUnknown := 'Não identificada'; FProcessorArchitectureBit := ' bits'; end; initialization if (UpperCase(GetSystemLanguage()) = 'PT') then Locale := TPortugueseBrazilianLocale.Create() else Locale := TLocale.Create(); end.
unit GridBuilder1; interface uses util1, FdefDac2; type TBuildGrid=class Npos:integer; { Nombre de positions } Memory:integer; { Memoire du système } maxLength:integer; maxGrid:integer; grid:array of smallint; { suite de grilles} sum,newSum:array of array of array of single; { sum[p1,p2,tau] } function getSM(p,t:integer):integer; property SM[p,t:integer]:integer read getSM; constructor create(nb,m0,maxL:integer); procedure addGrid(num:integer); procedure addGridRandom(num:integer); procedure calcul; procedure normalize; procedure WriteSums; end; procedure TestBuildGrid; implementation { TBuildGrid } constructor TBuildGrid.create(nb, m0, maxL: integer); var i:integer; begin Npos:=nb; memory:=m0; maxLength:=maxL; maxGrid:=1; for i:=1 to Nb do maxGrid:=maxGrid*2; setLength(sum,Nb,Nb,m0); setLength(Newsum,Nb,Nb,m0); setLength(grid,maxLength); end; procedure TBuildGrid.addGridRandom(num:integer); var p1,p2,tau:integer; begin grid[num]:=random(maxGrid-1)+1; for p1:=0 to npos-1 do for p2:=0 to npos-1 do for tau:=0 to memory-1 do begin Sum[p1,p2,tau]:=Sum[p1,p2,tau]+SM[p1,num]*SM[p2,num-tau]; end; end; procedure TBuildGrid.AddGrid(num:integer); var eval,maxSum:double; g,g0,p1,p2,tau:integer; nbS:integer; begin Eval:=1E20; for g:=1 to maxGrid-1 do begin grid[num]:=g; maxSum:=0; nbS:=0; for p1:=0 to npos-1 do for p2:=0 to npos-1 do for tau:=0 to memory-1 do if (p1<>p2) or (tau>0) then begin maxSum:=maxSum+abs(Sum[p1,p2,tau]+SM[p1,num]*SM[p2,num-tau]); inc(nbS); {if abs(newSum)>maxSum then maxSum:=abs(newSum);} end; maxSum:=maxSum/nbS; if maxSum<Eval then begin Eval:=maxSum; g0:=g; end; end; grid[num]:=g0; for p1:=0 to npos-1 do for p2:=0 to npos-1 do for tau:=0 to memory-1 do begin Sum[p1,p2,tau]:=Sum[p1,p2,tau]+SM[p1,num]*SM[p2,num-tau]; end; end; procedure TBuildGrid.calcul; var i:integer; p1,p2,tau:integer; begin for p1:=0 to npos-1 do for p2:=0 to npos-1 do for tau:=0 to memory-1 do Sum[p1,p2,tau]:=0; for i:=0 to memory-1 do grid[i]:=1+random(maxGrid-1); for i:=0 to memory-1 do begin for p1:=0 to npos-1 do for p2:=0 to npos-1 do for tau:=0 to memory-1 do if i>=tau then Sum[p1,p2,tau]:=Sum[p1,p2,tau]+SM[p1,i]*SM[p2,i-tau]; end; for i:=memory to maxlength-1 do AddGrid(i); end; function TBuildGrid.getSM(p, t: integer): integer; begin if t>=0 then result:= ((grid[t] shr p) and 1 )*2-1 else result:=0; end; procedure TBuildGrid.normalize; var p1,p2,tau:integer; begin for p1:=0 to npos-1 do for p2:=0 to npos-1 do for tau:=0 to memory-1 do if Sum[p1,p2,tau]<>0 then Sum[p1,p2,tau]:=Sum[p1,p2,tau]/maxLength; end; procedure TBuildGrid.WriteSums; begin SaveArrayAsDac2File('c:\dac2\Grid.dat',grid[0],maxLength,G_smallint); SaveArrayAsDac2File('c:\dac2\BuildGrid.dat',Sum[0,0,0],memory,G_single); end; procedure TestBuildGrid; var grid:Tbuildgrid; begin grid:=Tbuildgrid.create(4,50,1000); grid.calcul; grid.writeSums; grid.free; end; end.
unit PedidoVenda; interface uses DBXJSONReflect, RTTI, DBXPlatform, Generics.Collections, ItemPedidoVenda, Cliente, Funcionario; type TDoubleInterceptor = class(TJSONInterceptor) public function StringConverter(Data: TObject; Field: string): string; override; procedure StringReverter(Data: TObject; Field: string; Arg: string); override; end; TPedidoVenda = class private FCodigo: string; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FData: TDateTime; FCliente: TCliente; FNomeClienteAvulso: string; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FDesconto: Currency; FTipoPagamento: Integer; FItens: TList<TItemPedidoVenda>; FFechada: Boolean; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FDescontoPercentual: Currency; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FTotal: Currency; FCancelada: Boolean; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FRecebido: Currency; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FTroco: Currency; FLoginUsuario: string; FParcelamento: Integer; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FRestante: Currency; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FValorParcela: Currency; [JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)] FPrimeiroVencimento: TDateTime; FFuncionario: TFuncionario; public property Codigo: string read FCodigo write FCodigo; property Data: TDateTime read FData write FData; property Cliente: TCliente read FCliente write FCliente; property NomeClienteAvulso: string read FNomeClienteAvulso write FNomeClienteAvulso; property Desconto: Currency read FDesconto write FDesconto; property TipoPagamento: Integer read FTipoPagamento write FTipoPagamento; property Itens: TList<TItemPedidoVenda> read FItens write FItens; property Fechada: Boolean read FFechada write FFechada; property DescontoPercentual: Currency read FDescontoPercentual write FDescontoPercentual; property Total: Currency read FTotal write FTotal; property Cancelada: Boolean read FCancelada write FCancelada; property Recebido: Currency read FRecebido write FRecebido; property Troco: Currency read FTroco write FTroco; property LoginUsuario: string read FLoginUsuario write FLoginUsuario; property Parcelamento: Integer read FParcelamento write FParcelamento; property Restante: Currency read FRestante write FRestante; property ValorParcela: Currency read FValorParcela write FValorParcela; property PrimeiroVencimento: TDateTime read FPrimeiroVencimento write FPrimeiroVencimento; property Funcionario: TFuncionario read FFuncionario write FFuncionario; end; implementation { TDoubleInterceptor } function TDoubleInterceptor.StringConverter(Data: TObject; Field: string): string; var LRttiContext: TRttiContext; LValue: Double; begin LValue := LRttiContext.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<Double>; Result := TDBXPlatform.JsonFloat(LValue); end; procedure TDoubleInterceptor.StringReverter(Data: TObject; Field, Arg: string); var LRttiContext: TRttiContext; LValue: Double; begin LValue := TDBXPlatform.JsonToFloat(Arg); LRttiContext.GetType(Data.ClassType).GetField(Field).SetValue(Data, TValue.From<Double>(LValue)); end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, Vcl.ExtCtrls, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, VCL.TMSFNCGoogleMaps, Vcl.StdCtrls, AdvEdit, AdvGlowButton; type TFrmMain = class(TForm) Map: TTMSFNCGoogleMaps; Panel1: TPanel; btnCopy: TAdvGlowButton; procedure FormCreate(Sender: TObject); procedure btnCopyClick(Sender: TObject); private { Private declarations } procedure OnCaptureScreenshot( Sender: TObject; ABitmap: TTMSFNCBitmap ); public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses IOUtils, Flix.Utils.Maps, TMSFNCMapsCommonTypes, ClipBrd ; procedure TFrmMain.btnCopyClick(Sender: TObject); begin Map.OnCaptureScreenShot := OnCaptureScreenshot; Map.CaptureScreenShot; end; procedure TFrmMain.FormCreate(Sender: TObject); var LStyle: TStringlist; begin var LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) ); try Map.APIKey := LKeys.GetKey( msGoogleMaps ); finally LKeys.Free; end; LStyle := TStringlist.Create; try LStyle.LoadFromFile('..\resources\styles\black-map.json'); Map.Options.MapStyle := LStyle.Text; finally LStyle.Free; end; end; procedure TFrmMain.OnCaptureScreenshot(Sender: TObject; ABitmap: TTMSFNCBitmap); begin Clipboard.Assign( ABitmap ); end; end.
{*******************************************************} { } { Cards Report } { } { Copyright (c) 2018 - 2021 Sergey Lubkov } { } {*******************************************************} unit CR.Options; interface uses System.Classes, System.SysUtils, System.Variants, App.Options, App.Params, App.DB.Options, {$IFDEF REG_STORAGE}System.Win.Registry{$ELSE}System.IniFiles{$ENDIF}; type TCROptions = class(TCLDBOptions) private {$IFDEF REG_STORAGE} FDayStart: TRegStringParam; {$ELSE} FDayStart: TIniStringParam; {$ENDIF} function GetLogicDate: TDate; function GetDayStart: string; public constructor Create(Owner: TComponent); override; destructor Destroy(); override; procedure Load(const Context: {$IFDEF REG_STORAGE}TRegistry{$ELSE}TIniFile{$ENDIF}); override; procedure Save(const Context: {$IFDEF REG_STORAGE}TRegistry{$ELSE}TIniFile{$ENDIF}); override; procedure LoadSettingsFromDB(); override; property DayStart: string read GetDayStart; property LogicDate: TDate read GetLogicDate; end; implementation const SettingsGroup = 'Settings'; DayStartParamName = 'DayStart'; DeyStartDefault = '08:00'; { TCROptions } constructor TCROptions.Create(Owner: TComponent); begin inherited; {$IFDEF REG_STORAGE} FDayStart := TRegStringParam.Create(DayStartParamName, SettingsGroup, DeyStartDefault); {$ELSE} FDayStart := TIniStringParam.Create(DayStartParamName, SettingsGroup, DeyStartDefault); {$ENDIF} end; destructor TCROptions.Destroy; begin FDayStart.Free; inherited; end; procedure TCROptions.Load(const Context: {$IFDEF REG_STORAGE}TRegistry{$ELSE}TIniFile{$ENDIF}); begin inherited; FPassword.Load(Context); FDayStart.Load(Context); end; procedure TCROptions.Save(const Context: {$IFDEF REG_STORAGE}TRegistry{$ELSE}TIniFile{$ENDIF}); begin inherited; FPassword.Save(Context); FDayStart.Save(Context); end; function TCROptions.GetDayStart: string; begin Result := FDayStart.Value; end; function TCROptions.GetLogicDate: TDate; var DaySrartTime: TDateTime; begin Result := Date; if not TryStrToTime(DayStart, DaySrartTime) then DaySrartTime := StrToTime(DeyStartDefault); if Time < DaySrartTime then Result := Date - 1; end; procedure TCROptions.LoadSettingsFromDB; begin inherited; end; end.
{*******************************************************} { } { Run-time Library for Borland Delphi 5 } { TImButton - Image Button } { } { Copyright (c) 2001-2002 by Veresov Dmitry } { } { ***** } { ** ** } { ** ** ************ } { ** ** ** ** ** } { ** ** ** ** ** } { ** ** ** ** ** } { ***** *** *** **** } { } {*******************************************************} unit Dmitry.Controls.ImButton; interface uses Winapi.Windows, Winapi.Messages, System.Types, System.SysUtils, System.Classes, System.Math, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Dmitry.Graphics.Types; type TDmImageButtonView = (DmIm_Left, DmIm_Right, DmIm_Home_Standart, DmIm_None, DmIm_Minimize, DmIm_Maximize, DmIm_Normalize, DmIm_Close, DmIm_Help); TDmImageState = (ImSt_Normal, ImSt_Enter, ImSt_Click, ImSt_Disabled); TDmImageAnimate = set of TDmImageState; TXFilter = procedure(var Image : TBitmap) of object; type TImButton = class(TWinControl) private { Private declarations } FCanvas: TCanvas; Fstate: TDmImageState; Fdown: Boolean; Fonclick: TNotifyEvent; Fimage1: TPicture; Fimage2: TPicture; Fimage3: TPicture; Fimage4: TPicture; FTransparent: Boolean; FView: TDmImageButtonView; FEnabled: Boolean; FOnMouseLeave: TNotifyEvent; FOnMouseEnter: TNotifyEvent; FMouseInClientZone: Boolean; FShowCaption: Boolean; FFontNormal: TFont; FFontEnter: TFont; FPixelsBetweenPictureAndText: Integer; FFadeDelay: Integer; Ffadenowpicture: Tbitmap; Fpicture: TBitmap; FTimer: Ttimer; Fstep: Integer; Fsteps: Integer; Fdefaultcolor: Tcolor; Fspicture: Tbitmap; Fanimations: TDmImageAnimate; Flock: Boolean; FAniShow: Boolean; Fbackground: TBitmap; FaHide: Boolean; Fnowshow: Boolean; Fb: Tbitmap; FOnEndFade: TNotifyEvent; FOnEndFadeOnShow: TNotifyEvent; FBeginHide: TNotifyEvent; FOnBeginShow: TNotifyEvent; FMaskImage: TGraphicControl; Fautosetimage: Boolean; Fusecoolfont: Boolean; Fcoolcolor: Tcolor; FCoolColorSize: Integer; Ffilter: TXFilter; FMaskBitmap: TBitmap; FVirtualDraw: Boolean; procedure CMTextChanged(var message: TMessage); message CM_TEXTCHANGED; procedure CMFontChanged(var message: TMessage); message CM_FontCHANGED; procedure Setimage1(const Value: TPicture); procedure Setimage2(const Value: TPicture); procedure Setimage3(const Value: TPicture); procedure Setimage4(const Value: TPicture); procedure SetTransparent(const Value: Boolean); procedure Setview(const Value: TDmImageButtonView); procedure SetImEnabled(const Value: Boolean); procedure SetOnMouseEnter(const Value: TNotifyEvent); procedure SetOnMouseleave(const Value: TNotifyEvent); procedure SetShowCaption(const Value: Boolean); procedure SetFontNormal(const Value: TFont); procedure SetFontEnter(const Value: TFont); procedure SetPixelsBetweenPictureAndText(const Value: Integer); procedure SetFadeDelay(const Value: Integer); procedure Fadenow(Sender: Tobject); procedure Setsteps(const Value: Integer); procedure Setdefaultcolor(const Value: Tcolor); procedure Newstatepicture(State: TDmImageState); procedure Setanimations(const Value: TDmImageAnimate); procedure SetAniShow(const Value: Boolean); procedure SetOnEndFade(const Value: TNotifyEvent); procedure SetOnEndFadeOnShow(const Value: TNotifyEvent); procedure SetBeginHide(const Value: TNotifyEvent); procedure SetOnBeginShow(const Value: TNotifyEvent); procedure Fontch(Sender: TObject); procedure SetMaskImage(const Value: TGraphicControl); procedure Setautosetimage(const Value: Boolean); procedure Setusecoolfont(const Value: Boolean); procedure Setcoolcolor(const Value: Tcolor); procedure SetCoolColorSize(const Value: Integer); procedure Setfilter(const Value: TXFilter); procedure SetMaskBitmap(const Value: TBitmap); procedure SetVirtualDraw(const Value: Boolean); protected { Protected declarations } procedure Paint(var Msg: Tmessage); message Wm_paint; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public { Public declarations } constructor Create(AOwner: Tcomponent); override; destructor Destroy; override; procedure CMMOUSELEAVE(var message: TWMNoParams); message CM_MOUSELEAVE; procedure CMMOUSEEnter(var message: TWMNoParams); message CM_MOUSEenter; procedure WMSIZE(var Msg: Tmessage); message Wm_size; published { Published declarations } property Hint; property ShowHint; property Top; property Left; property Width; property Height; property ImageNormal: TPicture read Fimage1 write Setimage1; property ImageEnter: TPicture read Fimage2 write Setimage2; property ImageClick: TPicture read Fimage3 write Setimage3; property ImageDisabled: TPicture read Fimage4 write Setimage4; property OnClick: TNotifyEvent read Fonclick write Fonclick; property Transparent: Boolean read FTransparent write SetTransparent; property View: TDmImageButtonView read FView write Setview; property Enabled: Boolean read FEnabled write SetImEnabled; property Visible; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write SetOnMouseleave; property OnMouseEnter: TNotifyEvent read FOnMouseEnter write SetOnMouseEnter; property OnBeginShow: TNotifyEvent read FOnBeginShow write SetOnBeginShow; property OnBeginHide: TNotifyEvent read FBeginHide write SetBeginHide; property OnMouseDown; property OnMouseUp; property OnMouseMove; property ShowCaption: Boolean read FShowCaption write SetShowCaption; property Caption; property Color; property FontNormal: TFont read FFontNormal write SetFontNormal; property FontEnter: TFont read FFontEnter write SetFontEnter; property PixelsBetweenPictureAndText : Integer read FPixelsBetweenPictureAndText write SetPixelsBetweenPictureAndText; property FadeDelay: Integer read FFadeDelay write SetFadeDelay; property FadeSteps: Integer read Fsteps write Setsteps; procedure SetNewPicture(Image: Tbitmap); procedure SetNewPictureWithoutFade(Image: Tbitmap); property Defaultcolor: Tcolor read Fdefaultcolor write Setdefaultcolor; property Animations: TDmImageAnimate read Fanimations write Setanimations; property AnimatedShow: Boolean read FAniShow write SetAniShow; procedure Animatedshownow; property Filter: TXFilter read Ffilter write Setfilter; procedure Animatedhide; procedure Show; procedure Setallanmations; property OnEndFadeOnHide: TNotifyEvent read FOnEndFade write SetOnEndFade; property OnEndFadeOnShow: TNotifyEvent read FOnEndFadeOnShow write SetOnEndFadeOnShow; property MaskImage: TGraphicControl read FMaskImage write SetMaskImage; property Autosetimage: Boolean read Fautosetimage write Setautosetimage; property Usecoolfont: Boolean read Fusecoolfont write Setusecoolfont; property Coolcolor: Tcolor read Fcoolcolor write Setcoolcolor; property CoolColorSize: Integer read FCoolColorSize write SetCoolColorSize; property MaskBitmap: TBitmap read FMaskBitmap write SetMaskBitmap; procedure Refresh; procedure RefreshBackGround(X: Integer = 0; Y: Integer = 0; Bitmap: TBitmap = nil); property VirtualDraw: Boolean read FVirtualDraw write SetVirtualDraw; end; procedure Register; implementation procedure Register; begin RegisterComponents('Dm', [Timbutton]); end; { Timbutton } {$R CaptionButtons.res} procedure CoolDrawText(Bitmap: Tbitmap; X, Y: Integer; Text: string; Coolcount: Integer; Coolcolor: Tcolor); var Drawrect: Trect; C: Integer; Tempb, Temp: Tbitmap; I, J, K: Integer; P, P1, Pv, Pn, Pc: PARGB; begin Tempb := Tbitmap.Create; Tempb.PixelFormat := Pf24bit; Tempb.Canvas.Font.Assign(Bitmap.Canvas.Font); Tempb.Canvas.Brush.Color := $FFFFFF; Tempb.Width := Tempb.Canvas.TextWidth(Text) + 2 * Coolcount; Tempb.Height := Tempb.Canvas.Textheight(Text) + 2 * Coolcount; Tempb.Canvas.Brush.Style := BsClear; Tempb.Canvas.Font.Color := $0; DrawRect := Rect(Point(Coolcount, 0), Point(Tempb.Width + Coolcount, Tempb.Height + Coolcount)); DrawText(Tempb.Canvas.Handle, PChar(Text), Length(Text), DrawRect, DT_NOCLIP); Temp := Tbitmap.Create; Temp.PixelFormat := pf24bit; Temp.Canvas.Brush.Color := $0; Temp.Width := Tempb.Canvas.TextWidth(Text) + Coolcount; Temp.Height := Tempb.Canvas.Textheight(Text) + Coolcount; Tempb.Canvas.Font.Assign(Bitmap.Canvas.Font); for I := 0 to Temp.Height - 1 do begin P1 := Temp.ScanLine[I]; P := Tempb.ScanLine[I]; for J := 0 to Temp.Width - 1 do begin if P[J].R <> $FF then begin P1[J].R := $FF; P1[J].G := $FF; P1[J].B := $FF; end; end; end; Tempb.Canvas.Brush.Color := $0; Tempb.Canvas.Pen.Color := $0; Tempb.Canvas.Rectangle(0, 0, Tempb.Width, Tempb.Height); for K := 1 to Coolcount do begin for I := 1 to Temp.Height - 2 do begin P := Tempb.ScanLine[I]; Pv := Temp.ScanLine[I - 1]; Pc := Temp.ScanLine[I]; Pn := Temp.ScanLine[I + 1]; for J := 1 to Temp.Width - 2 do begin C := 9; if (Pv[J - 1].R <> 0) then Dec(C); if (Pv[J + 1].R <> 0) then Dec(C); if (Pn[J - 1].R <> 0) then Dec(C); if (Pn[J + 1].R <> 0) then Dec(C); if (Pc[J - 1].R <> 0) then Dec(C); if (Pc[J + 1].R <> 0) then Dec(C); if (Pn[J].R <> 0) then Dec(C); if (Pv[J].R <> 0) then Dec(C); if C <> 9 then begin P[J].R := Min($FF, P[J].R + (Pv[J - 1].R + Pv[J + 1].R + Pn[J - 1].R + Pn[J + 1].R + Pc[J - 1].R + Pc[J + 1] .R + Pn[J].R + Pv[J].R) div (C + 1)); P[J].G := Min($FF, P[J].G + (Pv[J - 1].G + Pv[J + 1].G + Pn[J - 1].G + Pn[J + 1].G + Pc[J - 1].G + Pc[J + 1] .G + Pn[J].G + Pv[J].G) div (C + 1)); P[J].B := Min($FF, P[J].B + (Pv[J - 1].B + Pv[J + 1].B + Pn[J - 1].B + Pn[J + 1].B + Pc[J - 1].B + Pc[J + 1] .B + Pn[J].B + Pv[J].B) div (C + 1)); end; end; end; Temp.Assign(Tempb); end; Bitmap.PixelFormat := Pf24bit; if Bitmap.Width = 0 then Exit; for I := Max(0, Y) to Min(Tempb.Height - 1 + Y, Bitmap.Height - 1) do begin P := Bitmap.ScanLine[I]; P1 := Tempb.ScanLine[I - Y]; for J := Max(0, X) to Min(Tempb.Width + X - 1, Bitmap.Width - 1) do begin P[J].R := Min(Round(P[J].R * (1 - P1[J - X].R / 255)) + Round(Getrvalue(Coolcolor) * P1[J - X].R / 255), 255); P[J].G := Min(Round(P[J].G * (1 - P1[J - X].G / 255)) + Round(Getgvalue(Coolcolor) * P1[J - X].G / 255), 255); P[J].B := Min(Round(P[J].B * (1 - P1[J - X].B / 255)) + Round(Getbvalue(Coolcolor) * P1[J - X].B / 255), 255); end; end; DrawRect := Rect(Point(X + Coolcount, Y), Point(X + Temp.Width + Coolcount, Temp.Height + Y + Coolcount)); Bitmap.Canvas.Brush.Style := BsClear; DrawText(Bitmap.Canvas.Handle, PChar(Text), Length(Text), DrawRect, DT_NOCLIP); Temp.Free; Tempb.Free; end; procedure Copyrectfromimage(S, D: TBitmap; Top, Left, Width, Height: Integer); var I, J: Integer; P1, P2: Pargb; H, W: Integer; begin D.Width := Width; D.Height := Height; D.PixelFormat := Pf24bit; if S = nil then Exit; if S.Width = 0 then Exit; if S.Height = 0 then Exit; if Left + Width > S.Width then Exit; if Top + Height > S.Height then Exit; S.PixelFormat := Pf24bit; H := Min(Top + Height, S.Height); W := Min(Left + Width, S.Width); for I := Top to H - 1 do begin P1 := S.ScanLine[I]; P2 := D.ScanLine[I - Top]; for J := Left to W - 1 do P2[J - Left] := P1[J]; end; end; procedure Timbutton.CMMOUSEEnter(var message: TWMNoParams); begin FMouseInClientZone := True; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); FCanvas.Font.Assign(FFontEnter); if FEnabled then begin if Fdown then Fstate := ImSt_Click else Fstate := ImSt_Enter; Newstatepicture(Fstate); end; end; procedure Timbutton.CMMOUSELEAVE(var message: TWMNoParams); begin FMouseInClientZone := False; FCanvas.Font.Assign(FFontNormal); if FEnabled then begin if Fstate = ImSt_click then Fdown := True; Fstate := ImSt_normal; Newstatepicture(Fstate); end; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; constructor Timbutton.Create(AOwner: Tcomponent); begin inherited; Fcoolcolor := $0; VirtualDraw := False; FCoolColorSize := 3; Fusecoolfont := False; Fautosetimage := True; Fnowshow := False; Fahide := False; FMaskBitmap := nil; Flock := True; Fdefaultcolor := Clbtnface; FCanvas := TControlCanvas.Create; TControlCanvas(FCanvas).Control := Self; Fbackground := TBitmap.Create; Fbackground.Pixelformat := Pf24bit; if FMaskBitmap <> nil then begin Copyrectfromimage(FMaskBitmap, Fbackground, { (FMaskImage as timage).ScreenToClient(ClientToScreen(Point(top, left))).x } Top, { ScreenToClient(ClientToScreen(Point(top, left))).y } Left, Width, Height); end else begin if AOwner is Timage then begin FMaskImage := AOwner as Timage; end; if FMaskImage is Timage then if (FMaskImage as Timage).Picture.Bitmap <> nil then Copyrectfromimage((FMaskImage as Timage).Picture.Bitmap, Fbackground, { (FMaskImage as timage).ScreenToClient(ClientToScreen(Point(top, left))).x } Top, { ScreenToClient(ClientToScreen(Point(top, left))).y } Left, Width, Height); end; Fstep := 0; FTimer := Ttimer.Create(Self); Ftimer.Enabled := False; Ftimer.Ontimer := Fadenow; Ftimer.Interval := 55; Ffadedelay := 10; Fsteps := 20; FMouseInClientZone := False; FPixelsBetweenPictureAndText := 10; Fimage1 := TPicture.Create; Fimage2 := TPicture.Create; Fimage3 := TPicture.Create; Fimage4 := TPicture.Create; Fb := Tbitmap.Create; Fb.Pixelformat := Pf24bit; FPicture := TBitmap.Create; FPicture.Pixelformat := pf24bit; FSPicture := TBitmap.Create; FSPicture.Pixelformat := pf24bit; Ffadenowpicture := Tbitmap.Create; Ffadenowpicture.Pixelformat := pf24bit; FView := DmIm_Right; Ffadenowpicture.Handle := Loadbitmap(Hinstance, 'RIGHT_NORMAL'); Fpicture.Handle := Loadbitmap(Hinstance, 'RIGHT_NORMAL'); Fimage1.Bitmap.Handle := Loadbitmap(Hinstance, 'RIGHT_NORMAL'); Fimage2.Bitmap.Handle := Loadbitmap(Hinstance, 'RIGHT_ENTER'); Fimage3.Bitmap.Handle := Loadbitmap(Hinstance, 'RIGHT_CLICK'); Fimage4.Bitmap.Handle := Loadbitmap(Hinstance, 'RIGHT_DISABLED'); Fstate := ImSt_normal; FCanvas.Brush.Style := BsClear; FFontNormal := TFont.Create; FFontEnter := TFont.Create; FFontNormal.OnChange := Fontch; FFontEnter.OnChange := Fontch; FShowCaption := False; Height := Fimage1.Graphic.Height; FEnabled := True; Flock := False; Fanimations := [ImSt_Normal] + [ImSt_Enter] + [ImSt_Click] + [ImSt_Disabled]; end; destructor Timbutton.Destroy; begin inherited; FImage1.Free; FImage2.Free; FImage3.Free; FImage4.Free; FCanvas.Free; Fb.Free; Fbackground.Free; FPicture.Free; FSPicture.Free; Ffadenowpicture.Free; FFontNormal.Free; FFontEnter.Free; end; procedure Timbutton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(OnMouseDown) then OnMouseDown(Self, Button, Shift, X, Y); if FEnabled then begin if Button = MbLeft then begin Fstate := ImSt_click; Newstatepicture(Fstate); end; end; end; procedure Timbutton.Mouseup(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Click: Boolean; begin if Assigned(Onmouseup) then Onmouseup(Self, Button, Shift, X, Y); if FEnabled then begin if Button = Mbleft then begin Click := False; if CsCaptureMouse in ControlStyle then MouseCapture := False; if Fstate = ImSt_click then Click := True else Fstate := ImSt_normal; Fdown := False; if Fstate = ImSt_normal then Click := False; if Click then begin Fstate := ImSt_enter; if Assigned(FOnclick) and not(SsCtrl in Shift) then FOnclick(Owner); end else Fmouseinclientzone := False; end; Newstatepicture(Fstate); end; end; procedure Timbutton.Paint; begin inherited; if not FVirtualDraw then Fcanvas.Draw(0, 0, Fspicture); end; procedure Timbutton.SetImEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; if not FEnabled then FState := ImSt_disabled else FState := ImSt_normal; Newstatepicture(Fstate); end; end; procedure Timbutton.Setimage1(const Value: TPicture); begin Fimage1.Assign(Value); if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if ShowCaption then Width := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText; Height := Fimage1.Height; View := DmIm_None; Newstatepicture(Fstate); end; procedure Timbutton.Setimage2(const Value: TPicture); begin Fimage2.Assign(Value); View := DmIm_None; end; procedure Timbutton.Setimage3(const Value: TPicture); begin Fimage3.Assign(Value); View := DmIm_None; end; procedure Timbutton.SetTransparent(const Value: Boolean); begin FTransparent := Value; FImage1.Graphic.Transparent := Value; FImage2.Graphic.Transparent := Value; FImage3.Graphic.Transparent := Value; FImage4.Graphic.Transparent := Value; Newstatepicture(Fstate); end; procedure Timbutton.Setview(const Value: TDmImageButtonView); var S: string; begin begin case Value of DmIm_Home_Standart: S := 'NONE_'; DmIm_Minimize: S := 'MINIMIZE_'; DmIm_Maximize: S := 'MAXIMIZE_'; DmIm_Normalize: S := 'NORMALIZE_'; DmIm_Close: S := 'CLOSE_'; DmIm_Help: S := 'HELP_'; DmIm_Right: S := 'RIGHT_'; DmIm_Left: S := 'LEFT_'; end; if S <> '' then begin Fimage1.Bitmap.Handle := LoadBitmap(HInstance, PChar(S + 'NORMAL')); Fimage2.Bitmap.Handle := LoadBitmap(HInstance, PChar(S + 'ENTER')); Fimage3.Bitmap.Handle := LoadBitmap(HInstance, PChar(S + 'CLICK')); Fimage4.Bitmap.Handle := LoadBitmap(HInstance, PChar(S + 'DISABLED')); if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if ShowCaption then Width := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText else Width := FImage1.Graphic.Width; Height := Fimage1.Graphic.Height; end; FView := Value; Newstatepicture(Fstate); end; end; procedure Timbutton.WMSIZE(var Msg: Tmessage); begin if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if ShowCaption then Width := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText else Width := FImage1.Graphic.Width; Height := Fimage1.Graphic.Height; end; procedure Timbutton.Setimage4(const Value: TPicture); begin Fimage4.Assign(Value); View := DmIm_None; Newstatepicture(Fstate); end; procedure TImButton.SetOnMouseEnter(const Value: TNotifyEvent); begin FOnMouseEnter := Value; end; procedure TImButton.SetOnMouseleave(const Value: TNotifyEvent); begin FOnMouseLeave := Value; end; procedure TImButton.SetShowCaption(const Value: Boolean); begin FShowCaption := Value; if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if ShowCaption then Width := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText else Width := FImage1.Graphic.Width; Newstatepicture(Fstate); end; procedure TImButton.CMTextChanged(var message: TMessage); var W0: Integer; begin if Parent <> nil then if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if FShowCaption then begin W0 := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText; if W0 > Width then begin if FMaskBitmap <> nil then begin Copyrectfromimage(FMaskBitmap, Fbackground, { (FMaskImage as timage).ScreenToClient(ClientToScreen(Point(top, left))).x } Top, { ScreenToClient(ClientToScreen(Point(top, left))).y } Left, Width, Height); end else begin if FMaskImage is Timage then if (FMaskImage as Timage).Picture.Bitmap <> nil then Copyrectfromimage((FMaskImage as Timage).Picture.Bitmap, Fbackground, { (FMaskImage as timage).ScreenToClient(ClientToScreen(Point(top, left))).x } Top, { ScreenToClient(ClientToScreen(Point(top, left))).y } Left, Width, Height); end; end; Width := W0; end else Width := FImage1.Graphic.Width; Newstatepicture(Fstate); end; procedure TImButton.SetFontNormal(const Value: TFont); var Msg: Tmessage; begin FFontNormal.Assign(Value); if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if ShowCaption then Width := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText else Width := FImage1.Graphic.Width; Paint(Msg); end; procedure TImButton.SetFontEnter(const Value: TFont); var Msg: Tmessage; begin FFontEnter.Assign(Value); if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); if ShowCaption then Width := FImage1.Graphic.Width + Fb.Canvas.TextWidth(Caption) + FPixelsBetweenPictureAndText else Width := FImage1.Graphic.Width; Paint(Msg); end; procedure TImButton.SetPixelsBetweenPictureAndText(const Value: Integer); begin FPixelsBetweenPictureAndText := Value; if (FPixelsBetweenPictureAndText < 0) or (FPixelsBetweenPictureAndText > 99) then FPixelsBetweenPictureAndText := 3; Newstatepicture(Fstate); end; procedure TImButton.CMFontChanged(var message: TMessage); begin Newstatepicture(Fstate); end; procedure TImButton.SetNewPicture(Image: Tbitmap); begin if Image = nil then Exit else begin FStep := 1; FsPicture.Canvas.Brush.Color := Fdefaultcolor; FPicture.Canvas.Brush.Color := Fdefaultcolor; FPicture.Assign(FsPicture); FfadenowPicture.Assign(Image); if Assigned(Ffilter) then Ffilter(FfadenowPicture); FTimer.Enabled := True; FsPicture.Width := FfadenowPicture.Width; FsPicture.Height := FfadenowPicture.Height; FPicture.Width := FfadenowPicture.Width; FPicture.Height := FfadenowPicture.Height; end; end; procedure TImButton.SetNewPictureWithoutFade(Image: Tbitmap); begin Ftimer.Enabled := False; Fspicture.Assign(Image); if Assigned(Ffilter) then Ffilter(Fspicture); if not Flock and (Parent <> nil) then if not FVirtualDraw then Fcanvas.Draw(0, 0, Image); end; procedure TImButton.SetFadeDelay(const Value: Integer); begin FFadeDelay := Value; Ftimer.Interval := Value; end; procedure TImButton.Fadenow(Sender: Tobject); var I, J: Integer; P1, P2, P3: Pargb; begin Inc(Fstep); for I := 0 to Ffadenowpicture.Height - 1 do begin P2 := FfadenowPicture.Scanline[I]; P1 := FPicture.ScanLine[I]; P3 := Fspicture.ScanLine[I]; for J := 0 to Ffadenowpicture.Width - 1 do begin P3[J].R := P1[J].R - Round((P1[J].R - P2[J].R) * FStep / FSteps); P3[J].G := P1[J].G - Round((P1[J].G - P2[J].G) * FStep / FSteps); P3[J].B := P1[J].B - Round((P1[J].B - P2[J].B) * FStep / FSteps); end; end; if Fcanvas <> nil then with Fcanvas do Draw(0, 0, Fspicture); if FStep >= FSteps then begin FTimer.Enabled := False; FStep := 0; FPicture.Assign(FfadenowPicture); if Fnowshow then if Assigned(FOnEndFadeOnShow) then FOnEndFadeOnShow(Self); Fnowshow := False; if Fahide then begin LockWindowUpdate(Parent.Handle); Hide; LockWindowUpdate(0); if Assigned(FOnEndFade) then FOnEndFade(Self); end; end; end; procedure TImButton.Setsteps(const Value: Integer); begin Fsteps := Value; end; procedure TImButton.Setdefaultcolor(const Value: Tcolor); begin Fdefaultcolor := Value; Newstatepicture(Fstate); end; procedure TImButton.Newstatepicture(State: TDmImageState); var Drawrect: TRect; begin if Fahide then Exit; Fb.Canvas.Brush.Color := Fdefaultcolor; Fb.Canvas.Pen.Color := Fdefaultcolor; Fb.Height := Self.Height; if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); Fb.Width := Self.Width; Drawrect.Left := Fimage1.Width + FPixelsBetweenPictureAndText; Drawrect.Top := Height div 2 - Fb.Canvas.TextHeight(Caption) div 2; if Drawrect.Top < 0 then Drawrect.Top := 0; Drawrect.Bottom := Fb.Canvas.TextWidth(Caption); Drawrect.Right := Fb.Canvas.TextHeight(Caption); if FMaskBitmap <> nil then begin Copyrectfromimage(FMaskBitmap, Fbackground, Top, Left, Width, Height); end else begin if FMaskImage is Timage then begin if (FMaskImage as Timage).Picture.Bitmap <> nil then begin Copyrectfromimage((FMaskImage as Timage).Picture.Bitmap, Fbackground, Top, Left, Width, Height); end else begin Fbackground.Canvas.Brush.Color := Color; Fbackground.Canvas.Pen.Color := Color; Fbackground.Canvas.Rectangle(0, 0, Fbackground.Width, Fbackground.Height); end; end else begin Fbackground.Canvas.Brush.Color := Color; Fbackground.Canvas.Pen.Color := Color; Fbackground.Canvas.Rectangle(0, 0, Fbackground.Width, Fbackground.Height); end; end; if Fbackground.Width = 0 then begin Fb.Canvas.Brush.Color := Color; Fb.Canvas.Pen.Color := Color; Fb.Canvas.Rectangle(0, 0, Fb.Width, Fb.Height); end else Fb.Canvas.Draw(0, 0, Fbackground); Fb.Canvas.Brush.Style := BsClear; if not Fusecoolfont then DrawText(Fb.Canvas.Handle, PChar(Caption), Length(Caption), DrawRect, DT_NOCLIP) else if Fshowcaption then Cooldrawtext(Fb, Drawrect.Left - 2 * CoolColorSize, Drawrect.Top, Caption, 3, Coolcolor); if State = ImSt_normal then Fb.Canvas.Draw(0, 0, Fimage1.Bitmap); if State = ImSt_enter then Fb.Canvas.Draw(0, 0, Fimage2.Bitmap); if State = ImSt_click then Fb.Canvas.Draw(0, 0, Fimage3.Bitmap); if State = ImSt_disabled then Fb.Canvas.Draw(0, 0, Fimage4.Bitmap); if State in Fanimations then SetNewPicture(Fb) else SetNewPicturewithoutfade(Fb); end; procedure TImButton.Setanimations(const Value: TDmImageAnimate); begin Fanimations := Value; end; procedure TImButton.SetAniShow(const Value: Boolean); begin FAniShow := Value; end; procedure TImButton.Animatedshownow; var ParentDC: HDC; begin if Assigned(Onbeginshow) then Onbeginshow(Self); Fahide := False; Fbackground.Width := Width; Fbackground.Height := Height; Fbackground.PixelFormat := Pf24bit; if FMaskBitmap <> nil then begin Copyrectfromimage(FMaskBitmap, Fbackground, Top, Left, Width, Height); end else begin if (FMaskImage as Timage).Picture.Bitmap <> nil then begin Copyrectfromimage((FMaskImage as Timage).Picture.Bitmap, Fbackground, Top, Left, Width, Height) end else begin ParentDC := GetDC(Parent.Handle); BitBlt(Fbackground.Canvas.Handle, 0, 0, Width, Height, ParentDC, Left, Top, SRCCOPY); ReleaseDC(0, ParentDC); end; end; Fspicture.Assign(Fbackground); Newstatepicture(Fstate); Fcanvas.Draw(0, 0, Fbackground); LockWindowUpdate(Parent.Handle); Show; LockWindowUpdate(0); end; procedure TImButton.Animatedhide; begin if Assigned(Onbeginhide) then Onbeginhide(Self); Fahide := True; Setnewpicture(Fbackground); end; procedure TImButton.Show; begin if Assigned(Onbeginshow) then Onbeginshow(Self); Fnowshow := True; Fahide := False; LockWindowUpdate(Parent.Handle); Visible := True; LockWindowUpdate(0); end; procedure TImButton.Setallanmations; begin Fanimations := [ImSt_Normal] + [ImSt_Enter] + [ImSt_Click] + [ImSt_Disabled]; end; procedure TImButton.SetOnEndFade(const Value: TNotifyEvent); begin FOnEndFade := Value; end; procedure TImButton.SetOnEndFadeOnShow(const Value: TNotifyEvent); begin FOnEndFadeOnShow := Value; end; procedure TImButton.SetBeginHide(const Value: TNotifyEvent); begin FBeginHide := Value; end; procedure TImButton.SetOnBeginShow(const Value: TNotifyEvent); begin FOnBeginShow := Value; end; procedure TImButton.Fontch(Sender: TObject); var M: TMessage; begin CMTextChanged(M); end; procedure TImButton.SetMaskImage(const Value: TGraphicControl); begin FMaskImage := Value; Newstatepicture(Fstate); end; procedure TImButton.Setautosetimage(const Value: Boolean); begin Fautosetimage := Value; end; procedure TImButton.Setusecoolfont(const Value: Boolean); begin Fusecoolfont := Value; end; procedure TImButton.Setcoolcolor(const Value: Tcolor); begin Fcoolcolor := Value; end; procedure TImButton.SetCoolColorSize(const Value: Integer); begin FCoolColorSize := Value; end; procedure TImButton.Refresh; begin Newstatepicture(Fstate); end; procedure TImButton.Setfilter(const Value: TXFilter); begin Ffilter := Value; end; procedure TImButton.SetMaskBitmap(const Value: TBitmap); begin FMaskBitmap := Value; end; procedure TImButton.RefreshBackGround(X: Integer = 0; Y: Integer = 0; Bitmap: TBitmap = nil); var Drawrect: TRect; begin if Fahide then Exit; Fb.Canvas.Brush.Color := Fdefaultcolor; Fb.Canvas.Pen.Color := Fdefaultcolor; Fb.Height := Self.Height; if FMouseInClientZone then Fb.Canvas.Font.Assign(FFontEnter) else Fb.Canvas.Font.Assign(FFontNormal); Fb.Width := Self.Width; Drawrect.Left := Fimage1.Width + FPixelsBetweenPictureAndText; Drawrect.Top := Height div 2 - Fb.Canvas.TextHeight(Caption) div 2; if Drawrect.Top < 0 then Drawrect.Top := 0; Drawrect.Bottom := Fb.Canvas.TextWidth(Caption); Drawrect.Right := Fb.Canvas.TextHeight(Caption); if FMaskBitmap <> nil then begin Copyrectfromimage(FMaskBitmap, Fbackground, Top, Left, Width, Height); end else begin if FMaskImage is Timage then if (FMaskImage as Timage).Picture.Bitmap <> nil then Copyrectfromimage((FMaskImage as Timage).Picture.Bitmap, Fbackground, Top, Left, Width, Height); end; Fb.Canvas.Draw(0, 0, Fbackground); Fb.Canvas.Brush.Style := BsClear; if not Fusecoolfont then DrawText(Fb.Canvas.Handle, PChar(Caption), Length(Caption), DrawRect, DT_NOCLIP) else if Fshowcaption then Cooldrawtext(Fb, Drawrect.Left - 2 * CoolColorSize, Drawrect.Top, Caption, 3, Coolcolor); if Fstate = ImSt_normal then Fb.Canvas.Draw(0, 0, Fimage1.Bitmap); if Fstate = ImSt_enter then Fb.Canvas.Draw(0, 0, Fimage2.Bitmap); if Fstate = ImSt_click then Fb.Canvas.Draw(0, 0, Fimage3.Bitmap); if Fstate = ImSt_disabled then Fb.Canvas.Draw(0, 0, Fimage4.Bitmap); if Assigned(Ffilter) then Ffilter(Fb); if VirtualDraw then Bitmap.Canvas.Draw(X, Y, Fb) else Fcanvas.Draw(0, 0, Fb); Ftimer.Enabled := False; Fspicture.Assign(Fb); end; procedure TImButton.SetVirtualDraw(const Value: Boolean); begin FVirtualDraw := Value; end; end.
unit uWMFillGrid; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, cxGridTableView, pFIBDataSet, BaseTypes; procedure FillWorkModeDSet(LocDataSet:TpFIBDataSet; DateBegIn, DateEndIn:TDate; LocWorkMode, Id_Man, Id_Post_Moving:Variant; LocShift, LocCntDays:Integer);stdcall; function GetNameDayByNumber(LocNumberDay:Integer):String;stdcall; function GetWorkModeInfo(LocDataSet:TpFIBDataSet; LocIdWorkMode:Variant):Variant;stdcall; function FillWorkModeGrid(LocWorkGrid:TcxGridTableView; LocDataSet:TpFIBDataSet):Boolean; implementation uses cxGridCustomTableView; procedure FillWorkModeDSet(LocDataSet:TpFIBDataSet; DateBegIn, DateEndIn:TDate; LocWorkMode, Id_Man, Id_Post_Moving:Variant; LocShift, LocCntDays:Integer);stdcall; begin try If VarIsNull(LocWorkMode) then Exit; if ((VarIsNull(Id_Man)) And (VarIsNull(Id_Post_Moving))) then begin LocDataSet.Close; LocDataSet.SQLs.SelectSQL.Clear; LocDataSet.SQLs.SelectSQL.Text:='select first('+IntToStr(LocCntDays)+') *'+ ' from tu_work_mode_s_by_period(:date_beg, :date_end, :id_work_mode, :shift, 0, null, null)'; LocDataSet.ParamByName('date_beg').AsDate:=DateBegIn; LocDataSet.ParamByName('date_end').AsDate:=DateEndIn; LocDataSet.ParamByName('id_work_mode').AsInteger:=LocWorkMode; LocDataSet.ParamByName('shift').AsInteger:=LocShift; LocDataSet.Open; end else begin LocDataSet.Close; LocDataSet.SQLs.SelectSQL.Clear; LocDataSet.SQLs.SelectSQL.Text:='select first('+IntToStr(LocCntDays)+') *'+ ' from tu_work_mode_s_by_period(:date_beg, :date_end, :id_work_mode, :shift, 1, :Id_Man, :Id_Post_Moving)'; LocDataSet.ParamByName('date_beg').AsDate:=DateBegIn; LocDataSet.ParamByName('date_end').AsDate:=DateEndIn; LocDataSet.ParamByName('id_work_mode').AsInteger:=LocWorkMode; LocDataSet.ParamByName('shift').AsInteger:=LocShift; LocDataSet.ParamByName('Id_Man').AsInteger:=Id_Man; LocDataSet.ParamByName('Id_Post_Moving').AsInteger:=Id_Post_Moving; LocDataSet.Open; end; except on e:Exception do agMessageDlg('Óâàãà', e.Message, mtInformation, [mbOK]); end; end; function FillWorkModeGrid(LocWorkGrid:TcxGridTableView; LocDataSet:TpFIBDataSet):Boolean; var i, j, CntItems:Integer; DateStr, HoursStr:String; begin if not LocDataSet.isEmpty then begin try LocDataSet.FetchAll; CntItems:=LocDataSet.RecordCount; with LocWorkGrid do begin DataController.BeginUpdate; If DataController.RecordCount=0 then begin DataController.InsertRecord(0); DataController.InsertRecord(1); end; for i:=0 to ColumnCount-1 do begin Columns[i].Caption:=''; for j:=0 to DataController.RecordCount-1 do DataController.Values[j, i]:=''; end; LocDataSet.First; for i:=0 to CntItems-1 do begin If VarIsNull(LocDataSet['Date_Loc']) then DateStr:='' Else DateStr :=DateToStr(LocDataSet['Date_Loc']); If VarIsNull(LocDataSet['HOURS_MIN']) then HoursStr:='' Else HoursStr:=LocDataSet['HOURS_MIN']; DataController.Values[0, 0]:='Äàòà'; DataController.Values[1, 0]:='Ãîäèíè'; DataController.Values[0, i+1]:=DateStr; DataController.Values[1, i+1]:=HoursStr; Columns[i+1].Caption:=GetNameDayByNumber(LocDataSet['DAY_WEEK']); DateStr:=''; HoursStr:=''; LocDataSet.Next; end; DataController.EndUpdate; Result:=True; end; except on e:Exception do begin agMessageDlg('Óâàãà', e.Message, mtInformation, [mbOK]); Result:=False; end; end; end; end; function GetNameDayByNumber(LocNumberDay:Integer):String; begin case LocNumberDay of 1: Result:='Ïí'; 2: Result:='Âò'; 3: Result:='Ñð'; 4: Result:='×ò'; 5: Result:='Ïò'; 6: Result:='Ñá'; 7: Result:='Âñ'; end; end; function GetWorkModeInfo(LocDataSet:TpFIBDataSet; LocIdWorkMode:Variant):Variant;stdcall; begin Result:=VarArrayCreate([0,2], varVariant); LocDataSet.Close; LocDataSet.SQLs.SelectSQL.Text:='select name '+ ' from dt_work_mode '+ ' where id_work_mode=:id_work_mode'; LocDataSet.ParamByName('id_work_mode').Value:=LocIdWorkMode; LocDataSet.Open; If not LocDataSet.IsEmpty then begin If VarIsNull(LocDataSet['Name']) then Result[0]:='' Else Result[0]:=LocDataSet['Name']; end; LocDataSet.Close; LocDataSet.SQLs.SelectSQL.Text:='select max(id_day_week) '+ ' from dt_workreg '+ ' where id_work_mode=:id_work_mode'; LocDataSet.ParamByName('id_work_mode').Value:=LocIdWorkMode; LocDataSet.Open; If not LocDataSet.IsEmpty then begin If VarIsNull(LocDataSet['Max']) then Result[1]:=0 Else Result[1]:=LocDataSet['Max']; end; end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit uFrmPalette; interface uses LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, ExtCtrls, uFPG; type TfrmPalette = class(TForm) imgPalette: TImage; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public fpg : TFpg; end; var frmPalette: TfrmPalette; implementation {$R *.lfm} procedure TfrmPalette.FormShow(Sender: TObject); var i, j, k : integer; area : TRect; begin j := -1; k := -1; for i:=0 to 255 do begin imgPalette.Picture.Bitmap.Canvas.Brush.Color := RGB(FPG.palette[i * 3], FPG.palette[(i * 3) + 1], FPG.palette[(i * 3) + 2]); if ((i mod 16) = 0) then begin j := j + 1; k := -1; end; k := k + 1; area.Left := k * 20; area.Top := j * 20; area.Right := area.Left + 20; area.Bottom := area.Top + 20; imgPalette.Picture.Bitmap.Canvas.FillRect(area); end; end; procedure TfrmPalette.FormCreate(Sender: TObject); begin imgPalette.Picture.Bitmap := TBitmap.Create; imgPalette.Picture.Bitmap.Width := 320; imgPalette.Picture.Bitmap.Height:= 320; end; end.
unit UnitClassRESTCallThread; interface uses System.Classes, REST.Client, VCL.StdCtrls; type TRESTCallThread = class(TThread) private FArtist: string; FMemo: TMemo; FElapsedMilliseconds: integer; protected procedure Execute; override; public property Artist:string read FArtist write FArtist; property ResponseMemo: TMemo read FMemo write FMemo; end; function DoRESTCall(aArtist: string): string; implementation uses System.SysUtils, System.Diagnostics; function DoRESTCall(aArtist: string): string; var lRESTClient: TRESTClient; lRESTRequest: TRESTRequest; lRESTResponse:TRESTResponse; begin lRESTClient := TRESTClient.Create('http://api.discogs.com'); lRESTRequest := TRESTRequest.Create(nil); lRESTResponse := TRESTResponse.Create(nil); lRESTRequest.Client := lRESTClient; lRESTRequest.Response := lRESTResponse; lRESTRequest.Resource := 'database/search?artist={NAME}'; lRESTRequest.Params[0].Value := aArtist; try lRESTRequest.Execute; Result := lRESTResponse.Content; finally {Free resources within thread execution} lRESTResponse.Free; lRESTRequest.Free; lRESTClient.Free; end; end; { TRESTCallThread } procedure TRESTCallThread.Execute; var lStopWatch: TStopWatch; lRESTContent: string; begin if not(FArtist.IsEmpty) then begin lStopWatch := TStopWatch.StartNew; lRESTContent := DoRESTCall(FArtist); lStopWatch.Stop; Synchronize(procedure begin if Assigned(FMemo) then begin FMemo.Lines.Add(lStopWatch.ElapsedMilliseconds.ToString + ' ms.'); FMemo.Lines.Add(lRESTContent); end; end); end else begin if Assigned(FMemo) then begin Synchronize(procedure begin FMemo.Clear; FMemo.Lines.Add('FArtist was leeg.'); end); end; end; end; end.
namespace OxygeneQueue; interface type QueueItem<T> = class public property Data: T; property Next: QueueItem<T>; end; Queue<T> = public class private property First: QueueItem<T>; public method Count: Integer; method Pop: T; method Push(aData: T); end; implementation method Queue<T>.Pop: T; begin if First=nil then Result := default(T) else begin Result := First.Data; First := First.Next; end; end; method Queue<T>.Push(aData: T); var last: QueueItem<T>; begin if First=nil then begin First := new QueueItem<T>; First.Data := aData; end else begin last := First; while last.Next <> nil do last := last.Next; last.Next := new QueueItem<T>; last.Next.Data := aData; end; end; method Queue<T>.Count: integer; var last: QueueItem<T>; begin if First = nil then exit(0); last := First; repeat inc(Result); last := last.Next; until last = nil; end; end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit hpInputs; {$MODE Delphi} interface uses constants,C2Delphi_header; {----------------------------------------------------------------* * Input high-pass filter *---------------------------------------------------------------} procedure hpInput( nIn:pareal; { (i) vector to filter } len:integer; { (i) length of vector to filter } nOut:pareal; { (o) the resulting filtered vector } mem:pareal { (i/o) the filter state } ); implementation procedure hpInput( nIn:pareal; { (i) vector to filter } len:integer; { (i) length of vector to filter } nOut:pareal; { (o) the resulting filtered vector } mem:pareal { (i/o) the filter state } ); var i:integer; pi, po:^real; begin { all-zero section} pi := @nIn[0]; po := @nOut[0]; for i:=0 to len-1 do begin po^ := hpi_zero_coefsTbl[0] * (pi^); po^ :=po^ + hpi_zero_coefsTbl[1] * mem[0]; po^ :=po^ + hpi_zero_coefsTbl[2] * mem[1]; mem[1] := mem[0]; mem[0] := pi^; inc(po); inc(pi); end; { all-pole section} po := @nOut[0]; for i:=0 to len-1 do begin po^ :=po^ - hpi_pole_coefsTbl[1] * mem[2]; po^ :=po^ - hpi_pole_coefsTbl[2] * mem[3]; mem[3] := mem[2]; mem[2] := po^; inc(po); end; end; end.
unit Main; interface procedure MainMenu; function ClrNum(str:string):string; function verifNum(str:string):boolean; implementation uses CRT, sysutils ,Graphics, Files, Types, Trees; { Constantes } const Titulo = 'MI AGENDA'; var Key : Char; MenuSelect : byte; procedure MainMenu; begin LoadFiles; { Cargar el archivo AGEBDA,TXT o AGENDA.DAT } loadTrees; { Cargar los contactos en arboles: A_tel, A_nom, A_dom } GraphicMainMenu; { Dibujamos el menu principal } end; function ClrNum(str:string):string; { Limpiar un string y que queden solo numeros } var i:cardinal; sl:string; begin fillchar(sl,length(sl),#0); for i:=1 to length(str) do if str[i] in ['0'..'9'] then sl:=sl+str[i]; { Si el caracter es un numero } if sl <> '' then ClrNum:= sl { String lipio } else ClrNum:= '0'; { Si no habia ningun numero devolvemos por defecto 0 } end; function verifNum(str:string):boolean; var i:cardinal; sl:string; begin fillchar(sl,length(sl),#0); for i:=1 to length(str) do if str[i] in ['0'..'9'] then sl:=sl+str[i]; if (length(sl) = length(str)) and (str <> '') then verifNum:= false else verifNum:= true; end; end.
unit uActionDlg; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, DB, ADODB, DBCtrls, Dialogs, Variants, UCCenterJournalNetZkz, uActionCore, Messages; type TSetParamProc = procedure(Value: Variant) of Object; TParamObj = class(TObject) private FLookup: TDBLookupControl; FSetParam: TSetParamProc; FNullValue: Variant; public property Lookup: TDBLookupControl read FLookup write FLookup; property SetParam: TSetParamProc read FSetParam write FSetParam; property NullValue: Variant read FNullValue write FNullValue; end; TActionDlg = class(TForm) dsResStatus: TDataSource; dsSrcStatus: TDataSource; dsAction: TDataSource; dsSrcBasis: TDataSource; dsResBasis: TDataSource; PanelOrderItem: TPanel; pnlTop_Order: TPanel; pnlTop_Price: TPanel; pnlTop_Client: TPanel; PanelSMS: TPanel; cbSendMessage: TCheckBox; edSMSText: TMemo; cbSendEmail: TCheckBox; Panel1: TPanel; Label1: TLabel; lcSrcStatus: TDBLookupComboBox; Label2: TLabel; Label3: TLabel; lcSrcBasis: TDBLookupComboBox; Label5: TLabel; lcResBasis: TDBLookupComboBox; Label4: TLabel; lcResStatus: TDBLookupComboBox; Label6: TLabel; edComments: TMemo; Panel2: TPanel; OKBtn: TButton; CancelBtn: TButton; lbAction: TDBLookupListBox; ExecTimer: TTimer; LabelAction: TLabel; PanelAddFields: TPanel; lbHistoryComments: TLabel; edHistoryComments: TMemo; lblSNote: TLabel; edSNote: TMemo; lbHistoryExecMsg: TLabel; edHistoryExecMsg: TMemo; Bevel1: TBevel; procedure lcResStatusCloseUp(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lcSrcBasisCloseUp(Sender: TObject); procedure lcResBasisCloseUp(Sender: TObject); procedure lbActionClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ExecTimerTimer(Sender: TObject); private { Private declarations } FActionType: Integer; FOrderId: Integer; FBPId: Integer; FInitActionCode: string; FActionCode: string; FSrcBasisId: Integer; FSrcStatusId: Integer; FResBasisId: Integer; FResStatusId: Integer; FUserId: Integer; FOrderItem: TJSO_OrderHeaderItem; FSpecItem: TJSO_ItemOrder; FSubItemId: Integer; FUserSession: TUserSession; FActionCore: TActionCore; FParamList: TStringList; FInitProcess: Boolean; FDoExec: Boolean; FReserveType: TReserveType; FSMSEnabled: Boolean; FNotShowCheckError: Boolean; procedure InitControls; procedure InitSrcStatus; procedure Inititialize; procedure SetParam(Value: Variant; ParamName: string); procedure SetAction(Value: Variant); procedure SetSrcBasis(Value: Variant); procedure SetResBasis(Value: Variant); procedure SetResStatus(Value: Variant); procedure UpdResStatus; procedure UpdSrcBasis; procedure UpdResBasis; procedure SetParamEnabled(ParamName: string; Value: Boolean); function CheckValues(var ErrMsg: string): Boolean; procedure UpdSMSControls; procedure UpdActionCore; procedure EnableCtrls(Value: Boolean); class function InnerExecute(AOrderId: Integer; ABPId: Integer; UserId: Integer; OrderItem: TJSO_OrderHeaderItem; UserSession: TUserSession; SpecItem: TJSO_ItemOrder; SubItemId: Integer; ActionCode: string; SrcBasisId: Variant; ResBasisId: Variant; DoExec: Boolean; ReserveType: TReserveType = rtNone): Boolean; overload; public { Public declarations } class function Execute(AOrderId: Integer; ABPId: Integer; UserId: Integer; OrderItem: TJSO_OrderHeaderItem; UserSession: TUserSession; SpecItem: TJSO_ItemOrder; SubItemId: Integer): Boolean; overload; class function Execute(AOrderId: Integer; ABPId: Integer; UserId: Integer; OrderItem: TJSO_OrderHeaderItem; UserSession: TUserSession; SpecItem: TJSO_ItemOrder; SubItemId: Integer; ActionCode: string; SrcBasisId: Variant; ResBasisId: Variant; ReserveType: TReserveType = rtNone): Boolean; overload; end; var ActionDlg: TActionDlg; implementation {$R *.dfm} uses UMain, uDMJSO, UtilsBase, uSprJoin, uSprQuery, Math, Util; class function TActionDlg.Execute(AOrderId: Integer; ABPId: Integer; UserId: Integer; OrderItem: TJSO_OrderHeaderItem; UserSession: TUserSession; SpecItem: TJSO_ItemOrder; SubItemId: Integer): Boolean; begin Result := InnerExecute(AOrderId, ABPId, UserId, OrderItem, UserSession, SpecItem, SubItemId, '', 0, 0, false); end; class function TActionDlg.Execute(AOrderId: Integer; ABPId: Integer; UserId: Integer; OrderItem: TJSO_OrderHeaderItem; UserSession: TUserSession; SpecItem: TJSO_ItemOrder; SubItemId: Integer; ActionCode: string; SrcBasisId: Variant; ResBasisId: Variant; ReserveType: TReserveType = rtNone): Boolean; begin Result := InnerExecute(AOrderId, ABPId, UserId, OrderItem, UserSession, SpecItem, SubItemId, ActionCode, SrcBasisId, ResBasisId, true, ReserveType); end; class function TActionDlg.InnerExecute(AOrderId: Integer; ABPId: Integer; UserId: Integer; OrderItem: TJSO_OrderHeaderItem; UserSession: TUserSession; SpecItem: TJSO_ItemOrder; SubItemId: Integer; ActionCode: string; SrcBasisId: Variant; ResBasisId: Variant; DoExec: Boolean; ReserveType: TReserveType = rtNone): Boolean; begin with TActionDlg.Create(nil) do try FInitProcess := False; FOrderId := AOrderId; FBPId := ABPId; FUserId := UserId; FOrderItem := OrderItem; FSpecItem := SpecItem; FSubItemId := SubItemId; FUserSession := UserSession; FInitActionCode := ActionCode; FActionCode := ''; FActionType := 0; FSrcBasisId := SrcBasisId; FResBasisId := ResBasisId; FSrcStatusId := 0; FResStatusId := 0; FReserveType := ReserveType; FDoExec := DoExec; FNotShowCheckError := FDoExec; try Inititialize; InitSrcStatus; InitControls; Result := ShowModal = mrOk; except on E: Exception do begin ShowError(E.Message); Result := false; end; end; finally Free; end; end; procedure TActionDlg.Inititialize; procedure AddParam(Name: string; Lookup: TDBLookupControl; Proc: TSetParamProc; NullValue: Variant); var vObj: TParamObj; begin vObj := TParamObj.Create; vObj.Lookup := Lookup; vObj.SetParam := Proc; vObj.NullValue := NullValue; FParamList.AddObject(Name, vObj); end; var vAddFields: TOrderHeaderHAddFields; begin edSMSText.Clear; FSMSEnabled := False; ExecTimer.Enabled := False; LabelAction.Caption := ''; FActionCore := TActionCore.Create(Self, Form1.ADOC_STAT, FUserId, FOrderItem, FUserSession); FActionCore.SpecItem := FSpecItem; FActionCore.SubItemId := FSubItemId; FActionCore.ReserveType := FReserveType; FParamList := TStringList.Create; AddParam('Action', lbAction, Self.SetAction, ''); AddParam('SrcBasis', lcSrcBasis, Self.SetSrcBasis, 0); AddParam('ResBasis', lcResBasis, Self.SetResBasis, 0); AddParam('ResStatus', lcResStatus, Self.SetResStatus, 0); AddParam('SrcStatus', lcSrcStatus, nil, 0); vAddFields := dmJSO.GetOrderHAddFields(FOrderID); edHistoryComments.Text := vAddFields.HistoryComments; edHistoryExecMsg.Text := vAddFields.HistoryExecMsg; edSNote.Text := FOrderItem.SNote; end; procedure TActionDlg.SetParam(Value: Variant; ParamName: string); var vIdx: Integer; vParam: TParamObj; vLC: TDBLookupComboBox; vLB: TDBLookupListBox; begin vIdx := FParamList.IndexOf(ParamName); if vIdx = - 1 then raise Exception.Create('Не найден параметр ' + ParamName); vLC := nil; vLB := nil; vParam := TParamObj(FParamList.Objects[vIdx]); if vParam.Lookup is TDBLookupComboBox then vLC := TDBLookupComboBox(vParam.Lookup); if vParam.Lookup is TDBLookupListBox then vLB := TDBLookupListBox(vParam.Lookup); if Assigned(vLC) then begin if not VarIsAssigned(Value) or (not vLC.ListSource.DataSet.Locate(vLC.KeyField, Value, [])) then begin vLC.KeyValue := Null; if Assigned(vParam.SetParam) then vParam.SetParam(vParam.NullValue); end else begin vLC.KeyValue := Value; if Assigned(vParam.SetParam) then vParam.SetParam(Value); end; end else if Assigned(vLB) then begin if not VarIsAssigned(Value) or (not vLB.ListSource.DataSet.Locate(vLB.KeyField, Value, [])) then begin vLB.KeyValue := Null; if Assigned(vParam.SetParam) then vParam.SetParam(vParam.NullValue); end else begin vLB.KeyValue := Value; if Assigned(vParam.SetParam) then vParam.SetParam(Value); end; end end; procedure TActionDlg.SetParamEnabled(ParamName: string; Value: Boolean); var vIdx: Integer; vParam: TParamObj; vLC: TDBLookupComboBox; vLB: TDBLookupListBox; begin vIdx := FParamList.IndexOf(ParamName); if vIdx = - 1 then raise Exception.Create('Не найден параметр ' + ParamName); vParam := TParamObj(FParamList.Objects[vIdx]); vParam.Lookup.Enabled := Value; if vParam.Lookup is TDBLookupComboBox then vLC := TDBLookupComboBox(vParam.Lookup); if vParam.Lookup is TDBLookupListBox then vLB := TDBLookupListBox(vParam.Lookup); if Assigned(vLC) then begin if Value then vLC.Color := clWindow else vLC.Color := clBtnFace; end else if Assigned(vLB) then begin if Value then vLB.Color := clWindow else vLB.Color := clBtnFace; end; end; procedure TActionDlg.InitSrcStatus; begin FSrcStatusId := FActionCore.GetLastOrderStatus(FOrderId); {spGetLastOrderStatus.Parameters.ParamValues['@OrderId'] := FOrderId; spGetLastOrderStatus.ExecProc; vIErr := spGetLastOrderStatus.Parameters.ParamValues['@RETURN_VALUE']; if vIErr <> 0 then begin vErrMsg := spGetLastOrderStatus.Parameters.ParamValues['@ErrMsg']; raise Exception.Create(vErrMsg); end else FSrcStatusId := spGetLastOrderStatus.Parameters.ParamValues['@StatusId']; } end; procedure TActionDlg.InitControls; var vCaption: string; begin //dmJSO.Debug := true; FInitProcess := true; try vCaption := 'Заказ № ' + IntToStr(FOrderId); pnlTop_Order.Caption := vCaption; pnlTop_Order.Width := TextPixWidth(vCaption, pnlTop_Order.Font) + 20; vCaption := 'Сумма ' + VarToStr(FOrderItem.orderAmount); pnlTop_Price.Caption := vCaption; pnlTop_Price.Width := TextPixWidth(vCaption, pnlTop_Price.Font) + 20; vCaption := FOrderItem.orderShipName; pnlTop_Client.Caption := vCaption; pnlTop_Client.Width := TextPixWidth(vCaption, pnlTop_Client.Font) + 10; SetParamEnabled('SrcStatus', False); SetParamEnabled('ResStatus', False); dsSrcStatus.DataSet := dmJSO.GetActionSrcOrderStatus(nil, FSrcStatusId); if dsSrcStatus.DataSet.RecordCount = 1 then begin lcSrcStatus.KeyValue := dsSrcStatus.DataSet.FieldByName(lcSrcStatus.KeyField).Value; end; dsAction.DataSet := dmJSO.GetOrderActions(nil, FBpId, FSrcStatusId, true, FUserId); if dsAction.DataSet.RecordCount = 1 then FInitActionCode := dsAction.DataSet.FieldByName(lbAction.KeyField).AsString; if FInitActionCode <> '' then SetParam(FInitActionCode, 'Action'); dsSrcBasis.DataSet := dmJSO.GetOrderSrcBasis(nil, FBpId, FSrcStatusId, FActionCode, true); if dsSrcBasis.DataSet.RecordCount = 1 then FSrcBasisId := dsSrcBasis.DataSet.FieldByName(lcSrcBasis.KeyField).AsInteger; if FSrcBasisId <> 0 then SetParam(FSrcBasisId, 'SrcBasis'); dsResBasis.DataSet := dmJSO.GetOrderResBasis(nil, FBpId, FSrcStatusId, FActionCode, FSrcBasisId, true); if dsResBasis.DataSet.RecordCount = 1 then FResBasisId := dsResBasis.DataSet.FieldByName(lcResBasis.KeyField).AsInteger else if dsResBasis.DataSet.RecordCount = 2 then begin dsResBasis.DataSet.First; FResBasisId := dsResBasis.DataSet.FieldByName(lcResBasis.KeyField).Value; end; if FResBasisId <> 0 then SetParam(FResBasisId, 'ResBasis'); dsResStatus.DataSet := dmJSO.GetActionResOrderStatus(nil, FBpId, FActionCode, FSrcStatusId, FSrcBasisId, FResBasisId, true); if dsResStatus.DataSet.RecordCount = 1 then FResStatusId := dsResStatus.DataSet.FieldByName(lcResStatus.KeyField).AsInteger; if FResStatusId <> 0 then SetParam(FResStatusId, 'ResStatus'); UpdSMSControls; if (not PanelSMS.Visible) then Self.Height := Self.Height - 76; if FDoExec then EnableCtrls(False); finally FInitProcess := false; end; end; procedure TActionDlg.SetAction(Value: Variant); var vValue: string; begin vValue := VarToStrExt(Value, ''); if FActionCode <> vValue then begin FActionCode := vValue; if (dsAction.DataSet.FieldByName(lbAction.KeyField).Value = vValue) or (dsAction.DataSet.Locate(lbAction.KeyField, vValue, [])) then FActionType := dsAction.DataSet.FieldByName('TypeAction').AsInteger; if not FInitProcess then begin UpdSrcBasis; UpdResBasis; UpdResStatus; end; end; //SetParamEnabled('ResBasis', FActionType > 0); UpdSMSControls; end; procedure TActionDlg.SetSrcBasis(Value: Variant); var vValue: Integer; begin vValue := VarToInt(Value, 0); if FSrcBasisId <> vValue then begin FSrcBasisId := vValue; if not FInitProcess then begin UpdResBasis; UpdResStatus; end; end; end; procedure TActionDlg.SetResBasis(Value: Variant); var vValue: Integer; begin vValue := VarToInt(Value, 0); if FResBasisId <> vValue then begin FResBasisId := vValue; if not FInitProcess then begin UpdResStatus; end; end; end; procedure TActionDlg.SetResStatus(Value: Variant); var vValue: Integer; begin vValue := VarToInt(Value, 0); if FResStatusId <> vValue then begin FResStatusId := vValue; end; end; procedure TActionDlg.lcResStatusCloseUp(Sender: TObject); begin SetResStatus(lcResStatus.KeyValue); end; procedure TActionDlg.UpdSrcBasis; var vValue: Variant; begin vValue := lcSrcBasis.KeyValue; dmJSO.GetOrderSrcBasis(TsprQuery(dsSrcBasis.DataSet), FBpId, FSrcStatusId, FActionCode); if dsSrcBasis.DataSet.RecordCount = 1 then begin lcSrcBasis.KeyValue := dsSrcBasis.DataSet.FieldByName(lcSrcBasis.KeyField).Value; SetSrcBasis(lcSrcBasis.KeyValue) end else begin if (not VarIsAssigned(vValue)) or (not dsSrcBasis.DataSet.Locate(lcSrcBasis.KeyField, vValue, [])) then begin lcSrcBasis.KeyValue := Null; SetSrcBasis(0); end; end; end; procedure TActionDlg.UpdResBasis; var vValue: Variant; begin vValue := lcResBasis.KeyValue; dmJSO.GetOrderResBasis(TsprQuery(dsResBasis.DataSet), FBpId, FSrcStatusId, FActionCode, FSrcBasisId); if dsResBasis.DataSet.RecordCount = 1 then begin lcResBasis.KeyValue := dsResBasis.DataSet.FieldByName(lcResBasis.KeyField).Value; SetResBasis(lcResBasis.KeyValue) end else if dsResBasis.DataSet.RecordCount = 2 then begin dsResBasis.DataSet.First; lcResBasis.KeyValue := dsResBasis.DataSet.FieldByName(lcResBasis.KeyField).Value; SetResBasis(lcResBasis.KeyValue) end else begin if (not VarIsAssigned(vValue)) or (not dsResBasis.DataSet.Locate(lcResBasis.KeyField, vValue, [])) then begin lcResBasis.KeyValue := Null; SetResBasis(0); end end; end; procedure TActionDlg.UpdResStatus; var vValue: Variant; begin vValue := lcResStatus.KeyValue; dmJSO.GetActionResOrderStatus(TsprQuery(dsResStatus.DataSet), FBpId, FActionCode, FSrcStatusId, FSrcBasisId, FResBasisId); if dsResStatus.DataSet.RecordCount = 1 then begin lcResStatus.KeyValue := dsResStatus.DataSet.FieldByName(lcResStatus.KeyField).Value; SetResStatus(lcResStatus.KeyValue) end else begin if (not VarIsAssigned(vValue)) or (not dsResStatus.DataSet.Locate(lcResStatus.KeyField, vValue, [])) then begin lcResStatus.KeyValue := Null; SetResStatus(0); end; end; end; function TActionDlg.CheckValues(var ErrMsg: string): Boolean; begin ErrMsg := ''; if FOrderId = 0 then ErrMsg := 'Не задан номер заказа' else if FBPId = 0 then ErrMsg := 'Не задан бизнес процесс' else if FActionCode = '' then ErrMsg := 'Не задано действие' else if FUserId = 0 then ErrMsg := 'Не задан пользователь' else if FSrcBasisId = 0 then ErrMsg := 'Не задано основание действия' else if (FActionType > 0) and (FResBasisId = 0) then ErrMsg := 'Не задано основание результата'; Result := ErrMsg = ''; { if not Result then Exit; Result := not((FResStatusId = 0) and (MessageDlg('Конечный статус НЕ задан. Подтвердите действие?', mtConfirmation, [mbOk, mbCancel], 0) <> mrOk));} end; procedure TActionDlg.OKBtnClick(Sender: TObject); var vErrMsg: string; vHistoryId: Integer; begin ExecTimer.Enabled := False; if not CheckValues(vErrMsg) and (vErrMsg <> '') then begin if not FNotShowCheckError then ShowError(vErrMsg); EnableCtrls(True); FNotShowCheckError := False; Exit; //raise Exception.Create(vErrMsg); end; FNotShowCheckError := False; EnableCtrls(False); LabelAction.Caption := 'Выполняется: ' + lbAction.SelectedItem; Self.Repaint; try try UpdActionCore; vHistoryId := FActionCore.StartOrderAction(FOrderId, FActionCode, FSrcStatusId, FSrcBasisId, edComments.Text); OKBtn.Enabled := False; CancelBtn.Enabled := False; try FActionCore.SafeExecuteAction(FActionCode, FActionType, FResBasisId); if FActionCore.ActionState <> asCancel then begin SetParam(FActionCore.ActionResult.ResBasisId, 'ResBasis'); if FActionCore.ActionResult.IErr <> 0 then begin if (FActionType <= 2) or (FActionCore.ErrType = etInternalErr) then ShowError(FActionCore.ActionResult.ExecMsg) end else begin if (FResStatusId = 0) then ShowError('Сбой при выполнении операции.' + chr(10) + 'Конечный статус НЕ задан'); end; end; FActionCore.EndOrderAction(FOrderId, vHistoryId, FResStatusId, FResBasisId, FActionCore.ActionResult.IErr, FActionCore.ActionResult.ExecMsg); except on E: Exception do begin ShowError('Сбой при выполнении операции.' + chr(10) + E.Message); FActionCore.EndOrderAction(FOrderId, vHistoryId, FSrcStatusId, cErrBasis, IfThen(FActionCore.ActionResult.IErr = 0, FActionCore.ActionResult.IErr, cDefError), E.Message + ' ' + FActionCore.ActionResult.ExecMsg); end; end; except on E:Exception do ShowError('Сбой при выполнении операции.' + chr(10) + E.Message); end; finally LabelAction.Caption := ''; EnableCtrls(True); end; ModalResult := mrOk; end; procedure TActionDlg.FormDestroy(Sender: TObject); var I: Integer; vDS: TDataSet; begin if Assigned(FActionCore) then FreeAndNil(FActionCore); if Assigned(FParamList) then begin for I := 0 to FParamList.Count - 1 do FParamList.Objects[I].Free; FParamList.Clear; FreeAndNil(FParamList); end; for I := 0 to Self.ComponentCount - 1 do if (Self.Components[I] is TDataSource) then begin vDS := TDataSource(Self.Components[I]).DataSet; if Assigned(vDS) then begin FreeAndNil(vDS); end; end; end; procedure TActionDlg.lcSrcBasisCloseUp(Sender: TObject); begin SetSrcBasis(lcSrcBasis.KeyValue); end; procedure TActionDlg.lcResBasisCloseUp(Sender: TObject); begin if lcResBasis.KeyValue = cErrBasis then lcResBasis.KeyValue := Null; SetResBasis(lcResBasis.KeyValue); end; procedure TActionDlg.UpdActionCore; begin FActionCore.SendSMS := cbSendMessage.Checked; FActionCore.SendEmail := cbSendEmail.Checked; FActionCore.SMSTExt := edSMSText.Text; end; procedure TActionDlg.UpdSMSControls; var vOrderShipment: string; vSendSMS: Boolean; begin vOrderShipment := Trim(AnsiUpperCase(FOrderItem.orderShipping)); PanelSMS.Visible := True;//((vOrderShipment = 'НОВАЯ ПОЧТА') or (vOrderShipment = 'НОВА ПОШТА')); if PanelSMS.Visible then begin cbSendMessage.Checked := False; cbSendEmail.Enabled := False; vSendSMS := (FActionCode = 'CloseOrder') or (FActionCode = 'OpenOrder'); cbSendMessage.Enabled := vSendSMS; cbSendEmail.Enabled := vSendSMS; FSMSEnabled := vSendSMS; if vSendSMS then begin if edSMSText.Text = '' then edSMSText.Text := FActionCore.GetDefaultSMSText(FOrderId, 3); end else edSMSText.Clear; end; end; procedure TActionDlg.lbActionClick(Sender: TObject); begin SetAction(lbAction.KeyValue); end; procedure TActionDlg.FormShow(Sender: TObject); var vResult: TModalResult; begin ExecTimer.Enabled := FDoExec; { if FDoExec then begin OKBtnClick(Self); vResult := ModalResult; PostMessage(Handle, WM_CLOSE, 0, 0); ModalResult := vResult; end;} end; procedure TActionDlg.ExecTimerTimer(Sender: TObject); begin OKBtnClick(Self); end; procedure TActionDlg.EnableCtrls(Value: Boolean); begin lbAction.Enabled := Value; lcSrcBasis.Enabled := Value; lcResBasis.Enabled := Value; edComments.Enabled := Value; OkBtn.Enabled := Value; CancelBtn.Enabled := Value; cbSendMessage.Enabled := Value and FSMSEnabled; cbSendEmail.Enabled := Value and FSMSEnabled; edSMSText.Enabled := Value and FSMSEnabled; end; end.
unit mpGUI; {$mode objfpc}{$H+} interface uses Classes, SysUtils, MasterPaskalForm, nosotime, graphics, strutils, forms, controls, grids,stdctrls, ExtCtrls, buttons, editbtn , menus, Clipbrd, IdContext, LCLTranslator, nosodebug, nosogeneral, nosocrypto, nosoconsensus,nosounit; type TFormInicio = class(Tform) procedure closeFormInicio(sender: TObject; var CanClose: boolean); private public end; TFormSlots = class(Tform) procedure GridMSlotsPrepareCanvas(sender: TObject; aCol, aRow: Integer;aState: TGridDrawState); private public end; function ThisPercent(percent, thiswidth : integer;RestarBarra : boolean = false):integer; Procedure CreateFormInicio(); Procedure CreateFormSlots(); Procedure UpdateSlotsGrid(); Function GetConnectedPeers():String; Procedure InicializarGUI(); Procedure OutText(Texto:String;inctime:boolean = false;canal : integer =0); Procedure ActualizarGUI(); Procedure Info(text:string); Procedure Processhint(sender:TObject); Procedure ShowGlobo(Titulo,texto:string); Procedure CloseAllForms(); Procedure UpdateRowHeigth(); var FormInicio : TFormInicio; GridInicio : TStringgrid; LastUpdateMonitor : int64 = 0; FormSlots : TFormSlots; GridMSlots : TStringgrid; SlotsLastUpdate : int64 = 0; implementation Uses mpParser, mpDisk, mpRed, mpProtocol,mpcoin, mpblock, formexplore, translation, mpMN; // Returns the X percentage of a specified number function ThisPercent(percent, thiswidth : integer;RestarBarra : boolean = false):integer; Begin result := (percent*thiswidth) div 100; if RestarBarra then result := result-20; End; // Crea el formulario para el inicio Procedure CreateFormInicio(); Begin FormInicio := TFormInicio.Createnew(form1); FormInicio.caption := 'Noso '+ProgramVersion+SubVersion; FormInicio.SetBounds(0, 0, 350, 200); FormInicio.BorderStyle := bssingle; FormInicio.Position:=poOwnerFormCenter; FormInicio.BorderIcons:=FormInicio.BorderIcons-[biminimize]-[bisystemmenu]; forminicio.ShowInTaskBar:=sTAlways; forminicio.OnCloseQuery:=@FormInicio.closeFormInicio; GridInicio := TStringGrid.Create(forminicio);GridInicio.Parent:=forminicio; GridInicio.Font.Name:='consolas'; GridInicio.Font.Size:=10; GridInicio.Left:=1;GridInicio.Top:=1;GridInicio.Height:=198;GridInicio.width:=348; GridInicio.FixedCols:=0;GridInicio.FixedRows:=0; GridInicio.rowcount := 0;GridInicio.ColCount:=1; GridInicio.ScrollBars:=ssAutoVertical; GridInicio.Options:= GridInicio.Options-[goRangeSelect]; GridInicio.ColWidths[0]:= 298; GridInicio.FocusRectVisible:=false; GridInicio.Enabled := true; GridInicio.GridLineWidth := 0; End; // Al cerrar el formulario de inicio Procedure TFormInicio.closeFormInicio(sender: TObject; var CanClose: boolean); Begin if G_launching then begin CompleteInicio; end else if RunningDoctor then canclose := false else begin forminicio.Visible:=false; form1.Visible:=true; end; End; // Color the conections form procedure TFormSlots.GridMSlotsPrepareCanvas(sender: TObject; aCol, aRow: Integer; aState: TGridDrawState); Begin if ( (Arow>0) and (conexiones[Arow].IsBusy) ) then begin (sender as TStringGrid).Canvas.Brush.Color := clmoneygreen; end; End; // Crea el formulario de monitorizacion de los slots Procedure CreateFormSlots(); Begin FormSlots := TFormSlots.Createnew(form1); FormSlots.caption := coinname+' Slots Monitor'; FormSlots.SetBounds(0, 0, 860, 410); FormSlots.BorderStyle := bssingle; //FormSlots.Position:=poOwnerFormCenter; FormSlots.Top:=1;FormSlots.Left:=1; FormSlots.BorderIcons:=FormSlots.BorderIcons-[biminimize]; FormSlots.ShowInTaskBar:=sTAlways; GridMSlots := TStringGrid.Create(FormSlots);GridMSlots.Parent:=FormSlots; GridMSlots.Font.Name:='consolas'; GridMSlots.Font.Size:=8; GridMSlots.Left:=1;GridMSlots.Top:=1;GridMSlots.Height:=408;GridMSlots.width:=854; GridMSlots.FixedCols:=0;GridMSlots.FixedRows:=1; GridMSlots.rowcount := MaxConecciones+1;GridMSlots.ColCount:=22; GridMSlots.ScrollBars:=ssVertical; GridMSlots.FocusRectVisible:=false; GridMSlots.Options:= GridMSlots.Options-[goRangeSelect]; GridMSlots.ColWidths[0]:= 20;GridMSlots.ColWidths[1]:= 80;GridMSlots.ColWidths[2]:= 25; GridMSlots.ColWidths[3]:= 20;GridMSlots.ColWidths[4]:= 48;GridMSlots.ColWidths[5]:= 40; GridMSlots.ColWidths[6]:= 40;GridMSlots.ColWidths[7]:= 25;GridMSlots.ColWidths[8]:= 25; GridMSlots.ColWidths[9]:= 70;GridMSlots.ColWidths[10]:= 30;GridMSlots.ColWidths[11]:= 25; GridMSlots.ColWidths[12]:= 40;GridMSlots.ColWidths[13]:= 25;GridMSlots.ColWidths[14]:= 29; GridMSlots.ColWidths[15]:= 40;GridMSlots.ColWidths[16]:= 25;GridMSlots.ColWidths[17]:= 80; GridMSlots.ColWidths[18]:= 25;GridMSlots.ColWidths[19]:= 40;GridMSlots.ColWidths[20]:= 40; GridMSlots.ColWidths[21]:= 40; GridMSlots.Enabled := true; GridMSlots.Cells[0,0]:='N';GridMSlots.Cells[1,0]:='IP';GridMSlots.Cells[2,0]:='T'; GridMSlots.Cells[3,0]:='Cx';GridMSlots.Cells[4,0]:='LBl';GridMSlots.Cells[5,0]:='LBlH'; GridMSlots.Cells[6,0]:='SumH';GridMSlots.Cells[7,0]:='Pen';GridMSlots.Cells[8,0]:='Pro'; GridMSlots.Cells[9,0]:='Ver';GridMSlots.Cells[10,0]:='LiP';GridMSlots.Cells[11,0]:='Off'; GridMSlots.Cells[12,0]:='HeaH';GridMSlots.Cells[13,0]:='Sta';GridMSlots.Cells[14,0]:='Ping'; GridMSlots.Cells[15,0]:='MNs';GridMSlots.Cells[16,0]:='#';GridMSlots.Cells[17,0]:='Besthash'; GridMSlots.Cells[18,0]:='MNC';GridMSlots.Cells[19,0]:='GVTs';GridMSlots.Cells[20,0]:='CFG'; GridMSlots.Cells[21,0]:='Mkl'; GridMSlots.GridLineWidth := 1; GridMSlots.OnPrepareCanvas:= @FormSlots.GridMSlotsPrepareCanvas; End; Procedure UpdateSlotsGrid(); var contador : integer; CurrentUTC : int64; Begin if WO_OmmitMemos then exit; BeginPerformance('UpdateSlotsGrid'); CurrentUTC := UTCTime; if CurrentUTC>SlotsLastUpdate then begin for contador := 1 to MaxConecciones do begin GridMSlots.Cells[0,contador]:= inttostr(contador); GridMSlots.Cells[1,contador]:= Conexiones[contador].ip; GridMSlots.Cells[2,contador]:= Conexiones[contador].tipo; GridMSlots.Cells[3,contador]:= IntToStr(Conexiones[contador].Connections); GridMSlots.Cells[4,contador]:= Conexiones[contador].Lastblock; GridMSlots.Cells[5,contador]:= copy(Conexiones[contador].LastblockHash,0,5); GridMSlots.Cells[6,contador]:= copy(Conexiones[contador].SumarioHash,0,5); GridMSlots.Cells[7,contador]:= IntToStr(Conexiones[contador].Pending); GridMSlots.Cells[8,contador]:= IntToStr(Conexiones[contador].Protocol); GridMSlots.Cells[9,contador]:= Conexiones[contador].Version; GridMSlots.Cells[10,contador]:= IntToStr(Conexiones[contador].ListeningPort); GridMSlots.Cells[11,contador]:= IntToStr(Conexiones[contador].offset); GridMSlots.Cells[12,contador]:= copy(Conexiones[contador].ResumenHash,0,5); GridMSlots.Cells[13,contador]:= IntToStr(Conexiones[contador].ConexStatus); GridMSlots.Cells[14,contador]:= IntToStr(UTCTime-StrToInt64Def(Conexiones[contador].lastping,UTCTime)); GridMSlots.Cells[15,contador]:= Conexiones[contador].MNsHash; GridMSlots.Cells[16,contador]:= IntToStr(Conexiones[contador].MNsCount); GridMSlots.Cells[17,contador]:= Conexiones[contador].BestHashDiff; GridMSlots.Cells[18,contador]:= Conexiones[contador].MNChecksCount.ToString; GridMSlots.Cells[19,contador]:= copy(Conexiones[contador].GVTsHash,0,5); GridMSlots.Cells[20,contador]:= Conexiones[contador].CFGHash; GridMSlots.Cells[21,contador]:= copy(Conexiones[contador].MerkleHash,0,5); end; SlotsLastUpdate := CurrentUTC; end; EndPerformance('UpdateSlotsGrid'); End; Function GetConnectedPeers():String; var counter : integer; Begin result := ''; For counter := 1 to MaxConecciones do begin if ( (Conexiones[counter].ip<>'') and (Conexiones[counter].ConexStatus>=3) ) then begin Result := result+Conexiones[counter].ip+' '; end; end; Trim(Result); End; // Inicializa el grid donde se muestran los datos Procedure InicializarGUI(); var contador : integer = 0; Begin // datapanel form1.DataPanel.Cells[0,0]:= 'Merkle'; form1.DataPanel.Cells[0,1]:=rs0505; //'Server' form1.DataPanel.Cells[0,2]:=rs0506; //'Connections' form1.DataPanel.Cells[0,3]:=rs0507; //'Headers' form1.DataPanel.Cells[0,4]:=rs0508; //'Summary' form1.DataPanel.Cells[0,5]:=rs0509; //Lastblock form1.DataPanel.Cells[0,6]:=rs0510; //'Blocks' form1.DataPanel.Cells[0,7]:=rs0511; //'Pending' form1.DataPanel.Cells[2,0]:= 'PoP Info'; form1.DataPanel.Cells[2,1]:= 'Next'; form1.DataPanel.Cells[2,2]:= 'Clients'; form1.DataPanel.Cells[2,3]:= 'OrdIndex'; form1.DataPanel.Cells[2,4]:= 'NosoCFG'; form1.DataPanel.Cells[2,5]:='GVTs'; form1.DataPanel.Cells[2,6]:='Masternodes'; form1.DataPanel.Cells[2,7]:='MNsCount'; Form1.SGridSC.Cells[0,0]:=rs0501; //'Destination' Form1.SGridSC.Cells[0,1]:=rs0502; //'Amount' Form1.SGridSC.Cells[0,2]:=rs0503; //'reference' //Direccionespanel form1.Direccionespanel.RowCount:=length(listadirecciones)+1; form1.Direccionespanel.Cells[0,0] := rs0514; //'Address' form1.Direccionespanel.Cells[1,0] := rs0515; //'Balance' for contador := 0 to length(ListaDirecciones)-1 do begin form1.Direccionespanel.Cells[0,contador+1] := ListaDirecciones[contador].Hash; form1.Direccionespanel.Cells[1,contador+1] := Int2Curr(ListaDirecciones[contador].Balance); end; // Nodes Grid form1.GridNodes.Cells[0,0] := 'Node'; form1.GridNodes.Cells[1,0] := 'Funds'; form1.GridNodes.Cells[2,0] := 'Last'; form1.GridNodes.Cells[3,0] := 'Total'; form1.GridNodes.Cells[4,0] := 'Conf'; form1.GridNodes.FocusRectVisible:=false; form1.GVTsGrid.Cells[0,0] := '#'; form1.GVTsGrid.Cells[1,0] := 'Address'; form1.GVTsGrid.FocusRectVisible:=false; NetSumarioHash.Value:='?'; NetLastBlock.Value:='?'; NetResumenHash.Value:='?'; End; // Ordena las salidas de informacion Procedure OutText(Texto:String;inctime:boolean = false;canal : integer =0); Begin if inctime then texto := timetostr(now)+' '+texto; if canal = 0 then AddLineToDebugLog('console',texto); if canal = 1 then // Salida al grid de inicio begin gridinicio.RowCount:=gridinicio.RowCount+1; gridinicio.Cells[0,gridinicio.RowCount-1]:=Texto; gridinicio.TopRow:=gridinicio.RowCount; Application.ProcessMessages; sleep(1); end; if canal = 2 then // A consola y label info begin AddLineToDebugLog('console',texto); info(texto); end; End; // Actualiza los datos en el grid Procedure ActualizarGUI(); Const LocalLastUpdate : int64 = 0; LastUpdateProcesses : int64 = 0; LastUpdateConsensus : int64 = 0; LastUpdateDataPanel : int64 = 0; var contador : integer = 0; LocalProcesses : TProcessCopy; FileProcs : TFileMCopy; LConsensus : TNodeConsensus; Begin if WO_OmmitMemos then exit; BeginPerformance('UpdateGUITime'); //Update Monitor Grid if ( (form1.PCMonitor.ActivePage = Form1.TabMonitorMonitor) and (LastUpdateMonitor<>UTCTime) ) then begin BeginPerformance('UpdateGUIMonitor'); if length(ArrPerformance)>0 then begin Form1.SG_Monitor.RowCount:=Length(ArrPerformance)+1; for contador := 0 to high(ArrPerformance) do begin try Form1.SG_Monitor.Cells[0,contador+1]:=ArrPerformance[contador].tag; Form1.SG_Monitor.Cells[1,contador+1]:=IntToStr(ArrPerformance[contador].Count); Form1.SG_Monitor.Cells[2,contador+1]:=IntToStr(ArrPerformance[contador].max); Form1.SG_Monitor.Cells[3,contador+1]:=IntToStr(ArrPerformance[contador].Average); Except on E:Exception do begin AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+format('Error showing ArrPerformance data(%s): %s',[ArrPerformance[contador].tag,E.Message])); end; end; end; end; LastUpdateMonitor := UTCTime; EndPerformance('UpdateGUIMonitor'); end; if LastUpdateProcesses<> UTCTime then begin if form1.PC_Processes.ActivePage = Form1.TabFiles then begin FileProcs := GetFileProcessCopy; Form1.SG_FileProcs.RowCount:=Length(FileProcs)+1; //Form1.SG_FileProcs.Cells[0,0]:=Format('Thread [%d]',[length(LocalProcesses)]); For contador := 0 to High(FileProcs) do begin Form1.SG_FileProcs.Cells[0,contador+1]:=FileProcs[contador].FiType; Form1.SG_FileProcs.Cells[1,contador+1]:=FileProcs[contador].FiFile; Form1.SG_FileProcs.Cells[2,contador+1]:=FileProcs[contador].FiPeer; end; end; end; if LastUpdateProcesses<> UTCTime then begin if form1.PC_Processes.ActivePage = Form1.TabThreads then begin LocalProcesses := GetProcessCopy; Form1.SG_OpenThreads.RowCount:=Length(LocalProcesses)+1; Form1.SG_OpenThreads.Cells[0,0]:=Format('Thread [%d]',[length(LocalProcesses)]); For contador := 0 to High(LocalProcesses) do begin Form1.SG_OpenThreads.Cells[0,contador+1]:=LocalPRocesses[contador].ThName; Form1.SG_OpenThreads.Cells[1,contador+1]:=TimeSinceStamp(LocalPRocesses[contador].ThStart); end; end; end; if LastUpdateConsensus <> UTCTime then begin if form1.PCMonitor.ActivePage = Form1.TabConsensus then begin form1.Label1.Caption:= Format('Last update : %d seconds',[UTCTime-LastConsensusTime]); form1.Label16.Caption:=Format('Block : %s',[GetConsensus(2)]); form1.Label17.Caption:=Format('Merkle : %s',[GetConsensus]); form1.Label18.Caption:=Format('Consensus : %d %% (%d/%d)',[Css_Percentage,Css_ReachedNodes,Css_TotalNodes]); form1.SGConSeeds.RowCount:=1+GetNodesArrayCount; for contador := 0 to GetNodesArrayCount-1 do begin LConsensus := GetNodesArrayIndex(contador); Form1.SGConSeeds.Cells[0,contador+1]:= LConsensus.host; Form1.SGConSeeds.Cells[1,contador+1]:= LConsensus.peers.ToString; end; end; end; LastUpdateProcesses := UTCTime; //if LocalLastUpdate = UTCTime then exit; LocalLastUpdate := UTCTime; if LastUpdateDataPanel <> UTCTime then begin form1.DataPanel.Cells[1,0]:= copy(GetConsensus(0),0,5); form1.DataPanel.Cells[1,1]:= NodeServerInfo; form1.DataPanel.Cells[1,2]:= IntToStr(GetTotalConexiones)+' ('+IntToStr(MyConStatus)+') ['+IntToStr(G_TotalPings)+']'; form1.DataPanel.Cells[1,3]:= Format('%s / %s',[copy(myResumenHash,0,5),GetConsensus(5)]); form1.DataPanel.Cells[1,4]:= format('%s / %s',[Copy(MySumarioHash,0,5),GetConsensus(17)]); form1.DataPanel.Cells[1,5]:= format('%s / %s',[Copy(MyLastBlockHash,0,5),copy(GetConsensus(10),0,5)]); form1.DataPanel.Cells[1,6]:= format('%d / %s',[MyLastBlock,GetConsensus(2)]); form1.DataPanel.Cells[1,7]:= format('(%d) %d/%s',[length(ArrayCriptoOp),GetPendingCount,GetConsensus(3)]); {<-- -->} form1.DataPanel.Cells[3,0]:= format('[%s] %s...',[BestHashReadeable(GetNMSData.Diff),Copy(GetNMSData.Miner,1,8)]); form1.DataPanel.Cells[3,1]:= Format('[%s] %s Noso',[BlockAge.ToString,Copy(Int2curr(GetBlockReward(Mylastblock+1)),0,5)]); form1.DataPanel.Cells[3,2]:= GEtOutgoingconnections.ToString+'/'+GetClientReadThreads.ToString; form1.DataPanel.Cells[3,3]:= Format('%d (%d)',[MyLastOrdIndex,length(ArrayOrdIndex)]); form1.DataPanel.Cells[3,4]:= format('%s / %s',[Copy(HashMd5String(GetNosoCFGString),0,5),GetConsensus(19)]); form1.DataPanel.Cells[3,5]:= format('%s / %s',[Copy(MyGVTsHash,0,5),GetConsensus(18)]); form1.DataPanel.Cells[3,6]:= format('%s / %s',[Copy(MyMNsHash,0,5),GetConsensus(8)]); form1.DataPanel.Cells[3,7]:= format('(%d) %d/%s (%d)',[GetMNsChecksCount,GetMNsListLength,GetConsensus(9),LengthWaitingMNs]); LastUpdateDataPanel := UTCTime; end; // update nodes grid if ((U_MNsGrid) or (UTCTime>U_MNsGrid_Last+59)) then begin //{ form1.GridNodes.RowCount:=1; if GetMNsListLength > 0 then begin for contador := 0 to length(MNsList)-1 do begin form1.GridNodes.RowCount := form1.GridNodes.RowCount+1; form1.GridNodes.Cells[0,1+contador] := MNsList[contador].Ip+':'+IntToStr(MNsList[contador].Port); form1.GridNodes.Cells[1,1+contador] := MNsList[contador].Fund; //form1.GridNodes.Cells[1,1+contador] := MNsList[contador].First.ToString; form1.GridNodes.Cells[2,1+contador] := MNsList[contador].Last.ToString; form1.GridNodes.Cells[3,1+contador] := MNsList[contador].Total.ToString; form1.GridNodes.Cells[4,1+contador] := MNsList[contador].Validations.ToString; ; end; end; //} U_MNsGrid_Last := UTCTime; form1.LabelNodesHash.Caption:='Count: '+GetMNsListLength.ToString; U_MNsGrid := false; end; if U_DirPanel then begin BeginPerformance('UpdateDirPanel'); form1.Direccionespanel.RowCount:=length(listadirecciones)+1; for contador := 0 to length(ListaDirecciones)-1 do begin if ListaDirecciones[contador].Custom<>'' then form1.Direccionespanel.Cells[0,contador+1] := ListaDirecciones[contador].Custom else form1.Direccionespanel.Cells[0,contador+1] := ListaDirecciones[contador].Hash; form1.Direccionespanel.Cells[1,contador+1] := Int2Curr(GetAddressBalanceIndexed(ListaDirecciones[contador].hash)-ListaDirecciones[contador].pending); end; form1.LabelBigBalance.Caption := Int2Curr(GetWalletBalance)+' '+CoinSimbol; U_DirPanel := false; EndPerformance('UpdateDirPanel'); end; EndPerformance('UpdateGUITime'); End; // Actualiza la informacion de la label info Procedure Info(text:string); Begin if WO_OmmitMemos then exit; Form1.InfoPanel.Caption:=copy(text,1,40); InfoPanelTime := Length(text)*50;If InfoPanelTime<1000 then InfoPanelTime:= 1000; Form1.InfoPanel.Visible:=true; Form1.InfoPanel.BringToFront; Form1.InfoPanel.Refresh; if form1.InfoTimer.Enabled=false then form1.InfoTimer.Enabled:=true; End; // Fija el texto de hint Procedure Processhint(sender:TObject); var texto : string = ''; Begin if sender=form1.ConnectButton then begin if MyConStatus = 0 then texto:='Disconnected.'; //'Disconnected' if MyConStatus = 1 then texto:='Connecting...'; //'Connecting...' if MyConStatus = 2 then texto:='Connected.'; //'Connected' if MyConStatus = 3 then texto:='Updated with '+IntToStr(GetTotalConexiones)+' peers'; //'Updated with '+ form1.ConnectButton.Hint:=texto; end; if sender=form1.ImageInc then begin form1.ImageInc.Hint:='Incoming: '+Int2curr(MontoIncoming); end; if sender=form1.ImageOut then begin form1.ImageOut.Hint:='Outgoing: '+Int2curr(MontoOutgoing); end; End; // Mostrar el globo del trayicon Procedure ShowGlobo(Titulo,texto:string); Begin if Form1.SystrayIcon.Visible then begin form1.SystrayIcon.BalloonTitle:=Titulo; Form1.SystrayIcon.BalloonHint:=Texto; form1.SystrayIcon.BalloonTimeout:=3000; form1.SystrayIcon.ShowBalloonHint; end; End; Procedure CloseAllForms(); Begin TRY formslots.Visible:=false; CloseExplorer; EXCEPT on E: Exception do begin end; END; {TRY} End; Procedure UpdateRowHeigth(); var contador : integer; Begin form1.DataPanel.Font.Size:=UserFontSize; for contador := 0 to form1.datapanel.RowCount-1 do begin form1.DataPanel.RowHeights[contador]:=UserRowHeigth; end; End; END. // END UNIT
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { "Alternate" OpenGL functions to handle multi-texturing. Using this functions allows specifying none/one/multiple ARB multi-texture coordinates with standard texture specification call. Before using any of the xglTexCoordXxxx functions, call one of the xglMapTexCoordToXxxx functions to establish the redirectors. This unit is Open-Source under MPL The history is logged in a former GLS version of the unit. } unit VXS.XOpenGL; interface {$I VXScene.inc} uses VXS.OpenGL; type TMapTexCoordMode = (mtcmUndefined, mtcmNull, mtcmMain, mtcmDual, mtcmSecond, mtcmArbitrary); { TexCoord functions will be ignored. } procedure xglMapTexCoordToNull; { TexCoord functions will define the main texture coordinates. } procedure xglMapTexCoordToMain; { TexCoord functions will define the second texture unit coordinates. } procedure xglMapTexCoordToSecond; { TexCoord functions will define the two first texture units coordinates. } procedure xglMapTexCoordToDual; { TexCoord functions will define the specified texture units coordinates. } procedure xglMapTexCoordToArbitrary(const units: array of Cardinal); overload; procedure xglMapTexCoordToArbitrary(const bitWiseUnits: Cardinal); overload; procedure xglMapTexCoordToArbitraryAdd(const bitWiseUnits: Cardinal); { Defers xglMap calls execution until xglEndUpdate is met. Calls to Begin/EndUpdate may be nested. } procedure xglBeginUpdate; { Applies xglMap calls if there were any since xglBeginUpdate was invoked. Calls to Begin/EndUpdate may be nested. } procedure xglEndUpdate; { Saves State on the stack. } procedure xglPushState; { Restores State from the stack. } procedure xglPopState; { Whenever called, 2nd texture units changes will be forbidden to . Use this function when you're using the 2nd texture unit for your own purposes and don't want to alter it. } procedure xglForbidSecondTextureUnit; { Allow to use the second texture unit again. } procedure xglAllowSecondTextureUnit; { Returns the complex mapping in bitwise form. } function xglGetBitWiseMapping: Cardinal; {$IFDEF MULTITHREADOPENGL} threadvar {$ELSE} var {$ENDIF} xglMapTexCoordMode: TMapTexCoordMode; vSecondTextureUnitForbidden: Boolean; // Explicit texture coordinates specification xglTexCoord2f: procedure(s, t: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexCoord2fv: procedure(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexCoord3f: procedure(s, t, r: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexCoord3fv: procedure(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexCoord4f: procedure(s, t, r, q: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexCoord4fv: procedure(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} // TexGen texture coordinates specification xglTexGenf: procedure(coord, pname: TGLEnum; param: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexGenfv: procedure(coord, pname: TGLEnum; params: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexGeni: procedure(coord, pname: TGLEnum; param: GLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglTexGeniv: procedure(coord, pname: TGLEnum; params: PGLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} // Vertex Arrays texture coordinates specification xglTexCoordPointer: procedure(size: TGLint; atype: GLEnum; stride: GLsizei; data: pointer); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglEnableClientState: procedure(aarray: TGLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglDisableClientState: procedure(aarray: TGLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} // Misc xglEnable: procedure(cap: TGLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} xglDisable: procedure(cap: TGLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} //=================================================================== implementation //=================================================================== var vUpdCount: Integer; vUpdNewMode: TMapTexCoordMode; vStateStack: array of TMapTexCoordMode; vComplexMapping: array of Cardinal; vComplexMappingN: Integer; // ------------------------------------------------------------------ // Multitexturing coordinates duplication functions // ------------------------------------------------------------------ // --------- Complex (arbitrary) mapping procedure glTexCoord2f_Arbitrary(s, t: Single); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; var i: Integer; begin for i := 0 to vComplexMappingN do glMultiTexCoord2f(vComplexMapping[i], s, t); end; procedure glTexCoord2fv_Arbitrary(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; var i: Integer; begin for i := 0 to vComplexMappingN do glMultiTexCoord2fv(vComplexMapping[i], v); end; procedure glTexCoord3f_Arbitrary(s, t, r: Single); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; var i: Integer; begin for i := 0 to vComplexMappingN do glMultiTexCoord3f(vComplexMapping[i], s, t, r); end; procedure glTexCoord3fv_Arbitrary(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; var i: Integer; begin for i := 0 to vComplexMappingN do glMultiTexCoord3fv(vComplexMapping[i], v); end; procedure glTexCoord4f_Arbitrary(s, t, r, q: Single); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; var i: Integer; begin for i := 0 to vComplexMappingN do glMultiTexCoord4f(vComplexMapping[i], s, t, r, q); end; procedure glTexCoord4fv_Arbitrary(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; var i: Integer; begin for i := 0 to vComplexMappingN do glMultiTexCoord4fv(vComplexMapping[i], v); end; procedure glTexGenf_Arbitrary(coord, pname: GLEnum; param: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glActiveTexture(vComplexMapping[i]); glTexGenf(coord, pname, param); end; glActiveTexture(GL_TEXTURE0_ARB); end; procedure glTexGenfv_Arbitrary(coord, pname: GLEnum; params: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glActiveTexture(vComplexMapping[i]); glTexGenfv(coord, pname, params); end; glActiveTexture(GL_TEXTURE0_ARB); end; procedure glTexGeni_Arbitrary(coord, pname: GLEnum; param: GLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glActiveTexture(vComplexMapping[i]); glTexGeni(coord, pname, param); end; glActiveTexture(GL_TEXTURE0_ARB); end; procedure glTexGeniv_Arbitrary(coord, pname: GLEnum; params: PGLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glActiveTexture(vComplexMapping[i]); glTexGeniv(coord, pname, params); end; glActiveTexture(GL_TEXTURE0_ARB); end; procedure glEnable_Arbitrary(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glActiveTexture(vComplexMapping[i]); glEnable(cap); end; glActiveTextureARB(GL_TEXTURE0_ARB); end; procedure glDisable_Arbitrary(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glActiveTexture(vComplexMapping[i]); glDisable(cap); end; glActiveTextureARB(GL_TEXTURE0_ARB); end; procedure xglTexCoordPointer_Arbitrary(size: GLint; atype: GLEnum; stride: GLsizei; data: pointer); {$IFDEF MSWINDOWS} stdcall;{$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glClientActiveTexture(vComplexMapping[i]); glTexCoordPointer(size, atype, stride, data); end; glActiveTextureARB(GL_TEXTURE0_ARB); end; procedure xglEnableClientState_Arbitrary(aarray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glClientActiveTexture(vComplexMapping[i]); glEnableClientState(aarray); end; glActiveTextureARB(GL_TEXTURE0_ARB); end; procedure xglDisableClientState_Arbitrary(aarray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} var i: Integer; begin for i := 0 to vComplexMappingN do begin glClientActiveTexture(vComplexMapping[i]); glDisableClientState(aarray); end; glActiveTextureARB(GL_TEXTURE0_ARB); end; // --------- Second unit Texturing procedure glTexCoord2f_Second(s, t: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glMultiTexCoord2f(GL_TEXTURE1, s, t); end; procedure glTexCoord2fv_Second(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glMultiTexCoord2fv(GL_TEXTURE1, v); end; procedure glTexCoord3f_Second(s, t, r: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glMultiTexCoord3f(GL_TEXTURE1, s, t, r); end; procedure glTexCoord3fv_Second(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glMultiTexCoord3fv(GL_TEXTURE1, v); end; procedure glTexCoord4f_Second(s, t, r, q: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glMultiTexCoord4f(GL_TEXTURE1, s, t, r, q); end; procedure glTexCoord4fv_Second(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glMultiTexCoord4fv(GL_TEXTURE1, v); end; procedure glTexGenf_Second(coord, pname: GLEnum; param: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glActiveTexture(GL_TEXTURE1); glTexGenf(coord, pname, param); glActiveTexture(GL_TEXTURE0); end; procedure glTexGenfv_Second(coord, pname: GLEnum; params: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glActiveTexture(GL_TEXTURE1); glTexGenfv(coord, pname, params); glActiveTexture(GL_TEXTURE0); end; procedure glTexGeni_Second(coord, pname: GLEnum; param: GLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glActiveTextureARB(GL_TEXTURE1_ARB); glTexGeni(coord, pname, param); glActiveTextureARB(GL_TEXTURE0_ARB); end; procedure glTexGeniv_Second(coord, pname: GLEnum; params: PGLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glActiveTexture(GL_TEXTURE1_ARB); glTexGeniv(coord, pname, params); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glEnable_Second(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glActiveTexture(GL_TEXTURE1_ARB); glEnable(cap); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glDisable_Second(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glActiveTexture(GL_TEXTURE1_ARB); glDisable(cap); glActiveTexture(GL_TEXTURE0_ARB); end; procedure xglTexCoordPointer_Second(size: GLint; atype: GLEnum; stride: GLsizei; data: pointer); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glClientActiveTexture(GL_TEXTURE1); glTexCoordPointer(size, atype, stride, data); glClientActiveTexture(GL_TEXTURE0); end; procedure xglEnableClientState_Second(aArray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glClientActiveTexture(GL_TEXTURE1); glEnableClientState(aarray); glClientActiveTexture(GL_TEXTURE0); end; procedure xglDisableClientState_Second(aArray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glClientActiveTexture(GL_TEXTURE1); glDisableClientState(aArray); glClientActiveTexture(GL_TEXTURE0); end; // --------- Dual Texturing procedure glTexCoord2f_Dual(s, t: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoord2f(s, t); glMultiTexCoord2f(GL_TEXTURE1, s, t); end; procedure glTexCoord2fv_Dual(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoord2fv(v); glMultiTexCoord2fv(GL_TEXTURE1, v); end; procedure glTexCoord3f_Dual(s, t, r: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoord3f(s, t, r); glMultiTexCoord3f(GL_TEXTURE1, s, t, r); end; procedure glTexCoord3fv_Dual(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoord3fv(v); glMultiTexCoord3fv(GL_TEXTURE1, v); end; procedure glTexCoord4f_Dual(s, t, r, q: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoord4f(s, t, r, q); glMultiTexCoord4f(GL_TEXTURE1, s, t, r, q); end; procedure glTexCoord4fv_Dual(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoord4fv(v); glMultiTexCoord4fv(GL_TEXTURE1, v); end; procedure glTexGenf_Dual(coord, pname: GLEnum; param: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexGenf(coord, pname, param); glActiveTexture(GL_TEXTURE1_ARB); glTexGenf(coord, pname, param); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glTexGenfv_Dual(coord, pname: GLEnum; params: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexGenfv(coord, pname, params); glActiveTexture(GL_TEXTURE1_ARB); glTexGenfv(coord, pname, params); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glTexGeni_Dual(coord, pname: GLEnum; param: GLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexGeni(coord, pname, param); glActiveTexture(GL_TEXTURE1_ARB); glTexGeni(coord, pname, param); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glTexGeniv_Dual(coord, pname: GLEnum; params: PGLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexGeniv(coord, pname, params); glActiveTexture(GL_TEXTURE1_ARB); glTexGeniv(coord, pname, params); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glEnable_Dual(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glEnable(cap); glActiveTexture(GL_TEXTURE1_ARB); glEnable(cap); glActiveTexture(GL_TEXTURE0_ARB); end; procedure glDisable_Dual(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glDisable(cap); glActiveTexture(GL_TEXTURE1); glDisable(cap); glActiveTexture(GL_TEXTURE0); end; procedure xglTexCoordPointer_Dual(size: GLint; atype: GLEnum; stride: GLsizei; data: pointer); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glTexCoordPointer(size, atype, stride, data); glClientActiveTexture(GL_TEXTURE1); glTexCoordPointer(size, atype, stride, data); glClientActiveTexture(GL_TEXTURE0); end; procedure xglEnableClientState_Dual(aarray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glEnableClientState(aarray); glClientActiveTexture(GL_TEXTURE1); glEnableClientState(aarray); glClientActiveTexture(GL_TEXTURE0); end; procedure xglDisableClientState_Dual(aArray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin glDisableClientState(aArray); glClientActiveTexture(GL_TEXTURE1); glDisableClientState(aArray); glClientActiveTexture(GL_TEXTURE0); end; // --------- Null Texturing procedure glTexCoord2f_Null(s, t: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexCoord2fv_Null(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexCoord3f_Null(s, t, r: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexCoord3fv_Null(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexCoord4f_Null(s, t, r, q: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexCoord4fv_Null(v: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexGenf_Null(coord, pname: GLEnum; param: Single); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexGenfv_Null(coord, pname: GLEnum; params: PGLfloat); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexGeni_Null(coord, pname: GLEnum; param: GLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glTexGeniv_Null(coord, pname: GLEnum; params: PGLint); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glEnable_Null(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure glDisable_Null(cap: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure xglTexCoordPointer_Null(size: GLint; atype: GLEnum; stride: GLsizei; data: pointer); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure xglEnableClientState_Null(aArray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; procedure xglDisableClientState_Null(aArray: GLEnum); {$IFDEF MSWINDOWS} stdcall; {$ELSE} cdecl; {$ENDIF} begin end; // ------------------------------------------------------------------ // Redirections management functions // ------------------------------------------------------------------ procedure xglBeginUpdate; begin if vUpdCount = 0 then begin vUpdCount := 1; vUpdNewMode := xglMapTexCoordMode; end else Inc(vUpdCount); end; procedure xglEndUpdate; begin Dec(vUpdCount); if (vUpdCount = 0) and (vUpdNewMode <> xglMapTexCoordMode) then begin case vUpdNewMode of mtcmNull: xglMapTexCoordToNull; mtcmMain: xglMapTexCoordToMain; mtcmDual: xglMapTexCoordToDual; mtcmSecond: xglMapTexCoordToSecond; mtcmArbitrary: xglMapTexCoordToArbitrary(vComplexMapping); else Assert(False); end; end; end; procedure xglPushState; var i: Integer; begin Assert(vUpdCount = 0); i := Length(vStateStack); SetLength(vStateStack, i + 1); vStateStack[i] := xglMapTexCoordMode; end; procedure xglPopState; var i: Integer; begin Assert(vUpdCount = 0); i := Length(vStateStack) - 1; Assert(i >= 0); case vStateStack[i] of mtcmNull: xglMapTexCoordToNull; mtcmMain: xglMapTexCoordToMain; mtcmDual: xglMapTexCoordToDual; mtcmSecond: xglMapTexCoordToSecond; mtcmArbitrary: xglMapTexCoordToArbitrary(vComplexMapping); else Assert(False); end; SetLength(vStateStack, i); end; procedure xglForbidSecondTextureUnit; begin vSecondTextureUnitForbidden := True; end; procedure xglAllowSecondTextureUnit; begin vSecondTextureUnitForbidden := False; end; procedure xglMapTexCoordToNull; begin if vUpdCount <> 0 then vUpdNewMode := mtcmNull else if xglMapTexCoordMode <> mtcmNull then begin xglMapTexCoordMode := mtcmNull; xglTexCoord2f := glTexCoord2f_Null; xglTexCoord2fv := glTexCoord2fv_Null; xglTexCoord3f := glTexCoord3f_Null; xglTexCoord3fv := glTexCoord3fv_Null; xglTexCoord4f := glTexCoord4f_Null; xglTexCoord4fv := glTexCoord4fv_Null; xglTexGenf := glTexGenf_Null; xglTexGenfv := glTexGenfv_Null; xglTexGeni := glTexGeni_Null; xglTexGeniv := glTexGeniv_Null; xglTexCoordPointer := xglTexCoordPointer_Null; xglEnableClientState := xglEnableClientState_Null; xglDisableClientState := xglDisableClientState_Null; xglEnable := glEnable_Null; xglDisable := glDisable_Null; end; end; procedure xglMapTexCoordToMain; begin if vUpdCount <> 0 then vUpdNewMode := mtcmMain else if xglMapTexCoordMode <> mtcmMain then begin xglMapTexCoordMode := mtcmMain; xglTexCoord2f := glTexCoord2f; xglTexCoord2fv := glTexCoord2fv; xglTexCoord3f := glTexCoord3f; xglTexCoord3fv := glTexCoord3fv; xglTexCoord4f := glTexCoord4f; xglTexCoord4fv := glTexCoord4fv; xglTexGenf := glTexGenf; xglTexGenfv := glTexGenfv; xglTexGeni := glTexGeni; xglTexGeniv := glTexGeniv; xglTexCoordPointer := glTexCoordPointer; xglEnableClientState := glEnableClientState; xglDisableClientState := glDisableClientState; xglEnable := glEnable; xglDisable := glDisable; end; end; procedure xglMapTexCoordToSecond; begin if vSecondTextureUnitForbidden then begin xglMapTexCoordToNull; Exit; end; if vUpdCount <> 0 then vUpdNewMode := mtcmSecond else if xglMapTexCoordMode <> mtcmSecond then begin xglMapTexCoordMode := mtcmSecond; Assert(GL_ARB_multitexture); xglTexCoord2f := glTexCoord2f_Second; xglTexCoord2fv := glTexCoord2fv_Second; xglTexCoord3f := glTexCoord3f_Second; xglTexCoord3fv := glTexCoord3fv_Second; xglTexCoord4f := glTexCoord4f_Second; xglTexCoord4fv := glTexCoord4fv_Second; xglTexGenf := glTexGenf_Second; xglTexGenfv := glTexGenfv_Second; xglTexGeni := glTexGeni_Second; xglTexGeniv := glTexGeniv_Second; xglTexCoordPointer := xglTexCoordPointer_Second; xglEnableClientState := xglEnableClientState_Second; xglDisableClientState := xglDisableClientState_Second; xglEnable := glEnable_Second; xglDisable := glDisable_Second; end; end; procedure xglMapTexCoordToDual; begin if vSecondTextureUnitForbidden then begin xglMapTexCoordToMain; Exit; end; if vUpdCount <> 0 then vUpdNewMode := mtcmDual else if xglMapTexCoordMode <> mtcmDual then begin xglMapTexCoordMode := mtcmDual; Assert(GL_ARB_multitexture); xglTexCoord2f := glTexCoord2f_Dual; xglTexCoord2fv := glTexCoord2fv_Dual; xglTexCoord3f := glTexCoord3f_Dual; xglTexCoord3fv := glTexCoord3fv_Dual; xglTexCoord4f := glTexCoord4f_Dual; xglTexCoord4fv := glTexCoord4fv_Dual; xglTexGenf := glTexGenf_Dual; xglTexGenfv := glTexGenfv_Dual; xglTexGeni := glTexGeni_Dual; xglTexGeniv := glTexGeniv_Dual; xglTexCoordPointer := xglTexCoordPointer_Dual; xglEnableClientState := xglEnableClientState_Dual; xglDisableClientState := xglDisableClientState_Dual; xglEnable := glEnable_Dual; xglDisable := glDisable_Dual; end; end; procedure xglMapTexCoordToArbitrary(const units: array of Cardinal); var i, j, n: Integer; begin n := Length(units); SetLength(vComplexMapping, n); j := 0; vComplexMappingN := n - 1; for i := 0 to vComplexMappingN do begin if (not vSecondTextureUnitForbidden) or (units[i] <> GL_TEXTURE1) then begin vComplexMapping[j] := units[i]; Inc(j); end; end; if vUpdCount <> 0 then vUpdNewMode := mtcmArbitrary else if xglMapTexCoordMode <> mtcmArbitrary then begin xglMapTexCoordMode := mtcmArbitrary; Assert(GL_ARB_multitexture); xglTexCoord2f := glTexCoord2f_Arbitrary; xglTexCoord2fv := glTexCoord2fv_Arbitrary; xglTexCoord3f := glTexCoord3f_Arbitrary; xglTexCoord3fv := glTexCoord3fv_Arbitrary; xglTexCoord4f := glTexCoord4f_Arbitrary; xglTexCoord4fv := glTexCoord4fv_Arbitrary; xglTexGenf := glTexGenf_Arbitrary; xglTexGenfv := glTexGenfv_Arbitrary; xglTexGeni := glTexGeni_Arbitrary; xglTexGeniv := glTexGeniv_Arbitrary; xglTexCoordPointer := xglTexCoordPointer_Arbitrary; xglEnableClientState := xglEnableClientState_Arbitrary; xglDisableClientState := xglDisableClientState_Arbitrary; xglEnable := glEnable_Arbitrary; xglDisable := glDisable_Arbitrary; end; end; procedure xglMapTexCoordToArbitrary(const bitWiseUnits: Cardinal); var i, n: Integer; units: array of Cardinal; begin n := 0; for i := 0 to 7 do begin if (bitWiseUnits and (1 shl i)) <> 0 then Inc(n); end; SetLength(units, n); n := 0; for i := 0 to 7 do begin if (bitWiseUnits and (1 shl i)) <> 0 then begin units[n] := GL_TEXTURE0 + i; Inc(n); end; end; xglMapTexCoordToArbitrary(units); end; procedure xglMapTexCoordToArbitraryAdd(const bitWiseUnits: Cardinal); var n: Cardinal; begin n := xglGetBitWiseMapping; xglMapTexCoordToArbitrary(n or bitWiseUnits); end; function xglGetBitWiseMapping: Cardinal; var i, n: Cardinal; mode: TMapTexCoordMode; begin if vUpdCount > 0 then mode := vUpdNewMode else mode := xglMapTexCoordMode; n := 0; case mode of mtcmMain: n := 1; mtcmDual: n := 3; mtcmSecond: n := 2; mtcmArbitrary: begin for i := 0 to vComplexMappingN do n := n or (1 shl (vComplexMapping[i] - GL_TEXTURE0)); end; else Assert(False); end; Result := n; end; // ------------------------------------------------------------------------ initialization // ------------------------------------------------------------------------ xglMapTexCoordMode := mtcmUndefined; xglMapTexCoordToNull; end.
unit DAW.Model.Device; interface type TdawDevice = record private FID: string; FName: string; FIP: string; FIsConnected: Boolean; public procedure SetIP(const Value: string); constructor Create(const AName, AID: string); procedure SetIsConnected(const Value: Boolean); function GetIsConnected: Boolean; property ID: string read FID write FID; property Name: string read FName write FName; property IP: string read FIP write SetIP; property IsConnected: Boolean read GetIsConnected write SetIsConnected; end; implementation { TdawDevice } constructor TdawDevice.Create(const AName, AID: string); begin Self.FID := AID; Self.FName := AName; SetIsConnected(False); end; function TdawDevice.GetIsConnected: Boolean; begin Result := FIsConnected; end; procedure TdawDevice.SetIP(const Value: string); begin FIP := Value; end; procedure TdawDevice.SetIsConnected(const Value: Boolean); begin FIsConnected := Value; end; end.
unit NSqlRenderer; {$I ..\NSql.Inc} interface uses NSqlIntf; type ISqlRenderer = interface ['{286C884D-8FC3-458F-B750-5B2984307629}'] function StrOfUpdateQuery(Query: IBaseUpdateQuery): UnicodeString; function StrOfInsertQuery(Query: IBaseInsertQuery): UnicodeString; function StrOfDeleteQuery(Query: IBaseDeleteQuery): UnicodeString; function StrOfSelectQuery(Query: IBaseSelectQuery): UnicodeString; function StrOfExecutableProcedure(Proc: IExecutableStoredProcedure): UnicodeString; end; function NewSqlRenderer(SqlEngine: TNativeSqlEngine): ISqlRenderer; implementation uses {$IFDEF NSQL_XE2UP} System.SysUtils, System.TypInfo, WinApi.Windows, Data.FmtBcd, {$ELSE} SysUtils, TypInfo, Windows, FmtBcd, {$ENDIF} NSqlTypes, NSqlQueries, NSqlConditions, NSqlSys; type TStatementType = (stNone, stInsert, stUpdate, stSelect); TUpdateElementType = (uetInsert, uetUpdate); TSqlRenderer = class(TNonInterlockedInterfacedObject, ISqlRenderer) private FAsString: UnicodeString; FSqlEngine: TNativeSqlEngine; function Quote(const S: UnicodeString): UnicodeString; function GetQuotedName(Table: ITable): UnicodeString; overload; function GetQuotedName(Field: IField): UnicodeString; overload; function StrOfStructureNameWithAlias(Structure: IStructureWithFields): UnicodeString; // function StrOfTableNameAlias(Table: ITable): UnicodeString; function StrOfFieldNameWithAlias(Field: IField): UnicodeString; function StrOfFieldName(Field: IField): UnicodeString; function StrOfTableAliasDotFieldName(Field: IField): UnicodeString; function StrOfConditionStatementElement(StatementElement: IStatementElement): UnicodeString; function StrOfCondition(Condition: ISqlCondition): UnicodeString; function StrOfParameter(Param: ISqlParam): UnicodeString; function StrOfInStatementValues(InStatementValues: IInStatementValues): UnicodeString; function StrOfSelectable(Selectable: ISelectable; UseShortNotation: Boolean; IsInSelectPart: Boolean; AddAsAlias: Boolean): UnicodeString; function StrOfSelectableByParam(SelectableByParam: ISelectableByParam; UseAlias: Boolean): UnicodeString; function StrOfGenerator(Generator: IGenerator): UnicodeString; function StrOfSelectableByQuery(SelectableByQuery: ISelectableByQuery; AddAsAlias: Boolean): UnicodeString; function MakeWhereStr(Condition: ISqlCondition): UnicodeString; // function StrOfDerivedTable(DerivedTable: IDerivedTable): UnicodeString; // function StrOfDerivedTableWithAlias(Selectable: ISelectable; DerivedTable: IDerivedTable): UnicodeString; function StrOfDerivantField(DerivantField: IDerivantField): UnicodeString; function StrOfSelectableSqlFunction(SelectableSqlFunction: ISelectableSqlFunction): UnicodeString; function StrOfSelectableSqlFunctionWithAlias(SelectableSqlFunction: ISelectableSqlFunction): UnicodeString; // function StrOfUnarySqlFunction(UnarySqlFunction: IUnarySqlFunction): UnicodeString; function StrOfSqlFunction(SqlFunction: ISqlFunction): UnicodeString; function StrOfBinarySqlOperator(BinarySqlOperator: IBinarySqlOperator): UnicodeString; function InternalStrOfSelectQuery(Query: IBaseSelectQuery; UseFieldsAliases: Boolean): UnicodeString; protected { ISqlRenderer } function StrOfUpdateQuery(Query: IBaseUpdateQuery): UnicodeString; function StrOfInsertQuery(Query: IBaseInsertQuery): UnicodeString; function StrOfDeleteQuery(Query: IBaseDeleteQuery): UnicodeString; function StrOfSelectQuery(Query: IBaseSelectQuery): UnicodeString; function StrOfExecutableProcedure(Proc: IExecutableStoredProcedure): UnicodeString; public constructor Create(ASqlEngine: TNativeSqlEngine); end; function Equals(const G1, G2: TGuid): Boolean; begin Result := CompareMem(@G1, @G2, SizeOf(TGuid)); end; function NewSqlRenderer(SqlEngine: TNativeSqlEngine): ISqlRenderer; begin Result := TSqlRenderer.Create(SqlEngine); end; {$IFDEF CPUX86} function InterlockedIncrement(var I: Integer): Integer; asm MOV EDX,1 XCHG EAX,EDX LOCK XADD [EDX],EAX INC EAX end; {$ENDIF} {$IFDEF CPUX64} function InterlockedIncrement(var I: Integer): Integer; asm MOV EAX,1 LOCK XADD [RCX].Integer,EAX INC EAX end; {$ENDIF CPUX64} var FParamGen: Integer = 0; FAliasGen: Integer = 0; function GenerateParamName: UnicodeString; begin { TODO : can returns negative numbers } Result := 'P' + IntToStr(InterlockedIncrement(FParamGen)); // Result := 'P' + IntToStr({$IFDEF CPUX64}WinApi.Windows.{$ENDIF}InterlockedIncrement(FParamGen)); end; function GenerateAlias(const Prefix: UnicodeString): UnicodeString; begin { TODO : can returns negative numbers } Result := Prefix + IntToStr(InterlockedIncrement(FAliasGen)); end; { TSqlRenderer } function TSqlRenderer.StrOfUpdateQuery( Query: IBaseUpdateQuery): UnicodeString; function MakeUpdateStr(List: TUpdateElementIntfArray): UnicodeString; var I: Integer; Line: UnicodeString; EndStr: UnicodeString; Element: IUpdateElement; ValueStr: UnicodeString; SqlParam: ISqlParam; Selectable: ISelectable; TableNameWithAlias: UnicodeString; CurrentTableNameWithAlias: UnicodeString; begin Assert(Assigned(List)); TableNameWithAlias := StrOfStructureNameWithAlias(List[0].Field.Structure); Result := 'update ' + TableNameWithAlias + ' set'#13#10; EndStr := ','#13#10; for I := 0 to High(List) do begin Element := List[I]; CurrentTableNameWithAlias := StrOfStructureNameWithAlias(Element.Field.Structure); Assert(CurrentTableNameWithAlias = TableNameWithAlias, CurrentTableNameWithAlias); if Supports(Element.Value, ISqlParam, SqlParam) then ValueStr := StrOfParameter(SqlParam) else if Supports(Element.Value, ISelectable, Selectable) then ValueStr := StrOfSelectable(Selectable, False, False, False) else Assert(False, Element.Value.ImplObjectClassName); Line := ' ' + StrOfTableAliasDotFieldName(Element.Field) + ' = ' + ValueStr; Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); end; var Update: UnicodeString; Where: UnicodeString; begin Update := MakeUpdateStr(Query.GetUpdateElements); Where := MakeWhereStr(Query.GetWhere); Result := Update; if Where <> '' then Result := Result + #13#10 + Where; end; function TSqlRenderer.StrOfSelectQuery(Query: IBaseSelectQuery): UnicodeString; begin Result := InternalStrOfSelectQuery(Query, True); end; function TSqlRenderer.StrOfDerivantField( DerivantField: IDerivantField): UnicodeString; begin if DerivantField.TableAlias = '' then Assert(False, 'DerivedSelectable.TableAlias is empty'); if DerivantField.FieldName = '' then Assert(False, 'DerivedSelectable.FieldName is empty'); if DerivantField.Alias = '' then Result := Quote(DerivantField.TableAlias) + '.' + Quote(DerivantField.FieldName) else Result := Quote(DerivantField.TableAlias) + '.' + Quote(DerivantField.FieldName) + FAsString + Quote(DerivantField.Alias); end; //function TSqlRenderer.StrOfDerivedTable(DerivedTable: IDerivedTable): UnicodeString; //begin // Result := InternalStrOfSelectQuery(DerivedTable.GetQuery, False); //end; //function TSqlRenderer.StrOfDerivedTableWithAlias(Selectable: ISelectable; // DerivedTable: IDerivedTable): UnicodeString; //begin //// if Selectable.Alias = '' then //// Selectable.Alias := GenerateAlias('F_'); // // Result := '(' + StrOfDerivedTable(DerivedTable) + ')' + FAsString + Quote(Selectable.Alias); //end; function TSqlRenderer.StrOfExecutableProcedure( Proc: IExecutableStoredProcedure): UnicodeString; var ProcedureParams: TStatementElementIntfArray; ProcedureParam: IStatementElement; I: Integer; EndStr: UnicodeString; begin ProcedureParams := Proc.GetProcedureParams; if Proc.ProcedureType <> sptExecutable then Assert(False); if Assigned(ProcedureParams) then begin EndStr := ', '; for I := 0 to High(ProcedureParams) do begin ProcedureParam := ProcedureParams[I]; Result := Result + StrOfConditionStatementElement(ProcedureParam) + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); end; Result := 'execute procedure ' + Quote(Proc.ProcedureName) + '(' + Result + ')'; end; function TSqlRenderer.StrOfInsertQuery(Query: IBaseInsertQuery): UnicodeString; function MakeInsertStr(List: TUpdateElementIntfArray): UnicodeString; var I: Integer; Line: UnicodeString; Element: IUpdateElement; EndStr: UnicodeString; TableName: UnicodeString; // CurrentTableName: UnicodeString; Structure: IStructureWithFields; CurrentStructure: IStructureWithFields; Table: ITable; begin Assert(Assigned(List)); Structure := List[0].Field.Structure; case Structure.StructureType of stTable: begin Table := (Structure as ITable); // TableName := (Structure as ITable).TableName; end; stStoredProc: Assert(False, 'inserts in stored procedures not allowed'); stDerivedTable: Assert(False, 'inserts in derived tables not allowed'); else Assert(False, 'unknown StructureType'); end; // TableName := List[0].Field.Structure.Name; // 1 Result := ''; EndStr := ', '; for I := 0 to High(List) do begin Element := List[I]; CurrentStructure := Element.Field.Structure; // CurrentTableName := Element.Field.Table.Name; if CurrentStructure <> Structure then Assert(False, 'insert to many tables not allowed'); // Assert(CurrentStructure = TableName, CurrentTableName); Line := GetQuotedName(Element.Field); Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); TableName := GetQuotedName(Table); Result := 'insert into ' + TableName + ' (' + Result + ')'; end; function MakeValuesStr(List: TUpdateElementIntfArray): UnicodeString; var I: Integer; Line: UnicodeString; Element: IUpdateElement; EndStr: UnicodeString; ValueStr: UnicodeString; SqlParam: ISqlParam; SelectableByParam: ISelectableByParam; SqlFunction: ISqlFunction; begin Assert(Assigned(List)); Result := ''; EndStr := ', '; for I := 0 to High(List) do begin Element := List[I]; if Supports(Element.Value, ISqlParam, SqlParam) then ValueStr := StrOfParameter(SqlParam) else if Supports(Element.Value, ISelectableByParam, SelectableByParam) then ValueStr := StrOfParameter(SelectableByParam.GetParam) else if Supports(Element.Value, ISqlFunction, SqlFunction) then ValueStr := StrOfSqlFunction(SqlFunction) else Assert(False, Element.Value.ImplObjectClassName); Line := ValueStr; Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); Result := 'values (' + Result + ')'; end; function MakeFirebirdReturnsStr(List: TSelectableIntfArray): UnicodeString; var I: Integer; Line: UnicodeString; Field: IField; EndStr: UnicodeString; begin if Assigned(List) then begin Result := ''; EndStr := ', '; for I := 0 to High(List) do begin Field := List[I] as IField; Line := GetQuotedName(Field); Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); end else Result := ''; end; // function CreateReturningSql(const Sql: UnicodeString; const ReturnFields: TStringDynArray): UnicodeString; // begin // Result := Sql; // if Assigned(ReturnFields) then // begin // if (Length(ReturnFields) = 1) and (UpperCase(ReturnFields[0]) = 'ID') then // Result := Result + Format(';'#13#10'SELECT LASTAUTOINC(STATEMENT) as "%s" FROM system.iota;', [ReturnFields[0]]) // else // begin // TableName := ExtractTableNameFromInsertSql(Sql); // Assert(False); // end; // end; // end; // function MakeAdsReturnsStr(const List: TSelectableIntfArray): UnicodeString; // var //// TableName: UnicodeString; //// I: Integer; // Field: IField; // begin // if Assigned(List) then // begin // Field := List[0] as IField; // if (Length(List) = 1) and Field.IsAutoGenerated then // begin // Result := Format('SELECT LASTAUTOINC(STATEMENT) as "%s" FROM system.iota;', [Field.Name]); // end // else // begin //// TableName := Query. ExtractTableNameFromInsertSql(Sql); // Assert(False); // end; // end // else // Result := ''; // end; var Insert: UnicodeString; Values: UnicodeString; Returns: UnicodeString; begin Insert := MakeInsertStr(Query.GetInsertElements); Values := MakeValuesStr(Query.GetInsertElements); Result := Insert + #13#10 + Values; // if FSqlEngine = nseFirebird then // begin Returns := MakeFirebirdReturnsStr(Query.GetReturnsElements); if Returns <> '' then Result := Result + #13#10 + 'returning ' + Returns; // end // else if FSqlEngine = nseAds then // begin // Returns := MakeAdsReturnsStr(Query.GetReturnsElements); // if Returns <> '' then // Result := Result + ';'#13#10 + Returns; // end; end; //function TSqlRenderer.StrOfTableNameAlias(Table: ITable): UnicodeString; //begin // if Table.Name <> Table.Alias then // Result := Quote(Table.Alias) // else // Result := GetQuotedName(Table); //end; function TSqlRenderer.StrOfStructureNameWithAlias(Structure: IStructureWithFields): UnicodeString; var StoredProcedure: IBaseStoredProcedure; ProcedureParams: TStatementElementIntfArray; // Params: TSqlParamIntfArray; ProcedureParam: IStatementElement; // Param: ISqlParam; I: Integer; EndStr: UnicodeString; DerivedTable: IDerivedTable; DerivedFieldsStr: UnicodeString; Query: IBaseSelectQuery; Selectables: TSelectableIntfArray; DerivantField: IDerivantField; Table: ITable; begin Assert(Assigned(Structure)); case Structure.StructureType of stStoredProc: begin if not Supports(Structure, IBaseStoredProcedure, StoredProcedure) then Assert(False); ProcedureParams := StoredProcedure.GetProcedureParams; // Params := StoredProcedure.GetParams; Result := ''; if StoredProcedure.ProcedureType <> sptSelectable then Assert(False); if Assigned(ProcedureParams) then begin EndStr := ', '; for I := 0 to High(ProcedureParams) do begin ProcedureParam := ProcedureParams[I]; Result := Result + StrOfConditionStatementElement(ProcedureParam) + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); end; if StoredProcedure.Alias = '' then StoredProcedure.Alias := GenerateAlias('SP_'); Result := Quote(StoredProcedure.ProcedureName) + '(' + Result + ') ' + Quote(StoredProcedure.Alias); end; stDerivedTable: begin if not Supports(Structure, IDerivedTable, DerivedTable) then Assert(False); Assert(DerivedTable.Alias <> '', 'DerivedTable.Alias not defined'); Query := DerivedTable.Query; Assert(Assigned(Query)); DerivedFieldsStr := ''; EndStr := ', '; Selectables := Query.GetSelectables; for I := 0 to High(Selectables) do begin DerivantField := Selectables[I].Derivant; Assert(Assigned(DerivantField), Format('Selectables[%d].Derivant not assigned', [I])); // if DerivantField.Alias = '' then // DerivantField.Alias := GenerateAlias('DTFA_'); // DerivedFieldsStr := DerivedFieldsStr + DerivantField.Alias + EndStr; if DerivantField.FieldName = '' then DerivantField.FieldName := GenerateAlias('DTF_'); DerivedFieldsStr := DerivedFieldsStr + Quote(DerivantField.FieldName) + EndStr; end; if Assigned(Selectables) then SetLength(DerivedFieldsStr, Length(DerivedFieldsStr) - Length(EndStr)); Result := '(' + StrOfSelectQuery(DerivedTable.Query) + ') as ' + Quote(DerivedTable.Alias) + ' (' + DerivedFieldsStr + ')'; end; stTable: begin if not Supports(Structure, ITable, Table) then Assert(False); if Table.TableName <> Table.Alias then Result := GetQuotedName(Table) + ' ' + Quote(Table.Alias) else Result := GetQuotedName(Table); end; else Assert(False, 'unknown StructureType'); end; end; function TSqlRenderer.StrOfBinarySqlOperator( BinarySqlOperator: IBinarySqlOperator): UnicodeString; var FuncStr: UnicodeString; // Selectable: ISelectable; begin Assert(BinarySqlOperator.OperatorType <> botInvalid, BinarySqlOperator.ImplObjectClassName); case BinarySqlOperator.OperatorType of botAdd: FuncStr := '%s + %s'; botSubtract: FuncStr := '%s - %s'; botMultiply: FuncStr := '%s * %s'; botDivide: FuncStr := '%s / %s'; botConcatenation: FuncStr := '%s || %s'; else Assert(False, GetEnumName(TypeInfo(TSqlBinaryOperatorType), Integer(BinarySqlOperator.OperatorType))); FuncStr := ''; end; Result := Format(FuncStr, [StrOfConditionStatementElement(BinarySqlOperator.FirstElement), StrOfConditionStatementElement(BinarySqlOperator.SecondElement)]); // if not InCondition then // begin // Assert(Supports(BinarySqlOperator, ISelectable, Selectable), BinarySqlOperator.ImplObjectClassName); // if Selectable.Alias = '' then // Selectable.Alias := GenerateAlias('F_'); //// Result := Result + FAsString + Selectable.Alias; // end; end; function TSqlRenderer.StrOfCondition(Condition: ISqlCondition): UnicodeString; function StrOfBinarySqlCondition(C: IBinarySqlCondition): UnicodeString; var CondStr: UnicodeString; ConditionType: IBinarySqlConditionType; begin Assert(Supports(C, IBinarySqlConditionType, ConditionType)); case ConditionType.Value of bctEQ: CondStr := '%s = %s'; bctNE: CondStr := '%s <> %s'; bctGE: CondStr := '%s >= %s'; bctLE: CondStr := '%s <= %s'; bctGreater: CondStr := '%s > %s'; bctLower: CondStr := '%s < %s'; bctContaining: CondStr := '%s CONTAINING(%s)'; bctStartingWith: CondStr := '%s STARTING WITH %s'; bctIn: CondStr := '%s IN %s'; else Assert(False, GetEnumName(TypeInfo(TBinarySqlConditionType), Integer(ConditionType.Value))); CondStr := ''; end; Result := Format('(' + CondStr + ')', [StrOfConditionStatementElement(C.FirstElement), StrOfConditionStatementElement(C.SecondElement)]); end; function StrOfUnarySqlCondition(C: IUnarySqlCondition): UnicodeString; var ConditionType: IUnarySqlConditionType; begin Assert(Supports(C, IUnarySqlConditionType, ConditionType)); case ConditionType.Value of uctNot: Result := 'not (' + StrOfConditionStatementElement(C.Element) + ')'; uctIsNull: Result := StrOfConditionStatementElement(C.Element) + ' is null'; uctIsNotNull: Result := StrOfConditionStatementElement(C.Element) + ' is not null'; else Assert(False, GetEnumName(TypeInfo(TUnarySqlConditionType), Integer(ConditionType.Value))); Result := ''; end; Result := '(' + Result + ')'; end; function StrOfCompoundSqlCondition(C: ICompoundSqlCondition): UnicodeString; var CondStr: UnicodeString; I: Integer; List: TSqlConditionIntfArray; EndStr: UnicodeString; ConditionType: ICompoundSqlConditionType; begin Result := '('; Assert(Supports(C, ICompoundSqlConditionType, ConditionType)); case ConditionType.Value of cctOr: CondStr := 'or'; cctAnd: CondStr := 'and'; else Assert(False, GetEnumName(TypeInfo(TCompoundSqlConditionType), Integer(ConditionType.Value))); CondStr := ''; end; EndStr := ' ' + CondStr + #13#10; List := C.Elements; Assert(Assigned(List)); for I := 0 to High(List) do Result := Result + StrOfCondition(List[I]) + EndStr; SetLength(Result, Length(Result) - Length(EndStr) + 1);; Result[Length(Result)] := ')'; end; var BinarySqlCondition: IBinarySqlCondition; UnarySqlCondition: IUnarySqlCondition; CompoundSqlCondition: ICompoundSqlCondition; begin if not Assigned(Condition) then Result := '' else if Supports(Condition, IBinarySqlCondition, BinarySqlCondition) then Result := StrOfBinarySqlCondition(BinarySqlCondition) else if Supports(Condition, IUnarySqlCondition, UnarySqlCondition) then Result := StrOfUnarySqlCondition(UnarySqlCondition) else if Supports(Condition, ICompoundSqlCondition, CompoundSqlCondition) then Result := StrOfCompoundSqlCondition(CompoundSqlCondition) else Assert(False, Condition.ImplObjectClassName); end; function TSqlRenderer.StrOfTableAliasDotFieldName( Field: IField): UnicodeString; var Table: ITable; StoredProcedure: IBaseStoredProcedure; DerivedTable: IDerivedTable; begin // Result := Quote(Field.Table.Alias) + '.' + GetQuotedName(Field); case Field.Structure.StructureType of stTable: begin Table := Field.Structure as ITable; if Table.TableName <> Table.Alias then Result := Quote(Table.Alias) + '.' + GetQuotedName(Field) else Result := GetQuotedName(Table) + '.' + GetQuotedName(Field); end; stStoredProc: begin StoredProcedure := Field.Structure as IBaseStoredProcedure; if StoredProcedure.ProcedureName <> StoredProcedure.Alias then Result := Quote(StoredProcedure.Alias) + '.' + GetQuotedName(Field) else Result := GetQuotedName(Field); end; stDerivedTable: begin DerivedTable := Field.Structure as IDerivedTable; if DerivedTable.Alias = '' then Assert(False); Result := Quote(DerivedTable.Alias) + '.' + GetQuotedName(Field); end; else Assert(False); end; end; function TSqlRenderer.StrOfFieldName(Field: IField): UnicodeString; begin Result := StrOfTableAliasDotFieldName(Field); end; function TSqlRenderer.StrOfFieldNameWithAlias(Field: IField): UnicodeString; begin if Field.Name <> Field.Alias then Result := StrOfFieldName(Field) + FAsString + Quote(Field.Alias) else Result := StrOfFieldName(Field); end; function TSqlRenderer.StrOfGenerator(Generator: IGenerator): UnicodeString; begin Result := '"' + Generator.Name + '"'; end; function TSqlRenderer.StrOfConditionStatementElement(StatementElement: IStatementElement): UnicodeString; var Field: IField; Condition: ISqlCondition; SqlParam: ISqlParam; InStatementValues: IInStatementValues; SelectableSqlFunction: ISelectableSqlFunction; DerivantField: IDerivantField; SelectableByParam: ISelectableByParam; SelectableByQuery: ISelectableByQuery; Generator: IGenerator; begin if Supports(StatementElement, ISqlCondition, Condition) then Result := StrOfCondition(Condition) else if Supports(StatementElement, IField, Field) then Result := StrOfTableAliasDotFieldName(Field) else if Supports(StatementElement, ISqlParam, SqlParam) then Result := StrOfParameter(SqlParam) else if Supports(StatementElement, IInStatementValues, InStatementValues) then Result := StrOfInStatementValues(InStatementValues) else if Supports(StatementElement, ISelectableSqlFunction, SelectableSqlFunction) then Result := StrOfSelectableSqlFunction(SelectableSqlFunction) else if Supports(StatementElement, IDerivantField, DerivantField) then Result := Quote(DerivantField.TableAlias) + '.' + Quote(DerivantField.FieldName) else if Supports(StatementElement, IGenerator, Generator) then Result := StrOfGenerator(Generator) else if Supports(StatementElement, ISelectableByParam, SelectableByParam) then Result := StrOfSelectableByParam(SelectableByParam, False) else if Supports(StatementElement, ISelectableByQuery, SelectableByQuery) then Result := StrOfSelectableByQuery(SelectableByQuery, False) else Assert(False, StatementElement.ImplObjectClassName); end; function TSqlRenderer.StrOfParameter(Param: ISqlParam): UnicodeString; // function BcdToStrEx(const Value: TBcd): UnicodeString; // var // F: TFormatSettings; // begin // F.DecimalSeparator := '.'; // Result := BcdToStr(Value, F); // end; var Len: Integer; begin if Param.Name = '' then Param.Name := GenerateParamName; if Param.IsConst then begin Assert(not Param.IsNull, Param.ImplObjectClassName); Param.UseAsConst := Param.DataType in [dtInteger, dtBoolean, {dtInt64, dtSmallInt,} dtBcd]; if Param.UseAsConst then begin case Param.DataType of dtInteger: Result := IntToStr((Param as IIntegerSqlParam).Value); // dtInt64: Result := IntToStr((Param as IInt64SqlParam).Value); dtBoolean: if FSqlEngine = nseFirebird30 then begin if (Param as IBooleanSqlParam).Value then Result := 'TRUE' else Result := 'FALSE'; end else if FSqlEngine = nseFirebird25 then begin if (Param as IBooleanSqlParam).Value then Result := '1' else Result := '0'; end else Assert(False); // dtSmallInt: Result := IntToStr((Param as ISmallIntSqlParam).Value); dtBcd: Result := NSqlBcdToString((Param as IBcdSqlParam).Value); else Assert(False); Result := ''; end; end else begin // Result := ':' + Param.Name; case Param.DataType of dtString: begin Len := Length((Param as IStringSqlParam).Value); if Len = 0 then Len := 1; Result := Format('CAST(:%s as VARCHAR(%d))', [Param.Name, Len]); end; dtBinaryString: begin Len := Length((Param as IBinaryStringSqlParam).Value); if Len = 0 then Len := 1; Result := Format('CAST(:%s as VARCHAR(%d) CHARACTER SET OCTETS)', [Param.Name, Len]); end; dtFloat: Result := Format('CAST(:%s as DOUBLE PRECISION)', [Param.Name]); dtDate: Result := Format('CAST(:%s as DATE)', [Param.Name]); dtTime: Result := Format('CAST(:%s as TIME)', [Param.Name]); dtDateTime: Result := Format('CAST(:%s as TIMESTAMP)', [Param.Name]); dtMemo: Result := Format('CAST(:%s as BLOB SUB_TYPE 1)', [Param.Name]); dtBlob: Result := Format('CAST(:%s as BLOB SUB_TYPE 0)', [Param.Name]); else Assert(False); Result := ''; end; end; end else begin Result := ':' + Param.Name; end; end; function TSqlRenderer.StrOfSelectable(Selectable: ISelectable; UseShortNotation: Boolean; IsInSelectPart: Boolean; AddAsAlias: Boolean): UnicodeString; var Field: IField; SelectableSqlFunction: ISelectableSqlFunction; SelectableByParam: ISelectableByParam; // DerivedTable: IDerivedTable; DerivantField: IDerivantField; SelectableByQuery: ISelectableByQuery; SelectableType: TSelectableType; begin SelectableType := Selectable.GetSelectableType; case SelectableType of stTableField: begin if not Supports(Selectable, IField, Field) then Assert(False); if IsInSelectPart then begin if AddAsAlias then Result := StrOfFieldNameWithAlias(Field) else Result := StrOfFieldName(Field); end else begin if not UseShortNotation then Result := StrOfTableAliasDotFieldName(Field) else begin Result := Quote(Field.Alias); Assert(False, 'can''t be here'); end; end; end; stStoredProcField: begin if not Supports(Selectable, IField, Field) then Assert(False); if IsInSelectPart then begin // if AddAsAlias then Result := StrOfFieldNameWithAlias(Field) // else // Result := StrOfFieldName(Field); end else begin // if not UseShortNotation then // Result := StrOfTableAliasDotFieldName(Field) // else // begin Result := Quote(Field.Alias); // Assert(False, 'can''t be here'); // end; end; end; stSelectableSqlFunction: begin if not Supports(Selectable, ISelectableSqlFunction, SelectableSqlFunction) then Assert(False); if IsInSelectPart then begin if AddAsAlias then Result := StrOfSelectableSqlFunctionWithAlias(SelectableSqlFunction) else Result := StrOfSelectableSqlFunction(SelectableSqlFunction); end else Result := StrOfSelectableSqlFunction(SelectableSqlFunction) end; stSelectableByParam: begin if not Supports(Selectable, ISelectableByParam, SelectableByParam) then Assert(False); if IsInSelectPart then Result := StrOfSelectableByParam(SelectableByParam, AddAsAlias) else Result := StrOfParameter(SelectableByParam.GetParam) end; stSelectableByQuery: begin if not Supports(Selectable, ISelectableByQuery, SelectableByQuery) then Assert(False); if IsInSelectPart then Result := StrOfSelectableByQuery(SelectableByQuery, AddAsAlias) else Result := StrOfSelectableByQuery(SelectableByQuery, AddAsAlias); end; stDerivantField: begin if not Supports(Selectable, IDerivantField, DerivantField) then Assert(False); if IsInSelectPart then Result := StrOfDerivantField(DerivantField{, UseFieldsAliases}) else Assert(False); // AddToTableInheritanceList(Field); end; else Assert(False, Selectable.ImplObjectClassName + ' ' + GetEnumName(TypeInfo(TSelectableType), Integer(SelectableType))); end; end; function TSqlRenderer.StrOfSelectableByParam( SelectableByParam: ISelectableByParam; UseAlias: Boolean): UnicodeString; begin Result := StrOfParameter(SelectableByParam.GetParam); if UseAlias then Result := Result + FAsString + SelectableByParam.Alias; end; function TSqlRenderer.StrOfSelectableByQuery( SelectableByQuery: ISelectableByQuery; AddAsAlias: Boolean): UnicodeString; begin Result := '(' + StrOfSelectQuery(SelectableByQuery.Query) + ')'; if AddAsAlias then begin if SelectableByQuery.Alias <> '' then Result := Result + FAsString + SelectableByQuery.Alias; end; end; function TSqlRenderer.GetQuotedName(Table: ITable): UnicodeString; begin if Table.HasCaseSensitiveName then Result := Quote(Table.TableName) else Result := Table.TableName; end; function TSqlRenderer.GetQuotedName(Field: IField): UnicodeString; begin if Field.HasCaseSensitiveName then Result := Quote(Field.Name) else Result := Field.Name; end; function TSqlRenderer.InternalStrOfSelectQuery(Query: IBaseSelectQuery; UseFieldsAliases: Boolean): UnicodeString; //type // TTableInheritance = record // TableList: TTableIntfArray; // Handled: Boolean; // end; //// TTableRecArray = array of TTableInheritance; // // TTableInheritanceList = array of TTableInheritance; procedure AddJoins(var Dest: TJoinIntfArray; const What: TJoinIntfArray); var I: Integer; StartIdx: Integer; // Join: IJoin; // Table: ITable; begin if Assigned(What) then begin StartIdx := Length(Dest); SetLength(Dest, Length(Dest) + Length(What)); for I := 0 to High(What) do Dest[StartIdx + I] := What[I]; // for I := 0 to High(What) do // begin // Join := What[I]; // if Supports(Join.Table, ITable, Table) then // AddJoins(Dest, Table.GetFkJoins); // end; end; end; //var // TableInheritanceList: TTableInheritanceList; // ExJoinArray: TJoinIntfArray; function GetReversed(const TableIntfArray: TTableIntfArray): TTableIntfArray; var I: Integer; begin SetLength(Result, Length(TableIntfArray)); for I := 0 to High(TableIntfArray) do Result[High(Result) - I] := TableIntfArray[I]; end; // function GetTableInheritanceOfField(Field: IField): TTableIntfArray; // var // Table: ITable; // begin // Result := nil; // Table := Field.Table; // SetLength(Result, Length(Result) + 1); // Result[High(Result)] := Table; // while Assigned(Table.InheritedByTable) do // begin // Table := Table.InheritedByTable; // SetLength(Result, Length(Result) + 1); // Result[High(Result)] := Table; // end; // Result := GetReversed(Result); // end; // // function IsFieldInheritedByTable(Field: IField; Table: ITable): Boolean; // var // E: ITable; // begin // Result := False; // E := Field.Table; // if E = Table then // Exit; // E := E.InheritedByTable; // while Assigned(E) do // begin // if E = Table then // begin // Result := True; // Exit; // end; // E := E.InheritedByTable; // end; // end; // // procedure AddToTableInheritanceList(Field: IField); // var // I: Integer; // TableInheritance: TTableIntfArray; // begin // if not Assigned(Field.Table.InheritedByTable) then // Exit; // TableInheritance := GetTableInheritanceOfField(Field); // // for I := 0 to High(TableInheritanceList) do // begin // if TableInheritanceList[I].TableList[0] = TableInheritance[0] then // begin // if Length(TableInheritanceList[I].TableList) < Length(TableInheritance) then // TableInheritanceList[I].TableList := TableInheritance; // //// Assert(Length(TableInheritanceList[I]) = Length(TableInheritance)); // Exit; // end // end; // SetLength(TableInheritanceList, Length(TableInheritanceList) + 1); // TableInheritanceList[High(TableInheritanceList)].TableList := TableInheritance; // TableInheritanceList[High(TableInheritanceList)].Handled := False; //// for I := 0 to High(ExJoins) do //// if Join.Table = ExJoins[I].Table then //// Exit; //// Join := TTypedJoin.Create(jtInner, Field.Table, EQ() //// SetLength(ExJoins, Length(ExJoins) + 1); //// ExJoins[High(ExJoins)] := Join; // end; function MakeSelectStr(List: TSelectableIntfArray): UnicodeString; var I{, J}: Integer; Selectable: ISelectable; // Field: IField; Line: UnicodeString; EndStr: UnicodeString; // SelectableSqlFunction: ISelectableSqlFunction; // DerivedTable: IDerivedTable; // DerivantField: IDerivantField; // SelectableByParam: ISelectableByParam; First: ISelectable; Skip: ISelectable; // SelectableByQuery: ISelectableByQuery; begin Result := 'select'; First := Query.GetFirst; if Assigned(First) then Result := Result + ' first (' + StrOfSelectable(First, True, False, False) + ')'; Skip := Query.GetSkip; if Assigned(Skip) then Result := Result + ' skip (' + StrOfSelectable(Skip, True, False, False) + ')'; if Query.IsDistinct then Result := Result + ' distinct'; Result := Result + #13#10; EndStr := ','#13#10; Assert(Assigned(List)); for I := 0 to High(List) do begin Selectable := List[I]; // if UseFieldsAliases then // begin if Selectable.Alias = '' then Selectable.Alias := GenerateAlias('F_'); // end; if Supports(Selectable, ICalculated) then Continue; Line := StrOfSelectable(Selectable, False, True, UseFieldsAliases); // if Supports(Selectable, ISelectableSqlFunction, SelectableSqlFunction) then // begin // if UseFieldsAliases then // Line := StrOfSelectableSqlFunctionWithAlias(SelectableSqlFunction) // else // Line := StrOfSelectableSqlFunction(SelectableSqlFunction); // end // else if Supports(Selectable, IDerivedTable, DerivedTable) then // begin // if UseFieldsAliases then // Line := StrOfDerivedTableWithAlias(Selectable, DerivedTable) // else // Line := StrOfDerivedTable(DerivedTable); // end // else if Supports(Selectable, IField, Field) then // begin // if UseFieldsAliases then // Line := StrOfFieldNameWithAlias(Field) // else // Line := StrOfFieldName(Field); //// AddToTableInheritanceList(Field); // end // else if Supports(Selectable, ISelectableByParam, SelectableByParam) then // begin // Line := StrOfSelectableByParam(SelectableByParam, UseFieldsAliases); //// AddToTableInheritanceList(Field); // end // else if Supports(Selectable, IDerivantField, DerivantField) then // begin // Line := StrOfDerivantField(DerivantField{, UseFieldsAliases}); //// AddToTableInheritanceList(Field); // end // else if Supports(Selectable, ISelectableByQuery, SelectableByQuery) then // begin // Line := StrOfSelectableByQuery(SelectableByQuery{, UseFieldsAliases}); //// AddToTableInheritanceList(Field); // end // else // Assert(False, Selectable.ImplObjectClassName); Result := Result + ' ' + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); end; // procedure ProcessFromForAddJoins(const List: TBaseTableIntfArray); // var // I: Integer; // Structure: IStructureWithFields; // Table: ITable; // begin // for I := 0 to High(List) do // begin // Structure := List[I]; // if Supports(Structure, ITable, Table) then // AddJoins(ExJoinArray, Table.GetFkJoins); // end; // end; function MakeFromStr(const List: TStructureWithFieldsIntfArray): UnicodeString; procedure ProcessDerivedTable(DerivedTable: IDerivedTable); var I: Integer; Query: IBaseSelectQuery; SelectableIntfArray: TSelectableIntfArray; Selectable: ISelectable; // Derivant: ISelectable; DerivedTableAlias: UnicodeString; begin Query := DerivedTable.Query; DerivedTableAlias := DerivedTable.Alias; SelectableIntfArray := Query.GetSelectables; for I := 0 to High(SelectableIntfArray) do begin Selectable := SelectableIntfArray[I]; if Assigned(Selectable.Derivant) then begin if DerivedTableAlias = '' then begin DerivedTableAlias := GenerateAlias('DT_'); DerivedTable.Alias := DerivedTableAlias; end; Selectable.Derivant.TableAlias := DerivedTableAlias; if Selectable.Derivant.FieldName = '' then Selectable.Derivant.FieldName := GenerateAlias('DTF_'); end; end; end; var I{, J, K}: Integer; // J: Integer; Structure: IStructureWithFields; // Table: ITable; Line: UnicodeString; EndStr: UnicodeString; // TableInheritance: TTableInheritance; begin Result := 'from '; EndStr := ', '; if not Assigned(List) then raise Exception.Create('NativeSql: table not defined in FROM clause'); Assert(Assigned(List)); for I := 0 to High(List) do begin Structure := List[I]; if Structure.StructureType = stDerivedTable then ProcessDerivedTable(Structure as IDerivedTable); Line := StrOfStructureNameWithAlias(Structure); Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); // for I := 0 to High(List) do // begin // Structure := List[I]; // if Supports(Structure, ITable, Table) then // begin // for J := 0 to High(TableInheritanceList) do // begin // TableInheritance := TableInheritanceList[J]; // if (not TableInheritance.Handled) and (TableInheritance.TableList[0] = Table) then // begin // for K := 1 to High(TableInheritance.TableList) do // begin // Table := TableInheritance.TableList[K]; // SetLength(ExJoinArray, Length(ExJoinArray) + 1); // ExJoinArray[High(ExJoinArray)] := TTypedJoin.Create(jtInner, Table, EQImpl(Table.InheritanceIdField, TableInheritance.TableList[K-1].InheritanceIdField)); //// Line := 'inner join ' + StrOfStructureNameWithAlias(Table) + ' on ' + //// Format('(%s.ID = %s.ID)', [StrOfTableNameAlias(Table), StrOfTableNameAlias(TableInheritance[K-1])]); //// Result := Result + Line + EndStr; // end; // TableInheritanceList[J].Handled := True; // end; // end; // AddJoins(ExJoinArray, Table.GetFkJoins); // end; // end; end; function MakeExJoins: UnicodeString; // var // I, J: Integer; // Line: UnicodeString; // EndStr: UnicodeString; // TableInheritance: TTableIntfArray; // Table: ITable; begin Result := ''; // EndStr := #13#10; // for I := 0 to High(TableInheritanceList) do // begin // TableInheritance := TableInheritanceList[I].TableList; // for J := 1 to High(TableInheritance) do // begin // Table := TableInheritance[J]; // // Line := 'inner join ' + StrOfStructureNameWithAlias(Table) + ' on ' + // Format('(%s.ID = %s.ID)', [StrOfTableNameAlias(Table), StrOfTableNameAlias(TableInheritance[J-1])]); // Result := Result + Line + EndStr; // end; // end; // SetLength(Result, Length(Result) - Length(EndStr)); end; function MakeJoinStr(List: TJoinIntfArray): UnicodeString; var EndStr: UnicodeString; ProcessedTables: TTableIntfArray; procedure ChangeTableAliasIfNeeded(Table: ITable); var I: Integer; ProcessedTable: ITable; begin for I := 0 to High(ProcessedTables) do begin if ProcessedTables[I] = Table then Exit; end; for I := 0 to High(ProcessedTables) do begin ProcessedTable := ProcessedTables[I]; if (ProcessedTable.TableName = Table.TableName) and (ProcessedTable.Alias = Table.Alias) then begin Table.Alias := GenerateAlias('JT_'); Break; end; end; SetLength(ProcessedTables, Length(ProcessedTables) + 1); ProcessedTables[High(ProcessedTables)] := Table; end; procedure ProcessJoin(Join: IJoin); var JoinType: IJoinType; JoinStr: UnicodeString; Line: UnicodeString; Table: ITable; I: Integer; FkJoins: TJoinIntfArray; begin Table := nil; if Join.Structure.StructureType = stTable then begin if not Supports(Join.Structure, ITable, Table) then Assert(False); ChangeTableAliasIfNeeded(Table); end; Assert(Supports(Join, IJoinType, JoinType)); case JoinType.Value of jtInner: JoinStr := 'inner'; jtLeft: JoinStr := 'left'; else JoinStr := ''; Assert(False, GetEnumName(TypeInfo(TJoinType), Integer(JoinType.Value))); end; Line := JoinStr + ' join ' + StrOfStructureNameWithAlias(Join.Structure) + ' on ' + StrOfCondition(Join.Condition); Result := Result + Line + EndStr; if Assigned(Table) then begin FkJoins := Table.GetFkJoins; for I := 0 to High(FkJoins) do begin ProcessJoin(FkJoins[I]); end; end; end; // function IsNeedOtherTableForJoin(Join: IJoin; out Table: ITable; out IdxInTableInheritanceList: Integer; // out IdxInTableInheritance: Integer): Boolean; // var // I, J, K: Integer; // E: ITable; // TableInheritance: TTableInheritance; // SelectableArray: TSelectableIntfArray; // Field: IField; // begin // Result := False; // E := Join.Table as ITable; // for I := 0 to High(TableInheritanceList) do // begin // TableInheritance := TableInheritanceList[I]; // if TableInheritance.TableList[0] = E then // begin // SelectableArray := Join.Condition.GetSelectableArray; // for J := 0 to High(SelectableArray) do // begin // if Supports(SelectableArray[J], IField, Field) then // begin // if IsFieldInheritedByTable(Field, E) then // begin // IdxInTableInheritanceList := I; // Table := Field.Table; // Result := True; // for K := 1 to High(TableInheritance.TableList) do // begin // if TableInheritance.TableList[K] = Table then // begin // IdxInTableInheritance := K; // Exit; // end; // end; // Assert(False); // end; // end; // end; // //// for J := 1 to High(TableInheritance.TableList) do //// begin //// Table := TableInheritance.TableList[J]; //// SetLength(ExJoinArray, Length(ExJoinArray) + 1); //// ExJoinArray[High(ExJoinArray)] := TTypedJoin.Create(jtInner, Table, EQ(Table.InheritanceIdField, TableInheritance.TableList[J-1].InheritanceIdField)); ////// Line := 'inner join ' + StrOfStructureNameWithAlias(Table) + ' on ' + ////// Format('(%s.ID = %s.ID)', [StrOfTableNameAlias(Table), StrOfTableNameAlias(TableInheritance[J-1])]); ////// Result := Result + Line + EndStr; //// end; //// TableInheritanceList[I].Handled := True; // end; // end; // end; var I{, J, K}: Integer; Join: IJoin; // NewJoin: IJoin; // Table: ITable; // NewTable: ITable; // TableInheritance: TTableInheritance; // IdxInTableInheritanceList: Integer; // IdxInTableInheritance: Integer; begin ProcessedTables := nil; Result := ''; EndStr := #13#10; // for I := 0 to High(ExJoinArray) do // ProcessJoin(ExJoinArray[I]); for I := 0 to High(List) do begin Join := List[I]; ProcessJoin(Join); // if Supports(Join.Table, ITable, Table) then // begin // if IsNeedOtherTableForJoin(Join, NewTable, IdxInTableInheritanceList, IdxInTableInheritance) then // begin // Assert(not TableInheritanceList[IdxInTableInheritanceList].Handled); // TableInheritance := TableInheritanceList[IdxInTableInheritanceList]; // // NewJoin := TTypedJoin.Create(jtInner, TableInheritance.TableList[IdxInTableInheritance], Join.Condition); // ProcessJoin(NewJoin); // for J := IdxInTableInheritance + 1 to High(TableInheritance.TableList) do // begin // Table := TableInheritance.TableList[J]; // NewJoin := TTypedJoin.Create(jtInner, Table, EQImpl(Table.InheritanceIdField, TableInheritance.TableList[J-1].InheritanceIdField)); // ProcessJoin(NewJoin); //// Line := 'inner join ' + StrOfStructureNameWithAlias(Table) + ' on ' + //// Format('(%s.ID = %s.ID)', [StrOfTableNameAlias(Table), StrOfTableNameAlias(TableInheritance[J-1])]); //// Result := Result + Line + EndStr; // end; // // Table := TableInheritance.TableList[0]; // NewJoin := TTypedJoin.Create(jtInner, Table, EQImpl(Table.InheritanceIdField, TableInheritance.TableList[IdxInTableInheritance].InheritanceIdField)); // ProcessJoin(NewJoin); // // for J := 1 to IdxInTableInheritance - 1 do // begin // Table := TableInheritance.TableList[J]; // NewJoin := TTypedJoin.Create(jtInner, Table, EQImpl(Table.InheritanceIdField, TableInheritance.TableList[J-1].InheritanceIdField)); // ProcessJoin(NewJoin); //// Line := 'inner join ' + StrOfStructureNameWithAlias(Table) + ' on ' + //// Format('(%s.ID = %s.ID)', [StrOfTableNameAlias(Table), StrOfTableNameAlias(TableInheritance[J-1])]); //// Result := Result + Line + EndStr; // end; // TableInheritanceList[IdxInTableInheritanceList].Handled := True; // end // else // ProcessJoin(Join); // for J := 0 to High(TableInheritanceList) do // begin // TableInheritance := TableInheritanceList[J]; // if not TableInheritance.Handled then // if TableInheritance.TableList[0] = Table then // begin // for K := 1 to High(TableInheritance.TableList) do // begin // Table := TableInheritance.TableList[K]; // NewJoin := TTypedJoin.Create(jtInner, Table, EQImpl(Table.InheritanceIdField, TableInheritance.TableList[K-1].InheritanceIdField)); // ProcessJoin(NewJoin); // // // Line := 'inner join ' + StrOfStructureNameWithAlias(Table) + ' on ' + // // Format('(%s.ID = %s.ID)', [StrOfTableNameAlias(Table), StrOfTableNameAlias(TableInheritance[K-1])]); // // Result := Result + Line + EndStr; // end; // TableInheritanceList[J].Handled := True; // end; // end; // end // else // ProcessJoin(Join); end; SetLength(Result, Length(Result) - Length(EndStr)); end; function IsSelectableInSelectPart(Selectable: ISelectable): Boolean; var Selectables: TSelectableIntfArray; Current: ISelectable; I: Integer; begin Selectable := Selectable as ISelectable; // must be Selectables := Query.GetSelectables; Result := True; for I := 0 to High(Selectables) do begin Current := Selectables[I]; if Current as ISelectable = Selectable then Exit; end; Result := False; end; function MakeOrderByStr(OrderByElement: IOrderByElement): UnicodeString; function NumberInSelectStatement(Selectable: ISelectable): Integer; var Selectables: TSelectableIntfArray; Current: ISelectable; I: Integer; begin Selectable := Selectable as ISelectable; // must be Selectables := Query.GetSelectables; for I := 0 to High(Selectables) do begin Current := Selectables[I]; if Current as ISelectable = Selectable then begin Result := I + 1; Exit; end; end; Result := 0; end; var I: Integer; Line: UnicodeString; EndStr: UnicodeString; OrderByElements: TOrderByElementRecArray; OrderSelectable: TOrderByElementRec; // Field: IField; begin Result := ''; if not Assigned(OrderByElement) then Exit; EndStr := ', '; OrderByElements := OrderByElement.Elements; Assert(Assigned(OrderByElements)); Result := 'order by '; for I := 0 to High(OrderByElements) do begin OrderSelectable := OrderByElements[I]; // if Supports(OrderSelectable, IField, Field) then // AddToTableInheritanceList(Field); if Supports(OrderSelectable.Element, IDerivedTable) then Line := IntToStr(NumberInSelectStatement(OrderSelectable.Element)) else begin if OrderSelectable.Element.Alias = '' then Line := StrOfSelectable(OrderSelectable.Element, False, False, False) else begin if IsSelectableInSelectPart(OrderSelectable.Element) then Line := Quote(OrderSelectable.Element.Alias) else Line := StrOfSelectable(OrderSelectable.Element, False, False, False); end end; if OrderSelectable.OrderType = otDesc then Line := Line + ' desc'; Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); // if OrderByElement.OrderType = otDesc then // Result := Result + ' desc'; end; function MakeGroupByStr(const Selectables: TSelectableIntfArray): UnicodeString; // function NumberInSelectStatement(Selectable: ISelectable): Integer; // var // Selectables: TSelectableIntfArray; // Current: ISelectable; // I: Integer; // begin // Selectables := Query.GetSelectables; // for I := 0 to High(Selectables) do // begin // Current := Selectables[I]; // if Current as ISelectable = Selectable as ISelectable then // begin // Result := I + 1; // Exit; // end; // end; // Result := 0; // end; var I: Integer; Line: UnicodeString; EndStr: UnicodeString; // Selectables: TSelectableIntfArray; Selectable: ISelectable; // Field: IField; begin Result := ''; if not Assigned(Selectables) then Exit; EndStr := ', '; Result := 'group by '; for I := 0 to High(Selectables) do begin Selectable := Selectables[I]; // if Supports(Selectable, IField, Field) then // AddToTableInheritanceList(Field); if Selectable.Alias = '' then Line := StrOfSelectable(Selectable, False, False, False) else begin if IsSelectableInSelectPart(Selectable) then Line := Quote(Selectable.Alias) else Line := StrOfSelectable(Selectable, False, False, False); end; // Line := Quote(OrderSelectable.Element.Alias); Result := Result + Line + EndStr; end; SetLength(Result, Length(Result) - Length(EndStr)); end; function MakeRowsStr(RowsElement: IRowsElement): UnicodeString; var FromSelectable: ISelectable; ToSelectable: ISelectable; begin if Assigned(RowsElement) then begin FromSelectable := RowsElement.GetFromSelectable; ToSelectable := RowsElement.GetToSelectable; if Assigned(FromSelectable) or Assigned(ToSelectable) then begin Result := 'rows'; if Assigned(FromSelectable) then Result := Result + ' (' + StrOfSelectable(FromSelectable, True, False, False) + ')'; if Assigned(ToSelectable) then Result := Result + ' to (' + StrOfSelectable(ToSelectable, True, False, False) + ')'; end; end else Result := ''; end; function MakeHavingStr(Condition: ISqlCondition): UnicodeString; begin Result := StrOfCondition(Condition); if Result <> '' then Result := 'having ' + Result; end; var Select: UnicodeString; From: UnicodeString; Joins: UnicodeString; Where: UnicodeString; GroupBy: UnicodeString; Having: UnicodeString; OrderBy: UnicodeString; RowsStr: UnicodeString; Selectables: TSelectableIntfArray; // ExJoins: UnicodeString; // S: UnicodeString; // I: Integer; SelectablesInQuery: TSelectableIntfArray; // Field: IField; begin // TableInheritanceList := nil; // ExJoinArray := nil; SelectablesInQuery := Query.GetSelectableArray; // for I := 0 to High(SelectablesInQuery) do // if Supports(SelectablesInQuery[I], IField, Field) then // AddToTableInheritanceList(Field); Selectables := Query.GetSelectables; From := MakeFromStr(Query.GetFromStructures); // must be before joins (and before select if it is select P1, P2 from derived table as (P1, P2)) Joins := MakeJoinStr(Query.GetJoins); Select := MakeSelectStr(Query.GetSelectables); Where := MakeWhereStr(Query.GetWhere); GroupBy := MakeGroupByStr(Query.GetGroupBy); Having := MakeHavingStr(Query.GetHaving); OrderBy := MakeOrderByStr(Query.GetOrderBy); RowsStr := MakeRowsStr(Query.GetRowsElement); // ExJoins := MakeExJoins; // S := Joins; // Joins := ExJoins; // ExJoins := S; // // if Joins <> '' then // begin // if ExJoins <> '' then // Joins := Joins + #13#10 + ExJoins; // end // else // Joins := ExJoins; Result := Select + #13#10 + From; if Joins <> '' then Result := Result + #13#10 + Joins; if Where <> '' then Result := Result + #13#10 + Where; if GroupBy <> '' then Result := Result + #13#10 + GroupBy; if Having <> '' then Result := Result + #13#10 + Having; if OrderBy <> '' then Result := Result + #13#10 + OrderBy; if RowsStr <> '' then Result := Result + #13#10 + RowsStr; // for I := 0 to High(TableInheritanceList) do // Assert(TableInheritanceList[I].Handled); end; function TSqlRenderer.MakeWhereStr(Condition: ISqlCondition): UnicodeString; begin Result := StrOfCondition(Condition); if Result <> '' then Result := 'where ' + Result; end; function TSqlRenderer.StrOfDeleteQuery(Query: IBaseDeleteQuery): UnicodeString; function MakeDeleteStr(Table: ITable): UnicodeString; begin Assert(Assigned(Table)); Result := 'delete from ' + StrOfStructureNameWithAlias(Table); end; var Delete: UnicodeString; Where: UnicodeString; begin Delete := MakeDeleteStr(Query.GetFromTable); Where := MakeWhereStr(Query.GetWhere); Result := Delete; if Where <> '' then Result := Result + ' ' + Where; end; function TSqlRenderer.StrOfSelectableSqlFunctionWithAlias( SelectableSqlFunction: ISelectableSqlFunction): UnicodeString; var Selectable: ISelectable; begin Assert(Supports(SelectableSqlFunction, ISelectable, Selectable), SelectableSqlFunction.ImplObjectClassName); Result := StrOfSelectableSqlFunction(SelectableSqlFunction) + FAsString + Quote(Selectable.Alias); end; function TSqlRenderer.StrOfInStatementValues( InStatementValues: IInStatementValues): UnicodeString; var I: Integer; SqlParam: ISqlParam; Element: IStatementElement; EndStr: UnicodeString; begin Result := '('; EndStr := ','; for I := 0 to InStatementValues.Count - 1 do begin Element := InStatementValues[I]; Assert(Supports(Element, ISqlParam, SqlParam), Element.ImplObjectClassName); Result := Result + StrOfParameter(SqlParam) + EndStr; end; if InStatementValues.Count > 0 then SetLength(Result, Length(Result) - Length(EndStr)); Result := Result + ')'; end; constructor TSqlRenderer.Create(ASqlEngine: TNativeSqlEngine); begin inherited Create;; FSqlEngine := ASqlEngine; FAsString := ' as '; end; function TSqlRenderer.StrOfSelectableSqlFunction( SelectableSqlFunction: ISelectableSqlFunction): UnicodeString; var // UnarySqlFunction: IUnarySqlFunction; SqlFunction: ISqlFunction; // IntSelectable: IIntegerSelectable; BinarySqlOperator: IBinarySqlOperator; begin // if Supports(SelectableSqlFunction, IUnarySqlFunction, UnarySqlFunction) then // begin // Result := StrOfUnarySqlFunction(UnarySqlFunction) // end if Supports(SelectableSqlFunction, IBinarySqlOperator, BinarySqlOperator) then begin Result := StrOfBinarySqlOperator(BinarySqlOperator) end else if Supports(SelectableSqlFunction, ISqlFunction, SqlFunction) then begin Result := StrOfSqlFunction(SqlFunction) end // else if Supports(SelectableSqlFunction, ICountSqlFunction) then // begin //// Assert(Supports(SelectableSqlFunction, IIntegerSelectable, IntSelectable), SelectableSqlFunction.ImplObjectClassName); //// Assert(IntSelectable.Alias <> ''); // Result := 'count(*)'; // end else Assert(False, SelectableSqlFunction.ImplObjectClassName); end; //function TSqlRenderer.StrOfUnarySqlFunction( // UnarySqlFunction: IUnarySqlFunction): UnicodeString; //var // FuncStr: UnicodeString; //// Selectable: ISelectable; //begin // Assert(UnarySqlFunction.FunctionType <> uftInvalid, UnarySqlFunction.ImplObjectClassName); // case UnarySqlFunction.FunctionType of // uftUpper: FuncStr := 'UPPER(%s)'; // uftMin: FuncStr := 'MIN(%s)'; // uftMax: FuncStr := 'MAX(%s)'; // uftSum: FuncStr := 'SUM(%s)'; // uftMinus: FuncStr := '-%s'; // else // Assert(False, GetEnumName(TypeInfo(TSqlUnaryFunctionType), Integer(UnarySqlFunction.FunctionType))); // FuncStr := ''; // end; // Result := Format(FuncStr, [StrOfConditionStatementElement(UnarySqlFunction.Param)]); //// if not InCondition then //// begin //// Assert(Supports(UnarySqlFunction, ISelectable, Selectable), UnarySqlFunction.ImplObjectClassName); //// if Selectable.Alias = '' then //// Selectable.Alias := GenerateAlias('F_'); ////// Result := Result + FAsString + Selectable.Alias; //// end; //end; function TSqlRenderer.StrOfSqlFunction( SqlFunction: ISqlFunction): UnicodeString; var // FuncStr: UnicodeString; // Selectable: ISelectable; I: Integer; Params: TStatementElementIntfArray; Param: IStatementElement; begin // Assert(SqlFunction.FunctionType <> uftInvalid, SqlFunction.ImplObjectClassName); if SqlFunction.Name = '' then Assert(False, 'function name is empty'); Params := SqlFunction.GetFunctionParams; if not Assigned(Params) then Result := SqlFunction.Name else begin Result := SqlFunction.Name + '('; for I := 0 to High(Params) do begin Param := Params[I]; Result := Result + StrOfConditionStatementElement(Param) + ', '; end; SetLength(Result, Length(Result) - 2); Result := Result + ')'; end; // case SqlFunction.FunctionType of // uftUpper: FuncStr := 'UPPER(%s)'; // uftMin: FuncStr := 'MIN(%s)'; // uftMax: FuncStr := 'MAX(%s)'; // uftSum: FuncStr := 'SUM(%s)'; // uftMinus: FuncStr := '-%s'; // else // Assert(False, GetEnumName(TypeInfo(TSqlUnaryFunctionType), Integer(SqlFunction.FunctionType))); // FuncStr := ''; // end; // Result := Format(FuncStr, [StrOfConditionStatementElement(SqlFunction.Param)]); //// if not InCondition then //// begin //// Assert(Supports(UnarySqlFunction, ISelectable, Selectable), UnarySqlFunction.ImplObjectClassName); //// if Selectable.Alias = '' then //// Selectable.Alias := GenerateAlias('F_'); ////// Result := Result + FAsString + Selectable.Alias; //// end; end; function TSqlRenderer.Quote(const S: UnicodeString): UnicodeString; begin Result := '"' + S + '"'; end; end.
unit UTextForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls; type { Выполняемая в файле операция } TOperation = (opCONVERT, opCALC_INFIX{, opCALC_POSTFIX}); { Запись о выражении в файле } TExpression = record operation: TOperation; expression: String; operands: String; result: Extended; converted: String; error: Integer; replaced: Boolean; line: Integer; position: Integer; end; { Массив строк } TText = array of String; { Массив выражений } TExpressions = array of TExpression; TfrmText = class(TForm) panelText: TPanel; reditText: TRichEdit; panelExpressions: TPanel; splitter: TSplitter; lvExpressions: TListView; panelButtons: TPanel; btnHelp: TButton; btnReplaceAll: TButton; labelExpressions: TLabel; btnSave: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lvExpressionsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure lvExpressionsEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure btnReplaceAllClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); private { Массив найденных выражений } FExpressions: TExpressions; { Текст из файла } FText: TText; { Выделенное выражение } FSelected: Integer; { Устанавливает столбцы в таблице вывода выражений } procedure setListViewColumns; { Считывает файл } procedure readFile(path: String); { Выводит текст } procedure textToRichEdit(text: TText); { Выводит выражения } procedure expressionsToListView(expressions: TExpressions); { Считает номер символа в тексте, по номеру строки } function countChars(text: TText; lines: Integer):Integer; { Ищет выражение в строке } procedure parseLine(numLine: Integer; line: String; var expressions: TExpressions); { Ищет выражения в тексте } function parseFile(text: TText):TExpressions; { Выполняет выражения } procedure processExpressions(var expressions: TExpressions); { Подсвечивает выражения } procedure highlightExpressions(expressions: TExpressions); { Подсвечивает выделенное выражение } procedure highlightSelected(expressions: TExpressions; num: Integer); { Заменяет выражение в тексте на результат } procedure replaceResult(var text: TText; var expressions: TExpressions; num: Integer; outputErrors: Boolean); public { Public declarations } end; var frmText: TfrmText; implementation uses UMain, UExpression, UTypes; resourceString sCAPTION = 'Файл - '; sEXPRESSION = 'Выражение'; sOPERATION = 'Операция'; sOPERANDS = 'Операнды'; sRESULT = 'Результат'; sERRORS = 'Ошибки'; sREPLACED = 'Заменено'; {$R *.dfm} { Устанавливает столбцы в таблице вывода выражений } procedure TfrmText.setListViewColumns; var listColumn: TListColumn; begin listColumn := lvExpressions.Columns.Add; listColumn.Caption := sEXPRESSION; listColumn.Width := 150; listColumn := lvExpressions.Columns.Add; listColumn.Caption := sOPERATION; listColumn.Width := 75; listColumn := lvExpressions.Columns.Add; listColumn.Caption := sOPERANDS; listColumn.Width := 100; listColumn := lvExpressions.Columns.Add; listColumn.Caption := sRESULT; listColumn.Width := 125; listColumn := lvExpressions.Columns.Add; listColumn.Caption := sERRORS; listColumn.Width := 75; listColumn := lvExpressions.Columns.Add; listColumn.Caption := sREPLACED; listColumn.Width := 75; end; { Считывает файл } procedure TfrmText.readFile(path: String); var f: TextFile; begin AssignFile(f, path); Reset(f); SetLength(FText, 0); while not eof(f) do begin SetLength(FText, length(FText) + 1); readln(f, FText[length(FText) - 1]); end; CloseFile(f); end; { Ищет выражение в строке } procedure TfrmText.parseLine(numLine: Integer; line: String; var expressions: TExpressions); var i, j: Integer; tempStr: String; tempExpression: TExpression; const OPERATIONS_SHORT: array [TOperation] of String = ('@TP@', '@CI@'{, '@CP@'}); begin i := 1; while i <= length(line) do begin tempStr := copy(line, i, 4); j := i + 4; if (tempStr = OPERATIONS_SHORT[opCONVERT]) or (tempStr = OPERATIONS_SHORT[opCALC_INFIX]) {or (tempStr = OPERATIONS_SHORT[opCALC_POSTFIX])} then begin tempExpression.operands := ''; tempExpression.replaced := false; tempExpression.line := numLine; tempExpression.position := i; while (j <= length(line)) and (line[j] <> '@') do inc(j); if j <= length(line) then tempExpression.expression := copy(line, i + 4, j - i - 4) else tempExpression.expression := ''; inc(j); end; if (tempStr = OPERATIONS_SHORT[opCONVERT]) then begin tempExpression.operation := opCONVERT; tempExpression.operands := ''; i := j; end; if (tempStr = OPERATIONS_SHORT[opCALC_INFIX]) then begin tempExpression.operation := opCALC_INFIX; i := j; while (j <= length(line)) and (line[j] <> '@') do inc(j); if j <= length(line) then tempExpression.operands := copy(line, i, j - i) else tempExpression.expression := ''; i := j; end; {if (tempStr = OPERATIONS_SHORT[opCALC_POSTFIX]) then begin tempExpression.operation := opCALC_POSTFIX; i := j; while (j <= length(line)) and (line[j] <> '@') do inc(j); if j <= length(line) then tempExpression.operands := copy(line, i, j - i) else tempExpression.expression := ''; i := j; end; } if tempExpression.expression <> '' then begin SetLength(expressions, length(expressions) + 1); expressions[length(expressions) - 1] := tempExpression; tempExpression.expression := ''; end; inc(i); end; end; { Ищет выражения в тексте } function TfrmText.parseFile(text: TText):TExpressions; var i: Integer; begin SetLength(result, 0); for i := 0 to length(text) - 1 do parseLine(i, text[i], result); end; { Выполняет выражения } procedure TfrmText.processExpressions(var expressions: TExpressions); var i: Integer; begin for i := 0 to length(expressions) - 1 do begin with expressions[i] do begin case operation of opCONVERT: begin error := check(expression); if error = 0 then converted := infixToPostfix(expression); end; opCALC_INFIX: begin error := check(expression, operands); if error = 0 then result := calculateInfix(expression, operands, error); end; end; end; end; end; { Выводит текст } procedure TfrmText.textToRichEdit(text: TText); var i: Integer; begin reditText.Lines.Clear; for i := 0 to length(text) - 1 do reditText.Lines.Add(text[i]); end; { Выводит выражения } procedure TfrmText.expressionsToListView(expressions: TExpressions); var i: Integer; listItem: TListItem; begin lvExpressions.Items.Clear; for i := 0 to length(expressions) - 1 do begin with expressions[i] do begin case operation of opCONVERT: begin listItem := lvExpressions.Items.Add; listItem.Caption := expression; listItem.SubItems.Add('Перевод'); listItem.SubItems.Add(''); if error <> 0 then begin listItem.SubItems.Add('-'); listItem.SubItems.Add('Ошибки в выражении'); end else begin listItem.SubItems.Add(converted); listItem.SubItems.Add('-'); end; listItem.SubItems.Add(BoolToStr(replaced, true)); end; opCALC_INFIX: begin listItem := lvExpressions.Items.Add; listItem.Caption := expression; listItem.SubItems.Add('Вычисление'); listItem.SubItems.Add(operands); if error <> 0 then begin listItem.SubItems.Add('-'); listItem.SubItems.Add('Ошибки в выражении'); end else begin listItem.SubItems.Add(FloatToStrF(result, ffFixed, 4, 5)); listItem.SubItems.Add('-'); end; listItem.SubItems.Add(BoolToStr(replaced, true)); end; end; end; end; end; { Считает номер символа в тексте, по номеру строки } function TfrmText.countChars(text: TText; lines: Integer): Integer; var i: Integer; begin result := 0; for i := 0 to lines - 1 do result := result + length(text[i]) + 2; end; { Подсвечивает выражения } procedure TfrmText.highlightExpressions(expressions: TExpressions); var i: Integer; begin for i := 0 to length(expressions) - 1 do begin with expressions[i] do begin reditText.SelStart := countChars(FText, line) + position - 1; if not replaced then begin if operation <> opCONVERT then reditText.SelLength := 6 + length(expression) + length(operands) else reditText.SelLength := 5 + length(expression); end else begin if operation <> opCONVERT then reditText.SelLength := length(FloatToStrF(result, ffFixed, 4, 5)) else reditText.SelLength := length(converted); end; reditText.SelAttributes.Color := clGreen; end; end; reditText.SelStart := 0; reditText.SelLength := 0; end; { При создании, устанавливает заголовок, считывает файл, ищет выражения в тексте, выводит выражения в таблицу, подсвечивает выражения в тексте } procedure TfrmText.FormCreate(Sender: TObject); begin Self.Caption := sCAPTION + ExtractFileName(frmMain.openedFile); readFile(frmMain.openedFile); textToRichEdit(FText); FExpressions := parseFile(FText); processExpressions(FExpressions); setListViewColumns; expressionsToListView(FExpressions); highlightExpressions(FExpressions); FSelected := -1; end; { При закрытии возвращает главную форму } procedure TfrmText.FormClose(Sender: TObject; var Action: TCloseAction); begin frmMain.Show; end; { Подсвечивает выделенное выражение } procedure TfrmText.highlightSelected(expressions: TExpressions; num: Integer); begin if FSelected <> -1 then begin with expressions[FSelected] do begin reditText.SelStart := countChars(FText, line) + position - 1; if not replaced then begin if operation <> opCONVERT then reditText.SelLength := 6 + length(expression) + length(operands) else reditText.SelLength := 5 + length(expression); end else begin if operation <> opCONVERT then reditText.SelLength := length(FloatToStrF(result, ffFixed, 4, 5)) else reditText.SelLength := length(converted); end; reditText.SelAttributes.Color := clGreen; end; end; with expressions[num] do begin FSelected := num; reditText.SelStart := countChars(FText, line) + position - 1; if not replaced then begin if operation <> opCONVERT then reditText.SelLength := 6 + length(expression) + length(operands) else reditText.SelLength := 5 + length(expression); end else begin if operation <> opCONVERT then reditText.SelLength := length(FloatToStrF(result, ffFixed, 4, 5)) else reditText.SelLength := length(converted); end; reditText.SelAttributes.Color := clRed; end; end; procedure TfrmText.lvExpressionsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then highlightSelected(FExpressions, Item.Index); end; { Заменяет выражение в тексте на результат } procedure TfrmText.replaceResult(var text: TText; var expressions: TExpressions; num: Integer; outputErrors: Boolean); var deltaLen, i: Integer; begin with expressions[num] do begin if (not replaced) and (error = 0) then begin replaced := true; if operation <> opCONVERT then begin deltaLen := length(FloatToStrF(result, ffFixed, 4, 5)) - (6 + length(expression) + length(operands)); delete(text[line], position, 6 + length(expression) + length(operands)); insert(FloatToStrF(result, ffFixed, 4, 5), text[line], position); i := num + 1; while expressions[i].line = line do begin expressions[i].position := expressions[i].position + deltaLen; inc(i); end; end else begin deltaLen := length(converted) - (5 + length(expression)); delete(text[line], position, 5 + length(expression)); insert(converted, text[line], position); i := num + 1; while expressions[i].line = line do begin expressions[i].position := expressions[i].position + deltaLen; inc(i); end; end; end else if (error <> 0) and outputErrors then ShowMessage('Выражение содержит ошибки:' + #13 + #10 + arrayToString(errorToArray(error))); end; end; { Заменяет все выражения на результат } procedure TfrmText.btnReplaceAllClick(Sender: TObject); var i: Integer; begin for i := 0 to length(FExpressions) - 1 do begin replaceResult(FText, FExpressions, i, false); end; textToRichEdit(FText); highlightExpressions(FExpressions); expressionsToListView(FExpressions); end; { При попытке изменить элемент в таблице, заменяет выражение на результат в тексте } procedure TfrmText.lvExpressionsEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); begin replaceResult(FText, FExpressions, Item.Index, true); textToRichEdit(FText); highlightExpressions(FExpressions); highlightSelected(FExpressions, Item.Index); expressionsToListView(FExpressions); AllowEdit := false; end; { Сохраняет текст в файл } procedure TfrmText.btnSaveClick(Sender: TObject); var f: TextFile; i: Integer; begin AssignFile(f, frmMain.openedFile); Rewrite(f); for i := 0 to length(FText) - 1 do begin writeln(f, FText[i]); end; CloseFile(f); end; procedure TfrmText.btnHelpClick(Sender: TObject); begin ShowMessage('Выражения для вычисления в файле должно иметь вид:' + #13 + #10 + '@Тип_Операции@Выражение@Операнды@, где Тип_Операции - CI или TP,' + #13 + #10 + 'Выражение, Операнды необходимые в выражении.'); end; end.
unit uFrmAskSalesPerson; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uPai, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DBCtrls; type TFrmAskSalesPerson = class(TFrmPai) btnOK: TButton; lbPrice: TLabel; cmbUser: TDBLookupComboBox; chcApplyAll: TCheckBox; lbUserCode: TLabel; edUserCode: TEdit; procedure cmbUserDropDown(Sender: TObject); procedure cmbUserCloseUp(Sender: TObject); procedure edUserCodeEnter(Sender: TObject); procedure edUserCodeExit(Sender: TObject); procedure edUserCodeKeyPress(Sender: TObject; var Key: Char); private FEnableRepeat : Boolean; function getUserByCode(Code:String):Boolean; public function Start(var IDUser, IDCommis, IDCommisType : Integer; var ApplyAll : Boolean; EnableRepeat, KeepSalesPerson : Boolean; var sUserName : String):Boolean; end; implementation uses UDM, uMsgBox, uMsgConstant; {$R *.dfm} { TFrmAskSalesPerson } function TFrmAskSalesPerson.Start(var IDUser, IDCommis, IDCommisType:Integer; var ApplyAll : Boolean; EnableRepeat, KeepSalesPerson : Boolean; var sUserName : String): Boolean; begin cmbUser.KeyValue := IDUser; IDUser := -1; chcApplyAll.Visible := EnableRepeat; if EnableRepeat then chcApplyAll.Checked := KeepSalesPerson; try DM.FiltraCDS(DM.cdsSystemUser, DM.GetStoreUsersFilter(DM.cdsSystemUser)); ShowModal; Result := (ModalResult = mrOK); Result := Result and DM.cdsSystemUser.Locate('IDUser', cmbUser.KeyValue, []); if Result then begin IDUser := DM.cdsSystemUserIDUser.AsInteger; IDCommis := DM.cdsSystemUserComissionID.AsInteger; IDCommisType := DM.cdsSystemUserIDTipoPessoa.AsInteger; sUserName := DM.cdsSystemUserSystemUser.AsString; ApplyAll := chcApplyAll.Checked; end; finally; DM.FiltraCDS(DM.cdsSystemUser, ''); end; end; procedure TFrmAskSalesPerson.cmbUserDropDown(Sender: TObject); begin inherited; btnOK.Default := False; end; procedure TFrmAskSalesPerson.cmbUserCloseUp(Sender: TObject); begin inherited; btnOK.Default := True; end; function TFrmAskSalesPerson.getUserByCode(Code: String): Boolean; begin if DM.cdsSystemUser.Locate('CodSystemUser', edUserCode.Text, []) then begin cmbUser.KeyValue := DM.cdsSystemUser.FieldByName('IDUser').AsInteger; btnOK.SetFocus; Result := True; end else begin MsgBox(MSG_INF_USE_NOT_FOUND, vbCritical + vbOkOnly); Result := False; end; edUserCode.Clear; end; procedure TFrmAskSalesPerson.edUserCodeEnter(Sender: TObject); begin inherited; btnOK.Default := False; end; procedure TFrmAskSalesPerson.edUserCodeExit(Sender: TObject); begin inherited; btnOK.Default := True; if edUserCode.Text <> '' then getUserByCode(edUserCode.Text); end; procedure TFrmAskSalesPerson.edUserCodeKeyPress(Sender: TObject; var Key: Char); begin inherited; if key = #13 then begin if (edUserCode.Text) = '' then ModalResult := mrOK else if getUserByCode(edUserCode.Text) then ModalResult := mrOK; end; end; end.
unit MeshRenumberingTypes; interface uses Generics.Collections, Generics.Defaults, FastGEO; type { @name indicates the type of node. @value(ntInner The node is in the interior of the mesh and may be moved or eliminated to improve the mesh.) @value(ntEdge The node is on the external boundary of the mesh. It may not be moved or eliminated.) @value(ntSubDomain The node is on an internal boundary of the mesh. It may not be moved or eliminated.) } TNodeType = (ntInner, ntEdge, ntSubDomain); TRenumberingAlgorithm = (raNone, CuthillMcKee, raSloanRandolph); IElement = interface; INode = interface(IInterface) function GetActiveElementCount: integer; function GetActiveElement(Index: integer): IElement; function GetNodeNumber: integer; procedure SetNodeNumber(Value: integer); function GetLocation: TPoint2D; procedure SetLocation(const Value: TPoint2D); function GetNodeType: TNodeType; property ActiveElementCount: integer read GetActiveElementCount; property ActiveElements[Index: integer]: IElement read GetActiveElement; property NodeNumber: integer read GetNodeNumber write SetNodeNumber; property Location: TPoint2D read GetLocation write SetLocation; property NodeType: TNodeType read GetNodeType; end; TINodeList = TList<INode>; TINodeComparer = TComparer<INode>; IElement = interface(IInterface) function GetActiveNode(Index: integer): INode; function GetActiveNodeCount: integer; function GetElementNumber: integer; procedure SetElementNumber(Value: integer); property NodeCount: integer read GetActiveNodeCount; property Nodes[Index: integer]: INode read GetActiveNode; property ElementNumber: integer read GetElementNumber write SetElementNumber; end; TIElementList = TList<IElement>; TIElementComparer = TComparer<IElement>; IMesh = interface(IInterface) function GetActiveNode(Index: integer): INode; function GetActiveNodeCount: integer; function GetActiveElementCount: integer; function GetActiveElement(Index: integer): IElement; property NodeCount: integer read GetActiveNodeCount; property Nodes[Index: integer]: INode read GetActiveNode; property ElementCount: integer read GetActiveElementCount; property Elements[Index: integer]: IElement read GetActiveElement; end; implementation end.
unit WGL; { Converted from wingdi.h (Microsoft PlatformSDK)} interface uses Windows; // OpenGL wgl prototypes type PROC = pointer; _POINTFLOAT = packed record x, y: single; end; POINTFLOAT = _POINTFLOAT; TPointFloat = _POINTFLOAT; PPointFloat = ^_POINTFLOAT; _GLYPHMETRICSFLOAT = packed record gmfBlackBoxX, gmfBlackBoxY: single; gmfptGlyphOrigin: TPointFloat; gmfCellIncX, gmfCellIncY: single; end; GLYPHMETRICSFLOAT = _GLYPHMETRICSFLOAT; TGlyphMetricsFloat = _GLYPHMETRICSFLOAT; PGlyphMetricsFloat = ^_GLYPHMETRICSFLOAT; function wglCopyContext (p1: HGLRC; p2: HGLRC; p3: UINT): BOOL; stdcall; function wglCreateContext (p1: HDC): HGLRC; stdcall; function wglCreateLayerContext (p1: HDC; p2: integer): HGLRC; stdcall; function wglDeleteContext (p1: HGLRC): BOOL; stdcall; function wglGetCurrentContext (): HGLRC; stdcall; function wglGetCurrentDC (): HDC; stdcall; function wglGetProcAddress (p1: LPCSTR): PROC; stdcall; function wglMakeCurrent (p1: HDC; p2: HGLRC): BOOL; stdcall; function wglShareLists (p1: HGLRC; p2: HGLRC): BOOL; stdcall; function wglUseFontBitmaps (p1: HDC; p2, p3, p4: DWORD): BOOL; stdcall; function wglUseFontBitmapsA (p1: HDC; p2, p3, p4: DWORD): BOOL; stdcall; function wglUseFontBitmapsW (p1: HDC; p2, p3, p4: DWORD): BOOL; stdcall; const WGL_FONT_LINES = 0; WGL_FONT_POLYGONS = 1; function wglUseFontOutlines(p1: HDC; p2, p3, p4: DWORD; p5, p6: single; p7: integer; p8: PGLYPHMETRICSFLOAT): BOOL; stdcall; function wglUseFontOutlinesA(p1: HDC; p2, p3, p4: DWORD; p5, p6: single; p7: integer; p8: PGLYPHMETRICSFLOAT): BOOL; stdcall; function wglUseFontOutlinesW(p1: HDC; p2, p3, p4: DWORD; p5, p6: single; p7: integer; p8: PGLYPHMETRICSFLOAT): BOOL; stdcall; type tagLAYERPLANEDESCRIPTOR = packed record nSize: WORD; nVersion: WORD; dwFlags: DWORD; iPixelType: BYTE; cColorBits: BYTE; cRedBits: BYTE; cRedShift: BYTE; cGreenBits: BYTE; cGreenShift: BYTE; cBlueBits: BYTE; cBlueShift: BYTE; cAlphaBits: BYTE; cAlphaShift: BYTE; cAccumBits: BYTE; cAccumRedBits: BYTE; cAccumGreenBits: BYTE; cAccumBlueBits: BYTE; cAccumAlphaBits: BYTE; cDepthBits: BYTE; cStencilBits: BYTE; cAuxBuffers: BYTE; iLayerPlane: BYTE; bReserved: BYTE; crTransparent: COLORREF; end; LAYERPLANEDESCRIPTOR = tagLAYERPLANEDESCRIPTOR; TLayerPlaneDescriptor = tagLAYERPLANEDESCRIPTOR; PLayerPlaneDescriptor = ^tagLAYERPLANEDESCRIPTOR; const // LAYERPLANEDESCRIPTOR flags LPD_DOUBLEBUFFER = $00000001; LPD_STEREO = $00000002; LPD_SUPPORT_GDI = $00000010; LPD_SUPPORT_OPENGL = $00000020; LPD_SHARE_DEPTH = $00000040; LPD_SHARE_STENCIL = $00000080; LPD_SHARE_ACCUM = $00000100; LPD_SWAP_EXCHANGE = $00000200; LPD_SWAP_COPY = $00000400; LPD_TRANSPARENT = $00001000; LPD_TYPE_RGBA = 0; LPD_TYPE_COLORINDEX = 1; // wglSwapLayerBuffers flags WGL_SWAP_MAIN_PLANE = $00000001; WGL_SWAP_OVERLAY1 = $00000002; WGL_SWAP_OVERLAY2 = $00000004; WGL_SWAP_OVERLAY3 = $00000008; WGL_SWAP_OVERLAY4 = $00000010; WGL_SWAP_OVERLAY5 = $00000020; WGL_SWAP_OVERLAY6 = $00000040; WGL_SWAP_OVERLAY7 = $00000080; WGL_SWAP_OVERLAY8 = $00000100; WGL_SWAP_OVERLAY9 = $00000200; WGL_SWAP_OVERLAY10 = $00000400; WGL_SWAP_OVERLAY11 = $00000800; WGL_SWAP_OVERLAY12 = $00001000; WGL_SWAP_OVERLAY13 = $00002000; WGL_SWAP_OVERLAY14 = $00004000; WGL_SWAP_OVERLAY15 = $00008000; WGL_SWAP_UNDERLAY1 = $00010000; WGL_SWAP_UNDERLAY2 = $00020000; WGL_SWAP_UNDERLAY3 = $00040000; WGL_SWAP_UNDERLAY4 = $00080000; WGL_SWAP_UNDERLAY5 = $00100000; WGL_SWAP_UNDERLAY6 = $00200000; WGL_SWAP_UNDERLAY7 = $00400000; WGL_SWAP_UNDERLAY8 = $00800000; WGL_SWAP_UNDERLAY9 = $01000000; WGL_SWAP_UNDERLAY10 = $02000000; WGL_SWAP_UNDERLAY11 = $04000000; WGL_SWAP_UNDERLAY12 = $08000000; WGL_SWAP_UNDERLAY13 = $10000000; WGL_SWAP_UNDERLAY14 = $20000000; WGL_SWAP_UNDERLAY15 = $40000000; function wglDescribeLayerPlane (p1: HDC; p2, p3: integer; p4: UINT; var p5: TLayerPlaneDescriptor): BOOL; stdcall; function wglSetLayerPaletteEntries (p1: HDC; p2, p3, p4: integer; var COLORREF): integer; stdcall; function wglGetLayerPaletteEntries (p1: HDC; p2, p3, p4: integer; var COLORREF): integer; stdcall; function wglRealizeLayerPalette(p1: HDC; p2: integer; p3: BOOL): BOOL; stdcall; function wglSwapLayerBuffers(p1: HDC; p2: UINT): BOOL; stdcall; type _WGLSWAP = packed record hdc: HDC; uiFlags: UINT; end; WGLSWAP = _WGLSWAP; TWGLSwap = _WGLSWAP; PWGLSwap = ^_WGLSWAP; const WGL_SWAPMULTIPLE_MAX = 16; function wglSwapMultipleBuffers (p1: UINT; var WGLSWAP): DWORD; stdcall; implementation const OPENGL_LIBRARY = 'opengl32.dll'; function wglCopyContext; stdcall; external OPENGL_LIBRARY; function wglCreateContext; stdcall; external OPENGL_LIBRARY; function wglCreateLayerContext; stdcall; external OPENGL_LIBRARY; function wglDeleteContext; stdcall; external OPENGL_LIBRARY; function wglGetCurrentContext; stdcall; external OPENGL_LIBRARY; function wglGetCurrentDC; stdcall; external OPENGL_LIBRARY; function wglGetProcAddress; stdcall; external OPENGL_LIBRARY; function wglMakeCurrent; stdcall; external OPENGL_LIBRARY; function wglShareLists; stdcall; external OPENGL_LIBRARY; function wglUseFontBitmaps; stdcall; external OPENGL_LIBRARY name 'wglUseFontBitmapsA'; function wglUseFontBitmapsA; stdcall; external OPENGL_LIBRARY; function wglUseFontBitmapsW; stdcall; external OPENGL_LIBRARY; function wglUseFontOutlines; stdcall; external OPENGL_LIBRARY name 'wglUseFontOutlinesA'; function wglUseFontOutlinesA; stdcall; external OPENGL_LIBRARY; function wglUseFontOutlinesW; stdcall; external OPENGL_LIBRARY; function wglDescribeLayerPlane; stdcall; external OPENGL_LIBRARY; function wglSetLayerPaletteEntries; stdcall; external OPENGL_LIBRARY; function wglGetLayerPaletteEntries; stdcall; external OPENGL_LIBRARY; function wglRealizeLayerPalette; stdcall; external OPENGL_LIBRARY; function wglSwapLayerBuffers; stdcall; external OPENGL_LIBRARY; function wglSwapMultipleBuffers; stdcall; external OPENGL_LIBRARY; end.
unit uMovementGuide; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, StdCtrls, Buttons, cxLabel, cxDBLabel, cxImage, cxDBEdit, ExtCtrls, dxSkinMetropolis, dxSkinMetropolisDark; type TfmMovementGuide = class(TForm) Panel6: TPanel; cxDBImage1: TcxDBImage; cxDBImageView: TcxDBImage; cxDBLabel1: TcxDBLabel; btnPrevImage: TBitBtn; btnNextImage: TBitBtn; cxDBLabel2: TcxDBLabel; procedure btnNextImageClick(Sender: TObject); procedure btnPrevImageClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var fmMovementGuide: TfmMovementGuide; implementation {$R *.dfm} procedure TfmMovementGuide.btnNextImageClick(Sender: TObject); var fname, nname : string; begin fname := cxDBImageView.DataBinding.DataField; if fname = 'P_IMAGE' then nname := 'P_IMAGE2' else if fname = 'P_IMAGE2' then nname := 'P_IMAGE3' else if fname = 'P_IMAGE3' then nname := 'P_IMAGE4' else nname := 'P_IMAGE'; cxDBImageView.DataBinding.DataField := nname; cxDBImageView.DataBinding.UpdateDisplayValue; end; procedure TfmMovementGuide.btnPrevImageClick(Sender: TObject); var fname, nname : string; begin fname := cxDBImageView.DataBinding.DataField; if fname = 'P_IMAGE' then nname := 'P_IMAGE4' else if fname = 'P_IMAGE2' then nname := 'P_IMAGE' else if fname = 'P_IMAGE3' then nname := 'P_IMAGE2' else nname := 'P_IMAGE3'; cxDBImageView.DataBinding.DataField := nname; cxDBImageView.DataBinding.UpdateDisplayValue; end; procedure TfmMovementGuide.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit uCommon; interface uses System.Classes; const DB_NAME = 'SuperEasyCamera.s3db'; type TDirData = class private FName: String; FId: Int64; FCreatedAt: String; FParentId: Int64; public property Id: Int64 read FId write FId; property Name: String read FName write FName; property ParentId: Int64 read FParentId write FParentId; property CreatedAt: String read FCreatedAt write FCreatedAt; end; TPicData = class private FName: String; FId: Int64; FDirId: Int64; FCreatedAt: String; public property Id: Int64 read FId write FId; property Name: String read FName write FName; property DirId: Int64 read FDirId write FDirId; property CreatedAt: String read FCreatedAt write FCreatedAt; end; implementation end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Ani, FMX.Objects; type TButton = class(FMX.StdCtrls.TButton) private FIsOk: Boolean; function GetData: Integer; procedure SetData(const Value: Integer); procedure SetIsOk(const Value: Boolean); published property IsOk: Boolean read FIsOk Write SetIsOk; property Data: Integer read GetData Write SetData; end; TForm1 = class(TForm) Layout1: TLayout; GridLayout1: TGridLayout; Layout2: TLayout; Layout3: TLayout; Layout4: TLayout; Label1: TLabel; LabelBestScore: TLabel; Label2: TLabel; LabelScore: TLabel; Button1: TButton; Rectangle1: TRectangle; Label3: TLabel; ButtonTryAgain: TButton; FloatAnimationGameOver: TFloatAnimation; FloatAnimation2: TFloatAnimation; RectAnimation1: TRectAnimation; Button2: TButton; FloatAnimation3: TFloatAnimation; RectAnimation2: TRectAnimation; Button3: TButton; FloatAnimation4: TFloatAnimation; RectAnimation3: TRectAnimation; Button4: TButton; FloatAnimation5: TFloatAnimation; RectAnimation4: TRectAnimation; Button5: TButton; FloatAnimation6: TFloatAnimation; RectAnimation5: TRectAnimation; Button6: TButton; FloatAnimation7: TFloatAnimation; RectAnimation6: TRectAnimation; Button7: TButton; FloatAnimation8: TFloatAnimation; RectAnimation7: TRectAnimation; Button8: TButton; FloatAnimation9: TFloatAnimation; RectAnimation8: TRectAnimation; Button9: TButton; FloatAnimation10: TFloatAnimation; RectAnimation9: TRectAnimation; Button10: TButton; FloatAnimation11: TFloatAnimation; RectAnimation10: TRectAnimation; Button11: TButton; FloatAnimation12: TFloatAnimation; RectAnimation11: TRectAnimation; Button12: TButton; FloatAnimation13: TFloatAnimation; RectAnimation12: TRectAnimation; Button13: TButton; FloatAnimation14: TFloatAnimation; RectAnimation13: TRectAnimation; Button14: TButton; FloatAnimation15: TFloatAnimation; RectAnimation14: TRectAnimation; Button15: TButton; FloatAnimation16: TFloatAnimation; RectAnimation15: TRectAnimation; Button16: TButton; FloatAnimation17: TFloatAnimation; RectAnimation16: TRectAnimation; Button17: TButton; FloatAnimation18: TFloatAnimation; RectAnimation17: TRectAnimation; Button18: TButton; FloatAnimation19: TFloatAnimation; RectAnimation18: TRectAnimation; Button19: TButton; FloatAnimation20: TFloatAnimation; RectAnimation19: TRectAnimation; Button20: TButton; FloatAnimation21: TFloatAnimation; RectAnimation20: TRectAnimation; Text1: TText; FloatAnimationPing: TFloatAnimation; FloatAnimationOpa: TFloatAnimation; FloatAnimationRun: TFloatAnimation; procedure ButtonTryAgainClick(Sender: TObject); procedure Button1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); procedure Button1DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); procedure FloatAnimation2Finish(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RectAnimation1Finish(Sender: TObject); procedure FloatAnimationRunFinish(Sender: TObject); private { Private declarations } public procedure Score(aPoints: Integer); procedure DataLoad; procedure DataSave; { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.Button1DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); Var T, D: TButton; begin T := TButton(Sender); D := TButton(Data.Source); T.Data := T.Data + D.Data; Score(T.Data); D.Data := 0; T.IsOk := True; end; procedure TForm1.Button1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); begin if (Sender is TButton) and (Data.Source is TButton) and Not(Sender = Data.Source) and (TButton(Sender).Text = TButton(Data.Source) .Text) and (TButton(Data.Source).Text <> '') then Operation := TDragOperation.Move else Operation := TDragOperation.None; end; procedure TForm1.ButtonTryAgainClick(Sender: TObject); Var I: Integer; begin LabelScore.Text := '0'; for I := GridLayout1.ChildrenCount - 1 DownTo 0 do TButton(GridLayout1.Children[I]).Data := 0; Rectangle1.Visible := False; FloatAnimationRun.Start; end; procedure TForm1.DataLoad; Var M: TMemoryStream; I: Integer; begin M := TMemoryStream.Create; try M.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'DragOverQuark.xcx'); M.Read(I, SizeOf(I)); LabelBestScore.Text := IntToStr(I); Except LabelBestScore.Text := '0'; end; M.Free; end; procedure TForm1.DataSave; Var M: TMemoryStream; I: Integer; begin M := TMemoryStream.Create; try I := LabelBestScore.Text.ToInteger; M.Write(I, SizeOf(I)); M.SaveToFile(ExtractFilePath(ParamStr(0)) + 'DragOverQuark.xcx'); Except ON E: Exception do ShowMessage(E.Message); end; M.Free; end; procedure TForm1.FloatAnimation2Finish(Sender: TObject); begin // end; procedure TForm1.FloatAnimationRunFinish(Sender: TObject); Var I, Z: Integer; A: Array of Integer; begin Z := 0; for I := GridLayout1.ChildrenCount - 1 DownTo 0 do if TButton(GridLayout1.Children[I]).Data = 0 then begin Z := Z + 1; SetLength(A, High(A) + 2); A[High(A)] := I; end; if Z > 0 then begin I := Random(High(A)); TButton(GridLayout1.Children[A[I]]).Data := Trunc(Exp(Ln(2) * (1 + Random(3)))); SetLength(A, 0); FloatAnimationRun.Start; end else begin Rectangle1.Visible := True; FloatAnimationGameOver.Start; end; end; procedure TForm1.FormCreate(Sender: TObject); begin RandSeed := 3827643; DataLoad; ButtonTryAgainClick(Nil); end; procedure TForm1.RectAnimation1Finish(Sender: TObject); begin TButton(TFmxObject(Sender).Parent).Margins.Rect := RectF(2, 2, 2, 2); end; procedure TForm1.Score(aPoints: Integer); Var I, B: Integer; begin B := LabelBestScore.Text.ToInteger; I := LabelScore.Text.ToInteger; I := I + aPoints; Text1.Text := '+' + IntToStr(aPoints); FloatAnimationPing.Start; FloatAnimationOpa.Start; LabelScore.Text := IntToStr(I); if I > B then begin LabelBestScore.Text := IntToStr(I); DataSave; end; end; { TButton } function TButton.GetData: Integer; begin if Text = '' then Result := 0 else Result := StrToInt(Text); end; procedure TButton.SetData(const Value: Integer); begin if Value > 0 then Text := IntToStr(Value) else Text := ''; end; procedure TButton.SetIsOk(const Value: Boolean); begin FIsOk := Value; StartTriggerAnimation(Self, 'IsOk=True'); end; end.
unit MethodsServerModule; interface uses SysUtils, Dialogs, Classes, DSServer, FMTBcd, DB, SqlExpr, Forms, Windows, Customer, DBXJSON, DBXJSONReflect, DSService; type // {$MethodInfo ON} TDSServerMethods = class(TDSServerModule) SQLJob: TSQLDataSet; SQLJobJOBID: TIntegerField; SQLJobJOBNAME: TStringField; SQLJobDESCRIPTION: TStringField; SQLJobJOBCMD: TStringField; procedure DSServerModuleCreate(Sender: TObject); private { Private declarations } protected function GetCustomer: TCustomer; public { Public declarations } function GetServerDateTime: TDateTime; procedure ExecuteJob(JobId: Integer); function MVPCustomer(): TJSONValue; function Customer(): TCustomer; procedure SendCustomer(C : TJSONObject); function ListofCustomer(): TJSONArray; function ListofDifferentTypes(): TJSONArray; end; var DSServerMethods: TDSServerMethods; implementation uses ServerContainer, ShellAPI; {$R *.dfm} { TDSServerMethods } function TDSServerMethods.Customer: TCustomer; begin Result := GetCustomer; end; procedure TDSServerMethods.DSServerModuleCreate(Sender: TObject); begin if TDSSessionManager.GetThreadSession <> nil then // CodeSite.Send('Thread ID', TDSSessionManager.GetThreadSession.Id); end; procedure TDSServerMethods.ExecuteJob(JobId: Integer); var cmd: array [0 .. 300] of Char; begin SQLJob.ParamByName('JOBID').AsInteger := JobId; SQLJob.Open; if not SQLJob.Eof then begin StrPCopy(cmd, SQLJobJOBCMD.AsString); if ShellExecute(Application.Handle, nil, cmd, nil, nil, SW_SHOW) <> 42 then begin SQLJob.Close; Raise Exception.Create('Job cmd error trying to execute'); end; end; SQLJob.Close; end; function TDSServerMethods.GetCustomer: TCustomer; begin Result := TCustomer.Create; Result.Name := 'Andreano Lanusse'; Result.Age := 32; Result.MaritalStatus := msMarried; end; function TDSServerMethods.GetServerDateTime: TDateTime; begin Result := Now; end; function TDSServerMethods.ListofCustomer: TJSONArray; var i: Integer; myCustomer: TCustomer; begin Result := TJSONArray.Create; for i := 0 to 19 do begin myCustomer := GetCustomer; myCustomer.Name := 'Customer ' + IntToStr(i); myCustomer.Age := i; Result.AddElement(myCustomer.ObjectToJSON<TCustomer>(myCustomer, nil)); end; end; function TDSServerMethods.ListofDifferentTypes: TJSONArray; var strval: TJSONString; trueval : TJSONTrue; falseval : TJSONFalse; numval: TJSONNumber; begin Result := TJSONArray.Create; strval := TJSONString.Create('Return String value from DataSnap Server'); Result.AddElement(strval); numval := TJSONNumber.Create(100); Result.AddElement(numval); numval := TJSONNumber.Create(99.99); Result.AddElement(numval); trueval := TJSONTrue.Create; Result.AddElement(trueval); falseval := TJSONFalse.Create; Result.AddElement(falseval); Result.AddElement(TCustomer.ObjectToJSON<TCustomer>(GetCustomer, nil)); end; function TDSServerMethods.MVPCustomer: TJSONValue; var myCustomer: TCustomer; begin myCustomer := GetCustomer; Result := TCustomer.ObjectToJSON<TCustomer>(myCustomer, nil); myCustomer.Free; end; procedure TDSServerMethods.SendCustomer(C: TJSONObject); var FUnMarshal : TJSONUnMarshal; cust : TCustomer; begin if Assigned(C) then begin FUnMarshal := TJSONUnMarshal.Create; try cust := TCustomer.JSONToObject<TCustomer>(TJSONObject(C), FUnMarshal); finally FreeAndNil(FUnMarshal) end end; end; end.
unit UDSessionInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpeSessionInfoDlg = class(TForm) pnlSessionIInfo: TPanel; lblTable: TLabel; lblUserID: TLabel; lblUserPassword: TLabel; lblDBPassword: TLabel; lbTables: TListBox; editUserID: TEdit; editUserPassword: TEdit; editDBPassword: TEdit; cbPropagate: TCheckBox; btnOk: TButton; btnClear: TButton; btnTest: TButton; lblCount: TLabel; editCount: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdateSessionInfo; procedure lbTablesClick(Sender: TObject); procedure editUserIDChange(Sender: TObject); procedure editUserPasswordChange(Sender: TObject); procedure editDBPasswordChange(Sender: TObject); procedure cbPropagateClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnTestClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure InitializeControls(OnOff: boolean); private { Private declarations } public { Public declarations } Cr : TCrpe; SIndex : smallint; end; var CrpeSessionInfoDlg: TCrpeSessionInfoDlg; bSessionInfo : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.FormCreate(Sender: TObject); begin bSessionInfo := True; LoadFormPos(Self); btnOk.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.FormShow(Sender: TObject); begin UpdateSessionInfo; end; {------------------------------------------------------------------------------} { UpdateSessionInfo } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.UpdateSessionInfo; var OnOff : boolean; i : integer; begin {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then begin OnOff := False; SIndex := -1; end else begin OnOff := (Cr.SessionInfo.Count > 0); {Get SessionInfo Index} if OnOff then begin if Cr.SessionInfo.ItemIndex > -1 then SIndex := Cr.SessionInfo.ItemIndex else SIndex := 0; end; end; InitializeControls(OnOff); {If there is SessionInfo information, fill the listbox} if OnOff then begin lbTables.Clear; for i := 0 to (Cr.SessionInfo.Count - 1) do lbTables.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.SessionInfo.Count); lbTables.ItemIndex := SIndex; lbTablesClick(Self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TRadioButton then TRadioButton(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbTablesClick } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.lbTablesClick(Sender: TObject); begin SIndex := lbTables.ItemIndex; {Fill in controls} editUserID.Text := Cr.SessionInfo[SIndex].UserID; editUserPassword.Text := Cr.SessionInfo.Item.UserPassword; editDBPassword.Text := Cr.SessionInfo.Item.DBPassword; cbPropagate.Checked := Cr.SessionInfo.Item.Propagate; end; {------------------------------------------------------------------------------} { editUserIDChange } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.editUserIDChange(Sender: TObject); begin Cr.SessionInfo.Item.UserID := editUserID.Text; end; {------------------------------------------------------------------------------} { editUserPasswordChange } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.editUserPasswordChange(Sender: TObject); begin Cr.SessionInfo.Item.UserPassword := editUserPassword.Text; end; {------------------------------------------------------------------------------} { editDBPasswordChange } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.editDBPasswordChange(Sender: TObject); begin Cr.SessionInfo.Item.DBPassword := editDBPassword.Text; end; {------------------------------------------------------------------------------} { cbPropagateClick } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.cbPropagateClick(Sender: TObject); begin Cr.SessionInfo.Item.Propagate := cbPropagate.Checked; end; {------------------------------------------------------------------------------} { btnTestClick } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.btnTestClick(Sender: TObject); begin if Cr.SessionInfo.Item.Test then MessageDlg('Session Connected!', mtInformation, [mbOk], 0) else MessageDlg('Session Failed.' + Chr(10) + Cr.LastErrorString, mtError, [mbOk], 0); end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.btnClearClick(Sender: TObject); begin Cr.SessionInfo.Clear; UpdateSessionInfo; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeSessionInfoDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bSessionInfo := False; Release; end; end.
program problem07; uses crt; (* Problem: 10001 Prime Problem 7 @Author: Chris M. Perez @Date: 5/15/2017 *) const MAX: longint = 10001; function isPrime(arg: longint): boolean; var prime: boolean = true; x: longint; i: longint; begin if arg < 2 then begin prime := false; end; if arg = 2 then begin prime := true; end; x := LongInt(Round(Sqrt(Extended(arg)))); for i := 2 to x do begin if arg mod i = 0 then prime := false; end; isPrime := prime; end; function primeNumbers(arg: longint): longint; var x: longint = 0; counter: longint = 0; begin repeat x := x + 1; if isPrime(x) then begin counter := counter + 1; end; until(counter = MAX); primeNumbers := x; end; var result: longint; begin result := primeNumbers(MAX); writeln(result); readkey; end.
{*******************************************************} { } { 基于HCView的电子病历程序 作者:荆通 } { } { 此代码仅做学习交流使用,不可用于商业目的,由此引发的 } { 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 } { 交流。 } { } {*******************************************************} unit frm_RectItemProperty; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, HCView, HCRectItem, ExtCtrls, Grids; type TfrmRectItemProperty = class(TForm) pnl1: TPanel; btnSave: TButton; pnlSize: TPanel; lbl1: TLabel; edtWidth: TEdit; lbl2: TLabel; edtHeight: TEdit; procedure btnSaveClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure SetHCView(const AHCView: THCView); end; implementation {$R *.dfm} procedure TfrmRectItemProperty.btnSaveClick(Sender: TObject); begin Self.ModalResult := mrOk; end; procedure TfrmRectItemProperty.SetHCView(const AHCView: THCView); var i: Integer; vRectItem: THCCustomRectItem; begin vRectItem := AHCView.ActiveSectionTopLevelData.GetActiveItem as THCCustomRectItem; edtWidth.Text := IntToStr(vRectItem.Width); edtHeight.Text := IntToStr(vRectItem.Height); Self.ShowModal; if Self.ModalResult = mrOk then begin vRectItem.Width := StrToIntDef(edtWidth.Text, vRectItem.Width); vRectItem.Height := StrToIntDef(edtHeight.Text, vRectItem.Height); AHCView.BeginUpdate; try AHCView.ActiveSection.ReFormatActiveItem; finally AHCView.EndUpdate; end; end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIRegClasses, uniGUIForm, uniGUIBaseClasses, cfs.GCharts.uniGUI; type TMainForm = class(TUniForm) uniGChartsFrame1: TuniGChartsFrame; procedure UniFormCreate(Sender: TObject); procedure uniGChartsFrame1Select(Sender: TuniGChartsFrame; const ChartId, Row, Column, Value, Category: string); private public end; function MainForm: TMainForm; implementation {$R *.dfm} uses uniGUIVars, MainModule, cfs.GCharts; function MainForm: TMainForm; begin Result := TMainForm(UniMainModule.GetFormInstance(TMainForm)); end; procedure TMainForm.UniFormCreate(Sender: TObject); var Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Topping'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Slices') ]); Chart.Data.AddRow(['Mushrooms', 3]); Chart.Data.AddRow(['Onions', 1]); Chart.Data.AddRow(['Olives', 1]); Chart.Data.AddRow(['Zucchini', 1]); Chart.Data.AddRow(['Pepperoni', 2]); // Options Chart.Options.Title('How Much Pizza I Ate Last Night'); // Generate uniGChartsFrame1.DocumentInit; uniGChartsFrame1.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>'); uniGChartsFrame1.DocumentGenerate('Chart', Chart); uniGChartsFrame1.DocumentPost; end; procedure TMainForm.uniGChartsFrame1Select(Sender: TuniGChartsFrame; const ChartId, Row, Column, Value, Category: string); begin ShowMessageN(Format('ChartId=%s, Row=%s, Column=%s, Value=%s, Category=%s', [ChartId, Row, Column, Value, Category])); end; initialization RegisterAppFormClass(TMainForm); end.
unit frmKeyEntryFreeOTFE; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // Panels layout on this form: // // +--------------------------------------------------+ // | | // | +----------------------------------------------+ | // | | pnlBasic (alTop) | | // | | | | // | | | | // | +----------------------------------------------+ | // | | // | +----------------------------------------------+ | // | | pnlLower (alClient) | | // | | +------------------------------------------+ | | // | | | pnlAdvanced (alTop) | | | // | | | | | | // | | | | | | // | | +------------------------------------------+ | | // | | | | // | | +------------------------------------------+ | | // | | | pnlButtons (alClient) | | | // | | | | | | // | | +------------------------------------------+ | | // | | | | // | +----------------------------------------------+ | // | | // +--------------------------------------------------+ interface uses Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms, Graphics, Messages, OTFEFreeOTFE_PasswordRichEdit, PKCS11Lib, OTFEFreeOTFE_U, OTFEFreeOTFEBase_U, PasswordRichEdit, pkcs11_library, pkcs11_session, SDUDropFiles, SDUFilenameEdit_U, SDUForms, SDUFrames, SDUGeneral, SDUSpin64Units, Spin64, StdCtrls, SysUtils, Windows; type TfrmKeyEntryFreeOTFE = class (TSDUForm) pnlBasic: TPanel; GroupBox1: TGroupBox; Label1: TLabel; Label6: TLabel; lblDrive: TLabel; preUserKey: TOTFEFreeOTFE_PasswordRichEdit; cbDrive: TComboBox; ckMountReadonly: TCheckBox; pnlLower: TPanel; pnlButtons: TPanel; pbCancel: TButton; pbOK: TButton; pbAdvanced: TButton; pnlAdvanced: TPanel; gbVolumeOptions: TGroupBox; Label8: TLabel; ckOffsetPointsToCDB: TCheckBox; gbMountAs: TGroupBox; Label9: TLabel; cbMediaType: TComboBox; ckMountForAllUsers: TCheckBox; GroupBox3: TGroupBox; Label2: TLabel; Label5: TLabel; Label7: TLabel; seSaltLength: TSpinEdit64; seKeyIterations: TSpinEdit64; cbPKCS11CDB: TComboBox; rbKeyfileFile: TRadioButton; rbKeyfilePKCS11: TRadioButton; cbPKCS11SecretKey: TComboBox; Label10: TLabel; se64UnitOffset: TSDUSpin64Unit_Storage; feKeyfile: TSDUFilenameEdit; SDUDropFiles_Keyfile: TSDUDropFiles; procedure pbOKClick(Sender: TObject); procedure preUserkeyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pbCancelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure feKeyfileChange(Sender: TObject); procedure seSaltLengthChange(Sender: TObject); procedure seKeyIterationsChange(Sender: TObject); procedure cbMediaTypeChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbAdvancedClick(Sender: TObject); procedure rbKeyfileFileClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cbPKCS11CDBChange(Sender: TObject); procedure rbKeyfilePKCS11Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SDUDropFiles_KeyfileFileDrop(Sender: TObject; DropItem: String; DropPoint: TPoint); protected fTokenCDB: TPKCS11CDBPtrArray; fTokenSecretKey: TPKCS11SecretKeyPtrArray; fPkcs11session: TPKCS11Session; fsilentResult: TModalResult; fsilent: Boolean; fVolumeFiles: TStringList; fmountedDrives: String; procedure PopulateDrives(); procedure PopulateMountAs(); procedure PopulatePKCS11CDB(); procedure PopulatePKCS11SecretKey(); procedure DoCancel(); procedure EnableDisableControls(); procedure EnableDisableControls_Keyfile(); procedure EnableDisableControls_SecretKey(); function GetDriveLetter(): Char; function GetMountAs(): TFreeOTFEMountAs; function SetMountAs(mountAs: TFreeOTFEMountAs): Boolean; function CheckInput(): Boolean; function AttemptMount(): Boolean; function GetPKCS11Session(): TPKCS11Session; function IsVolumeStoredOnReadonlyMedia(): Boolean; function IsVolumeMarkedAsReadonly(): Boolean; function INSMessageDlg(Content: String; DlgType: TMsgDlgType): Integer; procedure SetVolumeFilesText(Value: String); public procedure SetPassword(password: TSDUBytes); procedure SetReadOnly(ReadOnly: Boolean); procedure SetKeyfile(keyFilename: String); procedure SetOffset(offset: ULONGLONG); procedure SetSaltLength(saltLength: Integer); procedure SetKeyIterations(keyIterations: Integer); procedure SetCDBAtOffset(CDBAtOffset: Boolean); procedure DisplayAdvanced(displayAdvanced: Boolean); property Silent: Boolean Read fSilent Write fSilent; property VolumeFilesText: String Write SetVolumeFilesText; property MountedDrives: String Read fMountedDrives; end; implementation {$R *.DFM} uses ComObj, // Required for StringToGUID // Disable useless warnings about faReadOnly, etc and FileSetAttr(...) being // platform-specific // This is ineffective?! {$WARN SYMBOL_PLATFORM OFF} FileCtrl, // Required for TDriveType {$WARN SYMBOL_PLATFORM ON} OTFEConsts_U, DriverAPI, frmPKCS11Session, pkcs11_object, lcDialogs, SDUi18n, Shredder; resourcestring RS_NOT_SELECTED = '<none selected>'; RS_NONE_AVAILABLE = '<none available>'; RS_BUTTON_ADVANCED = '&Advanced'; function TfrmKeyEntryFreeOTFE.GetDriveLetter(): Char; begin Result := #0; // Note: The item at index zero is "Use default"; #0 is returned for this if (cbDrive.ItemIndex > 0) then begin Result := cbDrive.Items[cbDrive.ItemIndex][1]; end; end; procedure TfrmKeyEntryFreeOTFE.SetReadOnly(ReadOnly: Boolean); begin ckMountReadonly.Checked := ReadOnly; end; procedure TfrmKeyEntryFreeOTFE.SetKeyfile(keyFilename: String); begin rbKeyfileFile.Checked := True; feKeyfile.Filename := keyFilename; end; procedure TfrmKeyEntryFreeOTFE.SetOffset(offset: ULONGLONG); begin se64UnitOffset.Value := offset; end; procedure TfrmKeyEntryFreeOTFE.SetSaltLength(saltLength: Integer); begin seSaltLength.Value := saltLength; end; procedure TfrmKeyEntryFreeOTFE.SetKeyIterations(keyIterations: Integer); begin seKeyIterations.Value := keyIterations; end; procedure TfrmKeyEntryFreeOTFE.SetCDBAtOffset(CDBAtOffset: Boolean); begin ckOffsetPointsToCDB.Checked := CDBAtOffset; end; function TfrmKeyEntryFreeOTFE.GetMountAs(): TFreeOTFEMountAs; var currMountAs: TFreeOTFEMountAs; begin Result := low(TFreeOTFEMountAs); for currMountAs := low(TFreeOTFEMountAs) to high(TFreeOTFEMountAs) do begin if (cbMediaType.Items[cbMediaType.ItemIndex] = FreeOTFEMountAsTitle(currMountAs)) then begin Result := currMountAs; break; end; end; end; function TfrmKeyEntryFreeOTFE.SetMountAs(mountAs: TFreeOTFEMountAs): Boolean; var idx: Integer; begin idx := cbMediaType.Items.IndexOf(FreeOTFEMountAsTitle(mountAs)); cbMediaType.ItemIndex := idx; Result := (idx >= 0); end; procedure TfrmKeyEntryFreeOTFE.PopulateDrives(); var driveLetters: String; i: Integer; begin cbDrive.Items.Clear(); cbDrive.Items.Add(_('Use default')); driveLetters := SDUGetUnusedDriveLetters(); for i := 1 to length(driveLetters) do begin // Skip the drive letters traditionally reserved for floppy disk drives // if ( // (driveLetters[i] <> 'A') AND // (driveLetters[i] <> 'B') // ) then // begin cbDrive.Items.Add(driveLetters[i] + ':'); // end; end; end; procedure TfrmKeyEntryFreeOTFE.PopulateMountAs(); var currMountAs: TFreeOTFEMountAs; begin cbMediaType.Items.Clear(); for currMountAs := low(TFreeOTFEMountAs) to high(TFreeOTFEMountAs) do begin if (currMountAs <> fomaUnknown) then begin cbMediaType.Items.Add(FreeOTFEMountAsTitle(currMountAs)); end; end; end; procedure TfrmKeyEntryFreeOTFE.PopulatePKCS11CDB(); var errMsg: String; i: Integer; warnBadCDB: Boolean; session: TPKCS11Session; begin // Purge stored CDBs... DestroyAndFreeRecord_PKCS11CDB(FTokenCDB); session := GetPKCS11Session(); cbPKCS11CDB.items.Clear(); if (session <> nil) then begin if not (GetAllPKCS11CDB(session, FTokenCDB, errMsg)) then begin INSMessageDlg(_('Unable to get list of CDB entries from Token') + SDUCRLF + SDUCRLF + errMsg, mtError); end; end; // Sanity check - the CDBs stored are sensible, right? warnBadCDB := False; // Populate combobox... for i := low(FTokenCDB) to high(FTokenCDB) do begin // Sanity check - the CDBs stored are sensible, right? if (length(FTokenCDB[i].CDB) <> (CRITICAL_DATA_LENGTH div 8)) then begin warnBadCDB := True; end else begin cbPKCS11CDB.items.AddObject(FTokenCDB[i].XLabel, TObject(FTokenCDB[i])); end; end; if warnBadCDB then begin INSMessageDlg( _('One or more of the keyfiles stored on your token are invalid/corrupt and will be ignored') + SDUCRLF + SDUCRLF + _('Please check which keyfiles are stored on this token and correct'), mtWarning ); end; if (cbPKCS11CDB.items.Count > 0) then begin cbPKCS11CDB.items.InsertObject(0, RS_NOT_SELECTED, nil); end else begin cbPKCS11CDB.items.InsertObject(0, RS_NONE_AVAILABLE, nil); end; // If there's only one item in the list (apart from the the none // available/selected), select it if (cbPKCS11CDB.items.Count = 2) then begin cbPKCS11CDB.ItemIndex := 1; end else begin // Select the none available/selected item cbPKCS11CDB.ItemIndex := 0; end; end; procedure TfrmKeyEntryFreeOTFE.PopulatePKCS11SecretKey(); var errMsg: String; i: Integer; session: TPKCS11Session; begin // Purge stored CDBs... DestroyAndFreeRecord_PKCS11SecretKey(FTokenSecretKey); session := GetPKCS11Session(); cbPKCS11SecretKey.items.Clear(); if (session <> nil) then begin if not (GetAllPKCS11SecretKey(session, FTokenSecretKey, errMsg)) then begin INSMessageDlg(_('Unable to get a list of secret keys from Token') + SDUCRLF + SDUCRLF + errMsg, mtError); end; end; // Populate combobox... for i := low(FTokenSecretKey) to high(FTokenSecretKey) do begin cbPKCS11SecretKey.items.AddObject(FTokenSecretKey[i].XLabel, TObject(FTokenSecretKey[i])); end; if (cbPKCS11SecretKey.items.Count > 0) then begin cbPKCS11SecretKey.items.InsertObject(0, RS_NOT_SELECTED, nil); end else begin cbPKCS11SecretKey.items.InsertObject(0, RS_NONE_AVAILABLE, nil); end; // Select the none available/selected item cbPKCS11SecretKey.ItemIndex := 0; end; // Returns TRUE if at least *one* volume was mounted successfully function TfrmKeyEntryFreeOTFE.AttemptMount(): Boolean; var errMsg: String; cntMountOK: Integer; cntMountFailed: Integer; useKeyfilename: String; usePKCS11CDB: Ansistring; tmpCDBRecord: PPKCS11CDB; usePKCS11SecretKey: PPKCS11SecretKey; usedSlotID: Integer; begin Result := False; if CheckInput() then begin usedSlotID := PKCS11_NO_SLOT_ID; useKeyfilename := ''; if rbKeyfileFile.Checked then begin useKeyfilename := feKeyfile.Filename; end; usePKCS11CDB := ''; if rbKeyfilePKCS11.Checked then begin // >0 here because first item is "none selected/none available" if (cbPKCS11CDB.ItemIndex > 0) then begin tmpCDBRecord := PPKCS11CDB(cbPKCS11CDB.Items.Objects[cbPKCS11CDB.ItemIndex]); usePKCS11CDB := tmpCDBRecord.CDB; usedSlotID := FPKCS11Session.SlotID; end; end; usePKCS11SecretKey := nil; // >0 here because first item is "none selected/none available" if (cbPKCS11SecretKey.ItemIndex > 0) then begin usePKCS11SecretKey := PPKCS11SecretKey( cbPKCS11SecretKey.Items.Objects[cbPKCS11SecretKey.ItemIndex]); usedSlotID := FPKCS11Session.SlotID; end; fMountedDrives := ''; { TODO 1 -otdk -cbug : handle non ascii user keys - at least warn user } Result := GetFreeOTFEBase.MountFreeOTFE(fVolumeFiles, SDUStringToSDUBytes(preUserkey.Text), useKeyfilename, usePKCS11CDB, usedSlotID, FPKCS11Session, usePKCS11SecretKey, seKeyIterations.Value, GetDriveLetter(), ckMountReadonly.Checked, GetMountAs(), se64UnitOffset.Value, ckOffsetPointsToCDB.Checked, seSaltLength.Value, ckMountForAllUsers.Checked, fMountedDrives); if not (Result) then begin GetFreeOTFEBase.CountMountedResults( fMountedDrives, cntMountOK, cntMountFailed ); if (cntMountOK = 0) then begin // No volumes were mounted... errMsg := _('Unable to open container.'); // Specific problems when mounting... if (GetFreeOTFEBase.LastErrorCode = OTFE_ERR_WRONG_PASSWORD) then begin errMsg := _('Unable to open container; please ensure that you entered the correct details (keyphrase, etc)'); if (feKeyfile.Filename <> '') then begin errMsg := errMsg + SDUCRLF + SDUCRLF + _( 'Please ensure that you check/uncheck the "Data from offset includes CDB" option, as appropriate for your container'); end; end else if (GetFreeOTFEBase.LastErrorCode = OTFE_ERR_VOLUME_FILE_NOT_FOUND) then begin errMsg := _('Unable to find container/read container CDB.'); end else if (GetFreeOTFEBase.LastErrorCode = OTFE_ERR_KEYFILE_NOT_FOUND) then begin errMsg := _('Unable to find keyfile/read keyfile.'); end else if (GetFreeOTFEBase.LastErrorCode = OTFE_ERR_PKCS11_SECRET_KEY_DECRYPT_FAILURE) then begin errMsg := _('Unable to decrypt using PKCS#11 secret key.'); end else if (GetFreeOTFEBase.LastErrorCode = OTFE_ERR_NO_FREE_DRIVE_LETTERS) then begin errMsg := _('Unable to assign a new drive letter; please confirm you have drive letters free!'); end else if (not (ckMountReadonly.Checked) and IsVolumeStoredOnReadonlyMedia()) then begin errMsg := _('Unable to open container; if a container to be mounted is stored on readonly media (e.g. CDROM or DVD), please check the "open readonly" option.'); end else if (not (ckMountReadonly.Checked) and IsVolumeMarkedAsReadonly()) then begin errMsg := _('Unable to open container; if a container is readonly, please check the "open readonly" option.'); end; INSMessageDlg(errMSg, mtError); end else if (cntMountFailed > 0) then begin // At least one volume was mounted, but not all of them errMsg := SDUPluralMsg(cntMountOK, SDUParamSubstitute( _('%1 container was opened successfully, but %2 could not be opened'), [cntMountOK, cntMountFailed]), SDUParamSubstitute( _('%1 containers were opened successfully, but %2 could not be opened'), [cntMountOK, cntMountFailed])); INSMessageDlg(errMSg, mtWarning); Result := True; end; end; end; end; function TfrmKeyEntryFreeOTFE.IsVolumeStoredOnReadonlyMedia(): Boolean; var i: Integer; currVol: String; testDriveColonSlash: String; begin Result := False; for i := 0 to (fVolumeFiles.Count - 1) do begin currVol := fVolumeFiles[i]; if not (GetFreeOTFEBase.IsPartition_UserModeName(currVol)) then begin if (length(currVol) > 2) then begin // Check for ":" as 2nd char in filename; i.e. it's a filename with // <drive letter>:<path>\<filename> if (currVol[2] = ':') then begin testDriveColonSlash := currVol[1] + ':\'; if (TDriveType(GetDriveType(PChar(testDriveColonSlash))) = dtCDROM) then begin // At least one of the volumes is stored on a CDROM (readonly media) Result := True; break; end; end; end; end; end; end; function TfrmKeyEntryFreeOTFE.IsVolumeMarkedAsReadonly(): Boolean; var i: Integer; currVol: String; begin Result := False; for i := 0 to (fVolumeFiles.Count - 1) do begin currVol := fVolumeFiles[i]; if not (GetFreeOTFEBase.IsPartition_UserModeName(currVol)) then begin if (length(currVol) > 2) then begin // Check for ":" as 2nd char in filename; i.e. it's a filename with // <drive letter>:<path>\<filename> if (currVol[2] = ':') then begin if FileIsReadOnly(currVol) then begin // At least one of the volumes is readonly Result := True; break; end; end; end; end; end; end; function TfrmKeyEntryFreeOTFE.CheckInput(): Boolean; begin Result := True; if (seSaltLength.Value mod 8 <> 0) then begin INSMessageDlg( _('Salt length (in bits) must be a multiple of 8'), mtError ); Result := False; end; end; procedure TfrmKeyEntryFreeOTFE.pbOKClick(Sender: TObject); begin if AttemptMount() then begin ModalResult := mrOk; end; end; procedure TfrmKeyEntryFreeOTFE.preUserkeyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key = 27) then begin DoCancel(); end; end; procedure TfrmKeyEntryFreeOTFE.rbKeyfilePKCS11Click(Sender: TObject); begin PopulatePKCS11CDB(); // If there are no keyfiles; flip back if (cbPKCS11CDB.items.Count <= 1) then begin // If we have a session, the user's logged into the token. However, no // keyfiles are on the token, warn the user if (FPKCS11Session <> nil) then begin INSMessageDlg( _('No keyfiles could be found on the token inserted.'), mtInformation ); end; rbKeyfileFile.Checked := True; end; EnableDisableControls_Keyfile(); end; procedure TfrmKeyEntryFreeOTFE.SDUDropFiles_KeyfileFileDrop(Sender: TObject; DropItem: String; DropPoint: TPoint); begin SetKeyfile(DropItem); end; function TfrmKeyEntryFreeOTFE.GetPKCS11Session(): TPKCS11Session; var pkcs11Dlg: TfrmPKCS11Session; begin if (FPKCS11Session = nil) then begin if PKCS11LibraryReady(GetFreeOTFEBase.PKCS11Library) then begin // Setup PKCS11 session, as appropriate pkcs11Dlg := TfrmPKCS11Session.Create(nil); try pkcs11Dlg.PKCS11LibObj := GetFreeOTFEBase.PKCS11Library; pkcs11Dlg.AllowSkip := False; if (pkcs11Dlg.ShowModal = mrOk) then begin FPKCS11Session := pkcs11Dlg.Session; end; finally pkcs11Dlg.Free(); end; end; end; Result := FPKCS11Session; end; procedure TfrmKeyEntryFreeOTFE.rbKeyfileFileClick(Sender: TObject); begin EnableDisableControls_Keyfile(); end; procedure TfrmKeyEntryFreeOTFE.pbCancelClick(Sender: TObject); begin DoCancel(); end; procedure TfrmKeyEntryFreeOTFE.DoCancel(); begin ModalResult := mrCancel; end; procedure TfrmKeyEntryFreeOTFE.FormClose(Sender: TObject; var Action: TCloseAction); begin // Posting WM_CLOSE causes Delphi to reset ModalResult to mrCancel. // As a result, we reset ModalResult here if fsilent then begin ModalResult := FSilentResult; end; end; procedure TfrmKeyEntryFreeOTFE.FormCreate(Sender: TObject); begin fVolumeFiles := TStringList.Create; fsilent := False; pnlLower.BevelOuter := bvNone; pnlLower.BevelInner := bvNone; pnlLower.Caption := ''; pnlBasic.BevelOuter := bvNone; pnlBasic.BevelInner := bvNone; pnlBasic.Caption := ''; pnlAdvanced.BevelOuter := bvNone; pnlAdvanced.BevelInner := bvNone; pnlAdvanced.Caption := ''; pnlButtons.BevelOuter := bvNone; pnlButtons.BevelInner := bvNone; pnlButtons.Caption := ''; rbKeyfileFile.Checked := True; feKeyfile.Filename := ''; cbPKCS11CDB.Sorted := True; SetLength(FTokenCDB, 0); cbPKCS11CDB.Items.AddObject(RS_NOT_SELECTED, nil); SetLength(FTokenSecretKey, 0); cbPKCS11SecretKey.Items.AddObject(RS_NOT_SELECTED, nil); preUserKey.Plaintext := True; // FreeOTFE volumes CAN have newlines in the user's password preUserKey.WantReturns := True; preUserKey.WordWrap := True; preUserKey.Lines.Clear(); se64UnitOffset.Value := 0; ckOffsetPointsToCDB.Checked := True; seSaltLength.Increment := 8; seSaltLength.Value := DEFAULT_SALT_LENGTH; seKeyIterations.MinValue := 1; seKeyIterations.MaxValue := 999999; // Need *some* upper value, otherwise setting MinValue won't work properly seKeyIterations.Increment := DEFAULT_KEY_ITERATIONS_INCREMENT; seKeyIterations.Value := DEFAULT_KEY_ITERATIONS; DisplayAdvanced(False); end; procedure TfrmKeyEntryFreeOTFE.FormDestroy(Sender: TObject); begin DestroyAndFreeRecord_PKCS11CDB(FTokenCDB); DestroyAndFreeRecord_PKCS11SecretKey(FTokenSecretKey); if (FPKCS11Session <> nil) then begin FPKCS11Session.Logout(); FPKCS11Session.CloseSession(); FPKCS11Session.Free(); end; fVolumeFiles.Free; end; procedure TfrmKeyEntryFreeOTFE.FormShow(Sender: TObject); var i: Integer; currDriveLetter: DriveLetterChar; begin feKeyfile.Filter := FILE_FILTER_FLT_KEYFILES; feKeyfile.DefaultExt := FILE_FILTER_DFLT_KEYFILES; feKeyfile.OpenDialog.Options := feKeyfile.OpenDialog.Options + [ofDontAddToRecent]; feKeyfile.SaveDialog.Options := feKeyfile.SaveDialog.Options + [ofDontAddToRecent]; preUserKey.PasswordChar := GetFreeOTFEBase.PasswordChar; preUserKey.WantReturns := GetFreeOTFEBase.AllowNewlinesInPasswords; preUserKey.WantTabs := GetFreeOTFEBase.AllowTabsInPasswords; // Note: PKCS#11 CDB list only populated when selected; it's at that point // that the user is prompted for their token's PIN // PopulatePKCS11CDB(); PopulateDrives(); if (cbDrive.Items.Count > 0) then begin cbDrive.ItemIndex := 0; if (GetFreeOTFEBase is TOTFEFreeOTFE) then begin if (GetFreeOTFE.DefaultDriveLetter <> #0) then begin // Start from 1; skip the default for i := 1 to (cbDrive.items.Count - 1) do begin currDriveLetter := cbDrive.Items[i][1]; if (currDriveLetter >= GetFreeOTFE.DefaultDriveLetter) then begin cbDrive.ItemIndex := i; break; end; end; end; end; end; PopulateMountAs(); if (GetFreeOTFEBase is TOTFEFreeOTFE) then begin SetMountAs(GetFreeOTFE.DefaultMountAs); end else begin SetMountAs(fomaRemovableDisk); end; // Certain controls only visble if used in conjunction with drive mounting gbMountAs.Visible := GetFreeOTFEBase is TOTFEFreeOTFE; lblDrive.Visible := GetFreeOTFEBase is TOTFEFreeOTFE; cbDrive.Visible := GetFreeOTFEBase is TOTFEFreeOTFE; // If the mount options groupbox isn't visible, widen the volume options // groupbox so that there's no blank space to its left if not (gbMountAs.Visible) then begin gbVolumeOptions.Width := gbVolumeOptions.Width + (gbVolumeOptions.left - gbMountAs.left); gbVolumeOptions.left := gbMountAs.left; end; // Default to TRUE to allow formatting under Windows Vista ckMountForAllUsers.Checked := True; EnableDisableControls(); // Position cursor to the *end* of any password preUserKey.SelStart := length(preUserKey.Text); if fSilent then begin if AttemptMount() then begin ModalResult := mrOk; end else begin ModalResult := mrCancel; end; FSilentResult := ModalResult; PostMessage(Handle, WM_CLOSE, 0, 0); end; SDUDropFiles_Keyfile.Active := True; end; procedure TfrmKeyEntryFreeOTFE.EnableDisableControls(); var tmpMountAs: TFreeOTFEMountAs; begin // Ensure we know what to mount as ckMountReadonly.Enabled := False; tmpMountAs := GetMountAs(); if not (FreeOTFEMountAsCanWrite[tmpMountAs]) then begin ckMountReadonly.Checked := True; end; SDUEnableControl(ckMountReadonly, FreeOTFEMountAsCanWrite[tmpMountAs]); EnableDisableControls_Keyfile(); EnableDisableControls_SecretKey(); pbOK.Enabled := (tmpMountAs <> fomaUnknown) and (cbDrive.ItemIndex >= 0) and (seKeyIterations.Value > 0) and (seSaltLength.Value >= 0); end; procedure TfrmKeyEntryFreeOTFE.EnableDisableControls_SecretKey(); begin // PKCS#11 secret key controls... SDUEnableControl(cbPKCS11SecretKey, ( // Must have more than the "none" item (cbPKCS11SecretKey.items.Count > 1))); end; procedure TfrmKeyEntryFreeOTFE.EnableDisableControls_Keyfile(); begin // We never disable rbKeyfileFile, as keeping it enabled gives the user a // visual clue that they can enter a keyfile filename // SDUEnableControl(rbKeyfileFile, PKCS11LibraryReady(fFreeOTFEObj.PKCS11Library)); // Protect as this can be called as part of creation if (GetFreeOTFEBase <> nil) then begin SDUEnableControl(rbKeyfilePKCS11, PKCS11LibraryReady(GetFreeOTFEBase.PKCS11Library)); if not (PKCS11LibraryReady(GetFreeOTFEBase.PKCS11Library)) then begin rbKeyfileFile.Checked := True; rbKeyfilePKCS11.Checked := False; end; end; // File based keyfile controls... SDUEnableControl(feKeyfile, rbKeyfileFile.Checked); // PKCS#11 based keyfile controls... SDUEnableControl(cbPKCS11CDB, (rbKeyfilePKCS11.Checked and // Must have more than the "none" item (cbPKCS11CDB.items.Count > 1))); // If no keyfile/PKCS#11 CDB is specified, then the CDB must reside within // the volume file if ((rbKeyfileFile.Checked and (feKeyfile.Filename = '')) or (rbKeyfilePKCS11.Checked and (cbPKCS11CDB.ItemIndex = 0) // None available/none selected )) then begin ckOffsetPointsToCDB.Enabled := False; ckOffsetPointsToCDB.Checked := True; end else begin // If a keyfile is specified, then the user can specify if the volume file // includes a CDB ckOffsetPointsToCDB.Enabled := True; end; end; procedure TfrmKeyEntryFreeOTFE.pbAdvancedClick(Sender: TObject); begin DisplayAdvanced(not (pnlAdvanced.Visible)); end; procedure TfrmKeyEntryFreeOTFE.feKeyfileChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryFreeOTFE.seSaltLengthChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryFreeOTFE.seKeyIterationsChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryFreeOTFE.cbMediaTypeChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryFreeOTFE.cbPKCS11CDBChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmKeyEntryFreeOTFE.DisplayAdvanced(displayAdvanced: Boolean); var displayChanged: Boolean; begin displayChanged := (pnlAdvanced.Visible <> displayAdvanced); pnlAdvanced.Visible := displayAdvanced; if displayChanged then begin if pnlAdvanced.Visible then begin self.Height := self.Height + pnlAdvanced.Height; PopulatePKCS11SecretKey(); EnableDisableControls_SecretKey(); end else begin self.Height := self.Height - pnlAdvanced.Height; end; end; if pnlAdvanced.Visible then begin pbAdvanced.Caption := '<< ' + RS_BUTTON_ADVANCED; end else begin pbAdvanced.Caption := RS_BUTTON_ADVANCED + ' >>'; end; end; procedure TfrmKeyEntryFreeOTFE.SetPassword(password: TSDUBytes); begin preUserKey.Text := SDUBytesToString(password); end; // "INS" - "If Not Silent" // Display message, if "Silent" not set to TRUE function TfrmKeyEntryFreeOTFE.INSMessageDlg(Content: String; DlgType: TMsgDlgType): Integer; begin Result := mrOk; if not (fsilent) then begin Result := SDUMessageDlg(Content, DlgType); end; end; procedure TfrmKeyEntryFreeOTFE.SetVolumeFilesText(Value: String); begin fVolumeFiles.Text := Value; end; end.
{Una matriz cuadrada A se dice es simétrica si A[i, j] = A [j, i] para todo i, j dentro de los límites de matriz. Escribir una función que determine: a. Cuantos elementos simétricos son diferentes. b. Verificar si es o no simétrica.} Program Eje4; Type TM = array[1..10, 1..10] of integer; Procedure LeerMatriz(Var A:TM; Var N,M:byte); Var i,j:byte; begin write('Ingrese la cantidad de filas: ');readln(N); write('Ingrese la cantidad de columnas: ');readln(M); For i:= 1 to N do For j:= 1 to M do begin write('Ingrese un numero para la posicion ',i:3,j:3,' : ');readln(A[i,j]); end; end; Function Cuenta(A:TM; N,M:byte):byte; Var i,j,Cont:byte; begin Cont:= 0; For i:= 1 to N do For j:= 1 to M do begin If (A[i,j] <> A[j,i]) then Cont:= Cont + 1; end; Cuenta:= Cont; end; Var A:TM; N,M,Cont:byte; Begin LeerMatriz(A,N,M); Cont:= Cuenta(A,N,M); writeln; If (Cont = 0) then writeln('La matriz es simetrica') Else writeln('La cantidad de elementos simetricos diferentes son: ',Cont); end.
unit Xc12DataWorksheet5; {- ******************************************************************************** ******* XLSReadWriteII V5.00 ******* ******* ******* ******* Copyright(C) 1999,2013 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$H+} {$R-} {$I AxCompilers.inc} interface uses Classes, SysUtils, Contnrs, xpgParseDrawing, xpgPUtils, xpgPSimpleDOM, Xc12Utils5, Xc12Common5, Xc12DataSST5, Xc12DataStyleSheet5, Xc12DataComments5, Xc12DataAutofilter5, Xc12DataTable5, Xc12FileData5, XLSUtils5, XLSCellMMU5, XLSCellAreas5, XLSMoveCopy5, XLSClassFactory5, XLSFormulaTypes5; type TXc12CfType = (x12ctExpression,x12ctCellIs,x12ctColorScale,x12ctDataBar,x12ctIconSet,x12ctTop10,x12ctUniqueValues,x12ctDuplicateValues,x12ctContainsText,x12ctNotContainsText,x12ctBeginsWith,x12ctEndsWith,x12ctContainsBlanks,x12ctNotContainsBlanks,x12ctContainsErrors,x12ctNotContainsErrors,x12ctTimePeriod,x12ctAboveAverage); type TXc12ConditionalFormattingOperator = (x12cfoLessThan,x12cfoLessThanOrEqual,x12cfoEqual,x12cfoNotEqual,x12cfoGreaterThanOrEqual,x12cfoGreaterThan,x12cfoBetween,x12cfoNotBetween,x12cfoContainsText,x12cfoNotContains,x12cfoBeginsWith,x12cfoEndsWith); type TXc12TimePeriod = (x12tpToday,x12tpYesterday,x12tpTomorrow,x12tpLast7Days,x12tpThisMonth,x12tpLastMonth,x12tpNextMonth,x12tpThisWeek,x12tpLastWeek,x12tpNextWeek); type TXc12CfvoType = (x12ctNum,x12ctPercent,x12ctMax,x12ctMin,x12ctFormula,x12ctPercentile); type TXc12PageOrder = (x12poDownThenOver,x12poOverThenDown); type TXc12Orientation = (x12oDefault,x12oPortrait,x12oLandscape); type TXc12CellComments = (x12ccNone,x12ccAsDisplayed,x12ccAtEnd); type TXc12PrintError = (x12peDisplayed,x12peBlank,x12peDash,x12peNA); type TXc12SheetState = (x12ssVisible,x12ssHidden,x12ssVeryHidden); type TXc12SheetViewType = (x12svtNormal,x12svtPageBreakPreview,x12svtPageLayout); type TXc12PaneEnum = (x12pBottomRight,x12pTopRight,x12pBottomLeft,x12pTopLeft); type TXc12PaneState = (x12psSplit,x12psFrozen,x12psFrozenSplit); type TXc12Axis = (x12aAxisRow,x12aAxisCol,x12aAxisPage,x12aAxisValues,x12aUnknown); type TXc12PivotAreaType = (x12patNone,x12patNormal,x12patData,x12patAll,x12patOrigin,x12patButton,x12patTopRight); type TXc12DataValidationType = (x12dvtNone,x12dvtWhole,x12dvtDecimal,x12dvtList,x12dvtDate,x12dvtTime,x12dvtTextLength,x12dvtCustom); type TXc12DataValidationErrorStyle = (x12dvesStop,x12dvesWarning,x12dvesInformation); type TXc12DataValidationImeMode = (x12dvimNoControl,x12dvimOff,x12dvimOn,x12dvimDisabled,x12dvimHiragana,x12dvimFullKatakana,x12dvimHalfKatakana,x12dvimFullAlpha,x12dvimHalfAlpha,x12dvimFullHangul,x12dvimHalfHangul); type TXc12DataValidationOperator = (x12dvoBetween,x12dvoNotBetween,x12dvoEqual,x12dvoNotEqual,x12dvoLessThan,x12dvoLessThanOrEqual,x12dvoGreaterThan,x12dvoGreaterThanOrEqual); type TXc12WebSourceType = (x12wstSheet,x12wstPrintArea,x12wstAutoFilter,x12wstRange,x12wstChart,x12wstPivotTable,x12wstQuery,x12wstLabel); type TXc12DvAspect = (x12daDVASPECT_CONTENT,x12daDVASPECT_ICON); type TXc12OleUpdate = (x12ouOLEUPDATE_ALWAYS,x12ouOLEUPDATE_ONCALL); type TXc12DataConsolidateFunction = (x12dcfAverage,x12dcfCount,x12dcfCountNums,x12dcfMax,x12dcfMin,x12dcfProduct,x12dcfStdDev,x12dcfStdDevp,x12dcfSum,x12dcfVar,x12dcfVarp); type TXc12PhoneticType = (x12ptHalfwidthKatakana,x12ptFullwidthKatakana,x12ptHiragana,x12ptNoConversion); type TXc12PhoneticAlignment = (x12paNoControl,x12paLeft,x12paCenter,x12paDistributed); type TXc12ColumnOption = (xcoHidden,xcoBestFit,xcoCustomWidth,xcoPhonetic,xcoCollapsed); TXc12ColumnOptions = set of TXc12ColumnOption; type TXc12ColumnHit = (xchLess,xchCol2,xchCol1Match,xchMatch,xchTargetInside,xchCol2Match,xchInside,xchCol1,xchGreater); //================================ // 1----2 xchLess // +------+ //================================ // 1----2....x xchCol2 (can hit the entire target) // +------+ //================================ // 1----2 xchCol1Match // +------+ //================================ // 1------2 xchMatch // +------+ //================================ // 1--------2 xchTargetInside // +------+ //================================ // 1----2 xchCol2Match // +------+ //================================ // 1----2 xchInside // +------+ //================================ // x....1----2 xchCol1 (can hit the entire target) // +------+ //================================ // 1----2 xchGreater // +------+ //================================ type TXc12Colors = class(TList) private function GetItems(Index: integer): TXc12Color; protected public destructor Destroy; override; procedure Add(AColor: TXc12Color); overload; procedure Add(ARGB: longword); overload; property Items[Index: integer]: TXc12Color read GetItems; default; end; type TXc12Cfvo = class(TObject) private function GetAsFloat: double; procedure SetAsFloat(const Value: double); function GetAsPercent: double; protected FType: TXc12CfvoType; // Required FVal: AxUCString; FGte: boolean; FPtgs: PXLSPtgs; FPtgsSz: integer; public constructor Create; destructor Destroy; override; procedure Clear; overload; procedure Clear(AType: TXc12CfvoType; AVal: AxUCString; AGte: boolean = True); overload; property Type_: TXc12CfvoType read FType write FType; property Val: AxUCString read FVal write FVal; property AsFloat: double read GetAsFloat write SetAsFloat; property AsPercent: double read GetAsPercent; property Gte: boolean read FGte write FGte; property Ptgs: PXLSPtgs read FPtgs write FPtgs; property PtgsSz: integer read FPtgsSz write FPtgsSz; end; type TXc12Cfvos = class(TObjectList) private function GetItems(Index: integer): TXc12Cfvo; protected public constructor Create; function Add: TXc12Cfvo; overload; function Add(AType: TXc12CfvoType; const AVal: AxUCString; AGte: boolean = True): TXc12Cfvo; overload; property Items[Index: integer]: TXc12Cfvo read GetItems; default; end; type TXc12IconSet = class(TObject) protected FIconSet: TXc12IconSetType; FShowValue: boolean; FPercent: boolean; FReverse: boolean; FCfvos: TXc12Cfvos; public constructor Create; destructor Destroy; override; procedure Clear; property IconSet: TXc12IconSetType read FIconSet write FIconSet; property ShowValue: boolean read FShowValue write FShowValue; property Percent: boolean read FPercent write FPercent; property Reverse: boolean read FReverse write FReverse; property Cfvos: TXc12Cfvos read FCfvos; end; type TXc12DataBar = class(TObject) protected FMinLength: integer; FMaxLength: integer; FShowValue: boolean; FColor: TXc12Color; FCfvo1: TXc12Cfvo; FCfvo2: TXc12Cfvo; public constructor Create; destructor Destroy; override; procedure Clear; property MinLength: integer read FMinLength write FMinLength; property MaxLength: integer read FMaxLength write FMaxLength; property ShowValue: boolean read FShowValue write FShowValue; property Color: TXc12Color read FColor write FColor; property Cfvo1: TXc12Cfvo read FCfvo1; property Cfvo2: TXc12Cfvo read FCfvo2; end; type TXc12ColorScale = class(TObject) protected FCfvos: TXc12Cfvos; FColors: TXc12Colors; public constructor Create; destructor Destroy; override; procedure Clear; property Cfvos: TXc12Cfvos read FCfvos; property Colors: TXc12Colors read FColors; end; type TXc12CfRule = class(TObject) private function GetFormulas(Index: integer): AxUCString; procedure SerFormulas(Index: integer; const Value: AxUCString); function GetPtgs(Index: integer): PXLSPtgs; function GetPtgsSz(Index: integer): integer; procedure SetPtgs(Index: integer; const Value: PXLSPtgs); procedure SetPtgsSz(Index: integer; const Value: integer); function GetValues(Index: integer): double; function GetValuesCount: integer; procedure SetValues(Index: integer; const Value: double); procedure SetValuesCount(const Value: integer); protected FFormula: array[0..2] of AxUCString; FPtgs: array[0..2] of PXLSPtgs; FPtgsSz: array[0..2] of integer; FType_: TXc12CfType; FDXF: TXc12DXF; FPriority: integer; FStopIfTrue: boolean; FAboveAverage: boolean; FPercent: boolean; FBottom: boolean; FOperator: TXc12ConditionalFormattingOperator; FText: AxUCString; FTimePeriod: TXc12TimePeriod; FRank: integer; FStdDev: integer; FEqualAverage: boolean; FColorScale: TXc12ColorScale; FDataBar: TXc12DataBar; FIconSet: TXc12IconSet; // Used by XLSSpreadSheet. FValAverage: double; FValMin : double; FValMax : double; FValues : TDynDoubleArray; public constructor Create; destructor Destroy; override; procedure Clear; function FormulaMaxCount: integer; property Formulas[Index: integer]: AxUCString read GetFormulas write SerFormulas; property Ptgs[Index: integer]: PXLSPtgs read GetPtgs write SetPtgs; property PtgsSz[Index: integer]: integer read GetPtgsSz write SetPtgsSz; property Type_: TXc12CfType read FType_ write FType_; property DXF: TXc12DXF read FDXF write FDXF; property Priority: integer read FPriority write FPriority; property StopIfTrue: boolean read FStopIfTrue write FStopIfTrue; property AboveAverage: boolean read FAboveAverage write FAboveAverage; property Percent: boolean read FPercent write FPercent; property Bottom: boolean read FBottom write FBottom; property Operator_: TXc12ConditionalFormattingOperator read FOperator write FOperator; property Text: AxUCString read FText write FText; property TimePeriod: TXc12TimePeriod read FTimePeriod write FTimePeriod; property Rank: integer read FRank write FRank; property StdDev: integer read FStdDev write FStdDev; property EqualAverage: boolean read FEqualAverage write FEqualAverage; property ColorScale: TXc12ColorScale read FColorScale; property DataBar: TXc12DataBar read FDataBar; property IconSet: TXc12IconSet read FIconSet; // Used by XLSSpreadSheet. procedure SortValues; property ValAverage: double read FValAverage write FValAverage; property ValMin: double read FValMin write FValMin; property ValMax: double read FValMax write FValMax; property ValuesCount: integer read GetValuesCount write SetValuesCount; property Values[Index: integer]: double read GetValues write SetValues; end; type TXc12CfRules = class(TObjectList) private function GetItems(Index: integer): TXc12CfRule; protected public constructor Create; function Add: TXc12CfRule; property Items[Index: integer]: TXc12CfRule read GetItems; default; end; type TXc12ConditionalFormatting = class(TXLSMoveCopyItem) protected FPivot: boolean; FSQRef: TCellAreas; FCfRules: TXc12CfRules; public constructor Create; destructor Destroy; override; procedure Clear; property Pivot: boolean read FPivot write FPivot; property SQRef: TCellAreas read FSQRef; property CfRules: TXc12CfRules read FCfRules; end; type TXc12ConditionalFormattings = class(TXLSMoveCopyList) private function GetItems(Index: integer): TXc12ConditionalFormatting; protected FClassFactory: TXLSClassFactory; FXc12Sheet: TObject; function CreateMember: TXc12ConditionalFormatting; virtual; abstract; public constructor Create(AClassFactory: TXLSClassFactory); function Add: TXLSMoveCopyItem; override; function AddCF: TXc12ConditionalFormatting; property Xc12Sheet: TObject read FXc12Sheet write FXc12Sheet; property Items[Index: integer]: TXc12ConditionalFormatting read GetItems; default; end; type TXc12HeaderFooter = class(TObject) protected FDifferentOddEven: boolean; FDifferentFirst: boolean; FScaleWithDoc: boolean; FAlignWithMargins: boolean; FOddHeader: AxUCString; FOddFooter: AxUCString; FEvenHeader: AxUCString; FEvenFooter: AxUCString; FFirstHeader: AxUCString; FFirstFooter: AxUCString; public constructor Create; procedure Clear; property DifferentOddEven: boolean read FDifferentOddEven write FDifferentOddEven; property DifferentFirst: boolean read FDifferentFirst write FDifferentFirst; property ScaleWithDoc: boolean read FScaleWithDoc write FScaleWithDoc; property AlignWithMargins: boolean read FAlignWithMargins write FAlignWithMargins; property OddHeader: AxUCString read FOddHeader write FOddHeader; property OddFooter: AxUCString read FOddFooter write FOddFooter; property EvenHeader: AxUCString read FEvenHeader write FEvenHeader; property EvenFooter: AxUCString read FEvenFooter write FEvenFooter; property FirstHeader: AxUCString read FFirstHeader write FFirstHeader; property FirstFooter: AxUCString read FFirstFooter write FFirstFooter; end; type TXc12PageSetup = class(TObject) private procedure SetPrinterSettings(const Value: TStream); protected FPaperSize: integer; FScale: integer; FFirstPageNumber: integer; FFitToWidth: integer; FFitToHeight: integer; FPageOrder: TXc12PageOrder; FOrientation: TXc12Orientation; FUsePrinterDefaults: boolean; FBlackAndWhite: boolean; FDraft: boolean; FCellComments: TXc12CellComments; FUseFirstPageNumber: boolean; FErrors: TXc12PrintError; FHorizontalDpi: integer; FVerticalDpi: integer; FCopies: integer; FPrinterSettings: TStream; public constructor Create; destructor Destroy; override; procedure Clear; property PaperSize: integer read FPaperSize write FPaperSize; property Scale: integer read FScale write FScale; property FirstPageNumber: integer read FFirstPageNumber write FFirstPageNumber; property FitToWidth: integer read FFitToWidth write FFitToWidth; property FitToHeight: integer read FFitToHeight write FFitToHeight; property PageOrder: TXc12PageOrder read FPageOrder write FPageOrder; property Orientation: TXc12Orientation read FOrientation write FOrientation; property UsePrinterDefaults: boolean read FUsePrinterDefaults write FUsePrinterDefaults; property BlackAndWhite: boolean read FBlackAndWhite write FBlackAndWhite; property Draft: boolean read FDraft write FDraft; property CellComments: TXc12CellComments read FCellComments write FCellComments; property UseFirstPageNumber: boolean read FUseFirstPageNumber write FUseFirstPageNumber; property Errors: TXc12PrintError read FErrors write FErrors; property HorizontalDpi: integer read FHorizontalDpi write FHorizontalDpi; property VerticalDpi: integer read FVerticalDpi write FVerticalDpi; property Copies: integer read FCopies write FCopies; property PrinterSettings: TStream read FPrinterSettings write SetPrinterSettings; end; type TXc12PrintOptions = class(TObject) protected FHorizontalCentered: boolean; FVerticalCentered: boolean; FHeadings: boolean; FGridLines: boolean; FGridLinesSet: boolean; public constructor Create; procedure Clear; property HorizontalCentered: boolean read FHorizontalCentered write FHorizontalCentered; property VerticalCentered: boolean read FVerticalCentered write FVerticalCentered; property Headings: boolean read FHeadings write FHeadings; property GridLines: boolean read FGridLines write FGridLines; property GridLinesSet: boolean read FGridLinesSet write FGridLinesSet; end; type TXc12PageMargins = class(TObject) protected FLeft: double; FRight: double; FTop: double; FBottom: double; FHeader: double; FFooter: double; public constructor Create; procedure Clear; property Left: double read FLeft write FLeft; property Right: double read FRight write FRight; property Top: double read FTop write FTop; property Bottom: double read FBottom write FBottom; property Header: double read FHeader write FHeader; property Footer: double read FFooter write FFooter; end; type TXc12Break = class(TObject) protected FId: integer; FMin: integer; FMax: integer; FMan: boolean; FPt: boolean; public constructor Create; procedure Clear; property Id: integer read FId write FId; property Min: integer read FMin write FMin; property Max: integer read FMax write FMax; property Man: boolean read FMan write FMan; property Pt: boolean read FPt write FPt; end; type TXc12PageBreaks = class(TObjectList) private function GetItems(Index: integer): TXc12Break; protected public constructor Create; procedure Clear; override; function Add: TXc12Break; function Find(const AId: integer): integer; function Hits(const AId: integer): integer; property Items[Index: integer]: TXc12Break read GetItems; default; end; type TXc12Selection = class(TObject) protected FPane: TXc12PaneEnum; FActiveCell: TXLSCellArea; FActiveCellId: integer; FSQRef: TCellAreas; public constructor Create; destructor Destroy; override; procedure Clear; property Pane: TXc12PaneEnum read FPane write FPane; property ActiveCell: TXLSCellArea read FActiveCell write FActiveCell; property ActiveCellId: integer read FActiveCellId write FActiveCellId; property SQRef: TCellAreas read FSQRef; end; type TXc12Selections = class(TObjectList) private function GetItems(Index: integer): TXc12Selection; protected public constructor Create; function Add: TXc12Selection; property Items[Index: integer]: TXc12Selection read GetItems; default; end; type TXc12Pane = class(TObject) protected FXSplit: double; FYSplit: double; FTopLeftCell: TXLSCellArea; FActivePane: TXc12PaneEnum; FState: TXc12PaneState; FExcel97: boolean; public constructor Create; procedure Clear; property XSplit: double read FXSplit write FXSplit; property YSplit: double read FYSplit write FYSplit; property TopLeftCell: TXLSCellArea read FTopLeftCell write FTopLeftCell; property ActivePane: TXc12PaneEnum read FActivePane write FActivePane; property State: TXc12PaneState read FState write FState; property Excel97: boolean read FExcel97 write FExcel97; end; type TXc12PivotAreaReference = class(TObject) protected FField: integer; FSelected: boolean; FByPosition: boolean; FRelative: boolean; FDefaultSubtotal: boolean; FSumSubtotal: boolean; FCountASubtotal: boolean; FAvgSubtotal: boolean; FMaxSubtotal: boolean; FMinSubtotal: boolean; FProductSubtotal: boolean; FCountSubtotal: boolean; FStdDevSubtotal: boolean; FStdDevPSubtotal: boolean; FVarSubtotal: boolean; FVarPSubtotal: boolean; FValues: TIntegerList; public constructor Create; destructor Destroy; override; procedure Clear; property Field: integer read FField write FField; property Selected: boolean read FSelected write FSelected; property ByPosition: boolean read FByPosition write FByPosition; property Relative: boolean read FRelative write FRelative; property DefaultSubtotal: boolean read FDefaultSubtotal write FDefaultSubtotal; property SumSubtotal: boolean read FSumSubtotal write FSumSubtotal; property CountASubtotal: boolean read FCountASubtotal write FCountASubtotal; property AvgSubtotal: boolean read FAvgSubtotal write FAvgSubtotal; property MaxSubtotal: boolean read FMaxSubtotal write FMaxSubtotal; property MinSubtotal: boolean read FMinSubtotal write FMinSubtotal; property ProductSubtotal: boolean read FProductSubtotal write FProductSubtotal; property CountSubtotal: boolean read FCountSubtotal write FCountSubtotal; property StdDevSubtotal: boolean read FStdDevSubtotal write FStdDevSubtotal; property StdDevPSubtotal: boolean read FStdDevPSubtotal write FStdDevPSubtotal; property VarSubtotal: boolean read FVarSubtotal write FVarSubtotal; property VarPSubtotal: boolean read FVarPSubtotal write FVarPSubtotal; property Values: TIntegerList read FValues; end; type TXc12PivotAreaReferences = class(TObjectList) private function GetItems(Index: integer): TXc12PivotAreaReference; protected public constructor Create; function Add: TXc12PivotAreaReference; property Items[Index: integer]: TXc12PivotAreaReference read GetItems; default; end; type TXc12PivotArea = class(TObject) protected FField: integer; FType_: TXc12PivotAreaType; FDataOnly: boolean; FLabelOnly: boolean; FGrandRow: boolean; FGrandCol: boolean; FCacheIndex: boolean; FOutline: boolean; FOffset: TXLSCellArea; FCollapsedLevelsAreSubtotals: boolean; FAxis: TXc12Axis; FFieldPosition: integer; FReferences: TXc12PivotAreaReferences; public constructor Create; destructor Destroy; override; procedure Clear; property Field: integer read FField write FField; property Type_: TXc12PivotAreaType read FType_ write FType_; property DataOnly: boolean read FDataOnly write FDataOnly; property LabelOnly: boolean read FLabelOnly write FLabelOnly; property GrandRow: boolean read FGrandRow write FGrandRow; property GrandCol: boolean read FGrandCol write FGrandCol; property CacheIndex: boolean read FCacheIndex write FCacheIndex; property Outline: boolean read FOutline write FOutline; property Offset: TXLSCellArea read FOffset write FOffset; property CollapsedLevelsAreSubtotals: boolean read FCollapsedLevelsAreSubtotals write FCollapsedLevelsAreSubtotals; property Axis: TXc12Axis read FAxis write FAxis; property FieldPosition: integer read FFieldPosition write FFieldPosition; property References: TXc12PivotAreaReferences read FReferences; end; type TXc12PivotSelection = class(TObject) protected FPane: TXc12PaneEnum; FShowHeader: boolean; FLabel_: boolean; FData: boolean; FExtendable: boolean; FCount: integer; FAxis: TXc12Axis; FDimension: integer; FStart: integer; FMin: integer; FMax: integer; FActiveRow: integer; FActiveCol: integer; FPreviousRow: integer; FPreviousCol: integer; FClick: integer; FRId: TXc12RId; FPivotArea: TXc12PivotArea; public constructor Create; destructor Destroy; override; procedure Clear; property Pane: TXc12PaneEnum read FPane write FPane; property ShowHeader: boolean read FShowHeader write FShowHeader; property Label_: boolean read FLabel_ write FLabel_; property Data: boolean read FData write FData; property Extendable: boolean read FExtendable write FExtendable; property Count: integer read FCount write FCount; property Axis: TXc12Axis read FAxis write FAxis; property Dimension: integer read FDimension write FDimension; property Start: integer read FStart write FStart; property Min: integer read FMin write FMin; property Max: integer read FMax write FMax; property ActiveRow: integer read FActiveRow write FActiveRow; property ActiveCol: integer read FActiveCol write FActiveCol; property PreviousRow: integer read FPreviousRow write FPreviousRow; property PreviousCol: integer read FPreviousCol write FPreviousCol; property Click: integer read FClick write FClick; property RId: TXc12RId read FRId write FRId; property PivotArea: TXc12PivotArea read FPivotArea; end; type TXc12PivotSelections = class(TObjectList) private function GetItems(Index: integer): TXc12PivotSelection; protected public constructor Create; destructor Destroy; override; function Add: TXc12PivotSelection; property Items[Index: integer]: TXc12PivotSelection read GetItems; default; end; type TXc12CustomSheetView = class(TObject) protected FClassFactory: TXLSClassFactory; FGuid: AxUCString; FScale: integer; FColorId: integer; FShowPageBreaks: boolean; FShowFormulas: boolean; FShowGridLines: boolean; FShowRowCol: boolean; FOutlineSymbols: boolean; FZeroValues: boolean; FFitToPage: boolean; FPrintArea: boolean; FFilter: boolean; FShowAutoFilter: boolean; FHiddenRows: boolean; FHiddenColumns: boolean; FState: TXc12SheetState; FFilterUnique: boolean; FView: TXc12SheetViewType; FShowRuler: boolean; FTopLeftCell: TXLSCellArea; FPane: TXc12Pane; FSelection: TXc12Selection; FRowBreaks: TXc12PageBreaks; FColBreaks: TXc12PageBreaks; FPageMargins: TXc12PageMargins; FPrintOptions: TXc12PrintOptions; FPageSetup: TXc12PageSetup; FHeaderFooter: TXc12HeaderFooter; FAutoFilter: TXc12AutoFilter; public constructor Create(AClassFactory: TXLSClassFactory); destructor Destroy; override; procedure Clear; property GUID: AxUCString read FGUID write FGUID; property Scale: integer read FScale write FScale; property ColorId: integer read FColorId write FColorId; property ShowPageBreaks: boolean read FShowPageBreaks write FShowPageBreaks; property ShowFormulas: boolean read FShowFormulas write FShowFormulas; property ShowGridLines: boolean read FShowGridLines write FShowGridLines; property ShowRowCol: boolean read FShowRowCol write FShowRowCol; property OutlineSymbols: boolean read FOutlineSymbols write FOutlineSymbols; property ZeroValues: boolean read FZeroValues write FZeroValues; property FitToPage: boolean read FFitToPage write FFitToPage; property PrintArea: boolean read FPrintArea write FPrintArea; property Filter: boolean read FFilter write FFilter; property ShowAutoFilter: boolean read FShowAutoFilter write FShowAutoFilter; property HiddenRows: boolean read FHiddenRows write FHiddenRows; property HiddenColumns: boolean read FHiddenColumns write FHiddenColumns; property State: TXc12SheetState read FState write FState; property FilterUnique: boolean read FFilterUnique write FFilterUnique; property View: TXc12SheetViewType read FView write FView; property ShowRuler: boolean read FShowRuler write FShowRuler; property TopLeftCell: TXLSCellArea read FTopLeftCell write FTopLeftCell; property Pane: TXc12Pane read FPane; property Selection: TXc12Selection read FSelection; property RowBreaks: TXc12PageBreaks read FRowBreaks; property ColBreaks: TXc12PageBreaks read FColBreaks; property PageMargins: TXc12PageMargins read FPageMargins; property PrintOptions: TXc12PrintOptions read FPrintOptions; property PageSetup: TXc12PageSetup read FPageSetup; property HeaderFooter: TXc12HeaderFooter read FHeaderFooter; property AutoFilter: TXc12AutoFilter read FAutoFilter; end; type TXc12CustomSheetViews = class(TObjectList) private function GetItems(Index: integer): TXc12CustomSheetView; protected FClassFactory: TXLSClassFactory; public constructor Create(AClassFactory: TXLSClassFactory); function Add: TXc12CustomSheetView; property Items[Index: integer]: TXc12CustomSheetView read GetItems; default; end; type TXc12SheetView = class(TObject) protected FWindowProtection: boolean; FShowFormulas: boolean; FShowGridLines: boolean; FShowRowColHeaders: boolean; FShowZeros: boolean; FRightToLeft: boolean; FTabSelected: boolean; FShowRuler: boolean; FShowOutlineSymbols: boolean; FDefaultGridColor: boolean; FShowWhiteSpace: boolean; FView: TXc12SheetViewType; FTopLeftCell: TXLSCellArea; FColorId: integer; FZoomScale: integer; FZoomScaleNormal: integer; FZoomScaleSheetLayoutView: integer; FZoomScalePageLayoutView: integer; FWorkbookViewId: integer; FPane: TXc12Pane; FSelection: TXc12Selections; FPivotSelection: TXc12PivotSelections; // Used by chart sheets. FZoomToFit: boolean; public constructor Create; destructor Destroy; override; procedure Clear; property WindowProtection: boolean read FWindowProtection write FWindowProtection; property ShowFormulas: boolean read FShowFormulas write FShowFormulas; property ShowGridLines: boolean read FShowGridLines write FShowGridLines; property ShowRowColHeaders: boolean read FShowRowColHeaders write FShowRowColHeaders; property ShowZeros: boolean read FShowZeros write FShowZeros; property RightToLeft: boolean read FRightToLeft write FRightToLeft; property TabSelected: boolean read FTabSelected write FTabSelected; property ShowRuler: boolean read FShowRuler write FShowRuler; property ShowOutlineSymbols: boolean read FShowOutlineSymbols write FShowOutlineSymbols; property DefaultGridColor: boolean read FDefaultGridColor write FDefaultGridColor; property ShowWhiteSpace: boolean read FShowWhiteSpace write FShowWhiteSpace; property View: TXc12SheetViewType read FView write FView; property TopLeftCell: TXLSCellArea read FTopLeftCell write FTopLeftCell; property ColorId: integer read FColorId write FColorId; property ZoomScale: integer read FZoomScale write FZoomScale; property ZoomScaleNormal: integer read FZoomScaleNormal write FZoomScaleNormal; property ZoomScaleSheetLayoutView: integer read FZoomScaleSheetLayoutView write FZoomScaleSheetLayoutView; property ZoomScalePageLayoutView: integer read FZoomScalePageLayoutView write FZoomScalePageLayoutView; property WorkbookViewId: integer read FWorkbookViewId write FWorkbookViewId; property Pane: TXc12Pane read FPane; property Selection: TXc12Selections read FSelection; property PivotSelection: TXc12PivotSelections read FPivotSelection; property ZoomToFit: boolean read FZoomToFit write FZoomToFit; end; type TXc12SheetViews = class(TObjectList) private function GetItems(Index: integer): TXc12SheetView; protected public constructor Create; function Add: TXc12SheetView; property Items[Index: integer]: TXc12SheetView read GetItems; default; end; type TXc12CellSmartTagPr = class(TObject) protected FKey: AxUCString; FVal: AxUCString; public constructor Create; procedure Clear; property Key: AxUCString read FKey write FKey; property Val: AxUCString read FVal write FVal; end; type TXc12CellSmartTag = class(TObjectList) private function GetItems(Index: integer): TXc12CellSmartTagPr; protected FType_: integer; FDeleted: boolean; FXmlBased: boolean; public constructor Create; function Add: TXc12CellSmartTagPr; procedure Clear; override; property Type_: integer read FType_ write FType_; property Deleted: boolean read FDeleted write FDeleted; property XmlBased: boolean read FXmlBased write FXmlBased; property Items[Index: integer]: TXc12CellSmartTagPr read GetItems; default; end; type TXc12CellSmartTags = class(TObjectList) private function GetItems(Index: integer): TXc12CellSmartTag; protected FRef: TCellRef; public constructor Create; destructor Destroy; override; function Add: TXc12CellSmartTag; procedure Clear; override; property Ref: TCellRef read FRef write FRef; property Items[Index: integer]: TXc12CellSmartTag read GetItems; end; type TXc12SmartTags = class(TObjectList) private function GetItems(Index: integer): TXc12CellSmartTags; protected public constructor Create; function Add: TXc12CellSmartTags; property Items[Index: integer]: TXc12CellSmartTags read GetItems; default; end; type TXc12MergedCell = class(TCellArea) protected FRef: TXLSCellArea; function GetCol1: integer; override; function GetRow1: integer; override; function GetCol2: integer; override; function GetRow2: integer; override; procedure SetCol1(const AValue: integer); override; procedure SetRow1(const AValue: integer); override; procedure SetCol2(const AValue: integer); override; procedure SetRow2(const AValue: integer); override; public procedure Assign(const AItem: TXc12MergedCell); property Ref: TXLSCellArea read FRef write FRef; end; type TXc12MergedCells = class(TSolidCellAreas) private function GetItems(Index: integer): TXc12MergedCell; protected FClassFactory: TXLSClassFactory; function CreateObject: TCellArea; override; function CreateMember: TXc12MergedCell; public constructor Create(AClassFactory: TXLSClassFactory); function Add(const ARef: TXLSCellArea): TXc12MergedCell; overload; property Items[Index: integer]: TXc12MergedCell read GetItems; default; end; type TXc12Hyperlink = class(TCellArea) private procedure SetRawAddress(const Value: AxUCString); protected FHyperlinkType: TXLSHyperlinkType; FDisplay : AxUCString; FAddress : AxUCString; FLocation : AxUCString; FRef : TXLSCellArea; FTooltip : AxUCString; // Used by Excel 97 FTargetFrame : AxUCString; FScreenTip : AxUCString; FHyperlinkEnc : TXLSHyperlinkType; procedure Parse; virtual; public constructor Create; procedure Clear; property HyperlinkType: TXLSHyperlinkType read FHyperlinkType write FHyperlinkType; property Display : AxUCString read FDisplay write FDisplay; property RawAddress : AxUCString read FAddress write SetRawAddress; property Location : AxUCString read FLocation write FLocation; property Ref : TXLSCellArea read FRef write FRef; property Tooltip : AxUCString read FTooltip write FTooltip; property TargetFrame : AxUCString read FTargetFrame write FTargetFrame; property ScreenTip : AxUCString read FScreenTip write FScreenTip; property HyperlinkEnc : TXLSHyperlinkType read FHyperlinkEnc write FHyperlinkEnc; end; type TXc12Hyperlinks = class(TCellAreas) private function GetItems(Index: integer): TXc12Hyperlink; protected FClassFactory: TXLSClassFactory; function CreateMember: TXc12Hyperlink; public constructor Create(AClassFactory: TXLSClassFactory); function Add: TXc12Hyperlink; property Items[Index: integer]: TXc12Hyperlink read GetItems; default; end; type TXc12Column = class(TXc12Data) protected FMin: integer; FMax: integer; FWidth: double; FStyle: TXc12XF; FOutlineLevel: integer; FOptions: TXc12ColumnOptions; public constructor Create; destructor Destroy; override; procedure Clear; procedure Assign(ASource: TXc12Column); function Equal(ACol: TXc12Column): boolean; // Equal, except for position. function EqualProps(ACol: TXc12Column): boolean; function Hit(ACol: integer): TXc12ColumnHit; overload; function Hit(ACol1,ACol2: integer): TXc12ColumnHit; overload; property Min: integer read FMin write FMin; property Max: integer read FMax write FMax; property Width: double read FWidth write FWidth; property Style: TXc12XF read FStyle write FStyle; property OutlineLevel: integer read FOutlineLevel write FOutlineLevel; property Options: TXc12ColumnOptions read FOptions write FOptions; end; type TXc12Columns = class(TObjectList) private function GetItems(Index: integer): TXc12Column; protected public constructor Create; function Add: TXc12Column; overload; function Add(AStyle: TXc12XF): TXc12Column; overload; procedure Add(ACol: TXc12Column; AStyle: TXc12XF); overload; procedure NilAndDelete(AIndex: integer); property Items[Index: integer]: TXc12Column read GetItems; default; end; type TXc12WebPublishItem = class(TObject) protected FId: integer; FDivId: AxUCString; FSourceType: TXc12WebSourceType; FSourceRef: TCellRef; FSourceObject: AxUCString; FDestinationFile: AxUCString; FTitle: AxUCString; FAutoRepublish: boolean; public constructor Create; destructor Destroy; override; procedure Clear; property Id: integer read FId write FId; property DivId: AxUCString read FDivId write FDivId; property SourceType: TXc12WebSourceType read FSourceType write FSourceType; property SourceRef: TCellRef read FSourceRef write FSourceRef; property SourceObject: AxUCString read FSourceObject write FSourceObject; property DestinationFile: AxUCString read FDestinationFile write FDestinationFile; property Title: AxUCString read FTitle write FTitle; property AutoRepublish: boolean read FAutoRepublish write FAutoRepublish; end; type TXc12WebPublishItems = class(TObjectList) private function GetItems(Index: integer): TXc12WebPublishItem; protected public constructor Create; function Add: TXc12WebPublishItem; property Items[Index: integer]: TXc12WebPublishItem read GetItems; default; end; type TXc12Control = class(TObject) protected FShapeId: integer; FRId: TXc12RId; FName: AxUCString; public constructor Create; procedure Clear; property ShapeId: integer read FShapeId write FShapeId; property RId: TXc12RId read FRId write FRId; property Name: AxUCString read FName write FName; end; type TXc12Controls = class(TObjectList) private function GetItems(Index: integer): TXc12Control; protected public constructor Create; function Add: TXc12Control; property Items[Index: integer]: TXc12Control read GetItems; default; end; type TXc12OleObject = class(TObject) protected FProgId: AxUCString; FDvAspect: TXc12DvAspect; FLink: AxUCString; FOleUpdate: TXc12OleUpdate; FAutoLoad: boolean; FShapeId: integer; FRId: TXc12RId; public constructor Create; procedure Clear; property ProgId: AxUCString read FProgId write FProgId; property DvAspect: TXc12DvAspect read FDvAspect write FDvAspect; property Link: AxUCString read FLink write FLink; property OleUpdate: TXc12OleUpdate read FOleUpdate write FOleUpdate; property AutoLoad: boolean read FAutoLoad write FAutoLoad; property ShapeId: integer read FShapeId write FShapeId; property RId: TXc12RId read FRId write FRId; end; type TXc12OleObjects = class(TObjectList) private function GetItems(Index: integer): TXc12OleObject; protected public constructor Create; function Add: TXc12OleObject; property Items[Index: integer]: TXc12OleObject read GetItems; default; end; type TXc12IgnoredError = class(TObject) protected FSqref: TCellAreas; FEvalError: boolean; FTwoDigitTextYear: boolean; FNumberStoredAsText: boolean; FFormula: boolean; FFormulaRange: boolean; FUnlockedFormula: boolean; FEmptyCellReference: boolean; FListDataValidation: boolean; FCalculatedColumn: boolean; public constructor Create; destructor Destroy; override; procedure Clear; property Sqref: TCellAreas read FSqref; property EvalError: boolean read FEvalError write FEvalError; property TwoDigitTextYear: boolean read FTwoDigitTextYear write FTwoDigitTextYear; property NumberStoredAsText: boolean read FNumberStoredAsText write FNumberStoredAsText; property Formula: boolean read FFormula write FFormula; property FormulaRange: boolean read FFormulaRange write FFormulaRange; property UnlockedFormula: boolean read FUnlockedFormula write FUnlockedFormula; property EmptyCellReference: boolean read FEmptyCellReference write FEmptyCellReference; property ListDataValidation: boolean read FListDataValidation write FListDataValidation; property CalculatedColumn: boolean read FCalculatedColumn write FCalculatedColumn; end; type TXc12IgnoredErrors = class(TObjectList) private function GetItems(Index: integer): TXc12IgnoredError; protected public constructor Create; function Add: TXc12IgnoredError; property Items[Index: integer]: TXc12IgnoredError read GetItems; default; end; type TXc12CustomProperty = class(TObject) protected FName: AXUCString; FRId: AXUCString; public constructor Create; procedure Clear; property Name: AXUCString read FName write FName; property RId: AXUCString read FRId write FRId; end; type TXc12CustomProperties = class(TObjectList) private function GetItems(Index: integer): TXc12CustomProperty; protected public constructor Create; function Add: TXc12CustomProperty; property Items[Index: integer]: TXc12CustomProperty read GetItems; default; end; type TXc12DataValidation = class(TXLSMoveCopyItem) protected FType_: TXc12DataValidationType; FErrorStyle: TXc12DataValidationErrorStyle; FImeMode: TXc12DataValidationImeMode; FOperator_: TXc12DataValidationOperator; FAllowBlank: boolean; FShowDropDown: boolean; FShowInputMessage: boolean; FShowErrorMessage: boolean; FErrorTitle: AxUCString; FError: AxUCString; FPromptTitle: AxUCString; FPrompt: AxUCString; FSqref: TCellAreas; FFormula1: AxUCString; FFormula2: AxUCString; public constructor Create; destructor Destroy; override; procedure Clear; property Type_: TXc12DataValidationType read FType_ write FType_; property ErrorStyle: TXc12DataValidationErrorStyle read FErrorStyle write FErrorStyle; property ImeMode: TXc12DataValidationImeMode read FImeMode write FImeMode; property Operator_: TXc12DataValidationOperator read FOperator_ write FOperator_; property AllowBlank: boolean read FAllowBlank write FAllowBlank; property ShowDropDown: boolean read FShowDropDown write FShowDropDown; property ShowInputMessage: boolean read FShowInputMessage write FShowInputMessage; property ShowErrorMessage: boolean read FShowErrorMessage write FShowErrorMessage; property ErrorTitle: AxUCString read FErrorTitle write FErrorTitle; property Error: AxUCString read FError write FError; property PromptTitle: AxUCString read FPromptTitle write FPromptTitle; property Prompt: AxUCString read FPrompt write FPrompt; property Sqref: TCellAreas read FSqref write FSqref; property Formula1: AxUCString read FFormula1 write FFormula1; property Formula2: AxUCString read FFormula2 write FFormula2; end; type TXc12DataValidations = class(TXLSMoveCopyList) private function GetItems(Index: integer): TXc12DataValidation; protected FClassFactory: TXLSClassFactory; FDisablePrompts: boolean; FXWindow: integer; FYWindow: integer; function CreateMember: TXc12DataValidation; public constructor Create(AClassFactory: TXLSClassFactory); procedure Clear; override; function Add: TXLSMoveCopyItem; override; function AddDV: TXc12DataValidation; property DisablePrompts: boolean read FDisablePrompts write FDisablePrompts; property XWindow: integer read FXWindow write FXWindow; property YWindow: integer read FYWindow write FYWindow; property Items[Index: integer]: TXc12DataValidation read GetItems; default; end; type TXc12DataRef = class(TObject) protected FRef: TXLSCellArea; FName: AxUCString; FSheet: AxUCString; FRId: TXc12RId; public constructor Create; procedure Clear; property Ref: TXLSCellArea read FRef write FRef; property Name: AxUCString read FName write FName; property Sheet: AxUCString read FSheet write FSheet; property RId: TXc12RId read FRId write FRId; end; type TXc12DataRefs = class(TObjectList) private function GetItems(Index: integer): TXc12DataRef; protected public constructor Create; function Add: TXc12DataRef; property Items[Index: integer]: TXc12DataRef read GetItems; default; end; type TXc12InputCell = class(TObject) protected FRow: integer; FCol: integer; FDeleted: boolean; FUndone: boolean; FVal: AxUCString; FNumFmtId: integer; public constructor Create; procedure Clear; property Row: integer read FRow write FRow; property Col: integer read FCol write FCol; property Deleted: boolean read FDeleted write FDeleted; property Undone: boolean read FUndone write FUndone; property Val: AxUCString read FVal write FVal; property NumFmtId: integer read FNumFmtId write FNumFmtId; end; type Tx12InputCells = class(TObjectList) private function GetItems(Index: integer): TXc12InputCell; protected public constructor Create; function Add: TXc12InputCell; overload; function Add(ACellRef: AxUCString): TXc12InputCell; overload; property Items[Index: integer]: TXc12InputCell read GetItems; default; end; type TXc12Scenario = class(TObject) protected FName: AxUCString; FLocked: boolean; FHidden: boolean; FCount: integer; FUser: AxUCString; FComment: AxUCString; FInputCells: Tx12InputCells; public constructor Create; destructor Destroy; override; procedure Clear; property Name: AxUCString read FName write FName; property Locked: boolean read FLocked write FLocked; property Hidden: boolean read FHidden write FHidden; property Count: integer read FCount write FCount; property User: AxUCString read FUser write FUser; property Comment: AxUCString read FComment write FComment; property InputCells: Tx12InputCells read FInputCells; end; type TXc12Scenarios = class(TObjectList) private function GetItems(Index: integer): TXc12Scenario; protected FCurrent: integer; FShow: integer; FSqref: TCellAreas; public constructor Create; destructor Destroy; override; procedure Clear; override; function Add: TXc12Scenario; property Items[Index: integer]: TXc12Scenario read GetItems; default; property Current: integer read FCurrent write FCurrent; property Show: integer read FShow write FShow; property _Sqref: TCellAreas read FSqref; end; type TXc12ProtectedRange = class(TObject) protected FPassword: integer; FSqref: TCellAreas; FName: AxUCString; // Required FSecurityDescriptor: AxUCString; public constructor Create; destructor Destroy; override; procedure Clear; property Password: integer read FPassword write FPassword; property Sqref: TCellAreas read FSqref write FSqref; property Name: AxUCString read FName write FName; property SecurityDescriptor: AxUCString read FSecurityDescriptor write FSecurityDescriptor; end; type TXc12ProtectedRanges = class(TObjectList) private function GetItems(Index: integer): TXc12ProtectedRange; protected public constructor Create; function Add: TXc12ProtectedRange; property Items[Index: integer]: TXc12ProtectedRange read GetItems; default; end; type TXc12OutlinePr = class(TObject) protected FApplyStyles: boolean; FSummaryBelow: boolean; FSummaryRight: boolean; FShowOutlineSymbols: boolean; public constructor Create; procedure Clear; property ApplyStyles: boolean read FApplyStyles write FApplyStyles; property SummaryBelow: boolean read FSummaryBelow write FSummaryBelow; property SummaryRight: boolean read FSummaryRight write FSummaryRight; property ShowOutlineSymbols: boolean read FShowOutlineSymbols write FShowOutlineSymbols; end; type TXc12PageSetupPr = class(TObject) protected FAutoPageBreaks: boolean; FFitToPage: boolean; public constructor Create; procedure Clear; property AutoPageBreaks: boolean read FAutoPageBreaks write FAutoPageBreaks; property FitToPage: boolean read FFitToPage write FFitToPage; end; type TXc12SheetPr = class(TObject) protected FSyncHorizontal: boolean; FSyncVertical: boolean; FSyncRef: TXLSCellArea; FTransitionEvaluation: boolean; FTransitionEntry: boolean; FPublished_: boolean; FCodeName: AxUCString; FFilterMode: boolean; FEnableFormatConditionsCalculation: boolean; FTabColor: TXc12Color; FOutlinePr: TXc12OutlinePr; FPageSetupPr: TXc12PageSetupPr; public constructor Create; destructor Destroy; override; procedure Clear; property SyncHorizontal: boolean read FSyncHorizontal write FSyncHorizontal; property SyncVertical: boolean read FSyncVertical write FSyncVertical; property SyncRef: TXLSCellArea read FSyncRef write FSyncRef; property TransitionEvaluation: boolean read FTransitionEvaluation write FTransitionEvaluation; property TransitionEntry: boolean read FTransitionEntry write FTransitionEntry; property Published_: boolean read FPublished_ write FPublished_; property CodeName: AxUCString read FCodeName write FCodeName; property FilterMode: boolean read FFilterMode write FFilterMode; property EnableFormatConditionsCalculation: boolean read FEnableFormatConditionsCalculation write FEnableFormatConditionsCalculation; property TabColor: TXc12Color read FTabColor write FTabColor; property OutlinePr: TXc12OutlinePr read FOutlinePr; property PageSetupPr: TXc12PageSetupPr read FPageSetupPr; end; type TXc12SheetFormatPr = class(TObject) protected FBaseColWidth: integer; FDefaultColWidth: double; FDefaultRowHeight: double; FCustomHeight: boolean; FZeroHeight: boolean; FThickTop: boolean; FThickBottom: boolean; FOutlineLevelRow: integer; FOutlineLevelCol: integer; public constructor Create; procedure Clear; property BaseColWidth: integer read FBaseColWidth write FBaseColWidth; property DefaultColWidth: double read FDefaultColWidth write FDefaultColWidth; property DefaultRowHeight: double read FDefaultRowHeight write FDefaultRowHeight; property CustomHeight: boolean read FCustomHeight write FCustomHeight; property ZeroHeight: boolean read FZeroHeight write FZeroHeight; property ThickTop: boolean read FThickTop write FThickTop; property ThickBottom: boolean read FThickBottom write FThickBottom; property OutlineLevelRow: integer read FOutlineLevelRow write FOutlineLevelRow; property OutlineLevelCol: integer read FOutlineLevelCol write FOutlineLevelCol; end; type TXc12SheetCalcPr = class(TObject) protected FFullCalcOnLoad: boolean; public constructor Create; procedure Clear; property FullCalcOnLoad: boolean read FFullCalcOnLoad write FFullCalcOnLoad; end; type TXc12SheetProtection = class(TObject) private function GetPasswordAsString: AxUCString; procedure SetPasswordAsString(const Value: AxUCString); protected FPassword: word; FSheet: boolean; FObjects: boolean; FScenarios: boolean; FFormatCells: boolean; FFormatColumns: boolean; FFormatRows: boolean; FInsertColumns: boolean; FInsertRows: boolean; FInsertHyperlinks: boolean; FDeleteColumns: boolean; FDeleteRows: boolean; FSelectLockedCells: boolean; FSort: boolean; FAutoFilter: boolean; FPivotTables: boolean; FSelectUnlockedCells: boolean; public constructor Create; procedure Clear; property Password: word read FPassword write FPassword; property PasswordAsString: AxUCString read GetPasswordAsString write SetPasswordAsString; property Sheet: boolean read FSheet write FSheet; property Objects: boolean read FObjects write FObjects; property Scenarios: boolean read FScenarios write FScenarios; property FormatCells: boolean read FFormatCells write FFormatCells; property FormatColumns: boolean read FFormatColumns write FFormatColumns; property FormatRows: boolean read FFormatRows write FFormatRows; property InsertColumns: boolean read FInsertColumns write FInsertColumns; property InsertRows: boolean read FInsertRows write FInsertRows; property InsertHyperlinks: boolean read FInsertHyperlinks write FInsertHyperlinks; property DeleteColumns: boolean read FDeleteColumns write FDeleteColumns; property DeleteRows: boolean read FDeleteRows write FDeleteRows; property SelectLockedCells: boolean read FSelectLockedCells write FSelectLockedCells; property Sort: boolean read FSort write FSort; property AutoFilter: boolean read FAutoFilter write FAutoFilter; property PivotTables: boolean read FPivotTables write FPivotTables; property SelectUnlockedCells: boolean read FSelectUnlockedCells write FSelectUnlockedCells; end; type TXc12DataConsolidate = class(TObject) protected FFunction: TXc12DataConsolidateFunction; FLeftLabels: boolean; FTopLabels: boolean; FLink: boolean; FDataRefs: TXc12DataRefs; public constructor Create; destructor Destroy; override; procedure Clear; property Function_: TXc12DataConsolidateFunction read FFunction write FFunction; property LeftLabels: boolean read FLeftLabels write FLeftLabels; property TopLabels: boolean read FTopLabels write FTopLabels; property Link: boolean read FLink write FLink; property DataRefs: TXc12DataRefs read FDataRefs; end; type TXc12PhoneticPr = class(TObject) protected FFontId: integer; FType: TXc12PhoneticType; FAlignment: TXc12PhoneticAlignment; public constructor Create; procedure Clear; property FontId: integer read FFontId write FFontId; property Type_: TXc12PhoneticType read FType write FType; property Alignment: TXc12PhoneticAlignment read FAlignment write FAlignment; end; type TXc12DataWorksheet = class(TIndexObject) private function GetDimension: TXLSCellArea; procedure SetDimension(const Value: TXLSCellArea); function GetQuotedName: AxUCString; protected FClassFactory : TXLSClassFactory; FSST : TXc12DataSST; FStyles : TXc12DataStyleSheet; FCells : TXLSCellMMU; FColumns : TXc12Columns; FComments : TXc12Comments; FHyperlinks : TXc12Hyperlinks; FMergedCells : TXc12MergedCells; FAutofilter : TXc12AutoFilter; FCustomSheetViews : TXc12CustomSheetViews; FSheetViews : TXc12SheetViews; FPivotTables : TXLSPivotTables; FSheetPr : TXc12SheetPr; FSheetFormatPr : TXc12SheetFormatPr; FSheetCalcPr : TXc12SheetCalcPr; FSheetProtection : TXc12SheetProtection; FProtectedRanges : TXc12ProtectedRanges; FScenarios : TXc12Scenarios; FSortState : TXc12SortState; FDataConsolidate : TXc12DataConsolidate; FPhoneticPr : TXc12PhoneticPr; FConditionalFormatting: TXc12ConditionalFormattings; FDataValidations : TXc12DataValidations; FPrintOptions : TXc12PrintOptions; FPageMargins : TXc12PageMargins; FPageSetup : TXc12PageSetup; FHeaderFooter : TXc12HeaderFooter; FRowBreaks : TXc12PageBreaks; FColBreaks : TXc12PageBreaks; FCustomProperties : TXc12CustomProperties; FCellWatches : TCellRefs; FIgnoredErrors : TXc12IgnoredErrors; FSmartTags : TXc12SmartTags; FOleObjects : TXc12OleObjects; FControls : TXc12Controls; FWebPublishItems : TXc12WebPublishItems; FTables : TXc12Tables; FDrawing : TXPGDocXLSXDrawing; FVmlDrawing : TXpgSimpleDOM; // Originally in TXc12DataWorkbook.Sheets[x], but moved here. FName : AxUCString; FSheetId : integer; FState : TXc12Visibility; FRId : TXc12RId; FIsChartSheet : boolean; public constructor Create(AClassFactory: TXLSClassFactory; AIndex: integer; ASST: TXc12DataSST; AStyles: TXc12DataStyleSheet); destructor Destroy; override; procedure SetDefaultValues; procedure Clear; property Cells : TXLSCellMMU read FCells; property Columns : TXc12Columns read FColumns; property Comments : TXc12Comments read FComments; property Tables : TXc12Tables read FTables; property Hyperlinks : TXc12Hyperlinks read FHyperlinks; property MergedCells : TXc12MergedCells read FMergedCells; property Autofilter : TXc12AutoFilter read FAutofilter; property CustomSheetViews : TXc12CustomSheetViews read FCustomSheetViews; property SheetViews : TXc12SheetViews read FSheetViews; property PivotTables : TXLSPivotTables read FPivotTables; property SheetPr : TXc12SheetPr read FSheetPr; property Dimension : TXLSCellArea read GetDimension write SetDimension; property SheetFormatPr : TXc12SheetFormatPr read FSheetFormatPr; property SheetCalcPr : TXc12SheetCalcPr read FSheetCalcPr; property SheetProtection : TXc12SheetProtection read FSheetProtection; property ProtectedRanges : TXc12ProtectedRanges read FProtectedRanges; property Scenarios : TXc12Scenarios read FScenarios; property SortState : TXc12SortState read FSortState; property DataConsolidate : TXc12DataConsolidate read FDataConsolidate; property PhoneticPr : TXc12PhoneticPr read FPhoneticPr; property ConditionalFormatting: TXc12ConditionalFormattings read FConditionalFormatting; property DataValidations : TXc12DataValidations read FDataValidations; property PrintOptions : TXc12PrintOptions read FPrintOptions; property PageMargins : TXc12PageMargins read FPageMargins; property PageSetup : TXc12PageSetup read FPageSetup; property HeaderFooter : TXc12HeaderFooter read FHeaderFooter; property RowBreaks : TXc12PageBreaks read FRowBreaks; property ColBreaks : TXc12PageBreaks read FColBreaks; property CustomProperties : TXc12CustomProperties read FCustomProperties; property CellWatches : TCellRefs read FCellWatches; property IgnoredErrors : TXc12IgnoredErrors read FIgnoredErrors; property SmartTags : TXc12SmartTags read FSmartTags; property OleObjects : TXc12OleObjects read FOleObjects; property Controls : TXc12Controls read FControls; property WebPublishItems : TXc12WebPublishItems read FWebPublishItems; property Drawing : TXPGDocXLSXDrawing read FDrawing; property VmlDrawing : TXpgSimpleDOM read FVmlDrawing; property Name : AxUCString read FName write FName; // Returns the name quoted if the name contains other chars than letters and numbers, such as spaces. property QuotedName : AxUCString read GetQuotedName; // Don't use. It's only used for the display order of sheets. property _SheetId : integer read FSheetId write FSheetId; property State : TXc12Visibility read FState write FState; property RId : TXc12RId read FRId write FRId; property IsChartSheet : boolean read FIsChartSheet write FIsChartSheet; end; type TXc12DataWorksheets = class(TIndexObjectList) private function GetItems(Index: integer): TXc12DataWorksheet; protected FClassFactory: TXLSClassFactory; FSST : TXc12DataSST; FStyles : TXc12DataStyleSheet; public constructor Create(AClassFactory: TXLSClassFactory; ASST: TXc12DataSST; AStyles: TXc12DataStyleSheet); destructor Destroy; override; procedure Clear; reintroduce; function Add(const ASheetId: integer): TXc12DataWorksheet; function Insert(const AIndex: integer): TXc12DataWorksheet; function Find(const AName: AxUCString): integer; function FindSheetFromCells(const ACells: TXLSCellMMU): TXc12DataWorksheet; // property IdOrder[Index: integer]: TXc12DataWorksheet read GetIdOrder; property Items[Index: integer]: TXc12DataWorksheet read GetItems; default; end; implementation { TXc12DataWorksheet } procedure TXc12DataWorksheet.Clear; begin FCells.Clear; FColumns.Clear; FComments.Clear; FTables.Clear; FDrawing.WsDr.Clear; FVmlDrawing.Clear; FHyperlinks.Clear; FMergedCells.Clear; FAutofilter.Clear; FCustomSheetViews.Clear; FSheetViews.Clear; FPivotTables.Clear; FSheetPr.Clear; FSheetFormatPr.Clear; FSheetCalcPr.Clear; FSheetProtection.Clear; FProtectedRanges.Clear; FScenarios.Clear; FSortState.Clear; FDataConsolidate.Clear; FPhoneticPr.Clear; FConditionalFormatting.Clear; FDataValidations.Clear; FPrintOptions.Clear; FPageMargins.Clear; FPageSetup.Clear; FHeaderFooter.Clear; FRowBreaks.Clear; FColBreaks.Clear; FCustomProperties.Clear; FCellWatches.Clear; FIgnoredErrors.Clear; FSmartTags.Clear; FOleObjects.Clear; FControls.Clear; FWebPublishItems.Clear; SetDefaultValues; end; constructor TXc12DataWorksheet.Create(AClassFactory: TXLSClassFactory; AIndex: integer; ASST: TXc12DataSST; AStyles: TXc12DataStyleSheet); begin FClassFactory := AClassFactory; FIndex := AIndex; FSST := ASST; FStyles := AStyles; FCells := TXLSCellMMU.Create(FIndex,Nil,FSST,FStyles); FColumns := TXc12Columns.Create; FComments := TXc12Comments.Create(AStyles); FTables := TXc12Tables.Create(FClassFactory); FDrawing := TXPGDocXLSXDrawing(FClassFactory.CreateAClass(xcftDrawing)); FVmlDrawing := TXpgSimpleDOM.Create; FHyperlinks := TXc12Hyperlinks(FClassFactory.CreateAClass(xcftHyperlinks)); FMergedCells := TXc12MergedCells(FClassFactory.CreateAClass(xcftMergedCells)); FAutofilter := TXc12AutoFilter(FClassFactory.CreateAClass(xcftAutofilter,Self)); FCustomSheetViews := TXc12CustomSheetViews.Create(FClassFactory); FSheetViews := TXc12SheetViews.Create; FPivotTables := TXLSPivotTables.Create; FSheetPr := TXc12SheetPr.Create; FSheetFormatPr := TXc12SheetFormatPr.Create; FSheetCalcPr := TXc12SheetCalcPr.Create; FSheetProtection := TXc12SheetProtection.Create; FProtectedRanges := TXc12ProtectedRanges.Create; FScenarios := TXc12Scenarios.Create; FSortState := TXc12SortState.Create; FDataConsolidate := TXc12DataConsolidate.Create; FPhoneticPr := TXc12PhoneticPr.Create; FConditionalFormatting := TXc12ConditionalFormattings(FClassFactory.CreateAClass(xcftConditionalFormats)); FConditionalFormatting.Xc12Sheet := Self; FDataValidations := TXc12DataValidations(FClassFactory.CreateAClass(xcftDataValidations)); FPrintOptions := TXc12PrintOptions.Create; FPageMargins := TXc12PageMargins.Create; FPageSetup := TXc12PageSetup.Create; FHeaderFooter := TXc12HeaderFooter.Create; FRowBreaks := TXc12PageBreaks.Create; FColBreaks := TXc12PageBreaks.Create; FCustomProperties := TXc12CustomProperties.Create; FCellWatches := TCellRefs.Create; FIgnoredErrors := TXc12IgnoredErrors.Create; FSmartTags := TXc12SmartTags.Create; FOleObjects := TXc12OleObjects.Create; FControls := TXc12Controls.Create; FWebPublishItems := TXc12WebPublishItems.Create; SetDefaultValues; end; destructor TXc12DataWorksheet.Destroy; begin FCells.Free; FColumns.Free; FComments.Free; FTables.Free; FDrawing.Free; FVmlDrawing.Free; FHyperlinks.Free; FMergedCells.Free; FAutofilter.Free; FCustomSheetViews.Free; FSheetViews.Free; FPivotTables.Free; FSheetPr.Free; FSheetFormatPr.Free; FSheetCalcPr.Free; FSheetProtection.Free; FProtectedRanges.Free; FScenarios.Free; FSortState.Free; FDataConsolidate.Free; FPhoneticPr.Free; FConditionalFormatting.Free; FDataValidations.Free; FPrintOptions.Free; FPageMargins.Free; FPageSetup.Free; FHeaderFooter.Free; FRowBreaks.Free; FColBreaks.Free; FCustomProperties.Free; FCellWatches.Free; FIgnoredErrors.Free; FSmartTags.Free; FOleObjects.Free; FControls.Free; FWebPublishItems.Free; inherited; end; function TXc12DataWorksheet.GetDimension: TXLSCellArea; begin Result := FCells.Dimension; end; function TXc12DataWorksheet.GetQuotedName: AxUCString; var i: integer; begin for i := 1 to Length(FName) do begin if not CharInSet(FName[i],['a'..'z','A'..'Z','0'..'9']) then begin Result := '''' + FName + ''''; Exit; end; end; Result := FName; end; procedure TXc12DataWorksheet.SetDefaultValues; begin FSheetViews.Add; end; procedure TXc12DataWorksheet.SetDimension(const Value: TXLSCellArea); begin FCells.Dimension := Value; end; { TXc12DataWorksheets } function TXc12DataWorksheets.Add(const ASheetId: integer): TXc12DataWorksheet; begin Result := TXc12DataWorksheet.Create(FClassFactory,Count,FSST,FStyles); if ASheetId < 0 then Result._SheetId := Count + 1 else Result._SheetId := ASheetId; inherited Add(Result); end; procedure TXc12DataWorksheets.Clear; begin inherited Clear; FSST.Clear; FStyles.Clear; end; constructor TXc12DataWorksheets.Create(AClassFactory: TXLSClassFactory; ASST: TXc12DataSST; AStyles: TXc12DataStyleSheet); begin FClassFactory := AClassFactory; FSST := ASST; FStyles := AStyles; inherited Create; end; destructor TXc12DataWorksheets.Destroy; begin inherited; end; function TXc12DataWorksheets.Find(const AName: AxUCString): integer; var S: AxUCString; begin S := AnsiUppercase(AName); for Result := 0 to Count - 1 do begin if S = AnsiUppercase(Items[Result].Name) then Exit; end; Result := -1; end; function TXc12DataWorksheets.FindSheetFromCells(const ACells: TXLSCellMMU): TXc12DataWorksheet; var i: integer; begin for i := 0 to Count - 1 do begin if Items[i].FCells = ACells then begin Result := Items[i]; Exit; end; end; Result := Nil; end; function TXc12DataWorksheets.GetItems(Index: integer): TXc12DataWorksheet; begin Result := TXc12DataWorksheet(inherited Items[Index]); end; function TXc12DataWorksheets.Insert(const AIndex: integer): TXc12DataWorksheet; begin Result := TXc12DataWorksheet.Create(FClassFactory,Count,FSST,FStyles); Result._SheetId := Count + 1; inherited Insert(AIndex,Result); ReIndex; end; { TXc12Column } procedure TXc12Column.Assign(ASource: TXc12Column); begin FMin := ASource.FMin; FMax := ASource.FMax; FWidth := ASource.FWidth; FStyle := ASource.FStyle; FOutlineLevel := ASource.FOutlineLevel; FOptions := ASource.FOptions; end; procedure TXc12Column.Clear; begin FMin := 0; FMax := 0; FWidth := 0; FStyle := Nil; FOutlineLevel := 0; FOptions := []; end; constructor TXc12Column.Create; begin Clear; end; destructor TXc12Column.Destroy; begin FStyle := Nil; inherited; end; function TXc12Column.Equal(ACol: TXc12Column): boolean; begin Result := (FMin = ACol.FMin) and (FMax = ACol.FMax) and (FWidth = ACol.FWidth) and (FStyle = ACol.FStyle) and (FOutlineLevel = ACol.FOutlineLevel) and (FOptions = ACol.FOptions); end; function TXc12Column.EqualProps(ACol: TXc12Column): boolean; begin Result := (FWidth = ACol.FWidth) and (FStyle = ACol.FStyle) and (FOutlineLevel = ACol.FOutlineLevel) and (FOptions = ACol.FOptions); end; function TXc12Column.Hit(ACol1, ACol2: integer): TXc12ColumnHit; begin if (ACol1 < FMin) and (ACol2 < FMin) then Result := xchLess else if (ACol1 < FMin) and (ACol2 >= FMin) and (ACol2 <= FMax) then Result := xchCol2 else if (ACol1 = FMin) and (ACol2 = FMax) then Result := xchMatch else if (ACol1 = FMin) and (ACol2 >= FMin) and (ACol2 <= FMax) then Result := xchCol1Match else if (ACol1 < FMin) and (ACol2 > FMax) then Result := xchTargetInside else if (ACol1 >= FMin) and (ACol1 <= FMax) and (ACol2 = FMax) then Result := xchCol2Match else if (ACol1 >= FMin) and (ACol1 <= FMax) and (ACol2 >= FMin) and (ACol2 <= FMax) then Result := xchInside else if (ACol1 >= FMin) and (ACol1 <= FMax) and (ACol2 > FMax) then Result := xchCol1 else if (ACol1 > FMax) and (ACol2 > FMax)then Result := xchGreater else raise Exception.Create('Column hit error'); end; function TXc12Column.Hit(ACol: integer): TXc12ColumnHit; begin if ACol < FMin then Result := xchLess else if (ACol >= FMin) and (ACol <= FMax) then Result := xchInside else Result := xchGreater; end; { TXc12Columns } function TXc12Columns.Add(AStyle: TXc12XF): TXc12Column; begin Result := TXc12Column.Create; Result.Clear; Result.FStyle := AStyle; inherited Add(Result); end; procedure TXc12Columns.Add(ACol: TXc12Column; AStyle: TXc12XF); begin ACol.FStyle := AStyle; inherited Add(ACol); end; function TXc12Columns.Add: TXc12Column; begin Result := TXc12Column.Create; Result.Clear; inherited Add(Result); end; constructor TXc12Columns.Create; begin inherited Create; end; function TXc12Columns.GetItems(Index: integer): TXc12Column; begin Result := TXc12Column(inherited Items[Index]); end; procedure TXc12Columns.NilAndDelete(AIndex: integer); var C: TXc12Column; begin C := Items[AIndex]; C.Free; // Prevent the list from deleting the object. List[AIndex] := Nil; end; { TXc12Hyperlink } procedure TXc12Hyperlink.Clear; begin FHyperlinkType := xhltUnknown; FDisplay := ''; FAddress := ''; FLocation:= ''; ClearCellArea(FRef); FTooltip := ''; end; constructor TXc12Hyperlink.Create; begin Clear; end; procedure TXc12Hyperlink.Parse; begin end; procedure TXc12Hyperlink.SetRawAddress(const Value: AxUCString); begin FAddress := Value; Parse; end; { TXc12Hyperlinks } function TXc12Hyperlinks.Add: TXc12Hyperlink; begin Result := CreateMember; Result.Clear; inherited Add(Result); end; constructor TXc12Hyperlinks.Create(AClassFactory: TXLSClassFactory); begin inherited Create; FClassFactory := AClassFactory; end; function TXc12Hyperlinks.CreateMember: TXc12Hyperlink; begin Result := TXc12Hyperlink(FClassFactory.CreateAClass(xcftHyperlinksMember,Self)); end; function TXc12Hyperlinks.GetItems(Index: integer): TXc12Hyperlink; begin Result := TXc12Hyperlink(inherited Items[Index]); end; { TXc12Colors } procedure TXc12Colors.Add(AColor: TXc12Color); var P: PXc12Color; begin GetMem(P,SizeOf(TXc12Color)); System.Move(AColor,P^,SizeOf(TXc12Color)); inherited Add(P); end; procedure TXc12Colors.Add(ARGB: longword); var C: TXc12Color; begin C.ColorType := exctRgb; C.Tint := 0; C.OrigRGB := ARGB; Add(C); end; destructor TXc12Colors.Destroy; var i: integer; begin for i := 0 to Count - 1 do FreeMem(inherited Items[i]); end; function TXc12Colors.GetItems(Index: integer): TXc12Color; var P: PXc12Color; begin P := (inherited Items[Index]); System.Move(P^,Result,SizeOf(TXc12Color)); end; { TXc12Cfvo } procedure TXc12Cfvo.Clear; begin FType := x12ctNum; FVal := ''; FGte := True; end; procedure TXc12Cfvo.Clear(AType: TXc12CfvoType; AVal: AxUCString; AGte: boolean); begin FType := AType; FVal := AVal; FGte := AGte; end; constructor TXc12Cfvo.Create; begin Clear; end; destructor TXc12Cfvo.Destroy; begin if FPtgs <> Nil then FreeMem(FPtgs); inherited; end; function TXc12Cfvo.GetAsFloat: double; begin Result := XmlStrToFloatDef(FVal,0); end; function TXc12Cfvo.GetAsPercent: double; begin Result := XmlStrToFloatDef(FVal,0) / 100; end; procedure TXc12Cfvo.SetAsFloat(const Value: double); begin FVal := XmlFloatToStr(Value); end; { TXc12Cfvos } function TXc12Cfvos.Add(AType: TXc12CfvoType; const AVal: AxUCString; AGte: boolean): TXc12Cfvo; begin Result := TXc12Cfvo.Create; Result.Clear(AType,AVal,AGte); inherited Add(Result); end; function TXc12Cfvos.Add: TXc12Cfvo; begin Result := TXc12Cfvo.Create; inherited Add(Result); end; constructor TXc12Cfvos.Create; begin inherited Create; end; function TXc12Cfvos.GetItems(Index: integer): TXc12Cfvo; begin Result := TXc12Cfvo(inherited Items[Index]); end; { TXc12IconSet } procedure TXc12IconSet.Clear; begin FIconSet := x12ist3TrafficLights1; FShowValue := True; FPercent := True; FReverse := False; end; constructor TXc12IconSet.Create; begin FCfvos := TXc12Cfvos.Create; Clear; end; destructor TXc12IconSet.Destroy; begin FCfvos.Free; inherited; end; { TXc12DataBar } procedure TXc12DataBar.Clear; begin FMinLength := 10; FMaxLength := 90; FShowValue := True; FColor.ColorType := exctUnassigned; FCfvo1.Clear; FCfvo2.Clear; end; constructor TXc12DataBar.Create; begin FCfvo1 := TXc12Cfvo.Create; FCfvo2 := TXc12Cfvo.Create; Clear; end; destructor TXc12DataBar.Destroy; begin FCfvo1.Free; FCfvo2.Free; inherited; end; { TXc12ColorScale } procedure TXc12ColorScale.Clear; begin FCfvos.Clear; FColors.Clear; end; constructor TXc12ColorScale.Create; begin FCfvos := TXc12Cfvos.Create; FColors := TXc12Colors.Create; Clear; end; destructor TXc12ColorScale.Destroy; begin FCfvos.Free; FColors.Free; inherited; end; { TXc12CfRule } procedure TXc12CfRule.Clear; begin FType_ := TXc12CfType(XPG_UNKNOWN_ENUM); FDXF := Nil; FPriority := 0; FStopIfTrue := False; FAboveAverage := True; FPercent := False; FBottom := False; FOperator := TXc12ConditionalFormattingOperator(XPG_UNKNOWN_ENUM); FText := ''; FTimePeriod := TXc12TimePeriod(XPG_UNKNOWN_ENUM); FRank := 0; FStdDev := 0; FEqualAverage := False; FColorScale.Clear; FDataBar.Clear; FIconSet.Clear; end; constructor TXc12CfRule.Create; begin FColorScale := TXc12ColorScale.Create; FDataBar := TXc12DataBar.Create; FIconSet := TXc12IconSet.Create; Clear; end; destructor TXc12CfRule.Destroy; var i: integer; begin FColorScale.Free; FDataBar.Free; FIconSet.Free; for i := 0 to High(FPtgs) do begin if FPtgs[i] <> Nil then FreeMem(FPtgs[i]); end; inherited; end; function TXc12CfRule.FormulaMaxCount: integer; begin Result := Length(FFormula); end; function TXc12CfRule.GetFormulas(Index: integer): AxUCString; begin if (Index < 0) or (Index > High(FFormula)) then raise Exception.Create('Index out of range'); Result := FFormula[Index]; end; function TXc12CfRule.GetPtgs(Index: integer): PXLSPtgs; begin if (Index < 0) or (Index > High(FFormula)) then raise Exception.Create('Index out of range'); Result := FPtgs[Index]; end; function TXc12CfRule.GetPtgsSz(Index: integer): integer; begin if (Index < 0) or (Index > High(FFormula)) then raise Exception.Create('Index out of range'); Result := FPtgsSz[Index]; end; function TXc12CfRule.GetValues(Index: integer): double; begin Result := FValues[Index]; end; function TXc12CfRule.GetValuesCount: integer; begin Result := Length(FValues); end; procedure TXc12CfRule.SerFormulas(Index: integer; const Value: AxUCString); begin if (Index < 0) or (Index > High(FFormula)) then raise Exception.Create('Index out of range'); FFormula[Index] := Value; if FPtgs[Index] <> Nil then FreeMem(FPtgs[Index]); end; procedure TXc12CfRule.SetPtgs(Index: integer; const Value: PXLSPtgs); begin if (Index < 0) or (Index > High(FFormula)) then raise Exception.Create('Index out of range'); FPtgs[Index] := Value; end; procedure TXc12CfRule.SetPtgsSz(Index: integer; const Value: integer); begin if (Index < 0) or (Index > High(FFormula)) then raise Exception.Create('Index out of range'); FPtgsSz[Index] := Value; end; procedure TXc12CfRule.SetValues(Index: integer; const Value: double); begin FValues[Index] := Value; end; procedure TXc12CfRule.SetValuesCount(const Value: integer); begin SetLength(FValues,Value); end; procedure TXc12CfRule.SortValues; begin SortDoubleArray(FValues); end; { TXc12CfRules } function TXc12CfRules.Add: TXc12CfRule; begin Result := TXc12CfRule.Create; inherited Add(Result); end; constructor TXc12CfRules.Create; begin inherited Create; end; function TXc12CfRules.GetItems(Index: integer): TXc12CfRule; begin Result := TXc12CfRule(inherited Items[Index]); end; { TXc12ConditionalFormatting } procedure TXc12ConditionalFormatting.Clear; begin FSQRef.Clear; FCfRules.Clear; end; constructor TXc12ConditionalFormatting.Create; begin FSQRef := TCellAreas.Create; FCfRules := TXc12CfRules.Create; Clear; end; destructor TXc12ConditionalFormatting.Destroy; begin FSQRef.Free; FCfRules.Free; inherited; end; { TXc12ConditionalFormattings } function TXc12ConditionalFormattings.Add: TXLSMoveCopyItem; begin Result := CreateMember; inherited Add(Result); end; function TXc12ConditionalFormattings.AddCF: TXc12ConditionalFormatting; begin Result := TXc12ConditionalFormatting(Add); end; constructor TXc12ConditionalFormattings.Create(AClassFactory: TXLSClassFactory); begin inherited Create; FClassFactory := AClassFactory; end; function TXc12ConditionalFormattings.GetItems(Index: integer): TXc12ConditionalFormatting; begin Result := TXc12ConditionalFormatting(inherited Items[Index]); end; { TXc12HeaderFooter } procedure TXc12HeaderFooter.Clear; begin FDifferentOddEven := False; FDifferentFirst := False; FScaleWithDoc := True; FAlignWithMargins := True; FOddHeader := ''; FOddFooter := ''; FEvenHeader := ''; FEvenFooter := ''; FFirstHeader := ''; FFirstFooter := ''; end; constructor TXc12HeaderFooter.Create; begin Clear; end; { TXc12PageSetup } procedure TXc12PageSetup.Clear; begin FPaperSize := 0; FScale := 100; FFirstPageNumber := 1; FFitToWidth := 1; FFitToHeight := 1; FPageOrder := x12poDownThenOver; FOrientation := x12oDefault; FUsePrinterDefaults := True; FBlackAndWhite := False; FDraft := False; FCellComments := x12ccNone; FUseFirstPageNumber := False; FErrors := x12peDisplayed; FHorizontalDpi := 600; FVerticalDpi := 600; FCopies := 1; if FPrinterSettings <> Nil then FPrinterSettings.Free; FPrinterSettings := Nil; end; constructor TXc12PageSetup.Create; begin Clear; end; destructor TXc12PageSetup.Destroy; begin if FPrinterSettings <> Nil then FPrinterSettings.Free; inherited; end; procedure TXc12PageSetup.SetPrinterSettings(const Value: TStream); begin if FPrinterSettings <> Nil then FPrinterSettings.Free; FPrinterSettings := TMemoryStream.Create; FPrinterSettings.CopyFrom(Value,Value.Size); Value.Free; end; { TXc12PrintOptions } procedure TXc12PrintOptions.Clear; begin FHorizontalCentered := False; FVerticalCentered := False; FHeadings := False; FGridLines := False; FGridLinesSet := True; end; constructor TXc12PrintOptions.Create; begin Clear; end; { TXc12PageMargins } procedure TXc12PageMargins.Clear; begin FLeft := 0.70; FRight := 0.70; FTop := 0.75; FBottom := 0.75; FHeader := 0.30; FFooter := 0.30; end; constructor TXc12PageMargins.Create; begin Clear; end; { TXc12Break } procedure TXc12Break.Clear; begin FId := 0; FMin := 0; FMax := 0; FMan := False; FPt := False; end; constructor TXc12Break.Create; begin Clear; end; { TXc12PageBreaks } function TXc12PageBreaks.Add: TXc12Break; begin Result := TXc12Break.Create; inherited Add(Result); end; procedure TXc12PageBreaks.Clear; begin inherited Clear; end; constructor TXc12PageBreaks.Create; begin inherited Create; end; function TXc12PageBreaks.Find(const AId: integer): integer; begin for Result := 0 to Count - 1 do begin if Items[Result].Id = AId then Exit; end; Result := -1; end; function TXc12PageBreaks.GetItems(Index: integer): TXc12Break; begin Result := TXc12Break(inherited Items[Index]); end; function TXc12PageBreaks.Hits(const AId: integer): integer; var i: integer; begin Result := 0; for i := 0 to Count - 1 do begin if (AId >= Items[i].Min) and (AId <= Items[i].Max) then Inc(Result); end; end; { TXc12Selection } procedure TXc12Selection.Clear; begin FPane := x12pTopLeft; SetCellArea(FActiveCell,0,0); FActiveCellId := 0; FSQRef.Clear; FSQRef.Add(0,0); end; constructor TXc12Selection.Create; begin FSQRef := TCellAreas.Create; Clear; end; destructor TXc12Selection.Destroy; begin FSQRef.Free; inherited; end; { TXc12Selections } function TXc12Selections.Add: TXc12Selection; begin Result := TXc12Selection.Create; inherited Add(Result); end; constructor TXc12Selections.Create; begin inherited Create; end; function TXc12Selections.GetItems(Index: integer): TXc12Selection; begin Result := TXc12Selection(inherited Items[Index]); end; { TXc12Pane } procedure TXc12Pane.Clear; begin FXSplit := 0; FYSplit := 0; ClearCellArea(FTopLeftCell); FActivePane := x12pTopLeft; FState := x12psSplit; FExcel97 := False; end; constructor TXc12Pane.Create; begin Clear; end; { TXc12CustomSheetView } procedure TXc12CustomSheetView.Clear; begin {$ifdef D2006PLUS} FGUID.Empty; {$else} FillChar(FGUID, Sizeof(TGUID), 0); {$endif} FScale := 100; FColorId := 64; FShowPageBreaks := False; FShowFormulas := False; FShowGridLines := True; FShowRowCol := True; FOutlineSymbols := True; FZeroValues := True; FFitToPage := False; FPrintArea := False; FFilter := False; FShowAutoFilter := False; FHiddenRows := False; FHiddenColumns := False; FState := x12ssVisible; FFilterUnique := False; FView := x12svtNormal; FShowRuler := True; ClearCellArea(FTopLeftCell); FPane.Clear; FSelection.Clear; FRowBreaks.Clear; FColBreaks.Clear; FPageMargins.Clear; FPrintOptions.Clear; FPageSetup.Clear; FHeaderFooter.Clear; FAutoFilter.Clear; end; constructor TXc12CustomSheetView.Create(AClassFactory: TXLSClassFactory); begin FClassFactory := AClassFactory; FPane := TXc12Pane.Create; FSelection := TXc12Selection.Create; FRowBreaks := TXc12PageBreaks.Create; FColBreaks := TXc12PageBreaks.Create; FPageMargins := TXc12PageMargins.Create; FPrintOptions := TXc12PrintOptions.Create; FPageSetup := TXc12PageSetup.Create; FHeaderFooter := TXc12HeaderFooter.Create; FAutoFilter := TXc12AutoFilter.Create(FClassFactory); Clear; end; destructor TXc12CustomSheetView.Destroy; begin FPane.Free; FSelection.Free; FRowBreaks.Free; FColBreaks.Free; FPageMargins.Free; FPrintOptions.Free; FPageSetup.Free; FHeaderFooter.Free; FAutoFilter.Free; inherited; end; { TXc12CustomSheetViews } function TXc12CustomSheetViews.Add: TXc12CustomSheetView; begin Result := TXc12CustomSheetView.Create(FClassFactory); inherited Add(Result); end; constructor TXc12CustomSheetViews.Create(AClassFactory: TXLSClassFactory); begin inherited Create; FClassFactory := AClassFactory; end; function TXc12CustomSheetViews.GetItems(Index: integer): TXc12CustomSheetView; begin Result := TXc12CustomSheetView(inherited Items[Index]); end; { TXc12PivotSelection } procedure TXc12PivotSelection.Clear; begin FPane := x12pTopLeft; FShowHeader := False; FLabel_ := False; FData := False; FExtendable := False; FAxis := x12aUnknown; FDimension := 0; FStart := 0; FMin := 0; FMax := 0; FActiveRow := 0; FActiveCol := 0; FPreviousRow := 0; FPreviousCol := 0; FClick := 0; FRId := ''; FPivotArea.Clear; end; constructor TXc12PivotSelection.Create; begin FPivotArea := TXc12PivotArea.Create; Clear; end; destructor TXc12PivotSelection.Destroy; begin FPivotArea.Free; inherited; end; { TXc12PivotArea } constructor TXc12PivotArea.Create; begin FReferences := TXc12PivotAreaReferences.Create; Clear; end; destructor TXc12PivotArea.Destroy; begin FReferences.Free; inherited; end; procedure TXc12PivotArea.Clear; begin FField := 0; FType_ := x12patNormal; FDataOnly := True; FLabelOnly := False; FGrandRow := False; FGrandCol := False; FCacheIndex := False; FOutline := True; ClearCellArea(FOffset); FCollapsedLevelsAreSubtotals := False; FAxis := x12aUnknown; FFieldPosition := 0; FReferences.Clear; end; { TXc12PivotAreaReference } procedure TXc12PivotAreaReference.Clear; begin FField := 0; FSelected := True; FByPosition := False; FRelative := False; FDefaultSubtotal := False; FSumSubtotal := False; FCountASubtotal := False; FAvgSubtotal := False; FMaxSubtotal := False; FMinSubtotal := False; FProductSubtotal := False; FCountSubtotal := False; FStdDevSubtotal := False; FStdDevPSubtotal := False; FVarSubtotal := False; FVarPSubtotal := False; FValues.Clear; end; constructor TXc12PivotAreaReference.Create; begin FValues := TIntegerList.Create; Clear; end; destructor TXc12PivotAreaReference.Destroy; begin FValues.Free; inherited; end; { TXc12PivotAreaReferences } function TXc12PivotAreaReferences.Add: TXc12PivotAreaReference; begin Result := TXc12PivotAreaReference.Create; inherited Add(Result); end; constructor TXc12PivotAreaReferences.Create; begin inherited Create; end; function TXc12PivotAreaReferences.GetItems(Index: integer): TXc12PivotAreaReference; begin Result := TXc12PivotAreaReference(inherited Items[Index]); end; { TXc12PivotSelections } function TXc12PivotSelections.Add: TXc12PivotSelection; begin Result := TXc12PivotSelection.Create; inherited Add(Result); end; constructor TXc12PivotSelections.Create; begin inherited Create; end; destructor TXc12PivotSelections.Destroy; begin inherited; end; function TXc12PivotSelections.GetItems(Index: integer): TXc12PivotSelection; begin Result := TXc12PivotSelection(inherited Items[Index]); end; { TXc12SheetView } procedure TXc12SheetView.Clear; begin FWindowProtection := False; FShowFormulas := False; FShowGridLines := True; FShowRowColHeaders := True; FShowZeros := True; FRightToLeft := False; FTabSelected := False; FShowRuler := True; FShowOutlineSymbols := True; FDefaultGridColor := True; FShowWhiteSpace := True; FView := x12svtNormal; ClearCellArea(FTopLeftCell); FColorId := 64; FZoomScale := 100; FZoomScaleNormal := 0; FZoomScaleSheetLayoutView := 0; FZoomScalePageLayoutView := 0; FWorkbookViewId := 0; FPane.Clear; FSelection.Clear; FPivotSelection.Clear; end; constructor TXc12SheetView.Create; begin FPane := TXc12Pane.Create; FSelection := TXc12Selections.Create; FPivotSelection := TXc12PivotSelections.Create; Clear; end; destructor TXc12SheetView.Destroy; begin FPane.Free; FSelection.Free; FPivotSelection.Free; inherited; end; { TXc12SheetViews } function TXc12SheetViews.Add: TXc12SheetView; begin Result := TXc12SheetView.Create; inherited Add(Result); end; constructor TXc12SheetViews.Create; begin inherited Create; end; function TXc12SheetViews.GetItems(Index: integer): TXc12SheetView; begin Result := TXc12SheetView(inherited Items[Index]); end; { TXc12CellSmartTagPr } procedure TXc12CellSmartTagPr.Clear; begin FKey := ''; FVal := ''; end; constructor TXc12CellSmartTagPr.Create; begin Clear; end; { TXc12CellSmartTag } function TXc12CellSmartTag.Add: TXc12CellSmartTagPr; begin Result := TXc12CellSmartTagPr.Create; inherited Add(Result); end; procedure TXc12CellSmartTag.Clear; begin inherited Clear; FType_ := 0; FDeleted := False; FXmlBased := False; end; constructor TXc12CellSmartTag.Create; begin inherited Create; end; function TXc12CellSmartTag.GetItems(Index: integer): TXc12CellSmartTagPr; begin Result := TXc12CellSmartTagPr(inherited Items[Index]); end; { TXc12CellSmartTags } function TXc12CellSmartTags.Add: TXc12CellSmartTag; begin Result := TXc12CellSmartTag.Create; inherited Add(Result); end; procedure TXc12CellSmartTags.Clear; begin inherited Clear; FRef.Clear; end; constructor TXc12CellSmartTags.Create; begin inherited Create; FRef := TCellRef.Create; end; destructor TXc12CellSmartTags.Destroy; begin FRef.Free; inherited; end; function TXc12CellSmartTags.GetItems(Index: integer): TXc12CellSmartTag; begin Result := TXc12CellSmartTag(inherited Items[Index]); end; { TXc12SmartTags } function TXc12SmartTags.Add: TXc12CellSmartTags; begin Result := TXc12CellSmartTags.Create; inherited Add(Result); end; constructor TXc12SmartTags.Create; begin inherited Create; end; function TXc12SmartTags.GetItems(Index: integer): TXc12CellSmartTags; begin Result := TXc12CellSmartTags(inherited Items[Index]); end; { TXc12WebPublishItems } function TXc12WebPublishItems.Add: TXc12WebPublishItem; begin Result := TXc12WebPublishItem.Create; inherited Add(Result); end; constructor TXc12WebPublishItems.Create; begin inherited Create; end; function TXc12WebPublishItems.GetItems(Index: integer): TXc12WebPublishItem; begin Result := TXc12WebPublishItem(inherited Items[Index]); end; { TXc12Controls } function TXc12Controls.Add: TXc12Control; begin Result := TXc12Control.Create; inherited Add(Result); end; constructor TXc12Controls.Create; begin inherited Create; end; function TXc12Controls.GetItems(Index: integer): TXc12Control; begin Result := TXc12Control(inherited Items[Index]); end; { TXc12OleObjects } function TXc12OleObjects.Add: TXc12OleObject; begin Result := TXc12OleObject.Create; inherited Add(Result); end; constructor TXc12OleObjects.Create; begin inherited Create; end; function TXc12OleObjects.GetItems(Index: integer): TXc12OleObject; begin Result := TXc12OleObject(inherited Items[Index]); end; { TXc12IgnoredErrors } function TXc12IgnoredErrors.Add: TXc12IgnoredError; begin Result := TXc12IgnoredError.Create; inherited Add(Result); end; constructor TXc12IgnoredErrors.Create; begin inherited Create; end; function TXc12IgnoredErrors.GetItems(Index: integer): TXc12IgnoredError; begin Result := TXc12IgnoredError(inherited Items[Index]); end; { TXc12WebPublishItem } procedure TXc12WebPublishItem.Clear; begin FId := 0; FDivId := ''; FSourceType := x12wstSheet; FSourceRef.Clear; FSourceObject := ''; FDestinationFile := ''; FTitle := ''; FAutoRepublish := False; end; constructor TXc12WebPublishItem.Create; begin FSourceRef := TCellRef.Create; Clear; end; destructor TXc12WebPublishItem.Destroy; begin FSourceRef.Free; inherited; end; { TXc12Control } procedure TXc12Control.Clear; begin FShapeId := 0; FRId := ''; FName := ''; end; constructor TXc12Control.Create; begin Clear; end; { TXc12OleObject } procedure TXc12OleObject.Clear; begin FProgId := ''; FDvAspect := x12daDVASPECT_CONTENT; FLink := ''; FOleUpdate := x12ouOLEUPDATE_ALWAYS; FAutoLoad := False; FShapeId := 0; FRId := ''; end; constructor TXc12OleObject.Create; begin Clear; end; { TXc12IgnoredError } procedure TXc12IgnoredError.Clear; begin FEvalError := False; FTwoDigitTextYear := False; FNumberStoredAsText := False; FFormula := False; FFormulaRange := False; FUnlockedFormula := False; FEmptyCellReference := False; FListDataValidation := False; FCalculatedColumn := False; FSqref.Clear; end; constructor TXc12IgnoredError.Create; begin FSqref := TCellAreas.Create; Clear; end; destructor TXc12IgnoredError.Destroy; begin FSqref.Free; inherited; end; { TXc12CustomProperty } procedure TXc12CustomProperty.Clear; begin FName := ''; FRId := ''; end; constructor TXc12CustomProperty.Create; begin Clear; end; { TXc12DataValidation } procedure TXc12DataValidation.Clear; begin FType_ := x12dvtNone; FErrorStyle := x12dvesStop; FImeMode := x12dvimNoControl; FOperator_ := x12dvoBetween; FAllowBlank := False; FShowDropDown := False; FShowInputMessage := False; FShowErrorMessage := False; FErrorTitle := ''; FError := ''; FPromptTitle := ''; FPrompt := ''; FSqref.Clear; FFormula1 := ''; FFormula2 := ''; end; constructor TXc12DataValidation.Create; begin FSqref := TCellAreas.Create; Clear; end; destructor TXc12DataValidation.Destroy; begin FSqref.Free; inherited; end; { TXc12DataValidations } function TXc12DataValidations.Add: TXLSMoveCopyItem; begin Result := CreateMember; inherited Add(Result); end; function TXc12DataValidations.AddDV: TXc12DataValidation; begin Result := CreateMember; inherited Add(Result); end; procedure TXc12DataValidations.Clear; begin inherited Clear; FDisablePrompts := False; FXWindow := 0; FYWindow := 0; end; constructor TXc12DataValidations.Create(AClassFactory: TXLSClassFactory); begin inherited Create; FClassFactory := AClassFactory; end; function TXc12DataValidations.CreateMember: TXc12DataValidation; begin Result := TXc12DataValidation(FClassFactory.CreateAClass(xcftDataValidationsMember)); end; function TXc12DataValidations.GetItems(Index: integer): TXc12DataValidation; begin Result := TXc12DataValidation(inherited Items[Index]); end; { TXc12DataRef } procedure TXc12DataRef.Clear; begin ClearCellArea(FRef); FName := ''; FSheet := ''; FRId := ''; end; constructor TXc12DataRef.Create; begin Clear; end; { TXc12DataRefs } function TXc12DataRefs.Add: TXc12DataRef; begin Result := TXc12DataRef.Create; inherited Add(Result); end; constructor TXc12DataRefs.Create; begin inherited Create; end; function TXc12DataRefs.GetItems(Index: integer): TXc12DataRef; begin Result := TXc12DataRef(inherited Items[Index]); end; { TXc12InputCell } procedure TXc12InputCell.Clear; begin FRow := 0; FCol := 0; FDeleted := False; FUndone := False; FVal := ''; FNumFmtId := 0; end; constructor TXc12InputCell.Create; begin Clear; end; { Tx12InputCells } function Tx12InputCells.Add: TXc12InputCell; begin Result := TXc12InputCell.Create; inherited Add(Result); end; function Tx12InputCells.Add(ACellRef: AxUCString): TXc12InputCell; begin Result := Add; RefStrToColRow(ACellRef,Result.FCol,Result.FRow); end; constructor Tx12InputCells.Create; begin inherited Create; end; function Tx12InputCells.GetItems(Index: integer): TXc12InputCell; begin Result := TXc12InputCell(inherited Items[Index]); end; { TXc12Scenario } procedure TXc12Scenario.Clear; begin FName := ''; FLocked := False; FHidden := False; FUser := ''; FComment := ''; FInputCells.Clear; end; constructor TXc12Scenario.Create; begin FInputCells := Tx12InputCells.Create; Clear; end; destructor TXc12Scenario.Destroy; begin FInputCells.Free; inherited; end; { TXc12ProtectedRange } procedure TXc12ProtectedRange.Clear; begin FPassword := 0; FSqref.Clear; FName := ''; FSecurityDescriptor := ''; end; constructor TXc12ProtectedRange.Create; begin FSqref := TCellAreas.Create; Clear; end; destructor TXc12ProtectedRange.Destroy; begin FSqref.Free; inherited; end; { TXc12CustomProperties } function TXc12CustomProperties.Add: TXc12CustomProperty; begin Result := TXc12CustomProperty.Create; inherited Add(Result); end; constructor TXc12CustomProperties.Create; begin inherited Create; end; function TXc12CustomProperties.GetItems(Index: integer): TXc12CustomProperty; begin Result := TXc12CustomProperty(inherited Items[Index]); end; { TXc12ProtectedRanges } function TXc12ProtectedRanges.Add: TXc12ProtectedRange; begin Result := TXc12ProtectedRange.Create; inherited Add(Result); end; constructor TXc12ProtectedRanges.Create; begin inherited Create; end; function TXc12ProtectedRanges.GetItems(Index: integer): TXc12ProtectedRange; begin Result := TXc12ProtectedRange(inherited Items[Index]); end; { TXc12Scenarios } function TXc12Scenarios.Add: TXc12Scenario; begin Result := TXc12Scenario.Create; inherited Add(Result); end; constructor TXc12Scenarios.Create; begin inherited Create; FSqref := TCellAreas.Create; end; destructor TXc12Scenarios.Destroy; begin FSqref.Free; inherited; end; function TXc12Scenarios.GetItems(Index: integer): TXc12Scenario; begin Result := TXc12Scenario(inherited Items[Index]); end; procedure TXc12Scenarios.Clear; begin inherited Clear; FCurrent := 0; FShow := 0; //{$ifdef _AXOLOT_DEBUG} //{$message warn 'uncomment this causes an exception in FastMM when running in debug mode'} //{$endif} // FSqref.Clear; end; { TXc12OutlinePr } procedure TXc12OutlinePr.Clear; begin FApplyStyles := False; FSummaryBelow := True; FSummaryRight := True; FShowOutlineSymbols := True; end; constructor TXc12OutlinePr.Create; begin Clear; end; { TXc12PageSetupPr } procedure TXc12PageSetupPr.Clear; begin FAutoPageBreaks := True; FFitToPage := False; end; constructor TXc12PageSetupPr.Create; begin Clear; end; { TXc12SheetPr } procedure TXc12SheetPr.Clear; begin FSyncHorizontal := False; FSyncVertical := False; ClearCellArea(FSyncRef); FTransitionEvaluation := False; FTransitionEntry := False; FPublished_ := True; FCodeName := ''; FFilterMode := False; FEnableFormatConditionsCalculation := True; FTabColor.ColorType := exctUnassigned; FOutlinePr.Clear; FPageSetupPr.Clear; end; constructor TXc12SheetPr.Create; begin FOutlinePr := TXc12OutlinePr.Create; FPageSetupPr := TXc12PageSetupPr.Create; Clear; end; destructor TXc12SheetPr.Destroy; begin FOutlinePr.Free; FPageSetupPr.Free; inherited; end; { TXc12SheetFormatPr } procedure TXc12SheetFormatPr.Clear; begin FBaseColWidth := 8; FDefaultColWidth := 0; FDefaultRowHeight := 0; FCustomHeight := False; FZeroHeight := False; FThickTop := False; FThickBottom := False; FOutlineLevelRow := 0; FOutlineLevelCol := 0; end; constructor TXc12SheetFormatPr.Create; begin Clear; end; { TXc12SheetCalcPr } procedure TXc12SheetCalcPr.Clear; begin FFullCalcOnLoad := False; end; constructor TXc12SheetCalcPr.Create; begin Clear; end; { TXc12SheetProtection } procedure TXc12SheetProtection.Clear; begin FPassword := 0; FSheet := False; FObjects := False; FScenarios := False; FFormatCells := True; FFormatColumns := True; FFormatRows := True; FInsertColumns := True; FInsertRows := True; FInsertHyperlinks := True; FDeleteColumns := True; FDeleteRows := True; FSelectLockedCells := False; FSort := True; FAutoFilter := True; FPivotTables := True; FSelectUnlockedCells := False; end; constructor TXc12SheetProtection.Create; begin Clear; end; function TXc12SheetProtection.GetPasswordAsString: AxUCString; begin if FPassword <> 0 then Result := PasswordFromHash(FPassword) else Result := ''; end; procedure TXc12SheetProtection.SetPasswordAsString(const Value: AxUCString); begin FPassword := MakePasswordHash(AnsiString(Value)); end; { TXc12DataConsolidate } procedure TXc12DataConsolidate.Clear; begin FFunction := x12dcfSum; FLeftLabels := False; FTopLabels := False; FLink := False; FDataRefs.Clear; end; constructor TXc12DataConsolidate.Create; begin FDataRefs := TXc12DataRefs.Create; Clear; end; destructor TXc12DataConsolidate.Destroy; begin FDataRefs.Free; inherited; end; { TXc12PhoneticPr } procedure TXc12PhoneticPr.Clear; begin FFontId := 0; FType := x12ptFullwidthKatakana; FAlignment := x12paLeft; end; constructor TXc12PhoneticPr.Create; begin Clear; end; { TXc12MergedCells } function TXc12MergedCells.Add(const ARef: TXLSCellArea): TXc12MergedCell; begin Result := CreateMember; Add(Result); Result.Ref := ARef; end; constructor TXc12MergedCells.Create(AClassFactory: TXLSClassFactory); begin inherited Create; FClassFactory := AClassFactory; end; function TXc12MergedCells.CreateMember: TXc12MergedCell; begin Result := TXc12MergedCell(FClassFactory.CreateAClass(xcftMergedCellsMember)); end; function TXc12MergedCells.CreateObject: TCellArea; begin Result := TXc12MergedCell.Create; end; function TXc12MergedCells.GetItems(Index: integer): TXc12MergedCell; begin Result := TXc12MergedCell(inherited Items[Index]); end; { TXc12MergedCell } procedure TXc12MergedCell.Assign(const AItem: TXc12MergedCell); begin FRef := AItem.FRef; end; function TXc12MergedCell.GetCol1: integer; begin Result := FRef.Col1; end; function TXc12MergedCell.GetCol2: integer; begin Result := FRef.Col2; end; function TXc12MergedCell.GetRow1: integer; begin Result := FRef.Row1; end; function TXc12MergedCell.GetRow2: integer; begin Result := FRef.Row2; end; procedure TXc12MergedCell.SetCol1(const AValue: integer); begin PXLSCellArea(@FRef).Col1 := AValue; end; procedure TXc12MergedCell.SetCol2(const AValue: integer); begin PXLSCellArea(@FRef).Col2 := AValue; end; procedure TXc12MergedCell.SetRow1(const AValue: integer); begin PXLSCellArea(@FRef).Row1 := AValue; end; procedure TXc12MergedCell.SetRow2(const AValue: integer); begin PXLSCellArea(@FRef).Row2 := AValue; end; end.
unit uDXUtils; interface uses cxGrid,cxGridDBTableView, cxTreeView, Math, cxGridExportLink, cxExportPivotGridLink, cxGridDBBandedTableView, cxDBPivotGrid, cxCurrencyEdit, cxCustomPivotGrid, cxGridBandedTableView, cxDBExtLookupComboBox, cxCustomData, cxFilter, cxGridCustomTableView, cxDBTL, cxTLExportLink,cxCalendar, Dialogs, SysUtils, cxGridDBDataDefinitions, System.Classes, uAppUtils, uDBUtils, cxDropDownEdit, cxGridTableView, StrUtils, System.Contnrs, Vcl.Controls, Vcl.Forms, Windows, Messages, Variants, Graphics, ExtCtrls, ActnList, System.Actions, Vcl.StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxLookupEdit, cxDBLookupEdit, cxCheckBox, cxSpinEdit, Data.DB, cxPC, Vcl.ComCtrls, Vcl.Mask, Datasnap.DBClient, System.Rtti, uModApp, System.TypInfo, cxButtonEdit, System.DateUtils, cxCalc, cxGridLevel; type TTag = set of byte; TcxTextEditHelper = class helper for TcxTextEdit public function TextRest: string; end; DataControllerHelper = class helper for TcxGridDataController private public function GetFooterSummary(ASummaryIndex: Integer): Variant; overload; function GetFooterSummary(aColumn: TcxGridColumn): Variant; overload; function GetFooterSummaryFloat(aColumn: TcxGridColumn): Double; overload; end; DBDataControllerHelper = class helper for TcxGridDBDataController private public function GetFooterSummary(ASummaryIndex: Integer): Variant; overload; end; TcxDBBandGridHelper = class helper for TcxGridDBBandedTableView function GetFooterSummary(aColumn: TcxGridDBBandedColumn): Variant; public procedure AutoFormatCurrency(ADisplayFormat: String = ',0;(,0)'); procedure AutoFormatDate(ADisplayFormat: String = 'yyyy/mm/dd'); function BandByField(aFieldName: String): TcxGridBand; procedure ExportToXLS(sFileName: String = ''); procedure LoadFromCDS(ACDS: TClientDataSet; BestFit: Boolean = False); overload; procedure LoadFromCDS(ACDS: TClientDataSet; AutoFormat, DoBestFit: Boolean); overload; procedure PrepareFromCDS(ACDS: TClientDataSet); overload; procedure LoadFromSQL(aSQL: String; aOwner: TComponent); procedure SetAllUpperCaseColumn; procedure SetBandVisible(aFieldName: string; IsVisible: Boolean); procedure SetColumnsCaption(ColumnSets, ColumnCaption: Array Of String); procedure SetDetailKeyField(aKeyField: String); procedure SetMasterKeyField(aKeyField: String); procedure SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); end; TcxExtLookupPropHelper = class helper for TcxExtLookupComboBoxProperties private public procedure LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); overload; procedure LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); overload; procedure LoadFromSQL(aSQL, IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); procedure LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); overload; procedure LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); overload; procedure SetMultiPurposeLookup; procedure SetVisibleColumnsOnly(ColumnSets: Array Of String; IsVisible: Boolean = True); end; TcxExtLookupComboHelper = class helper for TcxExtLookupComboBox public function CDS: TClientDataSet; function DS: TDataset; function EditValueText: String; function EditValueRest: String; procedure LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); overload; procedure LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); overload; procedure LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); overload; procedure LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); overload; procedure SetDefaultValue(TriggerEvents: Boolean = True); procedure SetMultiPurposeLookup; procedure SetVisibleColumnsOnly(ColumnSets: Array Of String; IsVisible: Boolean = True); overload; end; TcxDBTreeHelper = class helper for TcxDBTreeList public procedure ExportToXLS(sFileName: String = ''; DoShowInfo: Boolean = True); procedure LoadFromCDS(ACDS: TClientDataSet; AKey, AParentKey: String; DoCreateAllItem: Boolean = False); procedure SetVisibleColumns(ColumnIndexes: Array Of Integer; IsVisible: Boolean); overload; procedure SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); overload; end; TcxDBPivotHelper = class helper for TcxDBPivotGrid public procedure ExportToXLS(ExpandAll: Boolean = True; sFileName: String = ''; DoShowInfo: Boolean = True); procedure LoadFromCDS(ACDS: TClientDataSet; ExpandAll: Boolean = True; ReCreateAllItem: Boolean = True); procedure SetAllUpperCaseColumn; procedure SetColColumns(ColumnSets: Array Of String); procedure SetColumnsCaption(ColumnSets, ColumnCaption: Array Of String); procedure SetColumnsWidth(ColumnSets: Array Of String; Widths: Array Of Integer); overload; procedure SetDataColumns(ColumnSets: Array Of String); procedure SetRowColumns(ColumnSets: Array Of String); overload; procedure SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); end; TcxDBGridHelper = class helper for TcxGridDBTableView private procedure DoFormatHeaderCXGRID; public procedure AutoFormatCurrency(ADisplayFormat: String =',0.00;(,0.00)'); procedure AutoFormatText; procedure AutoFormatDate(ADisplayFormat: String = 'yyyy/mm/dd'); procedure AutoFormatBoolean; function DS: TDataset; function CDS: TClientDataSet; procedure ExportToXLS(sFileName: String = ''; DoShowInfo: Boolean = True); function GetFooterSummary(sFieldName : String): Variant; overload; function GetFooterSummary(aColumn: TcxGridDBColumn): Variant; overload; procedure LoadFromCDS(ACDS: TClientDataSet; DoCreateAllItem: Boolean = True; DoBestFit: Boolean = True; AutoFormat: Boolean = True); procedure LoadFromSQL(aSQL: String; aOwner: TComponent); overload; procedure LoadFromSQL(aSQL: String); overload; procedure LoadFromDS(aDataSet: TDataSet; aOwner: TComponent; DoCreateAllItems: Boolean = true); overload; procedure PrepareFromCDS(ACDS: TClientDataSet); overload; procedure SetAllUpperCaseColumn; procedure SetColumnsCaption(ColumnSets, ColumnCaption: Array Of String); procedure SetSummaryByColumns(ColumnSets: Array Of String; SummaryKind: TcxSummaryKind = skSum; SFormat: String = ',0;(,0)'); procedure SetDetailKeyField(aKeyField: String); procedure SetMasterKeyField(aKeyField: String); procedure SetReadOnly(IsReadOnly: Boolean); procedure SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); overload; procedure SetVisibleColumns(ColumnIndexes: Array Of Integer; IsVisible: Boolean); overload; procedure SetColumnsWidth(ColumnSets: Array Of String; Widths: Array Of Integer); overload; procedure SetExtLookupCombo(ExtLookup: TcxExtLookupComboBox; IDField, DisplayField: String; HideIDField: Boolean = True); overload; procedure SetExtLookupCombo(ExtLookupProp: TcxExtLookupComboBoxProperties; IDField, DisplayField: String; HideIDField: Boolean = True); overload; procedure SetVisibleColumns(FromCol, ToCol: Integer; IsVisible: Boolean); overload; procedure SetReadOnlyColumns(ColumnSets: Array Of String; IsReadOnly: Boolean); overload; procedure SetReadOnlyAllColumns(IsReadOnly: Boolean); overload; procedure SetVisibleColumnsOnly(ColumnSets: Array Of String; IsVisible: Boolean = True); overload; end; TcxExtLookup= class(TcxExtLookupComboBoxProperties) protected public class procedure OnInitPopupCustom(Sender: TObject); class procedure OnClosePopupCustom(Sender: TObject); end; TFormHelper = class helper for TForm private procedure OnKeyEnter(Sender: TObject; var Key: Word; Shift: TShiftState); public procedure AssignKeyDownEvent; function CheckControlParent(ChildCtrl, ParentCtrl: TWinControl): Boolean; procedure ClearByTag(Tag: TTag; ParentCtrl: TWinControl = nil); function ValidateEmptyCtrl(Tag: TTag = [1]; ShowWarning: Boolean = True; ParentCtrl: TWinControl = nil): Boolean; class procedure OnEditValueChanged(Sender: TObject); function SetFocusRec(aWinCTRL: TWinControl): Boolean; function EnableDisableControl(ParentCtrl: TWinControl; aState: Boolean): Boolean; end; TcxGridTableViewHelper = class helper for TcxGridTableView public procedure FilterData(AColumn : TcxGridColumn; AOperatorKind: TcxFilterOperatorKind; const AValues : TStringArray; const ADisplayValues: TStringArray); procedure ClearRows; procedure SetValue(ARec, ACol : Integer; AValue : Variant); function Double(ARec, ACol : Integer): Double; function Date(ARec, ACol : Integer): TDatetime; procedure FilterDataLookUp(AColumn : TcxGridColumn; AFilterColumnCaption : String; AOperatorKind: TcxFilterOperatorKind; const AValues : TStringArray; const ADisplayValues: TStringArray); function GetFooterSummary(aColumn: TcxGridColumn): Variant; overload; function GetLevel: TcxGridLevel; function Int(ARec, ACol : Integer): Integer; function Text(ARec, ACol : Integer): string; procedure LoadObjectData(AObject : TModApp; ARow : Integer); function RecordIndex: Integer; procedure SetObjectData(AObject : TModApp; ARow : Integer); procedure SetVisibleColumns(FromCol, ToCol: Integer; IsVisible: Boolean); overload; function Validate: Boolean; function Values(ARec, ACol : Integer): Variant; overload; function Values(ARec : Integer; AColumnCaption : String): Variant; overload; end; type TEditHelper = class helper for TEdit public function TextRest: string; function TextTrim: string; end; type TComboboxHelper = class helper for TCombobox public function TextRest: string; end; function CreateCXDBGrid(ALeft, ATop, AWidth, AHeight : Integer; AParent : TWinControl): TcxGrid; function VarToInt(aValue: Variant): Integer; function VarToFloat(aValue: Variant): Double; implementation function CreateCXDBGrid(ALeft, ATop, AWidth, AHeight : Integer; AParent : TWinControl): TcxGrid; var cxGridLevel: TcxGridLevel; cxGridDBTableView: TcxGridDBTableView; begin Result := TcxGrid.Create(Application); Result.Parent := AParent; Result.Left := ALeft; Result.Top := ATop; Result.Height := AHeight; Result.Width := AWidth; Result.Visible := True; cxGridLevel := Result.Levels.Add; cxGridDBTableView := Result.CreateView(TcxGridDBTableView) as TcxGridDBTableView; cxGridLevel.GridView := cxGridDBTableView; end; function VarToFloat(aValue: Variant): Double; begin if VarIsNull(aValue) then Result := 0 else Result := aValue; end; function VarToInt(aValue: Variant): Integer; begin if VarIsNull(aValue) then Result := 0 else Result := aValue; end; function DataControllerHelper.GetFooterSummary(ASummaryIndex: Integer): Variant; begin Result := Self.Summary.FooterSummaryValues[ASummaryIndex]; end; function DataControllerHelper.GetFooterSummary(aColumn: TcxGridColumn): Variant; var i: Integer; begin Result := 0; with Self.Summary do begin for i :=0 to FooterSummaryItems.Count-1 do begin // If FooterSummaryItems.Items[i].ItemLink.ClassName <> aColumn.ClassName then // continue; If FooterSummaryItems.Items[i].ItemLink = aColumn then Result := FooterSummaryValues[i]; end; end; end; function DataControllerHelper.GetFooterSummaryFloat(aColumn: TcxGridColumn): Double; var i: Integer; begin Result := 0; with Self.Summary do begin for i :=0 to FooterSummaryItems.Count-1 do begin // If FooterSummaryItems.Items[i].ItemLink.ClassName <> aColumn.ClassName then // continue; If FooterSummaryItems.Items[i].ItemLink = aColumn then if not VarIsNull(FooterSummaryValues[i]) then Result := FooterSummaryValues[i]; end; end; end; function DBDataControllerHelper.GetFooterSummary(ASummaryIndex: Integer): Variant; begin Result := Self.Summary.FooterSummaryValues[ASummaryIndex]; end; procedure TcxDBBandGridHelper.AutoFormatCurrency(ADisplayFormat: String = ',0;(,0)'); var i: Integer; lDS: TDataSet; begin lDS := Self.DataController.DataSource.DataSet; //why use DS, because sometime format CDS <> grid.column.format for i := 0 to lDS.FieldCount-1 do begin If not Assigned(Self.GetColumnByFieldName(lDS.Fields[i].FieldName)) then continue; with Self.GetColumnByFieldName(lDS.Fields[i].FieldName) do begin If lDS.Fields[i].DataType = ftFloat then begin PropertiesClassName := 'TcxCurrencyEditProperties'; TcxCurrencyEditProperties( Properties).DisplayFormat := ADisplayFormat; TcxCurrencyEditProperties( Properties).Alignment.Horz := taRightJustify; DataBinding.ValueType := 'Float'; end; end; end; end; procedure TcxDBBandGridHelper.AutoFormatDate(ADisplayFormat: String = 'yyyy/mm/dd'); var i: Integer; lDS: TDataSet; begin lDS := Self.DataController.DataSource.DataSet; //why use DS, because sometime format CDS <> grid.column.format for i := 0 to lDS.FieldCount-1 do begin If not Assigned(Self.GetColumnByFieldName(lDS.Fields[i].FieldName)) then continue; with Self.GetColumnByFieldName(lDS.Fields[i].FieldName) do begin If lDS.Fields[i].DataType in [ftDate, ftDateTime] then begin PropertiesClassName := 'TcxDateEditProperties'; TcxDateEditProperties( Properties).DisplayFormat := ADisplayFormat; TcxDateEditProperties( Properties).EditMask := ADisplayFormat; DataBinding.ValueType := 'DateTime'; end; end; end; end; function TcxDBBandGridHelper.BandByField(aFieldName: String): TcxGridBand; begin Result := nil; If Assigned(Self.GetColumnByFieldName(aFieldName)) then Result := Self.GetColumnByFieldName(aFieldName).Position.Band; end; procedure TcxDBBandGridHelper.ExportToXLS(sFileName: String = ''); var DoSave: Boolean; lSaveDlg: TSaveDialog; begin DoSave := True; If sFileName = '' then begin lSaveDlg := TSaveDialog.Create(nil); Try if lSaveDlg.Execute then sFileName := lSaveDlg.FileName else DoSave := False; Finally lSaveDlg.Free; End; end; If DoSave then begin Try ExportGridToExcel(sFileName, TcxGrid(Self.Control)); TAppUtils.Information('Data berhasil diexport ke: ' + sFileName); except TAppUtils.Warning('Gagal menyimpan data ke excel'); end; end; end; function TcxDBBandGridHelper.GetFooterSummary(aColumn: TcxGridDBBandedColumn): Variant; var i: Integer; begin Result := 0; with Self.DataController.Summary do begin for i :=0 to FooterSummaryItems.Count-1 do begin // If FooterSummaryItems.Items[i].ItemLink.ClassName <> aColumn.ClassName then // continue; If FooterSummaryItems.Items[i].ItemLink = aColumn then Result := FooterSummaryValues[i]; end; end; end; procedure TcxDBBandGridHelper.LoadFromCDS(ACDS: TClientDataSet; BestFit: Boolean = False); begin If not Assigned(Self.DataController.DataSource) then begin Self.DataController.DataSource := TDataSource.Create(Self); end; Self.DataController.DataSource.DataSet := ACDS; Self.DataController.CreateAllItems(True); AutoFormatCurrency; SetAllUpperCaseColumn; Self.OptionsBehavior.BestFitMaxRecordCount := 100; if BestFit then Self.ApplyBestFit; end; procedure TcxDBBandGridHelper.LoadFromCDS(ACDS: TClientDataSet; AutoFormat, DoBestFit: Boolean); begin If not Assigned(Self.DataController.DataSource) then begin Self.DataController.DataSource := TDataSource.Create(Self); end; Self.DataController.DataSource.DataSet := ACDS; Self.DataController.CreateAllItems(True); if AutoFormat then begin AutoFormatDate; AutoFormatCurrency; SetAllUpperCaseColumn; end; If DoBestFit then begin Self.OptionsBehavior.BestFitMaxRecordCount := 100; Self.ApplyBestFit; end; end; procedure TcxDBBandGridHelper.PrepareFromCDS(ACDS: TClientDataSet); begin If not Assigned(Self.DataController.DataSource) then begin Self.DataController.DataSource := TDataSource.Create(Self); end; Self.DataController.DataSource.DataSet := ACDS; end; procedure TcxDBBandGridHelper.LoadFromSQL(aSQL: String; aOwner: TComponent); var lCDS: TClientDataSet; begin //method ini hanya digunakan sekali saja, //membuat cds sesuai owner form agar di free on destroy //ex digunakan utk extended lookup data master.. If Assigned(Self.DataController.DataSource) then Raise Exception.Create('DataSource already created'); lCDS := TDBUtils.OpenDataset(aSQL, aOwner); Self.LoadFromCDS(lCDS); end; procedure TcxDBBandGridHelper.SetAllUpperCaseColumn; var i: Integer; begin for i := 0 to Self.ColumnCount-1 do begin Self.Columns[i].Caption := UpperCase(Self.Columns[i].Caption); end; end; procedure TcxDBBandGridHelper.SetBandVisible(aFieldName: string; IsVisible: Boolean); begin If Self.BandByField(aFieldName) <> nil then Self.BandByField(aFieldName).Visible := IsVisible; end; procedure TcxDBBandGridHelper.SetColumnsCaption(ColumnSets, ColumnCaption: Array Of String); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Caption := ColumnCaption[i]; end; end; procedure TcxDBBandGridHelper.SetDetailKeyField(aKeyField: String); begin Self.DataController.MasterKeyFieldNames := aKeyField ; end; procedure TcxDBBandGridHelper.SetMasterKeyField(aKeyField: String); begin Self.DataController.DetailKeyFieldNames := aKeyField ; end; procedure TcxDBBandGridHelper.SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Visible := IsVisible; end; end; procedure TcxExtLookupPropHelper.LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); var aRepo: TcxGridViewRepository; aView: TcxGridDBTableView; i: Integer; begin if aCDS = nil then Exit; for i := 0 to aCDS.FieldDefs.Count-1 do aCDS.FieldDefs[i].Required := False; aRepo := nil; for i := 0 to aOwnerForm.ComponentCount - 1 do begin If aOwnerForm.Components[i] is TcxGridViewRepository then begin aRepo := aOwnerForm.Components[i] as TcxGridViewRepository; break; end; end; If not Assigned(aRepo) then begin aRepo := TcxGridViewRepository.Create( aOwnerForm ); aRepo.Name := 'ViewRepository_' + IntToStr(Integer(aRepo)); end; aView := aRepo.CreateItem(TcxGridDBTableView) as TcxGridDBTableView; aView.Name := 'GridView_' + IntToStr(Integer(aView)); aView.OptionsView.GroupByBox := False; aView.DataController.Filter.Active := True; aView.FilterBox.Visible := fvNever; aView.LoadFromCDS(aCDS, True, False); aView.SetVisibleColumns(HideFields,False); aView.SetExtLookupCombo(Self, IDField, DisplayField, False); aView.FindPanel.DisplayMode := fpdmManual; aView.FindPanel.ClearFindFilterTextOnClose := True; // aView.FindPanel.FocusViewOnApplyFilter := True; If Self.GetOwner is TcxExtLookupComboBox then begin if aView.VisibleColumnCount = 1 then begin If aView.VisibleColumns[0].Width < TcxExtLookupComboBox(Self.GetOwner).Width then aView.VisibleColumns[0].Width := TcxExtLookupComboBox(Self.GetOwner).Width end; end; end; procedure TcxExtLookupPropHelper.LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); begin Self.LoadFromCDS(aCDS, IDField, DisplayField,[IDField], aOwnerForm); end; procedure TcxExtLookupPropHelper.LoadFromSQL(aSQL, IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); var lCDS: TClientDataSet; begin //method ini hanya digunakan sekali saja, //membuat cds sesuai owner form agar di free on destroy lCDS := TDBUtils.OpenDataset(aSQL, aOwnerForm); Self.LoadFromCDS(lCDS, IDField, DisplayField, HideFields, aOwnerForm); end; procedure TcxExtLookupPropHelper.LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); var lCDS: TClientDataSet; begin //method ini hanya digunakan sekali saja, //membuat cds sesuai owner form agar di free on destroy lCDS := TDBUtils.DSToCDS(aDataSet, aOwnerForm); Self.LoadFromCDS(lCDS, IDField, DisplayField, HideFields, aOwnerForm); end; procedure TcxExtLookupPropHelper.LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); var lCDS: TClientDataSet; begin //method ini hanya digunakan sekali saja, //membuat cds sesuai owner form agar di free on destroy lCDS := TDBUtils.DSToCDS(aDataSet, aOwnerForm); Self.LoadFromCDS(lCDS, IDField, DisplayField, [IDField], aOwnerForm); end; procedure TcxExtLookupPropHelper.SetMultiPurposeLookup; begin //new feature dx 15 : findpanel if Self.View = nil then Exit; if TcxGridDBTableView(Self.View).DS = nil then Exit; AutoSearchOnPopup := True; FocusPopup := True; DropDownAutoSize := True; DropDownListStyle := lsEditList; If Self.View is TcxGridDBTableView then begin Self.View.OptionsData.Editing := False; Self.View.OptionsData.Inserting := False; Self.View.OptionsData.Deleting := False; Self.View.OptionsData.Appending := False; Self.PostPopupValueOnTab := True; Self.View.DataController.Filter.Options := [fcoCaseInsensitive]; TcxGridDBTableView(Self.View).FilterRow.InfoText := 'Ketik di sini (per kolom) atau CTRL+F untuk mencari di semua kolom'; TcxGridDBTableView(Self.View).FilterRow.Visible := True; TcxGridDBTableView(Self.View).FilterRow.ApplyChanges := fracImmediately; end; If not Assigned(Self.OnInitPopup) then Self.OnInitPopup := TcxExtLookup.OnInitPopupCustom; If not Assigned(Self.OnClosePopup) then Self.OnCloseUp := TcxExtLookup.OnClosePopupCustom; end; procedure TcxExtLookupPropHelper.SetVisibleColumnsOnly(ColumnSets: Array Of String; IsVisible: Boolean = True); begin if not Assigned(Self.View) then exit; TcxGridDBTableView(Self.View).SetVisibleColumnsOnly(ColumnSets, IsVisible); end; procedure TcxDBTreeHelper.ExportToXLS(sFileName: String = ''; DoShowInfo: Boolean = True); var DoSave: Boolean; lSaveDlg: TSaveDialog; begin DoSave := True; If sFileName = '' then begin lSaveDlg := TSaveDialog.Create(nil); Try if lSaveDlg.Execute then sFileName := lSaveDlg.FileName else DoSave := False; Finally lSaveDlg.Free; End; end; If DoSave then begin Try cxExportTLToExcel(sFileName, Self); If DoShowInfo then TAppUtils.Information('Data berhasil diexport ke: ' + sFileName); except If DoShowInfo then TAppUtils.Warning('Gagal menyimpan data ke excel'); end; end; end; procedure TcxDBTreeHelper.LoadFromCDS(ACDS: TClientDataSet; AKey, AParentKey: String; DoCreateAllItem: Boolean = False); begin If not Assigned(Self.DataController.DataSource) then Self.DataController.DataSource := TDataSource.Create(nil); Self.DataController.DataSource.DataSet := ACDS; Self.DataController.KeyField := AKey; Self.DataController.ParentField := AParentKey; If DoCreateAllItem then Self.CreateAllItems; end; procedure TcxDBTreeHelper.SetVisibleColumns(ColumnIndexes: Array Of Integer; IsVisible: Boolean); var i: Integer; begin for i := Low(ColumnIndexes) to High(ColumnIndexes) do begin Self.Columns[ColumnIndexes[i]].Visible := IsVisible; end; end; procedure TcxDBTreeHelper.SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Visible := IsVisible; end; end; procedure TcxDBPivotHelper.ExportToXLS(ExpandAll: Boolean = True; sFileName: String = ''; DoShowInfo: Boolean = True); var DoSave: Boolean; lSaveDlg: TSaveDialog; begin DoSave := True; If sFileName = '' then begin lSaveDlg := TSaveDialog.Create(nil); Try if lSaveDlg.Execute then sFileName := lSaveDlg.FileName else DoSave := False; Finally lSaveDlg.Free; End; end; If DoSave then begin Try cxExportPivotGridToExcel(sFileName, Self, ExpandAll); If DoShowInfo then TAppUtils.Information('Data berhasil diexport ke: ' + sFileName); except If DoShowInfo then TAppUtils.Warning('Gagal menyimpan data ke excel'); end; end; end; procedure TcxDBPivotHelper.LoadFromCDS(ACDS: TClientDataSet; ExpandAll: Boolean = True; ReCreateAllItem: Boolean = True); var i: Integer; begin if not Assigned(Self.DataSource) then Self.DataSource := TDataSource.Create(Self); Self.DataSource.DataSet := ACDS; If ReCreateAllItem then begin Self.DeleteAllFields; Self.CreateAllFields; end; for i:=0 to Self.FieldCount-1 do begin if MatchStr(Self.Fields[i].DataBinding.ValueType ,['Float','Currency']) then begin Self.Fields[i].PropertiesClass := TcxCurrencyEditProperties; TcxCurrencyEditProperties(Self.fields[i].Properties).DisplayFormat := ',0;(,0)'; TcxCurrencyEditProperties(Self.fields[i].Properties).ReadOnly := True; end; If ExpandAll then Self.Fields[i].ExpandAll; end; SetAllUpperCaseColumn; end; procedure TcxDBPivotHelper.SetAllUpperCaseColumn; var i: Integer; begin for i := 0 to Self.FieldCount-1 do begin Self.Fields[i].Caption := UpperCase(Self.Fields[i].Caption); end; end; procedure TcxDBPivotHelper.SetColColumns(ColumnSets: Array Of String); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetFieldByName(ColumnSets[i])) then Self.GetFieldByName(ColumnSets[i]).Area := faColumn; end; end; procedure TcxDBPivotHelper.SetColumnsCaption(ColumnSets, ColumnCaption: Array Of String); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetFieldByName(ColumnSets[i])) then Self.GetFieldByName(ColumnSets[i]).Caption := ColumnCaption[i]; end; end; procedure TcxDBPivotHelper.SetColumnsWidth(ColumnSets: Array Of String; Widths: Array Of Integer); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetFieldByName(ColumnSets[i])) then Self.GetFieldByName(ColumnSets[i]).Width := Widths[i]; end; end; procedure TcxDBPivotHelper.SetDataColumns(ColumnSets: Array Of String); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetFieldByName(ColumnSets[i])) then Self.GetFieldByName(ColumnSets[i]).Area := faData; end; end; procedure TcxDBPivotHelper.SetRowColumns(ColumnSets: Array Of String); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetFieldByName(ColumnSets[i])) then Self.GetFieldByName(ColumnSets[i]).Area := faRow; end; end; procedure TcxDBPivotHelper.SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetFieldByName(ColumnSets[i])) then Self.GetFieldByName(ColumnSets[i]).Hidden := not IsVisible; end; end; procedure TcxDBGridHelper.AutoFormatCurrency(ADisplayFormat: String =',0.00;(,0.00)'); var i: Integer; lDS: TDataSet; begin lDS := Self.DataController.DataSource.DataSet; //why use DS, because sometime format CDS <> grid.column.format for i := 0 to lDS.FieldCount-1 do begin If not Assigned(Self.GetColumnByFieldName(lDS.Fields[i].FieldName)) then continue; with Self.GetColumnByFieldName(lDS.Fields[i].FieldName) do begin If lDS.Fields[i].DataType in [ftFloat, ftFMTBcd, ftBCD] then begin PropertiesClassName := 'TcxCurrencyEditProperties'; TcxCurrencyEditProperties( Properties).DisplayFormat := ADisplayFormat; TcxCurrencyEditProperties( Properties).Alignment.Horz := taRightJustify; DataBinding.ValueType := 'Float'; end; end; end; end; procedure TcxDBGridHelper.AutoFormatText; var i: Integer; lCol: TcxGridDBColumn; lDS: TDataSet; begin lDS := Self.DataController.DataSource.DataSet; for i := 0 to lDS.FieldCount-1 do begin lCol := Self.GetColumnByFieldName(lDS.Fields[i].FieldName); If not Assigned(lCol) then continue; If lDS.Fields[i].DataType in [ftString] then begin lCol.DataBinding.ValueType := 'String'; if lCol.PropertiesClass = nil then lCol.PropertiesClassName := 'TcxTextEditProperties'; end; end; end; procedure TcxDBGridHelper.AutoFormatDate(ADisplayFormat: String = 'yyyy/mm/dd'); var i: Integer; lDS: TDataSet; begin lDS := Self.DataController.DataSource.DataSet; //why use DS, because sometime format CDS <> grid.column.format for i := 0 to lDS.FieldCount-1 do begin If not Assigned(Self.GetColumnByFieldName(lDS.Fields[i].FieldName)) then continue; with Self.GetColumnByFieldName(lDS.Fields[i].FieldName) do begin If lDS.Fields[i].DataType in [ftDate, ftDateTime, ftTimeStamp] then begin PropertiesClassName := 'TcxDateEditProperties'; TcxDateEditProperties( Properties).DisplayFormat := ADisplayFormat; TcxDateEditProperties( Properties).EditMask := ADisplayFormat; DataBinding.ValueType := 'DateTime'; end; end; end; end; procedure TcxDBGridHelper.AutoFormatBoolean; var i: Integer; lDS: TDataSet; begin lDS := Self.DataController.DataSource.DataSet; //why use DS, because sometime format CDS <> grid.column.format for i := 0 to lDS.FieldCount-1 do begin If not Assigned(Self.GetColumnByFieldName(lDS.Fields[i].FieldName)) then continue; with Self.GetColumnByFieldName(lDS.Fields[i].FieldName) do begin If lDS.Fields[i].DataType in [ftBoolean] then begin PropertiesClassName := 'TcxCheckBoxProperties'; DataBinding.ValueType := 'Boolean'; end; end; end; end; function TcxDBGridHelper.DS: TDataset; begin Result := Self.DataController.DataSource.DataSet; end; function TcxDBGridHelper.CDS: TClientDataSet; begin Result := TClientDataSet(Self.DS); end; procedure TcxDBGridHelper.DoFormatHeaderCXGRID; var I: Integer; begin for I := 0 to Self.ColumnCount - 1 do begin Self.Columns[i].Caption := StringReplace(Self.Columns[i].Caption,'_',' ', [rfReplaceAll]); Self.Columns[i].HeaderAlignmentHorz := taCenter; end; end; procedure TcxDBGridHelper.ExportToXLS(sFileName: String = ''; DoShowInfo: Boolean = True); var DoSave: Boolean; lSaveDlg: TSaveDialog; begin DoSave := True; If sFileName = '' then begin lSaveDlg := TSaveDialog.Create(nil); Try if lSaveDlg.Execute then sFileName := lSaveDlg.FileName else DoSave := False; Finally lSaveDlg.Free; End; end; If DoSave then begin Try ExportGridToExcel(sFileName, TcxGrid(Self.Control)); If DoSHowInfo then TAppUtils.Information('Data berhasil diexport ke: ' + sFileName); except If DoSHowInfo then TAppUtils.Warning('Gagal menyimpan data ke excel'); end; end; end; function TcxDBGridHelper.GetFooterSummary(aColumn: TcxGridDBColumn): Variant; var i: Integer; begin Result := 0; with Self.DataController.Summary do begin for i :=0 to FooterSummaryItems.Count-1 do begin // If FooterSummaryItems.Items[i].ItemLink.ClassName <> aColumn.ClassName then // continue; If FooterSummaryItems.Items[i].ItemLink = aColumn then Result := FooterSummaryValues[i]; end; end; end; function TcxDBGridHelper.GetFooterSummary(sFieldName : String): Variant; //var // i: Integer; begin Result := Self.GetFooterSummary(Self.GetColumnByFieldName(sFieldName)); end; procedure TcxDBGridHelper.LoadFromCDS(ACDS: TClientDataSet; DoCreateAllItem: Boolean = True; DoBestFit: Boolean = True; AutoFormat: Boolean = True); begin if not Assigned(ACDS) then exit; If not Assigned(Self.DataController.DataSource) then begin Self.DataController.DataSource := TDataSource.Create(Self); end; Self.DataController.DataSource.DataSet := ACDS; If DoCreateAllItem then Self.DataController.CreateAllItems(True); if AutoFormat then begin AutoFormatText; AutoFormatBoolean; AutoFormatDate; AutoFormatCurrency; SetAllUpperCaseColumn; DoFormatHeaderCXGRID; end; If DoBestFit then begin Self.OptionsBehavior.BestFitMaxRecordCount := 100; Self.ApplyBestFit; end; end; procedure TcxDBGridHelper.LoadFromSQL(aSQL: String; aOwner: TComponent); var lCDS: TClientDataSet; begin //method ini hanya digunakan sekali saja, //membuat cds sesuai owner form agar di free on destroy //ex digunakan utk extended lookup data master.. If Assigned(Self.DataController.DataSource) then Raise Exception.Create('DataSource already created'); lCDS := TDBUtils.OpenDataset(aSQL, aOwner); Self.LoadFromCDS(lCDS); end; procedure TcxDBGridHelper.LoadFromSQL(aSQL: String); begin Self.LoadFromSQL(aSQL, Self); end; procedure TcxDBGridHelper.LoadFromDS(aDataSet: TDataSet; aOwner: TComponent; DoCreateAllItems: Boolean = true); var lCDS: TClientDataSet; begin lCDS := TDBUtils.DSToCDS(aDataSet, aOwner); if Assigned(Self.DataController.DataSource) then if Self.DataController.DataSource.DataSet <> nil then Self.DataController.DataSource.DataSet.Free; Self.LoadFromCDS(lCDS, DoCreateAllItems); end; procedure TcxDBGridHelper.PrepareFromCDS(ACDS: TClientDataSet); begin If not Assigned(Self.DataController.DataSource) then begin Self.DataController.DataSource := TDataSource.Create(Self); end; Self.DataController.DataSource.DataSet := ACDS; end; procedure TcxDBGridHelper.SetAllUpperCaseColumn; var i: Integer; begin for i := 0 to Self.ColumnCount-1 do begin Self.Columns[i].Caption := UpperCase(Self.Columns[i].Caption); end; end; procedure TcxDBGridHelper.SetColumnsCaption(ColumnSets, ColumnCaption: Array Of String); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Caption := ColumnCaption[i]; end; end; procedure TcxDBGridHelper.SetSummaryByColumns(ColumnSets: Array Of String; SummaryKind: TcxSummaryKind = skSum; SFormat: String = ',0;(,0)'); var i: Integer; begin If not Self.OptionsView.Footer then Self.OptionsView.Footer := True; for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then begin GetColumnByFieldName(ColumnSets[i]).Summary.FooterKind := SummaryKind; GetColumnByFieldName(ColumnSets[i]).Summary.FooterFormat := SFormat; end; end; end; procedure TcxDBGridHelper.SetDetailKeyField(aKeyField: String); begin Self.DataController.MasterKeyFieldNames := aKeyField ; end; procedure TcxDBGridHelper.SetMasterKeyField(aKeyField: String); begin Self.DataController.DetailKeyFieldNames := aKeyField ; end; procedure TcxDBGridHelper.SetReadOnly(IsReadOnly: Boolean); begin Self.OptionsData.Editing := not IsReadOnly; Self.OptionsData.Inserting := not IsReadOnly; Self.OptionsData.Appending := not IsReadOnly; Self.OptionsData.Deleting := not IsReadOnly; end; procedure TcxDBGridHelper.SetVisibleColumns(ColumnSets: Array Of String; IsVisible: Boolean); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Visible := IsVisible; end; end; procedure TcxDBGridHelper.SetVisibleColumns(ColumnIndexes: Array Of Integer; IsVisible: Boolean); var i: Integer; begin for i := Low(ColumnIndexes) to High(ColumnIndexes) do begin Self.Columns[ColumnIndexes[i]].Visible := IsVisible; end; end; procedure TcxDBGridHelper.SetColumnsWidth(ColumnSets: Array Of String; Widths: Array Of Integer); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Width := Widths[i]; end; end; procedure TcxDBGridHelper.SetExtLookupCombo(ExtLookup: TcxExtLookupComboBox; IDField, DisplayField: String; HideIDField: Boolean = True); begin SetExtLookupCombo( ExtLookup.Properties , IDField, DisplayField, HideIDField); end; procedure TcxDBGridHelper.SetExtLookupCombo(ExtLookupProp: TcxExtLookupComboBoxProperties; IDField, DisplayField: String; HideIDField: Boolean = True); begin if not Assigned(ExtLookupProp) then exit; with ExtLookupProp do begin View := Self; KeyFieldNames := IDField; If HideIDField then Self.SetVisibleColumns([IDField],False); ListFieldItem := Self.GetColumnByFieldName(DisplayField); DropDownAutoSize := True; end; ExtLookupProp.PopupAutoSize := True; Self.OptionsBehavior.BestFitMaxRecordCount := 0; Self.ApplyBestFit; end; procedure TcxDBGridHelper.SetVisibleColumns(FromCol, ToCol: Integer; IsVisible: Boolean); var i: Integer; begin for i := FromCol to ToCol do begin Self.Columns[i].Visible := IsVisible; end; end; procedure TcxDBGridHelper.SetReadOnlyColumns(ColumnSets: Array Of String; IsReadOnly: Boolean); var i: Integer; begin for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then begin if Self.GetColumnByFieldName(ColumnSets[i]).PropertiesClassName = 'TcxTextEditProperties' then TcxTextEditProperties(Self.GetColumnByFieldName(ColumnSets[i]).Properties).ReadOnly := IsReadOnly else if Self.GetColumnByFieldName(ColumnSets[i]).PropertiesClassName = 'TcxCurrencyEditProperties' then TcxCurrencyEditProperties(Self.GetColumnByFieldName(ColumnSets[i]).Properties).ReadOnly := IsReadOnly else if Self.GetColumnByFieldName(ColumnSets[i]).PropertiesClassName = 'TcxDateEditProperties' then TcxDateEditProperties(Self.GetColumnByFieldName(ColumnSets[i]).Properties).ReadOnly := IsReadOnly else if Self.GetColumnByFieldName(ColumnSets[i]).PropertiesClassName = 'TcxCheckBoxProperties' then TcxCheckBoxProperties(Self.GetColumnByFieldName(ColumnSets[i]).Properties).ReadOnly := IsReadOnly; end; end; end; procedure TcxDBGridHelper.SetReadOnlyAllColumns(IsReadOnly: Boolean); var i: Integer; begin SetReadOnly(not IsReadOnly); for i := 0 to Self.ColumnCount-1 do begin If Assigned(Self.Columns[i]) then begin if Self.Columns[i].PropertiesClassName = 'TcxTextEditProperties' then TcxTextEditProperties(Self.Columns[i].Properties).ReadOnly := IsReadOnly else if Self.Columns[i].PropertiesClassName = 'TcxCurrencyEditProperties' then TcxCurrencyEditProperties(Self.Columns[i].Properties).ReadOnly := IsReadOnly else if Self.Columns[i].PropertiesClassName = 'TcxDateEditProperties' then TcxDateEditProperties(Self.Columns[i].Properties).ReadOnly := IsReadOnly else if Self.Columns[i].PropertiesClassName = 'TcxCheckBoxProperties' then TcxCheckBoxProperties(Self.Columns[i].Properties).ReadOnly := IsReadOnly; end; end; end; procedure TcxDBGridHelper.SetVisibleColumnsOnly(ColumnSets: Array Of String; IsVisible: Boolean = True); var i: Integer; begin for i := 0 to Self.ColumnCount-1 do Self.Columns[i].Visible := not IsVisible; for i := Low(ColumnSets) to High(ColumnSets) do begin If Assigned(Self.GetColumnByFieldName(ColumnSets[i])) then Self.GetColumnByFieldName(ColumnSets[i]).Visible := IsVisible; end; end; class procedure TcxExtLookup.OnInitPopupCustom(Sender: TObject); begin If Sender is TcxExtLookupComboBox then begin TcxExtLookupComboBox(Sender).Properties.View.DataController.Filter.Clear; TcxExtLookupComboBox(Sender).Properties.ListFieldItem.Focused := True; end; end; class procedure TcxExtLookup.OnClosePopupCustom(Sender: TObject); begin If Sender is TcxExtLookupComboBox then begin TcxExtLookupComboBox(Sender).SetFocus; end; end; procedure TFormHelper.AssignKeyDownEvent; var C: TComponent; i: Integer; begin for i := 0 to Self.ComponentCount-1 do begin C := Self.Components[i]; if C.Tag = 999 then // untuk pengecualian Continue; if C is TEdit then If not Assigned(TEdit(C).OnKeyDown) then TEdit(C).OnKeyDown := OnKeyEnter; if C is TCheckBox then if not Assigned(TCheckBox(C).OnKeyDown) then TCheckBox(C).OnKeyDown := OnKeyEnter; if C is TComboBox then if not Assigned(TComboBox(C).OnKeyDown) then TComboBox(C).OnKeyDown := OnKeyEnter; if C is TMaskEdit then if not Assigned(TMaskEdit(C).OnKeyDown) then TMaskEdit(C).OnKeyDown := OnKeyEnter; if C is TcxSpinEdit then if not Assigned(TcxSpinEdit(C).OnKeyDown) then TcxSpinEdit(C).OnKeyDown := OnKeyEnter; if C is TcxExtLookupComboBox then if not Assigned(TcxExtLookupComboBox(C).OnKeyDown) then TcxExtLookupComboBox(C).OnKeyDown := OnKeyEnter; if C is TLabeledEdit then if not Assigned(TLabeledEdit(C).OnKeyDown) then TLabeledEdit(C).OnKeyDown := OnKeyEnter; if C is TDateTimePicker then if not Assigned(TDateTimePicker(C).OnKeyDown) then TDateTimePicker(C).OnKeyDown := OnKeyEnter; //------ devexpress ---------// if C is TcxExtLookupComboBox then begin //bug: lookup standar, ketika user memilih dengan keyboard panah, lalu enter tidak ngefek //bug: lookup generic / multipurpose harus enter 2x //fix by this code : //1st postpopupvalue must be active TcxExtLookupComboBox(C).Properties.PostPopupValueOnTab := True; //2nd utk generic lookup tambahkan editvaluechanged post tab agar fokus pindah dari view ke lookup if TcxExtLookupComboBox(C).Properties.FocusPopup then if not Assigned(TcxExtLookupComboBox(C).Properties.OnEditValueChanged) then TcxExtLookupComboBox(C).Properties.OnEditValueChanged := OnEditValueChanged; //3rd onEnter send tab key if not Assigned(TcxExtLookupComboBox(C).OnKeyDown) then TcxExtLookupComboBox(C).OnKeyDown:= OnKeyEnter; end else If C.InheritsFrom(TcxCustomEdit) then //for all devexpress If not Assigned(TcxCustomEdit(C).OnKeyDown) then TcxCustomEdit(C).OnKeyDown := OnKeyEnter; end; end; procedure TFormHelper.ClearByTag(Tag: TTag; ParentCtrl: TWinControl = nil); var C: TComponent; i: Integer; begin for i := 0 to Self.ComponentCount-1 do begin C := Self.Components[i]; if not (C.Tag in Tag) then continue; if not C.InheritsFrom(TWinControl) then continue; if ParentCtrl <> nil then if not CheckControlParent(TWinControl(C), ParentCtrl) then continue; if C is TEdit then TEdit(C).Clear; if C is TDateTimePicker then TDateTimePicker(C).Date := Now; if C is TcxDateEdit then TcxDateEdit(C).Date := Now else if C is TcxCurrencyEdit then TcxCurrencyEdit(C).Value := 0 else if C is TcxSpinEdit then TcxSpinEdit(C).Value := 0 else If C.InheritsFrom(TcxCustomEdit) then //standard devexpress parent TcxCustomEdit(C).Clear; end; end; function TFormHelper.CheckControlParent(ChildCtrl, ParentCtrl: TWinControl): Boolean; begin Result := ChildCtrl.Parent = ParentCtrl; if Result then exit; If ChildCtrl.Parent <> nil then Result := CheckControlParent(ChildCtrl.Parent, ParentCtrl); end; function TFormHelper.ValidateEmptyCtrl(Tag: TTag = [1]; ShowWarning: Boolean = True; ParentCtrl: TWinControl = nil): Boolean; var C: TComponent; i: Integer; iTabOrd: Integer; sMsg: string; EmptyCtrl: TWinControl; IsEmpty: Boolean; begin IsEmpty := False; iTabOrd := MaxInt; EmptyCtrl := nil; for i := 0 to Self.ComponentCount-1 do begin C := Self.Components[i]; if not (C.Tag in Tag) then continue; if not C.InheritsFrom(TWinControl) then continue; if ParentCtrl <> nil then if not CheckControlParent(TWinControl(C), ParentCtrl) then continue; if C is TcxExtLookupComboBox then IsEmpty := VarIsNull(TcxExtLookupComboBox(C).EditValue) else if C is TComboBox then IsEmpty := TComboBox(C).ItemIndex = -1 else if C is TEdit then IsEmpty := TRIM(TEdit(C).Text) = '' else if C is TcxComboBox then IsEmpty := TcxComboBox(C).ItemIndex = -1 else if C is TcxTextEdit then IsEmpty := TRIM(TcxTextEdit(C).Text) = '' else if C is TcxButtonEdit then IsEmpty := TRIM(TcxButtonEdit(C).Text) = '' else if C is TLabeledEdit then IsEmpty := TRIM(TLabeledEdit(C).Text) = ''; // else if C is TcxSpinEdit then IsEmpty := TcxSpinEdit(C).Value = 0 // else if C is TcxCurrencyEdit then IsEmpty := TcxCurrencyEdit(C).Value = 0; if (IsEmpty) and (TWinControl(C).TabOrder < iTabOrd) then begin EmptyCtrl := TWinControl(C); iTabOrd := EmptyCtrl.TabOrder; end; end; Result := EmptyCtrl = nil; if (not Result) {and (ShowWarning)} then begin SetFocusRec(EmptyCtrl); Application.ProcessMessages; If ShowWarning then begin if EmptyCtrl.HelpKeyword <> '' then sMsg := EmptyCtrl.HelpKeyword + ' tidak boleh kosong' else sMsg := 'Input Tidak Boleh Kosong'; //for debugging // sMsg := sMsg + #13 + EmptyCtrl.ClassName + '.' + EmptyCtrl.Name; TAppUtils.Warning(sMsg); end; end; end; procedure TFormHelper.OnKeyEnter(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) and (not (ssCtrl in Shift)) then begin if Sender is TcxExtLookupComboBox then Key := VK_TAB else SelectNext(Screen.ActiveControl, True, True); end else if Key = VK_F5 then begin // if Sender is TcxExtLookupComboBox then // TcxExtLookupComboBox(Sender).Properties.OnPopup(Sender); ; end; end; class procedure TFormHelper.OnEditValueChanged(Sender: TObject); var sDebug: string; begin if Sender is TcxExtLookupComboBox then begin //agar generic lookup cukup enter 1x utk pindah ke komponent Keybd_event(VK_TAB, 0, 0, 0); sDebug := TcxExtLookupComboBox(Sender).Name; end; end; function TFormHelper.SetFocusRec(aWinCTRL: TWinControl): Boolean; begin Result := False; If aWinCTRL.Enabled and aWinCTRL.Visible then begin //kapan2 diterusin // if (aWinCTRL is TcxTabSheet) and (not aWinCTRL.Visible) then // begin // If (TcxPageControl(aWinCTRL.Parent).Enabled) // and (TcxPageControl(aWinCTRL.Parent).Visible) then // TcxPageControl(aWinCTRL.Parent).ActivePage := TcxTabSheet(aWinCTRL); // Result := True; // end else If aWinCTRL.Parent <> nil then Result := SetFocusRec(aWinCTRL.Parent) else Result := True; If Result then aWinCTRL.SetFocus; end; end; function TFormHelper.EnableDisableControl(ParentCtrl: TWinControl; aState: Boolean): Boolean; var C: TComponent; i: Integer; // iTabOrd: Integer; // sMsg: string; // EmptyCtrl: TWinControl; // IsEmpty: Boolean; begin Result := False; // IsEmpty := False; // iTabOrd := MaxInt; // EmptyCtrl := nil; for i := 0 to Self.ComponentCount-1 do begin C := Self.Components[i]; if not C.InheritsFrom(TWinControl) then continue; if ParentCtrl <> nil then if not CheckControlParent(TWinControl(C), ParentCtrl) then continue; TWinControl(C).Enabled := aState; // if C is TcxExtLookupComboBox then // IsEmpty := VarIsNull(TcxExtLookupComboBox(C).EditValue) // else if C is TComboBox then IsEmpty := TComboBox(C).ItemIndex = -1 // else if C is TEdit then IsEmpty := TRIM(TEdit(C).Text) = '' // else if C is TcxComboBox then IsEmpty := TcxComboBox(C).ItemIndex = -1 // else if C is TcxTextEdit then IsEmpty := TRIM(TcxTextEdit(C).Text) = ''; //// else if C is TcxSpinEdit then IsEmpty := TcxSpinEdit(C).Value = 0 //// else if C is TcxCurrencyEdit then IsEmpty := TcxCurrencyEdit(C).Value = 0; // // if (IsEmpty) and (TWinControl(C).TabOrder < iTabOrd) then // begin // EmptyCtrl := TWinControl(C); // iTabOrd := EmptyCtrl.TabOrder; // end; end; end; function TcxExtLookupComboHelper.CDS: TClientDataSet; begin Result := TClientDataSet(Self.DS); end; function TcxExtLookupComboHelper.DS: TDataset; begin if Assigned(TcxGridDBTableView(Self.Properties.View).DataController.DataSource ) then Result := TcxGridDBTableView(Self.Properties.View).DataController.DataSource.DataSet else Result := nil; end; function TcxExtLookupComboHelper.EditValueText: String; begin if VarIsNull(EditValue) then Result := '' else Result := EditValue; end; procedure TcxExtLookupComboHelper.LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); begin Self.Properties.LoadFromCDS(aCDS, IDField, DisplayField, HideFields, aOwnerForm); end; procedure TcxExtLookupComboHelper.LoadFromCDS(aCDS: TClientDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); begin Self.Properties.LoadFromCDS(aCDS, IDField, DisplayField, [IDField], aOwnerForm); end; procedure TcxExtLookupComboHelper.LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; HideFields: Array Of String; aOwnerForm: TComponent); begin Self.Properties.LoadFromDS(aDataSet, IDField, DisplayField, HideFields, aOwnerForm); end; procedure TcxExtLookupComboHelper.LoadFromDS(aDataSet: TDataSet; IDField, DisplayField: String; aOwnerForm: TComponent); begin Self.Properties.LoadFromDS(aDataSet, IDField, DisplayField, [IDField], aOwnerForm); end; procedure TcxExtLookupComboHelper.SetDefaultValue(TriggerEvents: Boolean = True); var OnEditValChanged: TNotifyEvent; begin OnEditValChanged := nil; if not TriggerEvents then begin if Assigned(Self.Properties.OnEditValueChanged) then OnEditValChanged := Self.Properties.OnEditValueChanged; Self.Properties.OnEditValueChanged := nil; end; Try Self.Clear; if Self.DS <> nil then begin Self.EditValue := Self.DS.FieldByName(Self.Properties.KeyFieldNames).Value; end; Finally if not TriggerEvents then Self.Properties.OnEditValueChanged := OnEditValChanged; End; end; procedure TcxExtLookupComboHelper.SetMultiPurposeLookup; begin Self.Properties.SetMultiPurposeLookup; end; procedure TcxGridTableViewHelper.ClearRows; var I: Integer; begin BeginUpdate; try for I := DataController.RecordCount - 1 downto 0 do begin DataController.FocusedRecordIndex := i; DataController.DeleteFocused; end; finally EndUpdate; end; end; procedure TcxGridTableViewHelper.SetValue(ARec, ACol : Integer; AValue : Variant); begin Self.DataController.Values[ARec, ACol] := AValue; end; function TcxGridTableViewHelper.Double(ARec, ACol : Integer): Double; begin Result := 0; if not VarIsNull(Values(ARec,ACol)) then Result := Values(ARec,ACol); end; function TcxGridTableViewHelper.Date(ARec, ACol : Integer): TDatetime; begin Result := VarToDateTime(Self.DataController.Values[ARec, ACol]); end; procedure TcxGridTableViewHelper.FilterData(AColumn : TcxGridColumn; AOperatorKind: TcxFilterOperatorKind; const AValues : TStringArray; const ADisplayValues: TStringArray); var i: Integer; lItemList: TcxFilterCriteriaItemList; begin if High(AValues) <> High(ADisplayValues) then raise Exception.Create('Count Of Value is different from Count Of Display Value'); Self.DataController.Filter.BeginUpdate; try Self.DataController.Filter.Root.Clear; lItemList := Self.DataController.Filter.Root.AddItemList(fboOr); for I := Low(AValues) to High(AValues) do begin lItemList.AddItem(AColumn, AOperatorKind, AValues[i], ADisplayValues[i]); end; finally Self.DataController.Filter.EndUpdate; Self.DataController.Filter.Active := true; Self.FilterRow.Visible := False; end; end; procedure TcxGridTableViewHelper.FilterDataLookUp(AColumn : TcxGridColumn; AFilterColumnCaption : String; AOperatorKind: TcxFilterOperatorKind; const AValues : TStringArray; const ADisplayValues: TStringArray); var // i: Integer; lColumn: TcxGridColumn; lCXGrid: TcxGridDBTableView; begin if High(AValues) <> High(ADisplayValues) then raise Exception.Create('Count Of Value is different from Count Of Display Value'); lCXGrid := TcxExtLookupComboBoxProperties(AColumn.Properties).View as TcxGridDBTableView; lColumn := lCXGrid.GetColumnByFieldName(AFilterColumnCaption); lCXGrid.FilterData(lColumn,AOperatorKind, AValues, ADisplayValues); end; function TcxGridTableViewHelper.GetFooterSummary(aColumn: TcxGridColumn): Variant; var i: Integer; begin Result := 0; with Self.DataController.Summary do begin for i :=0 to FooterSummaryItems.Count-1 do begin // If FooterSummaryItems.Items[i].ItemLink.ClassName <> aColumn.ClassName then // continue; If FooterSummaryItems.Items[i].ItemLink = aColumn then Result := FooterSummaryValues[i]; end; end; end; function TcxGridTableViewHelper.GetLevel: TcxGridLevel; var I: Integer; begin Result := nil; for I := 0 to Self.Owner.ComponentCount - 1 do begin if Self.Owner.Components[i] is TcxGridLevel then Result := Self.Owner.Components[i] as TcxGridLevel; end; end; function TcxGridTableViewHelper.Int(ARec, ACol : Integer): Integer; begin if Self.DataController.Values[ARec, ACol] = null then Result := 0 else Result := Self.DataController.Values[ARec, ACol]; end; function TcxGridTableViewHelper.Text(ARec, ACol : Integer): string; begin if Self.DataController.Values[ARec, ACol] = null then Result := '' else Result := Self.DataController.Values[ARec, ACol]; end; procedure TcxGridTableViewHelper.LoadObjectData(AObject : TModApp; ARow : Integer); var ctx : TRttiContext; rt : TRttiType; prop : TRttiProperty; meth : TRttiMethod; I: Integer; lAppObject: TModApp; begin ctx := TRttiContext.Create(); try rt := ctx.GetType(AObject.ClassType); for prop in rt.GetProperties() do begin for I := 0 to Self.ColumnCount - 1 do begin if UpperCase(prop.Name) = UpperCase(Self.Columns[i].AlternateCaption) then begin if prop.Visibility <> mvPublished then Continue; case prop.PropertyType.TypeKind of tkInteger : prop.SetValue(AObject,Self.Int(ARow,i)); tkFloat : If LowerCase(Prop.PropertyType.Name) = LowerCase('TDateTime') then prop.SetValue(AObject,Self.Date(ARow,i)) ELSE prop.SetValue(AObject,Self.Double(ARow,i)); tkUString : prop.SetValue(AObject,Self.Text(ARow,i)); tkClass : begin meth := prop.PropertyType.GetMethod('ToArray'); if Assigned(meth) then begin Continue; end else begin meth := prop.PropertyType.GetMethod('Create'); lAppObject := TModApp(meth.Invoke(prop.PropertyType.AsInstance.MetaclassType, []).AsObject); lAppObject.ID := Self.Text(ARow,i); prop.SetValue(AOBject, lAppObject); end; end; end; end; end; end; finally ctx.Free(); end; end; function TcxGridTableViewHelper.RecordIndex: Integer; begin Result := Self.DataController.FocusedRecordIndex; end; procedure TcxGridTableViewHelper.SetObjectData(AObject : TModApp; ARow : Integer); var ctx : TRttiContext; rt : TRttiType; prop : TRttiProperty; j: Integer; begin ctx := TRttiContext.Create(); try rt := ctx.GetType(AObject.ClassType); for prop in rt.GetProperties() do begin for j := 0 to Self.ColumnCount - 1 do begin if UpperCase(prop.Name) <> UpperCase(Self.Columns[j].AlternateCaption) then Continue; case prop.PropertyType.TypeKind of tkClass : begin Self.SetValue(ARow,j,TModApp(prop.GetValue(AObject).AsObject).ID); end; tkInteger : Self.SetValue(ARow,j,prop.GetValue(AObject).AsInteger); tkFloat : //if CompareText('TDateTime',prop.PropertyType.Name)=0 then // Self.SetValue(i,j,QuotedStr(FormatDateTime('MM/dd/yyyy hh:mm:ss',prop.GetValue(AObject).AsExtended))) // else Self.SetValue(ARow,j,prop.GetValue(AObject).AsExtended); tkUString : Self.SetValue(ARow,j,prop.GetValue(AObject).AsString); end; end; end; finally ctx.Free; end; end; procedure TcxGridTableViewHelper.SetVisibleColumns(FromCol, ToCol: Integer; IsVisible: Boolean); var i: Integer; begin for i := FromCol to ToCol do begin Self.Columns[i].Visible := IsVisible; end; end; function TcxGridTableViewHelper.Validate: Boolean; var IsEmpty: Boolean; j: Integer; k: Integer; sMsg: string; begin Result := False; if Self.DataController.RecordCount = 0 then begin TAppUtils.Warning('Data Pada ' + Self.GetLevel.Caption + ' Masih Kosong' ); Exit; end; IsEmpty := False; for j := 0 to Self.ColumnCount - 1 do begin if not (Self.Columns[j].Tag = 1) then continue; for k := 0 to Self.DataController.RecordCount - 1 do begin if Self.Columns[j].PropertiesClass = TcxTextEditProperties then begin IsEmpty := Self.Text(k,j) = ''; if IsEmpty then Break; end else if Self.Columns[j].PropertiesClass = TcxButtonEditProperties then begin IsEmpty := Self.Text(k,j) = ''; if IsEmpty then Break; end else if Self.Columns[j].PropertiesClass = TcxExtLookupComboBoxProperties then begin IsEmpty := Self.Values(k,j) = null; if IsEmpty then Break; end else if Self.Columns[j].PropertiesClass = TcxCurrencyEditProperties then begin IsEmpty := Self.Double(k,j) = 0; if IsEmpty then Break; end else if Self.Columns[j].PropertiesClass = TcxCalcEditProperties then begin IsEmpty := Self.Int(k,j) = 0; if IsEmpty then Break; end else if Self.Columns[j].PropertiesClass = TcxDateEditProperties then begin IsEmpty := YearOf(Self.Date(k,j)) = 1899; if IsEmpty then Break; end else if Self.Columns[j].PropertiesClass = TcxCurrencyEditProperties then begin IsEmpty := Self.Double(k,j) = 0; if IsEmpty then Break; end; end; if IsEmpty then begin sMsg := 'Data ' + Self.Columns[j].Caption + ' Baris ' + IntToStr(k+1) + ' Masih Salah'; TAppUtils.Warning(sMsg); Exit; end; end; Result := True; end; function TcxGridTableViewHelper.Values(ARec, ACol : Integer): Variant; begin Result := Null; Result := Self.DataController.Values[ARec,ACol]; end; function TcxGridTableViewHelper.Values(ARec : Integer; AColumnCaption : String): Variant; var iCol: Integer; I: Integer; begin Result := Null; iCol := -1; for I := 0 to Self.ColumnCount - 1 do begin if Self.Columns[i].Caption = AColumnCaption then begin iCol := i; end; end; if iCol <> -1 then Result := Self.DataController.Values[ARec,iCol]; end; function TcxExtLookupComboHelper.EditValueRest: String; begin if VarIsNull(EditValue) then Result := '' else Result := EditValue; if Result = '' then Result := 'null'; end; procedure TcxExtLookupComboHelper.SetVisibleColumnsOnly(ColumnSets: Array Of String; IsVisible: Boolean = True); begin Self.Properties.SetVisibleColumnsOnly(ColumnSets, IsVisible); end; function TcxTextEditHelper.TextRest: string; begin Result := Trim(Self.Text); if Result = '' then Result := 'null'; end; function TEditHelper.TextRest: string; begin Result := Trim(Self.Text); if Result = '' then Result := 'null'; end; function TEditHelper.TextTrim: string; begin Result := Trim(Self.Text); end; function TComboboxHelper.TextRest: string; begin Result := Trim(Self.Text); if Result = '' then Result := 'null'; end; end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uViewIntegrator; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Contnrs, Types, IniFiles, math, Controls, Forms, Graphics, uIntegrator, uModel, uModelEntity, uFeedback, uConfig, uLayoutConcepts; type //Baseclass for integrators that are parented TViewIntegrator = class(TTwowayIntegrator) private Parent: TWinControl; function GetCurrentEntity: TModelEntity; class procedure SetCurrentEntity(const Value: TModelEntity); protected Feedback : IEldeanFeedback; procedure CurrentEntityChanged; virtual; public constructor Create(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil); virtual; destructor Destroy; override; //Current entity, all view integrators share the same instance property CurrentEntity : TModelEntity read GetCurrentEntity write SetCurrentEntity; end; //Class to show/edit a model in a powerpointy view TDiagramIntegrator = class(TViewIntegrator) private FOnUpdateToolbar: TNotifyEvent; FOnUpdateZoom: TNotifyEvent; FShowAssoc: boolean; protected FVisibilityFilter: TVisibility; FPathStyle: TPathLayoutStyle; FPackage: TAbstractPackage; procedure SetVisibilityFilter(const Value: TVisibility); virtual; procedure SetPackage(const Value: TAbstractPackage); virtual; procedure SetShowAssoc(const Value: boolean); virtual; procedure SetPathStyle(const Value: TPathLayoutStyle); virtual; function GetStorage(doCreate : boolean = False) : TCustomIniFile; virtual; procedure StoreDiagram; virtual; abstract; function FetchDiagram : integer; virtual; abstract; procedure DoOnUpdateToolbar; procedure DoOnUpdateZoom; public class function CreateDiagram(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil) : TDiagramIntegrator; constructor Create(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil); override; procedure GetDiagramSize(var W,H : integer); virtual; abstract; function GetSelectedRect : TRect; virtual; abstract; procedure PaintTo(Canvas: TCanvas; X, Y: integer; SelectedOnly : boolean); virtual; abstract; procedure SaveAsPicture(const FileName : string); procedure DoLayout; virtual; abstract; function GetClickAreas : TStringList; virtual; abstract; procedure DrawZoom(Canvas : TCanvas; W,H : integer); virtual; abstract; procedure SetZoomedScroll(ScrollX,ScrollY,W,H : integer); virtual; abstract; procedure ScreenCenterEntity(E : TModelEntity); virtual; abstract; procedure HideSelectedDiagramElements; virtual; abstract; function HasHiddenElements : boolean; virtual; abstract; procedure UnHideAllElements; virtual; abstract; //Current package property Package: TAbstractPackage read FPackage write SetPackage; property VisibilityFilter : TVisibility read FVisibilityFilter write SetVisibilityFilter; property OnUpdateToolbar : TNotifyEvent read FOnUpdateToolbar write FOnUpdateToolbar; property OnUpdateZoom : TNotifyEvent read FOnUpdateZoom write FOnUpdateZoom; //True if associations are to be shown property ShowAssoc : boolean read FShowAssoc write SetShowAssoc; property PathStyle: TPathLayoutStyle read FPathStyle write SetPathStyle; end; procedure SetCurrentEntity(Value : TModelEntity); implementation uses uRtfdDiagram; var _CurrentEntity : TModelEntity = nil; _ViewIntegrators : TObjectList; { TViewIntegrator } constructor TViewIntegrator.Create(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil); begin inherited Create(om); Self.Parent := AParent; if Feedback=nil then Self.Feedback := NilFeedback else Self.Feedback := AFeedback; _ViewIntegrators.Add(Self); end; { TDiagramIntegrator } //Factoryfunction, creates an instance of TDiagramIntegrator class function TDiagramIntegrator.CreateDiagram(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil): TDiagramIntegrator; begin Result := TRtfdDiagram.Create(om, AParent, AFeedback); end; procedure TDiagramIntegrator.SetPackage(const Value: TAbstractPackage); begin FPackage := Value; end; //Creates storage space for the diagram function TDiagramIntegrator.GetStorage(doCreate: boolean): TCustomIniFile; var F : string; begin Result := nil; if Assigned(FPackage) then begin F := FPackage.GetConfigFile; if F='' then F := ChangeFileExt(Application.ExeName,ConfigFileExt); if FileExists(F) or doCreate then Result := TMemIniFile.Create(F); end; end; procedure TDiagramIntegrator.SetVisibilityFilter(const Value: TVisibility); begin if FVisibilityFilter<>Value then begin FVisibilityFilter := Value; DoOnUpdateToolbar; DoOnUpdateZoom; end; end; procedure TDiagramIntegrator.DoOnUpdateToolbar; begin if Assigned(FOnUpdateToolbar) then FOnUpdateToolbar(Self); end; procedure TDiagramIntegrator.DoOnUpdateZoom; begin if Assigned(FOnUpdateZoom) then FOnUpdateZoom(Self); end; procedure TDiagramIntegrator.SaveAsPicture(const FileName: string); var W,H : integer; procedure InToPng; var Png : TPortableNetworkGraphic; OldColors,UseMono : boolean; begin Png := TPortableNetworkGraphic.Create; try //Use b/w for large pictures to reduce memory consumption UseMono := Max(W,H)>16000; OldColors := Config.IsLimitedColors; if UseMono then begin Png.Monochrome := True; Config.IsLimitedColors := True; end else if ((W*H*4) div 1024>32000) then //Else if memory takes more than 32mb, use 8-bit (poor colors) Png.PixelFormat := pf8bit; Png.SetSize(W, H); //Othervise noething was drawn Png.Canvas.Rectangle(0, 0, W, H); PaintTo(Png.Canvas,0,0,False); if UseMono then Config.IsLimitedColors := OldColors; Png.SaveToFile( FileName ); finally Png.Free; end; end; begin GetDiagramSize(W{%H-},H{%H-}); InToPng end; procedure TDiagramIntegrator.SetShowAssoc(const Value: boolean); begin FShowAssoc := Value; end; procedure TDiagramIntegrator.SetPathStyle(const Value: TPathLayoutStyle); begin FPathStyle := Value; end; //-------------------------------------- procedure TViewIntegrator.CurrentEntityChanged; begin //stub end; destructor TViewIntegrator.Destroy; begin _ViewIntegrators.Remove(Self); inherited; end; function TViewIntegrator.GetCurrentEntity: TModelEntity; begin Result := _CurrentEntity; end; procedure SetCurrentEntity(Value : TModelEntity); var I : integer; begin if Value<>_CurrentEntity then begin _CurrentEntity := Value; for I := 0 to _ViewIntegrators.Count-1 do (_ViewIntegrators[I] as TViewIntegrator).CurrentEntityChanged; end; end; class procedure TViewIntegrator.SetCurrentEntity(const Value: TModelEntity); begin uViewIntegrator.SetCurrentEntity(Value); end; constructor TDiagramIntegrator.Create(om: TObjectModel; AParent: TWinControl; AFeedback: IEldeanFeedback); begin inherited Create(om, AParent, AFeedback); FShowAssoc := Config.DiShowAssoc; FVisibilityFilter := TVisibility( Config.DiVisibilityFilter ); end; initialization _ViewIntegrators := TObjectList.Create(False); finalization _ViewIntegrators.Free; end.
{----------------------------------------------------------} { Unit Reader_C - Common utilities for the READER } { for Russian SWAG Msg Base Reader } { v.4.0 beta H } { written 1993-2000 by Valery Votintsev 2:5021/22 } { E-Mail: rswag AT sources.ru } {----------------------------------------------------------} {Constants for RSWAG Reader} Unit Reader_C; {$i GSF_FLAG.PAS} Interface Uses CRT, dos, gsf_dos, gsf_glbl, gsf_shel, gsf_Date, vScreen, vMenu, vMemo, vKbd, vString; Type FileOfByte = File of byte; sMsgStyle = (UnKnown,GedStyle,RelcomStyle,SwagStyle); {----- Variable Definition -----} Const {**************** Title Parameters *************************} CopyRight : String[33] ='(c) 1993-2001 by Valery Votintsev'; Version : String[ 7] ='v.4.2'; RSWAG : String[12] = 'Russian SWAG'; GedStartOfMsg : String[8] =' Msg : '; GedEndOfHeader: String80 ='───────────────────────────────────────────────────────────────────────────────'; GedEndOfMsg : String12 =' * Origin: '; GedFromStr : String[8] =' From : '; GedSubjStr : String[8] =' Subj : '; RelStartOfMsg : String[8] ='From '; RelEndOfHeader: String[8] =''; RelDateStr : String[8] ='Date: '; RelFromStr : String[8] ='From: '; RelSubjStr : String12 ='Subject: '; RelOrgStr : String[14] ='Organization: '; RelEndOfMsg : String[8] ='From '; ToArea : String[8] ='X-Area: '; ToFile : String[12] ='X-Filename: '; PickNewArea : String[16] = '>>Pick New Area:'; {----------- Colors ---------------} { MainColor : Byte =Blue + Magenta*16; { главный фон } { WaitColor : Byte =LightGray; WarnColor : Byte = LightGray; AborColor : Byte = LightGray; DocColor : Byte = LightGray; SuspColor : Byte = LightGray; ReadyColor: Byte = LightGray; } AskMe = True; DontAsk = False; Var {-------[ Work Pathes ]----------------} BaseDir : String; { Path to Data Bases } ListDir : String; { Path to List Directory } SwagDir : String; { Path to English SWAG Directory } AreaBase : String12; { Area DataBase Name } {-------[ Areas & Msg Order by ]----------------} AreaOrder, { Area List Default Sort Order} MsgOrder : Integer; { Message Default Sort Order } {-------[ Other usefull variables ]----------------} DosColor : byte; { Old DOS Shell Color } FullScreen:Boolean; { True if MSG text viewed } Lastupdate:String12; { Last Updated by 'PatchName'} AreaID:string12; { Area ID (FileName) } AreaDescr:string80; { Area Description } MsgCounter:integer; { Area Msg Counter } RealAreaName:string12; AreaMsgCounter:string12; Size:string12; ErrorCode:integer; PageNum,MaxPageNum:integer; PageStrNum:string12; MsgNumber:integer; From:string80; Addr:string80; Date,ApDate:string12; Subj:string80; Project:string12; MsgSize:word; SnipetsPerPage:integer; Function CheckWorkPath:Boolean; {Check Work Path existing} Procedure DrawTitleScreen; Procedure ScanAreas; Procedure OpenMainBase(dbFile,dbAlias:String); Function OpenWorkBase(dbFile:String;cAlias:string;AskForCreate:Boolean):Boolean; Procedure CreateWorkBase(Name:String); Procedure CreateGrepBase(Name:String); Function OpenGrepBase(dbFile:String;cAlias:string):Boolean; Procedure Copy1Record(TargetArea:integer); Procedure UpdateMsgCounter(AddNum:integer); Procedure InsertRecord; Procedure Write1Message(Var nHandle:File;NeedHeader:Boolean;Table:pCodeTable); Procedure GetAreaParameters; Procedure GetMsgParameters; Function GetProject:string12; Implementation {---------------------------------------------------------} Procedure GetAreaParameters; begin RealAreaName:=lower(AllTrim(FieldGet('FILENAME'))); AreaID:=Upper(RealAreaName); AreaDescr:=AllTrim(FieldGet('AREA')); AreaMsgCounter:=AllTrim(FieldGet('MSGCOUNT')); Val(AreaMsgCounter,MsgCounter,ErrorCode); {nCounter = Number of messages} MaxPageNum:=(MsgCounter div SnipetsPerPage) + 1; PageNum:=1; end; {----------------------------} Function GetProject:string12; var s:string; n:integer; begin If not FieldExists('PROJECT') then s:='' else begin s:=lower(AllTrim(FieldGet('PROJECT'))); n:=pos('.',s); If n>0 then Byte(s[0]):=pred(n); end; GetProject:=s; end; {---------------------------------------------------------} Procedure GetMsgParameters; var n:longint; i,j:longint; begin From:=AllTrim(FieldGet('FROM')); Addr:=AllTrim(FieldGet('ADDR')); Subj:=AllTrim(FieldGet('SUBJ')); Date:=DateGet('DATE'); Project:=GetProject; n:=gsFileSize(listdir + '\'+RealAreaName+'\'+project+'.zip'); Size:=''; If n>0 then begin n:=(n div 1024); If n = 0 then n:=1; Str(n,Size); Size:=Size+'k'; end; end; {*******************************************************} Procedure WriteHeader(var nHandle:File;Table:pCodeTable); var cStr:String; n:word; begin cStr:='─ '+AreaID+' '; cStr:=cStr+Replicate('─',76-Length(AreaDescr)-Length(cStr)); cStr:=cStr+' '+AreaDescr+' ─'+CRLF; If Table <> NIL then cStr:=ReplaceAll(cStr,'<','&lt;'); cStr:=ConvertStr(cStr,Table); System.BlockWrite( nHandle, cStr[1],Length(cStr),n); cStr:=' Msg : '+IntToStr(RecNo)+' of '+IntToStr(RecCount); cStr:=PadR(cStr,45)+'Addr'; cStr:=PadR(cStr,73)+'Date'+CRLF; If Table <> NIL then cStr:=ReplaceAll(cStr,'<','&lt;'); cStr:=ConvertStr(cStr,Table); System.BlockWrite( nHandle, cStr[1],Length(cStr),n); cStr:=PadR(' From : '+FieldGet('FROM')+' '+ FieldGet('ADDR'),71) + DateGet('DATE')+CRLF; If Table <> NIL then cStr:=ReplaceAll(cStr,'<','&lt;'); cStr:=ConvertStr(cStr,Table); System.BlockWrite( nHandle, cStr[1],Length(cStr),n); cStr:=' Subj : '+RTrim(FieldGet('SUBJ'))+CRLF; If Table <> NIL then cStr:=ReplaceAll(cStr,'<','&lt;'); cStr:=ConvertStr(cStr,Table); System.BlockWrite( nHandle, cStr[1],Length(cStr),n); cStr:=Replicate('─',79)+CRLF; cStr:=ConvertStr(cStr,Table); System.BlockWrite( nHandle, cStr[1],Length(cStr),n); end; Procedure Write1Message(Var nHandle:File;NeedHeader:Boolean;Table:pCodeTable); var n:longint; bl,w:word; { MaxSize:Longint;} begin { MaxSize:=Memo_Size;} If NeedHeader then WriteHeader(nHandle,Table); n:=0; {Num of written for this Msg } bl:=MaxInt; {Block Length for write =32767 } If Memo_Size > 0 then begin If Table <> NIL then begin { ReplaceInMemo('<','&lt;');} ConvertMemo(Table); end; Repeat If (n + bl) > Memo_Size then bl := Memo_Size - n; System.BlockWrite( nHandle, Memo^[n],bl,w); inc(n,w); until (n >=Memo_Size) or (w = 0); end; System.BlockWrite( nHandle, CRLF[1],2,w); {Msg Divider = CRLF} end; {*────────────────────────────────────────────────────────────────────*} Function CheckWorkPath:Boolean; Var Ok:Boolean; begin Ok:=True; If not GsFileExists(BaseDir) then begin If AskYesNo(0,0,' Directory "'+BaseDir+'" not exists. Create it? ') then Ok:=MakeDir(BaseDir)=0 else Ok:=False; end; If Ok and (not GsFileExists(ImportDir)) then begin If AskYesNo(0,0,' Directory "'+ImportDir+'" not exists. Create it? ') then Ok:=MakeDir(ImportDir)=0 else Ok:=False; end; If Ok and (not GsFileExists(ExtractDir)) then begin If AskYesNo(0,0,' Directory "'+ExtractDir+'" not exists. Create it? ') then Ok:=MakeDir(ExtractDir)=0 else Ok:=False; end; CheckWorkPath:=Ok; If not Ok then begin Beep; Beep; WaitForOk('Sorry, No work directories :-(','Ok',White+Red*16,White); end; end; {*******************************} Procedure InsertRecord; { Insert a New Blank Record } var LastOrder:integer; begin LastOrder := IndexCurrentOrder; SetOrderTo(1); SetDeleted(False); GoTOP; If Deleted then begin RECALL; ClearRecord; end else begin ClearRecord; Append; end; SetOrderTo(LastOrder); SetDeleted(True); Replace; end; Procedure UpdateMsgCounter(AddNum:integer); {--- Update Msg Counter } Var ans: longint; begin { Select('AREAS');} Ans:=IntegerGet('MSGCOUNT'); Inc(Ans,AddNum); If Ans < 0 then Ans := 0; IntegerPut('MSGCOUNT',Ans); Replace; { Rewrite Msg Counter } { Select('WORK');} end; {*────────────────────────────────────────────────────────────────────*} {Procedure calling for AREA base Create} {$F+} Function MainFieldProc(FldNo: integer; var AField: String; var AType: char; var ALen, ADec: integer): boolean; Const MainStruct:Array[1..6] of GSR_FieldDesc = ( (FieldName:'AREA'; FieldType:'C';FieldLen:69;FieldDec:0), (FieldName:'FILENAME'; FieldType:'C';FieldLen: 8;FieldDec:0), (FieldName:'LASTREAD'; FieldType:'N';FieldLen: 6;FieldDec:0), (FieldName:'LASTORDER';FieldType:'N';FieldLen: 1;FieldDec:0), (FieldName:'MSGCOUNT'; FieldType:'N';FieldLen:10;FieldDec:0), (FieldName:''; FieldType:' ';FieldLen: 0;FieldDec:0) ); begin MainFieldProc := true; {Return true unless aborting DBFCreate} AField := MainStruct[FldNo].FieldName; AType := MainStruct[FldNo].FieldType; ALen := MainStruct[FldNo].FieldLen; ADec := MainStruct[FldNo].FieldDec; end; {*────────────────────────────────────────────────────────────────────*} {Procedure calling for MSG base Create} Function WorkFieldProc(FldNo: integer; var AField: String; var AType: char; var ALen, ADec: integer): boolean; Const WorkFields:Array[1..10] of GSR_FieldDesc = ( (FieldName:'FROM'; FieldType:'C';FieldLen:25;FieldDec:0), (FieldName:'ADDR'; FieldType:'C';FieldLen:35;FieldDec:0), (FieldName:'SUBJ'; FieldType:'C';FieldLen:52;FieldDec:0), (FieldName:'DATE'; FieldType:'D';FieldLen: 8;FieldDec:0), (FieldName:'APDATE';FieldType:'D';FieldLen: 8;FieldDec:0), (FieldName:'PROJECT'; FieldType:'C';FieldLen:12;FieldDec:0), (FieldName:'TEXT'; FieldType:'M';FieldLen:10;FieldDec:0), (FieldName:'ATTACHME'; FieldType:'M';FieldLen:10;FieldDec:0), (FieldName:'NEW'; FieldType:'L';FieldLen: 1;FieldDec:0), (FieldName:''; FieldType:' ';FieldLen: 0;FieldDec:0) ); begin WorkFieldProc := true; {Return true unless aborting DBFCreate} AField := WorkFields[FldNo].FieldName; AType := WorkFields[FldNo].FieldType; ALen := WorkFields[FldNo].FieldLen; ADec := WorkFields[FldNo].FieldDec; end; {*────────────────────────────────────────────────────────────────────*} {Procedure calling for MSG base Create} Function GrepFieldProc(FldNo: integer; var AField: String; var AType: char; var ALen, ADec: integer): boolean; Const WorkFields:Array[1..12] of GSR_FieldDesc = ( (FieldName:'FROM'; FieldType:'C';FieldLen:25;FieldDec:0), (FieldName:'ADDR'; FieldType:'C';FieldLen:35;FieldDec:0), (FieldName:'SUBJ'; FieldType:'C';FieldLen:52;FieldDec:0), (FieldName:'DATE'; FieldType:'D';FieldLen: 8;FieldDec:0), (FieldName:'APDATE';FieldType:'D';FieldLen: 8;FieldDec:0), (FieldName:'PROJECT'; FieldType:'C';FieldLen:12;FieldDec:0), (FieldName:'TEXT'; FieldType:'M';FieldLen:10;FieldDec:0), (FieldName:'ATTACHME'; FieldType:'M';FieldLen:10;FieldDec:0), (FieldName:'NEW'; FieldType:'L';FieldLen: 1;FieldDec:0), (FieldName:'AREA'; FieldType:'C';FieldLen:69;FieldDec:0), (FieldName:'FILENAME'; FieldType:'C';FieldLen: 8;FieldDec:0), (FieldName:''; FieldType:' ';FieldLen: 0;FieldDec:0) ); begin GrepFieldProc := true; {Return true unless aborting DBFCreate} AField := WorkFields[FldNo].FieldName; AType := WorkFields[FldNo].FieldType; ALen := WorkFields[FldNo].FieldLen; ADec := WorkFields[FldNo].FieldDec; end; {$F-} {*────────────────────────────────────────────────────────────────────*} Procedure CreateMainBase(Name:String); begin {Create new AREA dBase file} If AskYesNo(0,0,' Create '+Name+'? ') then begin CreateDBF(Name, 'F', MainFieldProc); {3 = dBase3,4 = dBase4,C = Clipper,F = FoxPro} end else begin Beep; Beep; WaitForOk('Sorry, can''t work without "'+NAME+'"...','Ok',White+Red*16,White); Halt(1); end; GsFileDelete (name+'.id1'); GsFileDelete (name+'.id2'); GsFileDelete (name+'.cdx'); end; {*────────────────────────────────────────────────────────────────────*} Procedure CreateWorkBase(Name:String); begin {Create new MSG dBase file} { If AskYesNo(0,0,' Create '+Name+'? ') then begin} CreateDBF(Name, 'F', WorkFieldProc); {3 = dBase3,4 = dBase4,C = Clipper,F = FoxPro} { end;} GsFileDelete (name+'.id1'); GsFileDelete (name+'.id2'); GsFileDelete (name+'.cdx'); end; {*────────────────────────────────────────────────────────────────────*} Procedure CreateGrepBase(Name:String); begin {Create new MSG dBase file} { If AskYesNo(0,0,' Create '+Name+'? ') then begin} CreateDBF(Name, 'F', GrepFieldProc); {3 = dBase3,4 = dBase4,C = Clipper,F = FoxPro} { end;} GsFileDelete (name+'.id1'); GsFileDelete (name+'.id2'); GsFileDelete (name+'.cdx'); end; {--------------------------------------------------------------} Function OpenWorkBase(dbFile:String;cAlias:string;AskForCreate:Boolean):Boolean; Var l:boolean; begin l:=False; If not GsFileExists(BaseDir+'\'+dbFile+'.dbf') then begin If AskForCreate then begin If AskYesNo(0,0,' Create "'+dbFile+'" database? ') then begin CreateWorkBase(BaseDir+'\'+dbFile+'.dbf'); end; end else begin CreateWorkBase(BaseDir+'\'+dbFile+'.dbf'); end; end; If GsFileExists(BaseDir+'\'+dbFile+'.dbf') then begin SetCentury(False); { Select(nArea);} Use(BaseDir+'\'+dbFile,cAlias,NewArea); { SetAlias(cAlias);} if not GsFileExists(BaseDir+'\'+dbFile+'.cdx') then begin IndexOn(BaseDir+'\'+dbFile+'.cdx','Subj','UPPER(SUBJ)','',Duplicates,Ascending); IndexOn(BaseDir+'\'+dbFile+'.cdx','From','UPPER(FROM)','',Duplicates,Ascending); end; Index(BaseDir+'\'+dbFile+'.cdx','SUBJ'); SetOrderTo(MsgOrder); { SetMemoPacked(True);} SetDeleted(True); l:=True; end; OpenWorkBase:=l; end; {--------------------------------------------------------------} Function OpenGrepBase(dbFile:String;cAlias:string):Boolean; Var l:boolean; begin l:=False; If not GsFileExists(BaseDir+'\'+dbFile+'.dbf') then CreateGrepBase(BaseDir+'\'+dbFile+'.dbf'); If GsFileExists(BaseDir+'\'+dbFile+'.dbf') then begin SetCentury(False); { Select(nArea);} Use(BaseDir+'\'+dbFile,cAlias,NewArea); { SetAlias(cAlias);} if not GsFileExists(BaseDir+'\'+dbFile+'.cdx') then begin IndexOn(BaseDir+'\'+dbFile+'.cdx','Subj','UPPER(SUBJ)','',Duplicates,Ascending); IndexOn(BaseDir+'\'+dbFile+'.cdx','From','UPPER(FROM)','',Duplicates,Ascending); end; Index(BaseDir+'\'+dbFile+'.cdx','SUBJ'); SetOrderTo(MsgOrder); { SetMemoPacked(True);} SetDeleted(True); l:=True; end; OpenGrepBase:=l; end; {--------------------------------------------------------------} Procedure OpenMainBase(dbFile,dbAlias:String); begin If not GsFileExists(BaseDir+'\'+dbFile+'.dbf') then CreateMainBase(BaseDir+'\'+dbFile); { Select(1);} Use(BaseDir+'\'+dbFile,dbAlias,NewArea); { SetAlias('AREAS');} if not GsFileExists(BaseDir+'\'+dbFile+'.cdx') then begin IndexOn(BaseDir+'\'+dbFile+'.cdx','AreaID','UPPER(FILENAME)','',Duplicates,Ascending); IndexOn(BaseDir+'\'+dbFile+'.cdx','AreaDescr','UPPER(AREA)','',Duplicates,Ascending); end; Index(BaseDir+'\'+dbFile+'.cdx','AREAID'); SetOrderTo(AreaOrder); { SetMemoPacked(True);} SetDeleted(True); SetExact(True); end; {**********************************************************************} Procedure Copy1Record(TargetArea:integer); Var tmpStr:String; OldArea : Integer; BEGIN { ObjFrom := DbfActive;} oldarea := DBFUsed; SelectArea(TargetArea); ClearRecord; Append; {-----------------------} SelectArea(OldArea); tmpStr:=FieldGet('FROM'); SelectArea(TargetArea); FieldPut('FROM',tmpStr); {-----------------------} SelectArea(OldArea); tmpStr:=FieldGet('ADDR'); SelectArea(TargetArea); FieldPut('ADDR',tmpStr); {-----------------------} SelectArea(OldArea); tmpStr:=FieldGet('DATE'); SelectArea(TargetArea); FieldPut('DATE',tmpStr); {-----------------------} SelectArea(OldArea); tmpStr:=FieldGet('APDATE'); SelectArea(TargetArea); { Today:=Gs_Date_Curr; {Get Current Date} { FieldPut('APDATE',DTOS(Today)); {Put Current Date to 'ApDate' field} FieldPut('APDATE',tmpstr); {Put the Append Date to 'ApDate' field} {-----------------------} SelectArea(OldArea); tmpStr:=FieldGet('SUBJ'); SelectArea(TargetArea); FieldPut('SUBJ',tmpStr); {-----------------------} SelectArea(OldArea); If FieldExists('PROJECT') then tmpStr:=FieldGet('PROJECT') else tmpStr:=''; SelectArea(TargetArea); If FieldExists('PROJECT') then FieldPut('PROJECT',tmpStr); {-----------------------} SelectArea(OldArea); tmpStr:=FieldGet('NEW'); SelectArea(TargetArea); FieldPut('NEW',tmpStr); {-----------------------} SelectArea(OldArea); ReadMemo('TEXT'); SelectArea(TargetArea); If Memo_Size > 0 then WriteMemo('TEXT'); {------ATTACHMENT-----------------} SelectArea(OldArea); If FieldExists('ATTACHME') then begin {If field exists} If MemoSize('ATTACHME') <> 0 then begin {If attachment not empty} TmpStr:=FieldGet('PROJECT'); {Get Project Name} AttExtract(AllTrim(TmpStr)); {Extract the attachment} SelectArea(TargetArea); If FieldExists('ATTACHME') then AttImport(TmpStr); {Attach extracted file} gsFileDelete(TmpStr); {Erase this file} end; end; SelectArea(TargetArea); DbfActive^.RecModified:=True; Replace; SelectArea(OldArea); Go(RecNo); END; { Copy1Record } {--------------------------------------------------------------} Procedure DrawTitleScreen; var i:integer; begin SetColor('W+/N'); for i:=1 to 24 do Fill_Char(1,i,'▒',80); {Write n char} SetColor('GR+/N'); Box(3,2,77,22,Single,Shadow); SAY(7, 3,'╔╦══╦╗ ╔╦══╦╗'); SAY(7, 4,'║║ ║║ R U S S I A N S W A G ║║ ║║'); SAY(7, 5,'║║ ║║ ╔╦══╦╗ ╔╗ ╔╗ ╔╗ ╔╦══╦╗ ║║ ╚╝'); SAY(7, 6,'║║ ║║ ║║ ╚╝ ║║ ║║ ║║ ║║ ║║ ║║ ╔╦╗'); SAY(7, 7,'║╠═╦╩╝ ╚╩══╦╗ ║║ ║║ ║║ ║╠══╣║ ║║ ║║║'); SAY(7, 8,'║║ ║╔╗ ╔╗ ║║ ║║ ╔╩╩╗ ║║ ║║ ║║ ║║ ║║'); SAY(7, 9,'╩╩ ╚╩╝ ╚╩══╩╝ ╚╩═╝ ╚═╩╝ ╚╝ ╚╝ ╚╩══╩╝'); SAY(49, 2,'┬'); SAY( 3, 10,'├'); SAY(77, 10,'┤'); for i:=3 to 9 do SAY(49, i,'│'); Fill_Char(4,10,'─',73); {Write n char} SAY(49, 10,'┴'); SetColor('W+/N'); SAY(50, 4,' The '+RSWAG); SAY(50, 5,' Message Reader '+Version); SAY(50, 6,' Written 1998-2001'); SAY(50, 7,' by Valery Votintsev'); SAY(50, 8,' FIDO:2:5021/22'); SAY(50, 9,'(Thanks to Odinn Sorensen!)'); SAY(19,12,'* * * Work In Progress: Getting There * * *'); SAY(5,14,'* Registered to:'); SAY(5,15,'* Registration serial number: absent'); SAY(5,16,'* Valid for DOS versions.'); SetColor('W/B'); ClearLine(25); SetColor('W+/B'); SAY(1,25,AllTrim(AreaBase)); SAY(Length(AreaBase)+2,25, Version); SAY(25,25,'│ Scanning Area:'); end; {-------------------------------------} Procedure ScanAreas; Var n,m:longint; fn:string[8]; begin GoTop; While not dEOF do begin fn:=AllTRim(FieldGet('FILENAME')); SAY(42,25,PadR(fn,8)); n:=0; If fn <> '' then begin If not GsFileExists(BaseDir+'\'+fn+'.dbf') then n:=0 else begin OpenWorkBase(fn,'WORK',DontAsk); n:=RecCount; { If RecCount > 0 then begin { n:=IndexRecNo;} { GoBottom; n:=IndexRecNo; { n:=m-n+1;} { end; } Use('','',False); { Close Current DataBase } end; end; Select('AREAS'); IntegerPut('MSGCOUNT',n); {Rewrite Msg Counter} Replace; Skip(1); end; GoTop; Delay(500); end; begin {READER_C} BaseDir:=''; ListDir:=''; SwagDir:=''; end.
unit VH_Display; interface Uses Windows,SysUtils,OpenGl15,Math3d,VH_Types,Voxel,VH_Voxel,VH_Global,Normals,HVA,Math; {$define DEBUG_VOXEL_BOUNDS} Procedure DrawBox(Position,Color : TVector3f; Size : TVector3f; const VoxelBox: TVoxelBox); overload; Procedure DrawBox(Position: TVector3f; Color : TVector4f; Size : TVector3f; const VoxelBox: TVoxelBox); overload; Procedure DrawBox(_CameraPosition, _BoxPosition, _CameraRotation, _BoxSize : TVector3f); overload; Procedure DrawBoundingBox(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift: TVector3f; const _Rotation: single); overload; Procedure DrawBoundingBox(_CameraPosition, _CenterPosition, _CameraRotation, _BoundingSize : TVector3f); overload; Procedure DrawBullet(_BulletPosition, _BulletSize : TVector3f); Procedure DrawVoxel(const PVxl : PVoxel; const Vxl : TVoxel; Var VoxelBoxes : TVoxelBoxs; VoxelBox_No : integer; HVAOpen : boolean; const HVA : THVA; HVAFrame : Integer); Procedure DrawVoxels(ShiftX,ShiftY,ShiftZ,Rot : Extended); Procedure DrawWorld; Procedure DrawGround(Tex : Integer; Position,Rotation,Color : TVector3f; Size : single); procedure DrawSkyBox(Rotation,Rotation2 : TVector3f); Procedure DrawCenterLines(_CameraPosition, _CenterPosition, _CameraRotation : TVector3f); Procedure DrawSectionCenterLines(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift: TVector3f; const _Rotation: single); Procedure BuildSkyBox; procedure BuildFont; procedure KillFont; procedure glPrint(const text : pchar); function GetPow2Size(Size : Cardinal) : Cardinal; implementation Uses Textures; procedure DoNormals(Normal : Integer); var N : integer; begin N := Normal; if N = -1 then begin glNormal3f(0,0,0); exit; end; if VoxelFile.Section[0].Tailer.Unknown = 4 then if N > 243 then N := 243; if VoxelFile.Section[0].Tailer.Unknown = 2 then if N > 35 then N := 35; if N < 0 then N := 0; if VoxelFile.Section[0].Tailer.Unknown = 2 then glNormal3f(TSNormals[trunc(N)].X{*1.2}, TSNormals[trunc(N)].Y{*1.2}, TSNormals[trunc(N)].Z{*1.2}) else glNormal3f(RA2Normals[trunc(N)].X{*1.2}, RA2Normals[trunc(N)].Y{*1.2}, RA2Normals[trunc(N)].Z{*1.2}); end; Procedure DrawBox(Position,Color : TVector3f; Size : TVector3f; const VoxelBox: TVoxelBox); var Color4f: TVector4f; begin Color4f.X := Color.X; Color4f.Y := Color.Y; Color4f.Z := Color.Z; Color4f.W := 0; DrawBox(Position, Color4f, Size, VoxelBox); end; Procedure DrawBox(Position: TVector3f; Color : TVector4f; Size : TVector3f; const VoxelBox: TVoxelBox); var East,West,South,North,Ceil,Floor : single; begin East := Position.X + Size.X; West := Position.X - Size.X; Ceil := Position.Y + Size.Y; Floor := Position.Y - Size.Y; South := Position.Z + Size.Z; North := Position.Z - Size.Z; glBegin(GL_QUADS); glColor4f(Color.X,Color.Y,Color.Z,Color.W); // Set The Color DoNormals(VoxelBox.Normal); if VoxelBox.Faces[1] then begin glVertex3f(East, Ceil, North); // Top Right Of The Quad (Top) glVertex3f(West, Ceil, North); // Top Left Of The Quad (Top) glVertex3f(West, Ceil, South); // Bottom Left Of The Quad (Top) glVertex3f(East, Ceil, South); // Bottom Right Of The Quad (Top) end; if VoxelBox.Faces[2] then begin glVertex3f(East, Floor, South); // Top Right Of The Quad (Bottom) glVertex3f(West, Floor, South); // Top Left Of The Quad (Bottom) glVertex3f(West, Floor, North); // Bottom Left Of The Quad (Bottom) glVertex3f(East, Floor, North); // Bottom Right Of The Quad (Bottom) end; if VoxelBox.Faces[3] then begin glVertex3f(East, Ceil, South); // Top Right Of The Quad (Front) glVertex3f(West, Ceil, South); // Top Left Of The Quad (Front) glVertex3f(West, Floor,South); // Bottom Left Of The Quad (Front) glVertex3f(East, Floor,South); // Bottom Right Of The Quad (Front) end; if VoxelBox.Faces[4] then begin glVertex3f(East, Floor,North); // Bottom Left Of The Quad (Back) glVertex3f(West, Floor,North); // Bottom Right Of The Quad (Back) glVertex3f(West, Ceil, North); // Top Right Of The Quad (Back) glVertex3f(East, Ceil, North); // Top Left Of The Quad (Back) end; if VoxelBox.Faces[5] then begin glVertex3f(West, Ceil, South); // Top Right Of The Quad (Left) glVertex3f(West, Ceil, North); // Top Left Of The Quad (Left) glVertex3f(West, Floor,North); // Bottom Left Of The Quad (Left) glVertex3f(West, Floor,South); // Bottom Right Of The Quad (Left) end; if VoxelBox.Faces[6] then begin glVertex3f( East, Ceil, North); // Top Right Of The Quad (Right) glVertex3f( East, Ceil, South); // Top Left Of The Quad (Right) glVertex3f( East, Floor,South); // Bottom Left Of The Quad (Right) glVertex3f( East, Floor,North); // Bottom Right Of The Quad (Right) end; glEnd(); end; Procedure DrawVoxel(const PVxl : PVoxel; const Vxl : TVoxel; Var VoxelBoxes : TVoxelBoxs; VoxelBox_No : integer; HVAOpen : boolean; const HVA : THVA; HVAFrame : Integer); var x,s : integer; Scale,FinalScale,Offset, BulletPosition, TurretTranslate, TurretScale : TVector3f; begin if VoxelBox_No < 1 then exit; for s := 0 to VoxelBoxes.NumSections-1 do If ((CurrentSection = s) and (PVxl = CurrentSectionVoxel)) or (DrawAllOfVoxel) or (CurrentSection = -1) then begin GETMinMaxBounds(Vxl,s,Scale,Offset); inc(VoxelsUsed,VoxelBoxes.Sections[s].NumBoxs); FinalScale := ScaleVector(Scale,Size); If (VoxelBoxes.Sections[s].List < 1) or RebuildLists then begin if (VoxelBoxes.Sections[s].List > 0) then glDeleteLists(VoxelBoxes.Sections[s].List,1); VoxelBoxes.Sections[s].List := glGenLists(1); glNewList(VoxelBoxes.Sections[s].List, GL_COMPILE); glPushMatrix; for x := 0 to VoxelBoxes.Sections[s].NumBoxs-1 do begin DrawBox(GetPosWithSize(ScaleVector3f(VoxelBoxes.Sections[s].Boxs[x].Position,Scale),Size),GetVXLColorWithSelection(Vxl,VoxelBoxes.Sections[s].Boxs[x].Color,VoxelBoxes.Sections[s].Boxs[x].Normal,VoxelBoxes.Sections[s].Boxs[x].Section),FinalScale,VoxelBoxes.Sections[s].Boxs[x]); end; glPopMatrix; glEndList; glColor3f(1,1,1); end; glPushMatrix; ApplyMatrix(HVA,Vxl,FinalScale,s,HVAFrame); glTranslatef(Offset.X*Size*2, Offset.Y*Size*2, Offset.Z*Size*2); if (Vxl = VoxelTurret) or (Vxl = VoxelBarrel) then glTranslatef(TurretOffset.X * Size * 2 * LeptonSize,TurretOffset.Y * Size * 2 * LeptonSize,TurretOffset.Z * Size * 2 * LeptonSize); glCallList(VoxelBoxes.Sections[s].List); //if DrawPrimaryFireFLH and (((Vxl = VoxelFile) and (s = (VoxelBoxes.NumSections-1)) and (VoxelBarrel = nil)) or ((VoxelBarrel <> nil) and (Vxl = VoxelTurret))) then if DrawPrimaryFireFLH and (Vxl = VoxelFile) and (s = (VoxelBoxes.NumSections-1)) then begin BulletPosition.X := (PrimaryFireFLH.X + TurretOffset.X) * FinalScale.X * 2 * LeptonSize; BulletPosition.Y := PrimaryFireFLH.Y * FinalScale.Y * 2 * LeptonSize; // This is a 2.5D trick. BulletPosition.Z := PrimaryFireFLH.Z * FinalScale.Z * 2 * LeptonSize; // This is a 2.5D trick. BulletPosition := AddVector(BulletPosition, SetVector((Vxl.Section[s].Tailer.XSize * FinalScale.X) - Size, (Vxl.Section[s].Tailer.YSize * FinalScale.Y) - Size, -1 * Size)); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); DrawBullet(BulletPosition, SetVector(Size * 2 * BulletSize, Size * 2 * BulletSize, Size * 2 * BulletSize)); glEnable(GL_LIGHTING); glEnable(GL_CULL_FACE); end; glPopMatrix; end; end; Procedure DrawVoxels(ShiftX,ShiftY,ShiftZ,Rot : Extended); begin glPushMatrix; VoxelsUsed := 0; // Temporary code: HVAFile.HigherLevel := nil; glLoadIdentity; glTranslatef(CameraCenter.X,CameraCenter.Y, Depth); glRotatef(XRot, 1, 0, 0); glRotatef(YRot, 0, 0, 1); //glTranslatef(UnitShift.X+(x*15)-(2*15), UnitShift.Y+(y*15)-(2*15),0); glTranslatef(ShiftX,ShiftY,ShiftZ); glRotatef(Rot, 0, 0, 1); DrawVoxel(@VoxelFile,VoxelFile,VoxelBoxes,VoxelBox_No,True,HVAFile,HVAFrame); glPushMatrix; glRotatef(VXLTurretRotation.X, 0, 0, 1); If DrawTurret then begin // Temporary code: HVATurret.HigherLevel := @HVAFile; DrawVoxel(@VoxelTurret,VoxelTurret,VoxelBoxesT,VoxelBox_NoT,True,HVATurret,HVAFrameT); end; If DrawBarrel then begin // Temporary code: HVABarrel.HigherLevel := @HVATurret; DrawVoxel(@VoxelBarrel,VoxelBarrel,VoxelBoxesB,VoxelBox_NoB,True,HVABarrel,HVAFrameB); end; glPopMatrix; If RebuildLists then RebuildLists := False; glPopMatrix; end; Procedure DrawTexture(Texture : Cardinal; X,Y : Single; Width,Height,AWidth,AHeight : Cardinal; XOff : Cardinal = 0; YOff : Cardinal = 0; XOffWidth : Cardinal = Cardinal(-1); YOffHeight : Cardinal = Cardinal(-1)); var TexCoordX, TexCoordY, TexCoordOffX, TexCoordOffY : Single; begin //glDisable(GL_CULL_FACE); if XOffWidth = Cardinal(-1) then XOffWidth := Width; if YOffHeight = Cardinal(-1) then YOffHeight := Height; TexCoordX := XOffWidth/AWidth; TexCoordY := YOffHeight/AHeight; TexCoordOffX := XOff/AWidth; TexCoordOffY := YOff/AHeight; glBindTexture(GL_TEXTURE_2D, Texture); glBegin(GL_QUADS); //1 glTexCoord2f(TexCoordOffX, TexCoordOffY); glVertex2f(X, Y); //2 glTexCoord2f(TexCoordOffX+TexCoordX, TexCoordOffY); glVertex2f(X+Width, Y); //3 glTexCoord2f(TexCoordOffX+TexCoordX, TexCoordOffY+TexCoordY); glVertex2f(X+Width, Y+Height); //4 glTexCoord2f(TexCoordOffX, TexCoordOffY+TexCoordY); glVertex2f(X, Y+Height); glEnd; //glEnable(GL_CULL_FACE); end; function GetPow2Size(Size : Cardinal) : Cardinal; var Step : Byte; begin Step := 0; Repeat Result := Trunc(Power(2,Step)); inc(Step); Until (Result >= Size) or (Result >= 4096); if Result > 4096 then Result := 4096; end; Procedure DrawWorld; begin if FUpdateWorld then begin FUpdateWorld := False; if ColoursOnly then begin glDisable(GL_LIGHT0); glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); end else begin glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, @LightAmb); // Set The Ambient Lighting For Light0 glLightfv(GL_LIGHT0, GL_DIFFUSE, @LightDif); // Set The Diffuse Lighting For Light0 glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glNormal3f(0,0,0); end; if (UnitCount = 4) or (UnitCount = 8) then begin DrawVoxels(UnitShift.X-UnitSpace,UnitShift.Y,UnitShift.Z,UnitRot); DrawVoxels(UnitShift.X+UnitSpace,UnitShift.Y,UnitShift.Z,UnitRot+180); DrawVoxels(UnitShift.X,UnitShift.Y-UnitSpace,UnitShift.Z,UnitRot+90); DrawVoxels(UnitShift.X,UnitShift.Y+UnitSpace,UnitShift.Z,UnitRot-90); if UnitCount = 8 then begin DrawVoxels(UnitShift.X-UnitSpace,UnitShift.Y-UnitSpace,UnitShift.Z,UnitRot+45); DrawVoxels(UnitShift.X+UnitSpace,UnitShift.Y+UnitSpace,UnitShift.Z,UnitRot+45+180); DrawVoxels(UnitShift.X+UnitSpace,UnitShift.Y-UnitSpace,UnitShift.Z,UnitRot-45-180); DrawVoxels(UnitShift.X-UnitSpace,UnitShift.Y+UnitSpace,UnitShift.Z,UnitRot-45); end; end else DrawVoxels(UnitShift.X,UnitShift.Y,UnitShift.Z,UnitRot); glDisable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glColor3f(1,1,1); If Not LightGround then begin glDisable(GL_LIGHT0); glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); end else begin glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, @LightAmb); // Set The Ambient Lighting For Light0 glLightfv(GL_LIGHT0, GL_DIFFUSE, @LightDif); // Set The Diffuse Lighting For Light0 glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glNormal3f(0,0,0); end; if Ground_Tex_Draw then DrawGround(GroundTex.Tex,SetVector(CameraCenter.X,CameraCenter.Y,Depth),SetVector(XRot,0,YRot),SetVector(1,1,1),GSize); if DrawSky then DrawSkyBox(SetVector(XRot,0,YRot),SetVector(-90,0,180)); If Not LightGround then begin glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, @LightAmb); // Set The Ambient Lighting For Light0 glLightfv(GL_LIGHT0, GL_DIFFUSE, @LightDif); // Set The Diffuse Lighting For Light0 glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glNormal3f(0,0,0); end; glDisable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); If DrawCenter then DrawCenterLines(SetVector(CameraCenter.X,CameraCenter.Y, Depth),SetVector(0,0,0),SetVector(XRot,0,YRot)); If DrawSectionCenter then begin DrawSectionCenterLines(CurrentVoxel, CurrentHVA, CurrentVoxelSection, GetCurrentFrame(), UnitShift, UnitRot); end; if Highlight then begin DrawBoundingBox(CurrentVoxel, CurrentHVA, CurrentVoxelSection, GetCurrentFrame(), UnitShift, UnitRot); end; glEnable(GL_TEXTURE_2D); if FTexture = 0 then glGenTextures(1, @FTexture); glBindTexture(GL_TEXTURE_2D, FTexture); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, GetPow2Size(SCREEN_WIDTH),GetPow2Size(SCREEN_HEIGHT), 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); end; glDisable(GL_LIGHT0); glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glPushMatrix; glLoadIdentity; glOrtho(0,SCREEN_WIDTH,0,SCREEN_HEIGHT,-1,1); glMatrixMode(GL_MODELVIEW); glPushMatrix; glLoadIdentity; glEnable(GL_TEXTURE_2D); glColor3f(1,1,1); DrawTexture(FTexture,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,GetPow2Size(SCREEN_WIDTH),GetPow2Size(SCREEN_HEIGHT)); glDisable(GL_TEXTURE_2D); If (Not ScreenShot.Take) and (Not ScreenShot.TakeAnimation) and (Not ScreenShot.CaptureAnimation) and (Not ScreenShot.Take360DAnimation) then Begin glColor3f(FontColor.X,FontColor.Y,FontColor.Z); if ShowVoxelCount then begin glRasterPos2i(1,2); glPrint(pchar('Voxels Used: ' + inttostr(VoxelsUsed))); end; glRasterPos2i(1,SCREEN_HEIGHT-9); glPrint(pchar('FPS: ' + inttostr(gTimer.GetAverageFPS))); if DebugMode then begin glRasterPos2i(1,13); glPrint(pchar('Depth: ' + inttostr(trunc(Depth)))); glRasterPos2i(1,SCREEN_HEIGHT-29); glPrint(pchar('XRot:' + floattostr(XRot))); glRasterPos2i(1,SCREEN_HEIGHT-39); glPrint(pchar('YRot:' + floattostr(YRot))); end; end; glMatrixMode(GL_PROJECTION); glPopMatrix; glMatrixMode(GL_MODELVIEW); glPopMatrix; glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); end; procedure BuildFont; // Build Our Bitmap Font var font: HFONT; // Windows Font ID begin base := glGenLists(256); // Storage For 96 Characters SelectObject(H_DC, font); // Selects The Font We Want font := CreateFont(9, 0,0,0, FW_NORMAL, 0, 0, 0, OEM_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY , FF_DONTCARE + DEFAULT_PITCH, 'Terminal'); SelectObject(H_DC, font); wglUseFontBitmaps(H_DC, 0, 127, base); end; procedure KillFont; // Delete The Font begin glDeleteLists(base, 256); // Delete All 96 Characters end; procedure glPrint(const text : pchar); // Custom GL "Print" Routine begin if (text = '') then // If There's No Text Exit; // Do Nothing glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits glListBase(base); // Sets The Base Character glCallLists(length(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text glPopAttrib(); // Pops The Display List Bits end; Procedure DrawGround(Tex : Integer; Position,Rotation,Color : TVector3f; Size : single); var P : TVector3f; w,h,tx,ty : single; TexId : integer; begin glLoadIdentity(); // Reset The View glTranslatef(Position.X, Position.Y, Position.Z); glNormal3f(0,0,0); glRotatef(Rotation.Y, 0, 1, 0); glRotatef(Rotation.X, 1, 0, 0); glRotatef(Rotation.Z, 0, 0, 1); P := GetPosWithSize(SetVector(0, 0, GroundHeightOffset),0.1); glTranslatef(P.X,P.Y,P.Z); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glBindTexture(GL_TEXTURE_2D, Tex); TexId := GetTexInfoNo(Tex); w := 1; h := 1; if (TileGround) and (TexId <> -1) then begin w := ((Size*2)/0.1)/TexInfo[TexId].Width; h := ((Size*2)/0.1)/TexInfo[TexId].Height; end; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); TX := 0; TY := 0; if (TexId <> -1) then begin TX := TexShiftX*(10/TexInfo[TexId].Width); TY := TexShiftY*(10/TexInfo[TexId].Height); end; glBegin(GL_QUADS); glColor3f(Color.X,Color.Y,Color.Z); // Set The Color glTexCoord2f(TX+0.0,TY+0.0); glVertex3f( -Size, -Size, 0); // Top Right Of The Quad (Front) glTexCoord2f(TX+w, TY+0.0); glVertex3f(Size, -Size, 0); // Top Left Of The Quad (Front) glTexCoord2f(TX+w, TY+h); glVertex3f(Size,Size, 0); // Bottom Left Of The Quad (Front) glTexCoord2f(TX+0.0,TY+h); glVertex3f( -Size,Size, 0); // Bottom Right Of The Quad (Front) glEnd(); end; Procedure BuildSkyBox; var px,py,pz : GLfloat; begin // left, back und top sind falsch px := (- SkySize.X / 2);//+pos.x; py := (- SkySize.Y / 2);//+pos.y; pz := (- SkySize.Z / 2);//+pos.z; SkyList := glGenLists(1); glNewList(SkyList, GL_COMPILE); // Back glNormal3f(0,0,0); glBindTexture(GL_TEXTURE_2D, SkyTexList[SkyTex].Textures[3]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glTexCoord2f(1, 0); glVertex3f(px + SkySize.X, py, pz); glTexCoord2f(1, 1); glVertex3f(px + SkySize.X, py + SkySize.Y, pz); glTexCoord2f(0, 1); glVertex3f(px, py + SkySize.Y, pz); glTexCoord2f(0, 0); glVertex3f(px, py, pz); glEnd; // Front glBindTexture(GL_TEXTURE_2D, SkyTexList[SkyTex].Textures[2]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glTexCoord2f(1, 0); glVertex3f(px, py, pz + SkySize.Z); glTexCoord2f(1, 1); glVertex3f(px, py + SkySize.Y, pz + SkySize.Z); glTexCoord2f(0, 1); glVertex3f(px + SkySize.X, py + SkySize.Y, pz + SkySize.Z); glTexCoord2f(0, 0); glVertex3f(px + SkySize.X, py, pz + SkySize.Z); glEnd; // Bottom glBindTexture(GL_TEXTURE_2D, SkyTexList[SkyTex].Textures[5]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glTexCoord2f(1, 1); glVertex3f(px, py, pz); glTexCoord2f(1, 0); glVertex3f(px, py, pz + SkySize.Z); glTexCoord2f(0, 0); glVertex3f(px + SkySize.X, py, pz + SkySize.Z); glTexCoord2f(0, 1); glVertex3f(px + SkySize.X, py, pz); glEnd; // Top glBindTexture(GL_TEXTURE_2D, SkyTexList[SkyTex].Textures[4]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(px+SkySize.X, py + SkySize.Y, pz); glTexCoord2f(1, 0); glVertex3f(px+SkySize.X, py + SkySize.Y, pz + SkySize.Z); glTexCoord2f(1, 1); glVertex3f(px, py + SkySize.Y, pz + SkySize.Z); glTexCoord2f(0, 1); glVertex3f(px, py + SkySize.Y, pz); glEnd; // Left glBindTexture(GL_TEXTURE_2D, SkyTexList[SkyTex].Textures[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glTexCoord2f(1, 1); glVertex3f(px, py + SkySize.Y, pz); glTexCoord2f(0, 1); glVertex3f(px, py + SkySize.Y, pz + SkySize.Z); glTexCoord2f(0, 0); glVertex3f(px, py, pz + SkySize.Z); glTexCoord2f(1, 0); glVertex3f(px, py, pz); glEnd; // Right glBindTexture(GL_TEXTURE_2D, SkyTexList[SkyTex].Textures[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(px + SkySize.X, py, pz); glTexCoord2f(1, 0); glVertex3f(px + SkySize.X, py, pz + SkySize.Z); glTexCoord2f(1, 1); glVertex3f(px + SkySize.X, py + SkySize.Y, pz + SkySize.Z); glTexCoord2f(0, 1); glVertex3f(px + SkySize.X, py + SkySize.Y, pz); glEnd; glEndList; end; procedure DrawSkyBox(Rotation,Rotation2 : TVector3f); begin if SkyList = -1 then begin BuildSkyBox; end; glLoadIdentity; glMatrixMode(GL_MODELVIEW); glPushMatrix; glTranslatef(0, 0, Depth); glRotatef(Rotation.Y, 0, 1, 0); glRotatef(Rotation.X, 1, 0, 0); glRotatef(Rotation.Z, 0, 0, 1); glTranslatef(SkyPos.X, SkyPos.y, SkyPos.Z); glRotatef(Rotation2.Y, 0, 1, 0); glRotatef(Rotation2.X, 1, 0, 0); glRotatef(Rotation2.Z, 0, 0, 1); glCallList(SkyList); glPopMatrix; end; Procedure DrawBox(_CameraPosition, _BoxPosition, _CameraRotation, _BoxSize : TVector3f); var x,y,z : GLfloat; begin // Reset The View. glLoadIdentity(); // Camera. glTranslatef(_CameraPosition.X, _CameraPosition.Y, _CameraPosition.Z); glRotatef(_CameraRotation.Y, 0, 1, 0); glRotatef(_CameraRotation.X, 1, 0, 0); glRotatef(_CameraRotation.Z, 0, 0, 1); // Ensure that box ix centralized at _BoxPosition. x := -_BoxSize.x /2; y := -_BoxSize.y /2; z := -_BoxSize.z /2; glTranslatef(_BoxPosition.X, _BoxPosition.Y, _BoxPosition.Z); // Draw Box. glNormal3f(0,0,0); glBegin(GL_QUADS); glVertex3f(x + _BoxSize.X, y, z); glVertex3f(x + _BoxSize.X, y + _BoxSize.Y, z); glVertex3f(x, y + _BoxSize.Y, z); glVertex3f(x, y, z); glVertex3f(x, y, z + _BoxSize.Z); glVertex3f(x, y + _BoxSize.Y, z + _BoxSize.Z); glVertex3f(x + _BoxSize.X, y + _BoxSize.Y, z + _BoxSize.Z); glVertex3f(x + _BoxSize.X, y, z + _BoxSize.Z); glVertex3f(x, y, z); glVertex3f(x, y, z + _BoxSize.Z); glVertex3f(x + _BoxSize.X, y, z + _BoxSize.Z); glVertex3f(x + _BoxSize.X, y, z); glVertex3f(x + _BoxSize.X, y + _BoxSize.Y, z); glVertex3f(x + _BoxSize.X, y + _BoxSize.Y, z + _BoxSize.Z); glVertex3f(x, y + _BoxSize.Y, z + _BoxSize.Z); glVertex3f(x, y + _BoxSize.Y, z); glVertex3f(x, y + _BoxSize.Y, z); glVertex3f(x, y + _BoxSize.Y, z + _BoxSize.Z); glVertex3f(x, y, z + _BoxSize.Z); glVertex3f(x, y, z); glVertex3f(x + _BoxSize.X, y, z); glVertex3f(x + _BoxSize.X, y, z + _BoxSize.Z); glVertex3f(x + _BoxSize.X, y + _BoxSize.Y, z + _BoxSize.Z); glVertex3f(x + _BoxSize.X, y + _BoxSize.Y, z); glEnd; end; Procedure DrawBullet(_BulletPosition, _BulletSize : TVector3f); var East,West,South,North,Ceil,Floor : single; begin // Ensure that box ix centralized at _BoxPosition. East := _BulletPosition.X + _BulletSize.X/2; West := _BulletPosition.X - _BulletSize.X/ 2; Ceil := _BulletPosition.Y + _BulletSize.Y/2; Floor := _BulletPosition.Y - _BulletSize.Y/2; South := _BulletPosition.Z + _BulletSize.Z/2; North := _BulletPosition.Z - _BulletSize.Z/2; glColor4f(1, 1, 1, 1); glNormal3f(0, 0, 0); glBegin(GL_TRIANGLES); glVertex3f(_BulletPosition.X, _BulletPosition.Y, North); glVertex3f(West, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, Ceil, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, North); glVertex3f(West, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, Floor, _BulletPosition.Z); glVertex3f(West, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, South); glVertex3f(_BulletPosition.X, Ceil, _BulletPosition.Z); glVertex3f(West, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, South); glVertex3f(_BulletPosition.X, Floor, _BulletPosition.Z); glVertex3f(East, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, North); glVertex3f(_BulletPosition.X, Ceil, _BulletPosition.Z); glVertex3f(East, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, North); glVertex3f(_BulletPosition.X, Floor, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, South); glVertex3f(East, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, Ceil, _BulletPosition.Z); glVertex3f(_BulletPosition.X, _BulletPosition.Y, South); glVertex3f(East, _BulletPosition.Y, _BulletPosition.Z); glVertex3f(_BulletPosition.X, Floor, _BulletPosition.Z); glEnd(); end; Procedure DrawCenterLines(_CameraPosition, _CenterPosition, _CameraRotation : TVector3f); begin If Axis = 2 then glColor4f(1,1,1,1) else glColor4f(0,0,1,1); DrawBox(_CameraPosition, _CenterPosition, _CameraRotation, SetVector(30, Size * 2, Size * 2)); If Axis = 1 then glColor4f(1,1,1,1) else glColor4f(0,1,0,1); DrawBox(_CameraPosition, _CenterPosition, _CameraRotation, SetVector(Size * 2, Size * 2, 30)); If Axis = 0 then glColor4f(1,1,1,1) else glColor4f(1,0,0,1); DrawBox(_CameraPosition, _CenterPosition, _CameraRotation, SetVector(Size * 2, 30, Size * 2)); end; Procedure DrawBoundingBox(_CameraPosition, _CenterPosition, _CameraRotation, _BoundingSize : TVector3f); begin glColor4f(1,1,1,0.2); DrawBox(_CameraPosition, _CenterPosition, _CameraRotation, _BoundingSize); end; Procedure DrawBoundingBox(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift: TVector3f; const _Rotation: single); var StartPosition, CenterPosition, BoundingBoxSize: TVector3f; begin StartPosition := GetSectionStartPosition(_Voxel, _HVA, _Section, _Frame, _UnitShift, TurretOffset, _Rotation, Size); CenterPosition := GetSectionCenterPosition(_Voxel, _HVA, _Section, _Frame, _UnitShift, TurretOffset, _Rotation, Size); BoundingBoxSize.X := (CenterPosition.X - StartPosition.X) * 2; BoundingBoxSize.Y := (CenterPosition.Y - StartPosition.Y) * 2; BoundingBoxSize.Z := (CenterPosition.Z - StartPosition.Z) * 2; DrawBoundingBox(SetVector(CameraCenter.X,CameraCenter.Y, Depth), CenterPosition, SetVector(XRot,0,YRot), BoundingBoxSize); end; Procedure DrawSectionCenterLines(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift: TVector3f; const _Rotation: single); var Position: TVector3f; begin Position := GetSectionCenterPosition(_Voxel, _HVA, _Section, _Frame, _UnitShift, TurretOffset, _Rotation, Size); DrawCenterLines(SetVector(CameraCenter.X,CameraCenter.Y, Depth), Position, SetVector(XRot,0,YRot)); end; end.
unit EaterUnit; interface uses Classes, SysUtils, extctrls; const ForksAmount = 100; type PForks = ^TForks; TForks = Array [0..ForksAmount-1] of Boolean; TEater = class(TThread) private { Private declarations } FList: TStrings; FForks: PForks; T: TTimer; k: Integer; // forks #k and #(k+1) success: Boolean; procedure Outcomereport; procedure Start; protected procedure Execute; override; public procedure Tick (Sender: TObject); constructor Create (List: TStrings; Forks: Pointer); end; implementation { TEater } constructor TEater.Create (List: TStrings; Forks: Pointer); Begin inherited Create(True); FForks:= PForks(Forks); FList:= List; FreeOnTerminate:= False; T:= TTimer.Create(nil); End; procedure TEater.Start; Begin k:= Random(99); success:= FForks^[k] and FForks^[k+1]; If success Then Begin FForks^[k]:= False; FForks^[k+1]:= False; FList.Add('Forks #'+ IntToStr(k) + ' and #' + IntToStr(k+1) + ' are busy.'); End Else Begin FList.Add('Failure on forks #'+ IntToStr(k) + ' and #' + IntToStr(k+1)); End; End; procedure TEater.OutComeReport; Begin FForks^[k]:= True; FForks^[k+1]:= True; FList.Add('Forks #'+ IntToStr(k) + ' and #' + IntToStr(k+1) + ' are free.'); End; procedure TEater.Execute; begin Synchronize(Start); If success Then Begin T.OnTimer:= Tick; T.Interval:= 1000 + Random(3000); T.Enabled:= True; Repeat Until (Terminated); Synchronize (OutcomeReport); End; end; procedure TEater.Tick(Sender: TObject); Begin T.Enabled:= False; T.Destroy; Terminate; End; end.
{ @abstract(reads a surfer .clr file and provides rendering tools on a TBitMap level. Adapted by source code provided by Phil Scadden.) @author(Aaron Hochwimer <aaron@graphic-edge.co.nz>) @created(June 27, 2003) @lastmod(July 9, 2003) $Id: cColourSpectrum.pas,v 1.11 2004/07/08 09:54:53 hochwimmera Exp $ } unit cColourSpectrum; interface uses Winapi.Windows, System.Classes, System.SysUtils, Vcl.Graphics, GLVectorGeometry, GLvectorTypes, GLTexture, GLColor; type TRGBArray = array [0 .. 32767] of TRGBTriple; pRGBArray = ^TRGBArray; TColourSpectrumEntry = packed record colour: TRGBTriple; percentvalue: double; end; pColourSpectrumEntry = ^TColourSpectrumEntry; TriVertex = packed record x, y: DWORD; Red, Green, Blue, Alpha: Word; end; TColourSpectrum = class(TObject) private fBorder: boolean; fCLRLegend: boolean; fContinuous: boolean; fEntries: TList; fGLCol_Bottom: TGLColor; fGLCol_Top: TGLColor; fInvertScale: boolean; fInterval: double; fLabelCount: integer; fLabelFormat: string; fMaxColour: TColor; fMaxValue: double; fMinColour: TColor; fMinValue: double; fPixelsPerPercent: integer; fScalePalette: TBitmap; fScaleWithContours: boolean; fSingleColour: TColor; fSpectrumFile: string; fSpectrumMode: integer; procedure Add(dPercent: double; Red, Green, Blue: byte); procedure ClearEntries; procedure DrawBorder; function GetCount: integer; function GetEntry(iIndex: integer): TColourSpectrumEntry; procedure GFillRect(const canvas: TCanvas; start_colour, end_colour: TRGBTriple; rLeft, rTop, rRight, rBottom: integer); function MakeRGB(r, g, b: byte): TRGBTriple; procedure WriteLabel(dValue: double; iLeft, iTop: integer); procedure GenerateLegend(iLeft, iTop: integer); protected procedure SetCLRLegend(bLegend: boolean); procedure SetEntry(Index: integer; value: TColourSpectrumEntry); procedure SetSpectrumFile(sFile: string); procedure SetSpectrumMode(iMode: integer); public constructor Create; destructor Destroy; override; procedure GetColours(const dValue: double; const bForward: boolean; var col1, col2: TColor; var dRatio: double); function GetColourVector(const dValue: double; const bForward: boolean) : TColorVector; procedure MakePalette; procedure ReadCLRFile; property PixelsPerPercent: integer read fPixelsPerPercent write fPixelsPerPercent; property LabelFormat: string read fLabelFormat write fLabelFormat; property Border: boolean read fBorder write fBorder; property Continuous: boolean read fContinuous write fContinuous; property Count: integer read GetCount; property Entries: TList read fEntries write fEntries; property ScaleWithContours: boolean read fScaleWithContours write fScaleWithContours; property glCol_Bottom: TGLColor read fGLCol_Bottom write fGLCol_Bottom; property glCol_Top: TGLColor read fGLCol_Top write fGLCol_Top; property Interval: double read fInterval write fInterval; property SingleColour: TColor read fSingleColour write fSingleColour; property MinColour: TColor read fMinColour write fMinColour; property MaxColour: TColor read fMaxColour write fMaxColour; property SpectrumMode: integer read fSpectrumMode write SetSpectrumMode; property SpectrumFile: string read fSpectrumFile write SetSpectrumFile; property MinValue: double read fMinValue write fMinValue; property MaxValue: double read fMaxValue write fMaxValue; property Scalepalette: TBitmap read fScalePalette write fScalePalette; property InvertScale: boolean read fInvertScale write fInvertScale; property CLRLegend: boolean read fCLRLegend write SetCLRLegend; property LabelCount: integer read fLabelCount write fLabelCount; property Entry[iIndex: integer]: TColourSpectrumEntry read GetEntry write SetEntry; end; // Access a Windows API. May be possbile to use G32? function GradientFill(DC: hDC; pVertex: Pointer; dwNumVertex: DWORD; pMesh: Pointer; dwNumMesh, dwMode: DWORD): DWORD; stdcall; external 'msimg32.dll'; // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- implementation // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- procedure TColourSpectrum.Add(dPercent: double; Red, Green, Blue: byte); var Entry: pColourSpectrumEntry; begin New(Entry); with Entry^ do begin colour := MakeRGB(Red, Green, Blue); percentvalue := dPercent; end; Entries.Add(Entry); end; procedure TColourSpectrum.ClearEntries; var i: integer; begin for i := Entries.Count - 1 downto 0 do Dispose(pColourSpectrumEntry(Entries.Items[i])); Entries.Clear; end; procedure TColourSpectrum.DrawBorder; begin if Assigned(Scalepalette) then begin with Scalepalette.canvas do begin Pen.Color := clBlack; Pen.Mode := pmcopy; Brush.Color := clWhite; Rectangle(0, 1, Scalepalette.Width - 1, Scalepalette.Height - 1); end; end; end; function TColourSpectrum.GetCount: integer; begin result := Entries.Count; end; function TColourSpectrum.GetEntry(iIndex: integer): TColourSpectrumEntry; begin result := pColourSpectrumEntry(Entries.Items[iIndex])^; end; procedure TColourSpectrum.GFillRect(const canvas: TCanvas; start_colour, end_colour: TRGBTriple; rLeft, rTop, rRight, rBottom: integer); var vert: array [0 .. 1] of TriVertex; gRect: GRADIENT_RECT; begin with vert[0] do begin x := rLeft; y := rTop; Red := start_colour.rgbtred shl 8; Green := start_colour.rgbtgreen shl 8; Blue := start_colour.rgbtblue shl 8; Alpha := $0000; end; with vert[1] do begin x := rRight; y := rBottom; Red := end_colour.rgbtred shl 8; Green := end_colour.rgbtgreen shl 8; Blue := end_colour.rgbtblue shl 8; Alpha := $0000; end; gRect.UpperLeft := 0; gRect.LowerRight := 1; GradientFill(canvas.Handle, @vert[0], 2, @gRect, 1, GRADIENT_FILL_RECT_V); end; function TColourSpectrum.MakeRGB(r, g, b: byte): TRGBTriple; begin result.rgbtblue := b; result.rgbtgreen := g; result.rgbtred := r; end; // ----- TColourSpectrum.SetCLRLegend ------------------------------------------ procedure TColourSpectrum.SetCLRLegend(bLegend: boolean); begin fCLRLegend := bLegend; end; procedure TColourSpectrum.SetEntry(Index: integer; value: TColourSpectrumEntry); begin with pColourSpectrumEntry(Entries.Items[Index])^ do begin percentvalue := value.percentvalue; colour := value.colour; end; end; procedure TColourSpectrum.SetSpectrumFile(sFile: string); begin fSpectrumFile := sFile; end; procedure TColourSpectrum.SetSpectrumMode(iMode: integer); var bR, bG, bB: byte; begin fSpectrumMode := iMode; case iMode of // single colour 0: begin InvertScale := false; ClearEntries; bR := GetRValue(SingleColour); bG := GetGValue(SingleColour); bB := GetBValue(SingleColour); Add(0.0, bR, bG, bB); Add(100.0, bR, bG, bB); end; // min/max colour 1: begin InvertScale := false; ClearEntries; Add(0.0, GetRValue(MinColour), GetGValue(MinColour), GetBValue(MinColour)); Add(100.0, GetRValue(MaxColour), GetGValue(MaxColour), GetBValue(MaxColour)); end; // rainbow and inverse rainbow 2, 3: begin InvertScale := (iMode = 3); ClearEntries; Add(0.0, 0, 0, 255); Add(25.0, 0, 255, 255); Add(50.0, 0, 255, 0); Add(75.0, 255, 255, 0); Add(100.0, 255, 0, 0); end; // palette 4: begin InvertScale := false; ReadCLRFile; end; // inverse palette 5: begin InvertScale := true; ReadCLRFile; end; end; end; constructor TColourSpectrum.Create; begin inherited Create; fEntries := TList.Create; fGLCol_Bottom := TGLColor.Create(nil); fGLCol_Top := TGLColor.Create(nil); fSingleColour := clGreen; fMinColour := clBlue; fMaxColour := clRed; Scalepalette := TBitmap.Create; Scalepalette.PixelFormat := pf24bit; fBorder := true; fContinuous := true; fScaleWithContours := true; fLabelFormat := '%5.1g'; fPixelsPerPercent := 4; fInvertScale := false; fCLRLegend := false; // set from code fLabelCount := 2; // number of labels >=2 SpectrumMode := 2; // safe end; destructor TColourSpectrum.Destroy; begin fEntries.Free; fGLCol_Bottom.Free; fGLCol_Top.Free; if Assigned(Scalepalette) then Scalepalette.Free; inherited Destroy; end; procedure TColourSpectrum.GetColours(const dValue: double; const bForward: boolean; var col1, col2: TColor; var dRatio: double); var i, ibot, iTop: integer; dBot, dPercentage: double; begin Interval := MaxValue - MinValue; // clamp bottom colour if (dValue <= MinValue) then begin if bForward then iTop := 0 else iTop := GetCount - 1; col1 := RGB(pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtred, pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtgreen, pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtblue); col2 := col1; // clamp top colour end else if (dValue >= MaxValue) then begin if bForward then iTop := GetCount - 1 else iTop := 0; col1 := RGB(pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtred, pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtgreen, pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtblue); col2 := col1; end else begin dPercentage := 100.0 * (dValue - MinValue) / Interval; if (not bForward) then dPercentage := 100.0 - dPercentage; // miss the 100.0 entry (from count-2) for i := Entries.Count - 2 downto 0 do begin if (pColourSpectrumEntry(Entries.Items[i])^.percentvalue < dPercentage) then begin ibot := i; iTop := i + 1; break; end; end; col1 := RGB(pColourSpectrumEntry(Entries.Items[ibot])^.colour.rgbtred, pColourSpectrumEntry(Entries.Items[ibot])^.colour.rgbtgreen, pColourSpectrumEntry(Entries.Items[ibot])^.colour.rgbtblue); col2 := RGB(pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtred, pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtgreen, pColourSpectrumEntry(Entries.Items[iTop])^.colour.rgbtblue); dBot := pColourSpectrumEntry(Entries.Items[ibot])^.percentvalue; dRatio := (dPercentage - dBot) / (pColourSpectrumEntry(Entries.Items[iTop]) ^.percentvalue - dBot); end; end; function TColourSpectrum.GetColourVector(const dValue: double; const bForward: boolean): TColorVector; var rstar: double; col1, col2: TColor; begin GetColours(dValue, bForward, col1, col2, rstar); glCol_Bottom.AsWinColor := col1; glCol_Top.AsWinColor := col2; VectorLerp(glCol_Bottom.Color, glCol_Top.Color, rstar, result); end; procedure TColourSpectrum.WriteLabel(dValue: double; iLeft, iTop: integer); var sLegendString: string; csize: TSize; begin Scalepalette.canvas.Brush.Color := clWhite; sLegendString := Format(LabelFormat, [dValue]); csize := Scalepalette.canvas.TextExtent(sLegendString); Scalepalette.canvas.TextOut(iLeft, iTop - (csize.cy div 2), sLegendString) end; procedure TColourSpectrum.GenerateLegend(iLeft, iTop: integer); var i, iIndex, iHeight, n, iPos: integer; percent_bot, percent_top, val_top, val_bot: double; begin if not Assigned(Scalepalette) then exit; iPos := iTop; if InvertScale then iIndex := 0 else iIndex := n - 1; if CLRLegend then begin n := Count; with pColourSpectrumEntry(Entries.Items[iIndex])^ do begin percent_top := percentvalue; end; end else begin n := LabelCount; // minimum of 2 if InvertScale then percent_top := 0 else percent_top := 100; end; // writes the first label // WriteLabel(val_top,iLeft,iPos); if InvertScale then begin for i := 0 to n - 1 do begin if CLRLegend then begin with pColourSpectrumEntry(Entries.Items[i])^ do begin percent_bot := percentvalue; iHeight := -Round(PixelsPerPercent * (percent_top - percent_bot)); val_bot := MaxValue - 0.01 * percentvalue * Interval; end; end else begin percent_bot := ((n - 1 - i) / (n - 1)) * 100; iHeight := -Round(PixelsPerPercent * (percent_top - percent_bot)); val_bot := MaxValue - 0.01 * percent_bot * Interval; end; iPos := iPos + iHeight; WriteLabel(val_bot, iLeft, iPos); percent_top := percent_bot; end; end else begin for i := n - 1 downto 0 do begin if CLRLegend then begin with pColourSpectrumEntry(Entries.Items[i])^ do begin percent_bot := percentvalue; iHeight := Round(PixelsPerPercent * (percent_top - percent_bot)); val_bot := MinValue + 0.01 * percentvalue * Interval; end; end else begin percent_bot := i / (n - 1) * 100; iHeight := Round(PixelsPerPercent * (percent_top - percent_bot)); val_bot := MinValue + 0.01 * percent_bot * Interval; end; iPos := iPos + iHeight; WriteLabel(val_bot, iLeft, iPos); percent_top := percent_bot; end; end; end; procedure TColourSpectrum.MakePalette; const iLeft = 5; iTop = 12; var BoxSize: integer; i, iBoxPos, iDepth, iHeight, n: integer; percent_bot, percent_top, val_bot, val_top: double; colour_bot, colour_top: TRGBTriple; r: TRect; iIndex: integer; begin n := Count; if (n = 0) then exit; Interval := (MaxValue - MinValue); if Assigned(Scalepalette) then Scalepalette.Free; Scalepalette := TBitmap.Create; with Scalepalette do begin Transparent := true; PixelFormat := pf24bit; end; iBoxPos := 12; BoxSize := 20; Scalepalette.Width := 60; Scalepalette.Height := (100 * PixelsPerPercent) + 25; Scalepalette.canvas.Font.Height := 12; Scalepalette.canvas.Font.Name := 'Tahoma'; if Border then DrawBorder; Scalepalette.canvas.Pen.Color := clBlack; Scalepalette.canvas.Pen.Mode := pmcopy; iDepth := PixelsPerPercent * 100 + iBoxPos + 1; Scalepalette.canvas.Rectangle(iLeft, iTop - 1, BoxSize, iDepth + 1); if InvertScale then iIndex := 0 else iIndex := n - 1; with pColourSpectrumEntry(Entries.Items[iIndex])^ do begin colour_top := colour; percent_top := percentvalue; if InvertScale then val_top := MaxValue - 0.01 * percent_top * Interval else val_top := MinValue + 0.01 * percent_top * Interval; end; // inverted scale. if InvertScale then begin for i := 1 to n - 1 do begin with pColourSpectrumEntry(Entries.Items[i])^ do begin colour_bot := colour; percent_bot := percentvalue; if i < n - 1 then iHeight := -Round(PixelsPerPercent * (percent_top - percentvalue)) else iHeight := (iDepth - iBoxPos); val_bot := MaxValue - 0.01 * percentvalue * Interval; end; Scalepalette.canvas.Brush.Color := clNone; if Continuous then begin if ScaleWithContours and (i < n - 1) then GFillRect(Scalepalette.canvas, colour_top, colour_bot, iLeft + 1, iBoxPos, BoxSize - 1, iBoxPos + iHeight - 1) else GFillRect(Scalepalette.canvas, colour_top, colour_bot, iLeft + 1, iBoxPos, BoxSize - 1, iBoxPos + iHeight); end else begin Scalepalette.canvas.Brush.Color := RGB(colour_bot.rgbtred, colour_bot.rgbtgreen, colour_bot.rgbtblue); r.Left := iLeft + 1; r.Top := iBoxPos; r.Right := BoxSize - 1; r.Bottom := iBoxPos + iHeight; if ScaleWithContours and (i < n - 1) then r.Bottom := r.Bottom - 1; Scalepalette.canvas.FillRect(r); end; iBoxPos := iBoxPos + iHeight; colour_top := colour_bot; percent_top := percent_bot; end; GenerateLegend(BoxSize + 4, 12); end else begin for i := n - 2 downto 0 do begin with pColourSpectrumEntry(Entries.Items[i])^ do begin colour_bot := colour; percent_bot := percentvalue; if i > 0 then iHeight := Round(PixelsPerPercent * (percent_top - percentvalue)) else iHeight := iDepth - iBoxPos; val_bot := MinValue + 0.01 * percentvalue * Interval; end; Scalepalette.canvas.Brush.Color := clNone; if Continuous then begin if ScaleWithContours and (i > 0) then GFillRect(Scalepalette.canvas, colour_top, colour_bot, iLeft + 1, iBoxPos, BoxSize - 1, iBoxPos + iHeight - 1) else GFillRect(Scalepalette.canvas, colour_top, colour_bot, iLeft + 1, iBoxPos, BoxSize - 1, iBoxPos + iHeight); end else begin Scalepalette.canvas.Brush.Color := RGB(colour_bot.rgbtred, colour_bot.rgbtgreen, colour_bot.rgbtblue); r.Left := iLeft + 1; r.Top := iBoxPos; r.Right := BoxSize - 1; r.Bottom := iBoxPos + iHeight; if ScaleWithContours and (i > 0) then r.Bottom := r.Bottom - 1; Scalepalette.canvas.FillRect(r); end; iBoxPos := iBoxPos + iHeight; colour_top := colour_bot; percent_top := percent_bot; end; GenerateLegend(BoxSize + 4, 12); end; end; procedure TColourSpectrum.ReadCLRFile; var f: TextFile; dPercent: double; red1, green1, blue1: byte; sHeader: string; begin red1 := GetRValue(SingleColour); green1 := GetGValue(SingleColour); blue1 := GetBValue(SingleColour); if FileExists(SpectrumFile) then begin AssignFile(f, SpectrumFile); Reset(f); ReadLn(f, sHeader); if (Pos('ColorMap 1 1', sHeader) = 1) then begin ClearEntries; while not eof(f) do begin ReadLn(f, dPercent, red1, green1, blue1); Add(dPercent, red1, green1, blue1); end; end else begin ClearEntries; Add(0.0, red1, green1, blue1); Add(100.0, red1, green1, blue1); end; CloseFile(f); end else begin ClearEntries; Add(0.0, red1, green1, blue1); Add(100.0, red1, green1, blue1); end; end; // ============================================================================= end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit LPCencodes; {$MODE Delphi} interface uses iLBC_define, helpfun, lsf, constants,C2Delphi_header; {----------------------------------------------------------------* * lpc analysis (subrutine to LPCencode) *---------------------------------------------------------------} procedure SimpleAnalysis( lsf:pareal; { (o) lsf coefficients } data:pareal; { (i) new data vector } iLBCenc_inst:piLBC_Enc_Inst_t { (i/o) the encoder state structure } ); procedure LSFinterpolate2a_enc( a:pareal; { (o) lpc coefficients } lsf1:pareal;{ (i) first set of lsf coefficients } lsf2:pareal;{ (i) second set of lsf coefficients } coef:real; { (i) weighting coefficient to use between lsf1 and lsf2 } length:integer { (i) length of coefficient vectors } ); procedure SimpleInterpolateLSF( syntdenum:pareal; { (o) the synthesis filter denominator resulting from the quantized interpolated lsf } weightdenum:pareal; { (o) the weighting filter denominator resulting from the unquantized interpolated lsf } lsf:pareal; { (i) the unquantized lsf coefficients } lsfdeq:pareal; { (i) the dequantized lsf coefficients } lsfold:pareal; { (i) the unquantized lsf coefficients of the previous signal frame } lsfdeqold:pareal; { (i) the dequantized lsf coefficients of the previous signal frame } length:integer; { (i) should equate LPC_FILTERORDER } iLBCenc_inst:piLBC_Enc_Inst_t { (i/o) the encoder state structure } ); procedure SimplelsfQ( lsfdeq:pareal; { (o) dequantized lsf coefficients (dimension FILTERORDER) } index:painteger; { (o) quantization index } lsf:pareal; { (i) the lsf coefficient vector to be quantized (dimension FILTERORDER ) } lpc_n:integer { (i) number of lsf sets to quantize } ); procedure LPCencode( syntdenum:pareal; { (i/o) synthesis filter coefficients before/after encoding } weightdenum:pareal; { (i/o) weighting denumerator coefficients before/after encoding } lsf_index:painteger; { (o) lsf quantization index } data:pareal; { (i) lsf coefficients to quantize } iLBCenc_inst:piLBC_Enc_Inst_t { (i/o) the encoder state structure } ); implementation procedure SimpleAnalysis( lsf:pareal; { (o) lsf coefficients } data:pareal; { (i) new data vector } iLBCenc_inst:piLBC_Enc_Inst_t { (i/o) the encoder state structure } ); var k, iss:integer; temp:array [0..BLOCKL_MAX-1] of real; lp:array [0..LPC_FILTERORDER] of real; lp2:array [0..LPC_FILTERORDER ] of real; r:array [0..LPC_FILTERORDER] of real; begin iss:=LPC_LOOKBACK+BLOCKL_MAX-iLBCenc_inst^.blockl; move(data[0],iLBCenc_inst^.lpc_buffer[iss],iLBCenc_inst^.blockl*sizeof(real)); { No lookahead, last window is asymmetric } for k := 0 to iLBCenc_inst^.lpc_n-1 do begin iss := LPC_LOOKBACK; if (k < (iLBCenc_inst^.lpc_n - 1)) then begin window(@temp, @lpc_winTbl,@iLBCenc_inst^.lpc_buffer, BLOCKL_MAX); end else begin window(@temp, @lpc_asymwinTbl,@iLBCenc_inst^.lpc_buffer[iss], BLOCKL_MAX); end; autocorr(@r, @temp, BLOCKL_MAX, LPC_FILTERORDER);//這會爆 window(@r, @r, @lpc_lagwinTbl, LPC_FILTERORDER + 1); levdurb(@lp, @temp, @r, LPC_FILTERORDER); bwexpand(@lp2, @lp, LPC_CHIRP_SYNTDENUM, LPC_FILTERORDER+1); a2lsf(@lsf [ k*LPC_FILTERORDER], @lp2); end; iss:=LPC_LOOKBACK+BLOCKL_MAX-iLBCenc_inst^.blockl; move(iLBCenc_inst^.lpc_buffer[LPC_LOOKBACK+BLOCKL_MAX-iss],iLBCenc_inst^.lpc_buffer[0],iss*sizeof(real)); end; {----------------------------------------------------------------* * lsf interpolator and conversion from lsf to a coefficients * (subrutine to SimpleInterpolateLSF) *---------------------------------------------------------------} procedure LSFinterpolate2a_enc( a:pareal; { (o) lpc coefficients } lsf1:pareal;{ (i) first set of lsf coefficients } lsf2:pareal;{ (i) second set of lsf coefficients } coef:real; { (i) weighting coefficient to use between lsf1 and lsf2 } length:integer { (i) length of coefficient vectors } ); var lsftmp:array [0..LPC_FILTERORDER] of real; begin interpolate(@lsftmp, lsf1, lsf2, coef, length); lsf2a(a, @lsftmp); end; {----------------------------------------------------------------* * lsf interpolator (subrutine to LPCencode) *---------------------------------------------------------------} procedure SimpleInterpolateLSF( syntdenum:pareal; { (o) the synthesis filter denominator resulting from the quantized interpolated lsf } weightdenum:pareal; { (o) the weighting filter denominator resulting from the unquantized interpolated lsf } lsf:pareal; { (i) the unquantized lsf coefficients } lsfdeq:pareal; { (i) the dequantized lsf coefficients } lsfold:pareal; { (i) the unquantized lsf coefficients of the previous signal frame } lsfdeqold:pareal; { (i) the dequantized lsf coefficients of the previous signal frame } length:integer; { (i) should equate LPC_FILTERORDER } iLBCenc_inst:piLBC_Enc_Inst_t { (i/o) the encoder state structure } ); var i, pos, lp_length:integer; lp:array [0..LPC_FILTERORDER] of real; lsf2, lsfdeq2:pareal; begin lsf2 := @lsf [ length]; lsfdeq2 := @lsfdeq [ length]; lp_length := length + 1; if (iLBCenc_inst^.mode=30) then begin { sub-frame 1: Interpolation between old and first set of lsf coefficients } LSFinterpolate2a_enc(@lp[0], lsfdeqold, lsfdeq, lsf_weightTbl_30ms[0], length); move(lp[0],syntdenum[0],lp_length*sizeof(real)); LSFinterpolate2a_enc(@lp[0], lsfold, lsf, lsf_weightTbl_30ms[0], length); bwexpand(@weightdenum[0], @lp[0], LPC_CHIRP_WEIGHTDENUM, lp_length); { sub-frame 2 to 6: Interpolation between first and second set of lsf coefficients } pos := lp_length; for i := 1 to iLBCenc_inst^.nsub-1 do begin LSFinterpolate2a_enc(@lp[0], lsfdeq, lsfdeq2, lsf_weightTbl_30ms[i], length); move(lp[0],syntdenum [ pos],lp_length*sizeof(real)); LSFinterpolate2a_enc(@lp[0], lsf, lsf2, lsf_weightTbl_30ms[i], length); bwexpand(@weightdenum [ pos], @lp[0], LPC_CHIRP_WEIGHTDENUM, lp_length); pos :=pos + lp_length; end; end else begin pos := 0; for i := 0 to iLBCenc_inst^.nsub-1 do begin LSFinterpolate2a_enc(@lp[0], lsfdeqold, lsfdeq, lsf_weightTbl_20ms[i], length); move(lp[0],syntdenum[pos],lp_length*sizeof(real)); LSFinterpolate2a_enc(@lp[0], lsfold, lsf, lsf_weightTbl_20ms[i], length); bwexpand(@weightdenum[pos], @lp[0], LPC_CHIRP_WEIGHTDENUM, lp_length); pos :=pos + lp_length; end; end; { update memory } if (iLBCenc_inst^.mode=30) then begin move( lsf2[0],lsfold[0], length*sizeof(real)); move( lsfdeq2[0],lsfdeqold[0], length*sizeof(real)); end else begin move( lsf[0],lsfold[0], length*sizeof(real)); move( lsfdeq[0],lsfdeqold[0], length*sizeof(real)); end; end; {----------------------------------------------------------------* * lsf quantizer (subrutine to LPCencode) *---------------------------------------------------------------} procedure SimplelsfQ( lsfdeq:pareal; { (o) dequantized lsf coefficients (dimension FILTERORDER) } index:painteger; { (o) quantization index } lsf:pareal; { (i) the lsf coefficient vector to be quantized (dimension FILTERORDER ) } lpc_n:integer { (i) number of lsf sets to quantize } ); begin { Quantize first LSF with memoryless split VQ } SplitVQ(lsfdeq, index, lsf, @lsfCbTbl, LSF_NSPLIT, @dim_lsfCbTbl, @size_lsfCbTbl); if (lpc_n=2) then begin { Quantize second LSF with memoryless split VQ } SplitVQ(@lsfdeq [ LPC_FILTERORDER], @index [ LSF_NSPLIT], @lsf [ LPC_FILTERORDER], @lsfCbTbl, LSF_NSPLIT, @dim_lsfCbTbl, @size_lsfCbTbl); end; end; {----------------------------------------------------------------* * lpc encoder *---------------------------------------------------------------} procedure LPCencode( syntdenum:pareal; { (i/o) synthesis filter coefficients before/after encoding } weightdenum:pareal; { (i/o) weighting denumerator coefficients before/after encoding } lsf_index:painteger; { (o) lsf quantization index } data:pareal; { (i) lsf coefficients to quantize } iLBCenc_inst:piLBC_Enc_Inst_t { (i/o) the encoder state structure } ); var lsf:array [0..LPC_FILTERORDER * LPC_N_MAX-1] of real; lsfdeq:array [0..LPC_FILTERORDER * LPC_N_MAX-1] of real; change:integer; begin //change:=0; SimpleAnalysis(@lsf, data, iLBCenc_inst); SimplelsfQ(@lsfdeq, lsf_index, @lsf, iLBCenc_inst^.lpc_n); change:=LSF_check(@lsfdeq, LPC_FILTERORDER, iLBCenc_inst^.lpc_n); SimpleInterpolateLSF(syntdenum, weightdenum, @lsf, @lsfdeq, @iLBCenc_inst^.lsfold, @iLBCenc_inst^.lsfdeqold, LPC_FILTERORDER, iLBCenc_inst); end; end.
unit KFFile; interface uses Classes, SysUtils, UFuncoes; type TKFEntry = class(TObject) private public title: String; items: TStringList; constructor Create; destructor Destroy; override; end; TKFConfigFile = class(TObject) private function ModifyValue(newValue: String; EntryIndex, ItemIdex: Integer): Boolean; function RemoveEntryAt(index: Integer): Boolean; Function AddNewEntryAt(entry: TKFEntry; index: Integer): Boolean; function GetCategoryIndex(category: String; getLast: Boolean): Integer; function GetItemIndex(name: String; index: Integer): Integer; function GetTitleIndex(name: string; getLast: Boolean): Integer; function GetValue(EntryIndex, ItemIdex: Integer): String; function AddNewItemAt(NewItem: string; EntryIndex: Integer; at: Integer): Boolean; public Filename: String; FilePath: string; Entrys: array of TKFEntry; constructor Create; destructor Destroy; override; function LoadFile(path: String): Boolean; function SaveFile(path: String): Boolean; end; TKFWebIni = class(TKFConfigFile) private procedure CreateServerTags; public constructor Create; destructor Destroy; override; function GetWebStatus(): Boolean; procedure SetWebStatus(Status: Boolean); function GetWebPort(): Integer; procedure SetWebPort(Port: Integer); const CCategoryWeb = 'IpDrv.WebServer'; CWebPortTag = 'ListenPort'; CWebStatusTag = 'bEnabled'; end; TKFGameIni = class(TKFConfigFile) private public constructor Create; destructor Destroy; override; function GetMapNameAt(index: Integer): string; function AddMapEntry(name: String): Boolean; function RemoveMapEntry(name: String; removeAll: Boolean): Boolean; function AddMapCycle(name: String): Boolean; function RemoveMapCycle(name: String; removeAll: Boolean): Boolean; function GMCTextToStrings(GMCText: string): TStringList; function GMCStringsToText(GMCStrings: TStringList): string; function GetMapEntryIndex(name: String): Integer; function GetMapCycleIndex(name: String): Integer; function GetMapCycleList: TStringList; const CMapName = 'MapName'; CMapAssociation = 'MapAssociation'; CScreenShotPathName = 'ScreenshotPathName'; CDefaultScreenShot = 'UI_MapPreview_TEX.UI_MapPreview_Placeholder'; CType = 'KFMapSummary'; CGameInfo = 'KFGame.KFGameInfo'; CGameMapCycles = 'GameMapCycles'; end; TKFEngineIni = class(TKFConfigFile) private function AddWorkshopSection(): Boolean; public constructor Create; destructor Destroy; override; function AddWorkshopItem(ID: string): Boolean; function RemoveWorkshopItem(ID: string; removeAll: Boolean): Boolean; function AddWorkshopRedirect(): Boolean; function RemoveWorkshopRedirect(): Boolean; function GetWorkshopItemIndex(ID: string): Integer; function WorkshopRedirectInstalled: Boolean; function GetWorkshopSubcribeCount: Integer; function GetWorkshopSubcribeID(itemIndex: Integer): String; const CWorkshopSubTitle = 'OnlineSubsystemSteamworks.KFWorkshopSteamworks'; CWorkshopSubItem = 'ServerSubscribedWorkshopItems'; CTcpNetDriver = 'IpDrv.TcpNetDriver'; CDownloadManagers = 'DownloadManagers'; CDMWorkshop = 'OnlineSubsystemSteamworks.SteamWorkshopDownload'; end; implementation function IsCategory(text: String): Boolean; begin if (Length(text) > 1) and (text[1] = '[') and (text[StrLen(PChar(text))] = ']') then Result := true else Result := false; end; function GetCategoryName(text: String): String; var markpos1, markpos2: Integer; begin markpos1 := Pos(' ', text); markpos2 := Pos(']', text); Result := ''; if (markpos1 > 0) and (markpos2 > 0) then begin Result := Copy(text, markpos1 + 1, markpos2 - markpos1 - 1); end; end; { TKFEntry } constructor TKFEntry.Create; begin items := TStringList.Create; title := ''; end; destructor TKFEntry.Destroy; begin items.Free; inherited; end; { TKFConfigFile } constructor TKFConfigFile.Create; begin SetLength(Entrys, 0); end; destructor TKFConfigFile.Destroy; var i: Integer; begin for i := 0 to Length(Entrys) - 1 do FreeAndNil(Entrys[i]); inherited; end; function TKFConfigFile.LoadFile(path: String): Boolean; var configFile: TStringList; i, currentEntry: Integer; begin Result := false; try configFile := TStringList.Create; try for i := 0 to High(Entrys) do Entrys[i].Free; SetLength(Entrys, 0); currentEntry := 0; configFile.LoadFromFile(path); if configFile.Count > 1 then begin for i := 0 to configFile.Count - 1 do begin if IsCategory(configFile.Strings[i]) then begin SetLength(Entrys, Length(Entrys) + 1); currentEntry := High(Entrys); Entrys[currentEntry] := TKFEntry.Create; Entrys[currentEntry].title := configFile.Strings[i]; end else begin Entrys[currentEntry].items.Add(configFile.Strings[i]); end; end; Filename := ExtractFileName(path); FilePath := ExtractFilePath(path); Result := true; end; finally configFile.Free; end; except on e: Exception do raise Exception.Create('Falied to load ' + path + ': ' + e.Message); end; end; function TKFConfigFile.SaveFile(path: String): Boolean; var configFile: TStringList; i: Integer; begin Result := false; try configFile := TStringList.Create; try if High(Entrys) >= 1 then begin for i := 0 to High(Entrys) do begin configFile.Add(Entrys[i].title); configFile.AddStrings(Entrys[i].items); end; configFile.SaveToFile(path); Result := true; end; finally configFile.Free; end; except on e: Exception do raise Exception.Create('Falied to save ' + path + ': ' + e.Message); end; end; function TKFConfigFile.GetCategoryIndex(category: String; getLast: Boolean): Integer; var i: Integer; currentCategory: string; begin Result := -1; for i := 0 to High(Entrys) do begin currentCategory := GetCategoryName(Entrys[i].title); if currentCategory = category then begin Result := i; if getLast = false then Exit; end; end; end; function TKFConfigFile.GetItemIndex(name: String; index: Integer): Integer; var i: Integer; line, param: string; begin Result := -1; if (index > High(Entrys)) or (index < 0) then Exit; for i := 0 to Entrys[index].items.Count - 1 do begin line := Entrys[index].items[i]; param := Copy(line, 0, Pos('=', line) - 1); if param = name then begin Result := i; Exit; end; end; end; function TKFConfigFile.GetTitleIndex(name: string; getLast: Boolean): Integer; var i: Integer; begin Result := -1; for i := 0 to High(Entrys) do begin // ShowMessage(Copy(Entrys[i].title, 2, Length(Entrys[i].title) - 2)); if Copy(Entrys[i].title, 2, Length(Entrys[i].title) - 2) = name then begin Result := i; if getLast = false then Exit; end; end; end; function TKFConfigFile.ModifyValue(newValue: String; EntryIndex: Integer; ItemIdex: Integer): Boolean; var line, param1, param2: string; begin Result := false; if Pos('=', Entrys[EntryIndex].items[ItemIdex]) < 0 then Exit; try try line := Entrys[EntryIndex].items[ItemIdex]; param1 := Copy(line, 0, Pos('=', line) - 1); param2 := newValue; Entrys[EntryIndex].items[ItemIdex] := param1 + '=' + param2; Result := true; finally end; except Result := false end; end; function TKFConfigFile.GetValue(EntryIndex: Integer; ItemIdex: Integer): String; var line: string; begin Result := ''; if Pos('=', Entrys[EntryIndex].items[ItemIdex]) < 0 then Exit; try try line := Entrys[EntryIndex].items[ItemIdex]; Result := Copy(line, Pos('=', line) + 1, Length(line) - Pos('=', line)); finally end; except Result := ''; end; end; function TKFConfigFile.AddNewEntryAt(entry: TKFEntry; index: Integer): Boolean; var i: Integer; EntrysCopy: array of TKFEntry; begin Result := false; try try // Coping entrys SetLength(EntrysCopy, Length(Entrys)); for i := 0 to High(Entrys) do begin EntrysCopy[i] := TKFEntry.Create; EntrysCopy[i].title := Entrys[i].title; EntrysCopy[i].items.text := Entrys[i].items.text; end; // Adding new entry SetLength(Entrys, Length(Entrys) + 1); Entrys[ High(Entrys)] := TKFEntry.Create; Entrys[index].title := entry.title; Entrys[index].items.text := entry.items.text; // Remounting Entrys for i := index + 1 to High(Entrys) do begin Entrys[i].title := EntrysCopy[i - 1].title; Entrys[i].items.text := EntrysCopy[i - 1].items.text; end; Result := true; finally for i := 0 to High(EntrysCopy) do EntrysCopy[i].Free; SetLength(EntrysCopy, 0); end; except on e: Exception do raise Exception.Create('Falied add map entry: ' + e.Message); end; end; function TKFConfigFile.AddNewItemAt(NewItem: string; EntryIndex: Integer; at: Integer): Boolean; var i: Integer; StrListCopy: TStringList; begin Result := false; try // Coping entrys StrListCopy := TStringList.Create; try for i := 0 to Entrys[EntryIndex].items.Count - 1 do begin StrListCopy.Add(Entrys[EntryIndex].items[i]); end; Entrys[EntryIndex].items.Clear; for i := 0 to StrListCopy.Count - 1 do begin if i = at then begin Entrys[EntryIndex].items.Add(NewItem); Result := true; end; Entrys[EntryIndex].items.Add(StrListCopy.Strings[i]); end; finally StrListCopy.Free; end; except on e: Exception do raise Exception.Create('Falied to add new item: ' + e.Message); end; end; function TKFConfigFile.RemoveEntryAt(index: Integer): Boolean; var i: Integer; EntrysCopy: array of TKFEntry; begin Result := false; try try // Coping entrys SetLength(EntrysCopy, Length(Entrys)); for i := 0 to High(Entrys) do begin EntrysCopy[i] := TKFEntry.Create; EntrysCopy[i].title := Entrys[i].title; EntrysCopy[i].items.text := Entrys[i].items.text; end; // removing one item Entrys[ High(Entrys)].Free; SetLength(Entrys, Length(Entrys) - 1); // Remounting Entrys for i := 0 to High(EntrysCopy) do begin if i < index then begin Entrys[i].title := EntrysCopy[i].title; Entrys[i].items.text := EntrysCopy[i].items.text; end else begin if i > index then begin Entrys[i - 1].title := EntrysCopy[i].title; Entrys[i - 1].items.text := EntrysCopy[i].items.text; end; end; end; Result := true; finally for i := 0 to High(EntrysCopy) do EntrysCopy[i].Free; SetLength(EntrysCopy, 0); end; except on e: Exception do raise Exception.Create('Falied to remove item: ' + e.Message); end; end; { TKFGameIni } constructor TKFGameIni.Create; begin end; destructor TKFGameIni.Destroy; begin inherited; end; function TKFGameIni.GetMapNameAt(index: Integer): string; var Titleline: string; begin Result := ''; Titleline := Entrys[index].title; if GetCategoryName(Titleline) = CType then begin Result := Copy(Titleline, Pos('[', Titleline) + 1, Pos(' ', Titleline) - 2); end; end; function TKFGameIni.GMCTextToStrings(GMCText: string): TStringList; var chrInx: Integer; aMap: string; begin chrInx := 0; aMap := ''; Result := TStringList.Create; while chrInx < Length(GMCText) do begin if GMCText[chrInx] = '"' then begin while GMCText[chrInx + 1] <> '"' do begin aMap := aMap + GMCText[chrInx + 1]; chrInx := chrInx + 1; end; Result.Add(aMap); aMap := ''; chrInx := chrInx + 1; end; chrInx := chrInx + 1; end; end; function TKFGameIni.GMCStringsToText(GMCStrings: TStringList): string; var i: Integer; begin GMCStrings.Sort; Result := '(Maps=('; for i := 0 to GMCStrings.Count - 1 do begin Result := Result + '"' + GMCStrings.Strings[i] + '"'; if i < GMCStrings.Count - 1 then Result := Result + ',' end; Result := Result + '))'; end; function TKFGameIni.RemoveMapCycle(name: String; removeAll: Boolean): Boolean; var i, GI_index, GMC_index: Integer; newMapCycle, oldMapCycle: string; mapList: TStringList; begin Result := false; try try GI_index := GetTitleIndex(CGameInfo, false); GMC_index := GetItemIndex(CGameMapCycles, GI_index); if (GI_index < 0) or (GMC_index < 0) then begin raise Exception.Create('Falied to remove. GameMapCycles not found.'); Exit; end; oldMapCycle := GetValue(GI_index, GMC_index); mapList := GMCTextToStrings(oldMapCycle); i := 0; while i < mapList.Count do begin if mapList[i] = name then begin mapList.Delete(i); end else begin i := i + 1; end; end; newMapCycle := GMCStringsToText(mapList); ModifyValue(newMapCycle, GI_index, GMC_index); Result := true; finally end; except end; end; function TKFGameIni.AddMapCycle(name: String): Boolean; var newMapCycle, oldMapCycle: string; GI_index, GMC_index: Integer; mapList: TStringList; begin Result := false; try GI_index := GetTitleIndex(CGameInfo, false); GMC_index := GetItemIndex(CGameMapCycles, GI_index); if (GI_index < 0) or (GMC_index < 0) then begin raise Exception.Create('Falied to add. GameMapCycles not found.'); Exit; end; if Pos('"' + name + '"', GetValue(GI_index, GMC_index)) > 0 then begin RemoveMapCycle(name, true); end; oldMapCycle := GetValue(GI_index, GMC_index); mapList := GMCTextToStrings(oldMapCycle); try mapList.Add(name); newMapCycle := GMCStringsToText(mapList); ModifyValue(newMapCycle, GI_index, GMC_index); Result := true; finally mapList.Free; end; except on e: Exception do raise Exception.Create('Falied to edit: ' + e.Message); end; end; function TKFGameIni.GetMapCycleList(): TStringList; var mapCycle: string; GI_index, GMC_index: Integer; begin try try GI_index := GetTitleIndex(CGameInfo, false); GMC_index := GetItemIndex(CGameMapCycles, GI_index); if (GI_index < 0) or (GMC_index < 0) then begin raise Exception.Create ('Falied get map cycle. GameMapCycles not found.'); Exit; end; mapCycle := GetValue(GI_index, GMC_index); Result := GMCTextToStrings(mapCycle); Result.Sort; finally end; except on e: Exception do raise Exception.Create('Falied to get map cycle: ' + e.Message); end; end; function TKFGameIni.RemoveMapEntry(name: String; removeAll: Boolean): Boolean; var i: Integer; begin Result := false; i := 0; while i <= High(Entrys) do begin if (GetCategoryName(Entrys[i].title) = CType) and (GetMapNameAt(i) = name) then begin Result := RemoveEntryAt(i); if removeAll = false then Exit; end else begin i := i + 1; end; end; end; function TKFGameIni.AddMapEntry(name: String): Boolean; var newEntry: TKFEntry; begin if GetTitleIndex(name + ' ' + CType, true) >= 0 then begin RemoveMapEntry(name, true); end; newEntry := TKFEntry.Create; newEntry.title := '[' + name + ' ' + CType + ']'; newEntry.items.Add(CMapName + '=' + name); newEntry.items.Add(CMapAssociation + '=' + '0'); newEntry.items.Add(CScreenShotPathName + '=' + CDefaultScreenShot); newEntry.items.Add(''); Result := AddNewEntryAt(newEntry, GetCategoryIndex('KFMapSummary', true) + 1); end; function TKFGameIni.GetMapEntryIndex(name: String): Integer; begin Result := GetTitleIndex(name + ' ' + CType, true); end; function TKFGameIni.GetMapCycleIndex(name: String): Integer; var mapCycle: string; GI_index, GMC_index: Integer; mapList: TStringList; i: Integer; begin Result := -1; try GI_index := GetTitleIndex(CGameInfo, false); GMC_index := GetItemIndex(CGameMapCycles, GI_index); if (GI_index < 0) or (GMC_index < 0) then begin raise Exception.Create('Falied to read GameMapCycles.'); Exit; end; mapCycle := GetValue(GI_index, GMC_index); mapList := GMCTextToStrings(mapCycle); try for i := 0 to mapList.Count - 1 do begin if mapList[i] = name then begin Result := i; Exit; end; end; finally mapList.Free; end; except on e: Exception do raise Exception.Create('Falied to edit gameMapCycle: ' + e.Message); end; end; { TKFEngineIni } function TKFEngineIni.AddWorkshopItem(ID: string): Boolean; var WS_index: Integer; begin Result := false; try try if (GetTitleIndex(CWorkshopSubTitle, false) < 0) then AddWorkshopSection(); WS_index := GetTitleIndex(CWorkshopSubTitle, false); if (WS_index < 0) then begin raise Exception.Create ('Falied to add workshop section. Item not added.'); Result := false; Exit; end; // remove old if GetWorkshopItemIndex(ID) > 0 then begin RemoveWorkshopItem(ID, true); end; AddNewItemAt(CWorkshopSubItem + '=' + ID, WS_index, Entrys[WS_index].items.Count - 1); Result := true; finally end; except on e: Exception do raise Exception.Create('Falied to download: ' + e.Message); end; end; function TKFEngineIni.RemoveWorkshopItem(ID: string; removeAll: Boolean): Boolean; var i, WS_index: Integer; begin Result := false; try WS_index := GetTitleIndex(CWorkshopSubTitle, false); if (WS_index < 0) then begin raise Exception.Create('Falied to remove workshop item. Item not found.'); Exit; end; i := 0; while i < Entrys[WS_index].items.Count do begin if Entrys[WS_index].items.Strings[i] = CWorkshopSubItem + '=' + ID then begin Entrys[WS_index].items.Delete(i); Result := true; if removeAll = false then Exit; end else begin i := i + 1; end; end; except on e: Exception do raise Exception.Create('Falied to remove workshop item: ' + e.Message); end; end; function TKFEngineIni.GetWorkshopItemIndex(ID: string): Integer; var i, WS_index: Integer; begin Result := -1; try WS_index := GetTitleIndex(CWorkshopSubTitle, false); if (WS_index > 0) then begin for i := 0 to Entrys[WS_index].items.Count - 1 do begin if GetWorkshopSubcribeID(i) = ID then begin Result := i; end; end; Exit; end; except on e: Exception do raise Exception.Create('Falied to get workshop item: ' + e.Message); end; end; function TKFEngineIni.GetWorkshopSubcribeID(itemIndex: Integer): String; var WS_index: Integer; wks_value: string; i: Integer; begin Result := ''; try WS_index := GetTitleIndex(CWorkshopSubTitle, false); if (WS_index > 0) then begin if itemIndex <= Entrys[WS_index].items.Count - 1 then begin wks_value := GetValue(WS_index, itemIndex); for i := 1 to Length(wks_value) do begin if CharInSet(wks_value[i], ['0' .. '9']) then begin Result := Result + wks_value[i]; end else begin Break; end; end; end; end; except on e: Exception do raise Exception.Create('Falied to get workshop item: ' + e.Message); end; end; function TKFEngineIni.GetWorkshopSubcribeCount(): Integer; var WS_index: Integer; begin Result := -1; try WS_index := GetTitleIndex(CWorkshopSubTitle, false); if (WS_index > 0) then begin Result := Entrys[WS_index].items.Count; end; except on e: Exception do raise Exception.Create('Falied to get workshop item count: ' + e.Message); end; end; function TKFEngineIni.AddWorkshopRedirect: Boolean; var TND_index, DM_index: Integer; begin Result := false; try TND_index := GetTitleIndex(CTcpNetDriver, false); DM_index := GetItemIndex(CDownloadManagers, TND_index); if (TND_index < 0) or (DM_index < 0) then raise Exception.Create('Falied to find ' + CTcpNetDriver + '/' + CDownloadManagers + ' entry.'); Result := AddNewItemAt(CDownloadManagers + '=' + CDMWorkshop, TND_index, DM_index); except on e: Exception do raise Exception.Create('Falied add workshop redirect: ' + e.Message); end; end; function TKFEngineIni.RemoveWorkshopRedirect: Boolean; var i, WS_index: Integer; begin Result := false; try WS_index := GetTitleIndex(CTcpNetDriver, false); if (WS_index < 0) then raise Exception.Create('Falied to remove workshop redirect, ' + CTcpNetDriver + ' section not found.'); for i := 0 to Entrys[WS_index].items.Count - 1 do begin if StringReplace(Entrys[WS_index].items.Strings[i], ' ', '', [rfReplaceAll]) = CDownloadManagers + '=' + CDMWorkshop then begin Entrys[WS_index].items.Delete(i); Result := true; break; end; end; except on e: Exception do raise Exception.Create ('Falied to remove workshop redirect: ' + e.Message); end; end; function TKFEngineIni.WorkshopRedirectInstalled: Boolean; var i, WS_index: Integer; begin Result := false; try WS_index := GetTitleIndex(CTcpNetDriver, false); if (WS_index < 0) then Exception.Create('Falied get workshop redirect, ' + CTcpNetDriver + ' section not found.'); for i := 0 to Entrys[WS_index].items.Count - 1 do begin if StringReplace(Entrys[WS_index].items.Strings[i], ' ', '', [rfReplaceAll]) = CDownloadManagers + '=' + CDMWorkshop then begin Result := true; Exit; end; end; except on e: Exception do raise Exception.Create ('Falied get workshop redirect status: ' + e.Message); end; end; function TKFEngineIni.AddWorkshopSection: Boolean; var WorkshopSection: TKFEntry; begin Result := false; try try WorkshopSection := TKFEntry.Create; WorkshopSection.title := '[' + CWorkshopSubTitle + ']'; WorkshopSection.items.Add(''); Result := AddNewEntryAt(WorkshopSection, High(Entrys)); finally end; except end; end; constructor TKFEngineIni.Create; begin end; destructor TKFEngineIni.Destroy; begin inherited; end; { TKFWebIni } constructor TKFWebIni.Create; begin end; destructor TKFWebIni.Destroy; begin inherited; end; function TKFWebIni.GetWebPort(): Integer; var sectionIndex, ItemIdex: Integer; value: String; begin Result := 0; if High(Entrys) > 0 then begin try sectionIndex := GetTitleIndex(CCategoryWeb, false); ItemIdex := GetItemIndex(CWebPortTag, sectionIndex); if (sectionIndex >= 0) and (ItemIdex >= 0) then begin value := GetValue(sectionIndex, ItemIdex); if value <> '' then Result := TextToInt(value); end else begin raise Exception.Create(CWebPortTag + ' in [' + CCategoryWeb + '] not found.'); end; except on e: Exception do raise Exception.Create ('Falied to get web port number. ' + #13 + 'File: ' + Filename + #13 + e.Message); end; end else begin raise Exception.Create('KFWeb.ini is not loaded'); end; end; procedure TKFWebIni.SetWebPort(Port: Integer); var sectionIndex, ItemIdex: Integer; value: String; begin if High(Entrys) > 0 then begin try value := IntToStr(Port); sectionIndex := GetTitleIndex(CCategoryWeb, false); ItemIdex := GetItemIndex(CWebPortTag, sectionIndex); if (sectionIndex < 0) or (ItemIdex < 0) then begin CreateServerTags; sectionIndex := GetTitleIndex(CCategoryWeb, false); ItemIdex := GetItemIndex(CWebPortTag, sectionIndex); end; if (sectionIndex >= 0) and (ItemIdex >= 0) then begin ModifyValue(value, sectionIndex, ItemIdex); end else begin raise Exception.Create(CWebPortTag + ' in ' + CWebStatusTag + ' not found.'); end; except on e: Exception do raise Exception.Create ('Falied get web status. ' + #13 + 'File: ' + Filename + #13 + e.Message); end; end else begin raise Exception.Create('KFWeb.ini is not loaded'); end; end; function TKFWebIni.GetWebStatus(): Boolean; var sectionIndex, ItemIdex: Integer; value: String; begin Result := false; if High(Entrys) > 0 then begin try sectionIndex := GetTitleIndex(CCategoryWeb, false); ItemIdex := GetItemIndex(CWebStatusTag, sectionIndex); if (sectionIndex >= 0) and (ItemIdex >= 0) then begin value := GetValue(sectionIndex, ItemIdex); if UpperCase(CleanText(value)) = 'TRUE' then Result := true; end else begin raise Exception.Create(CWebStatusTag + ' in ' + CCategoryWeb + ' not found.'); end; except on e: Exception do raise Exception.Create ('Falied to get web status. ' + #13 + 'File: ' + Filename + #13 + e.Message); end; end else begin raise Exception.Create('KFWeb.ini is not loaded'); end; end; procedure TKFWebIni.SetWebStatus(Status: Boolean); var sectionIndex, ItemIdex: Integer; value: String; begin if High(Entrys) > 0 then begin try if Status then value := 'true' else value := 'false'; sectionIndex := GetTitleIndex(CCategoryWeb, false); ItemIdex := GetItemIndex(CWebStatusTag, sectionIndex); if (sectionIndex < 0) or (ItemIdex < 0) then begin CreateServerTags; sectionIndex := GetTitleIndex(CCategoryWeb, false); ItemIdex := GetItemIndex(CWebStatusTag, sectionIndex); end; if (sectionIndex >= 0) and (ItemIdex >= 0) then begin ModifyValue(value, sectionIndex, ItemIdex); end else begin raise Exception.Create (CWebStatusTag + ' in ' + CCategoryWeb + ' not found.'); end; except on e: Exception do raise Exception.Create ('Falied get web status. ' + #13 + 'File: ' + Filename + #13 + e.Message); end; end else begin raise Exception.Create('KFWeb.ini is not loaded'); end; end; procedure TKFWebIni.CreateServerTags; var sectionIndex, statusTagIdx, portTagIdx: Integer; newEntry: TKFEntry; begin sectionIndex := GetTitleIndex(CCategoryWeb, false); statusTagIdx := GetItemIndex(CWebStatusTag, sectionIndex); portTagIdx := GetItemIndex(CWebPortTag, sectionIndex); if (sectionIndex < 0) then begin newEntry := TKFEntry.Create; newEntry.title := ('['+CCategoryWeb+']' ); AddNewEntryAt(newEntry, High(Entrys)) end; if (statusTagIdx < 0) then begin begin sectionIndex := GetTitleIndex(CCategoryWeb, false); if sectionIndex >= 0 then Entrys[sectionIndex].items.Add(CWebStatusTag + '=true'); end; end; if (portTagIdx < 0) then begin begin sectionIndex := GetTitleIndex(CCategoryWeb, false); if sectionIndex >= 0 then Entrys[sectionIndex].items.Add(CWebPortTag + '=8080'); end; end; end; end.
//------------------------------------------------------------------------------ //ItemQueries UNIT //------------------------------------------------------------------------------ // What it does- // Item related database routines // // Changes - // February 28th, 2008 - RaX - Created // //------------------------------------------------------------------------------ unit ItemQueries; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} Classes, {Project} Item, EquipmentItem, UseableItem, MiscItem, Inventory, ItemInstance, QueryBase, Map, Character, Equipment, {3rd Party} ZSqlUpdate ; type //------------------------------------------------------------------------------ //TItemQueries CLASS //------------------------------------------------------------------------------ TItemQueries = class(TQueryBase) protected Procedure LoadDefinition( const AnItem : TItem ); Procedure LoadEquipmentDefinition( const AnItem : TEquipmentItem ); procedure LoadUseableDefinition( const AnItem : TUseableItem ); procedure LoadMiscDefinition( const AnItem : TMiscItem ); {Procedure LoadInstance( const AnItem : TItem ); } public procedure Load( var AnItem : TItem ); procedure Save( const AnItem : TItemInstance; const AnInventory : TInventory ); procedure New( const AnItem : TItemInstance; const AnInventory : TInventory ); procedure Delete( const ID : LongWord ); procedure FillInventory( const AChara : TCharacter ); procedure FillMapGround( const Map:TMap ); function Find( const ID : Word ):Boolean;overload; function Find( const Name : String ):Word;overload; procedure GetSpriteIDs( const AnEquipment : TEquipment ); end; //------------------------------------------------------------------------------ implementation uses {RTL/VCL} SysUtils, Types, {Project} GameTypes, ItemTypes, {3rd Party} ZDataset, DB //none ; //------------------------------------------------------------------------------ //Load PROCEDURE //------------------------------------------------------------------------------ // What it does- // Loads an item by ID or Name // // Changes - // February 28th, 2008 - RaX - Created. // [2008/09/19] Aeomin - Small tweak. // //------------------------------------------------------------------------------ Procedure TItemQueries.Load( var AnItem : TItem ); var EquipmentItem : TEquipmentItem; UseableItem : TUseableItem; MiscItem : TMiscItem; procedure ChangeType(const Input:TItem;const Output:TItem); begin Output.Name := Input.Name; Output.ID := Input.ID; Output.Weight := Input.Weight; Output.Price := Input.Price; Output.Sell := Input.Sell; Output.ItemType := Input.ItemType; Output.SpriteID := Input.SpriteID; end; begin LoadDefinition(AnItem); //LoadInstance(AnItem); if AnItem.ItemType = ItemTypes.Equipment then begin EquipmentItem := TEquipmentItem.Create; ChangeType(AnItem, EquipmentItem); AnItem.Free; LoadEquipmentDefinition(EquipmentItem); AnItem:=EquipmentItem; end else if AnItem.ItemType = Useable then begin UseableItem := TUseableItem.Create; ChangeType(AnItem, UseableItem); AnItem.Free; LoadUseableDefinition(UseableItem); AnItem:=UseableItem; end else if AnItem.ItemType = Misc then begin MiscItem := TMiscItem.Create; ChangeType(AnItem, MiscItem); AnItem.Free; LoadMiscDefinition(MiscItem); AnItem:=MiscItem; end; end;//Load //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadDefinition PROCEDURE //------------------------------------------------------------------------------ // What it does- // Loads an item by ID or Name // // Changes - // February 28th, 2008 - RaX - Created. // [2008/09/19] Aeomin - Changed AQuery from var to const. // //------------------------------------------------------------------------------ Procedure TItemQueries.LoadDefinition( const AnItem : TItem ); const AQuery = 'SELECT name, price_buy, weight, item_type, sprite_id '+ 'FROM itemdefinitions WHERE id=:ID'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //Level AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := AnItem.ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataset.First; if NOT ADataSet.Eof then begin AnItem.Name := ADataSet.Fields[0].AsString; AnItem.Price := ADataSet.Fields[1].AsInteger; AnItem.Sell := AnItem.Price DIV 2; AnItem.Weight := ADataSet.Fields[2].AsInteger; AnItem.ItemType := ByteToItemType(ADataSet.Fields[3].AsInteger); AnItem.SpriteID := ADataSet.Fields[4].AsInteger; end; finally ADataSet.Free; end; end;//LoadDefinition //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadEquipmentDefinition PROCEDURE //------------------------------------------------------------------------------ // What it does- // Loads an equipment item by definition ID // // Changes - // February 28th, 2008 - RaX - Created. // [2008/09/19] Aeomin - Changed AQuery from var to const. // //------------------------------------------------------------------------------ Procedure TItemQueries.LoadEquipmentDefinition( const AnItem : TEquipmentItem ); const AQuery = 'SELECT slots, weapon_level, refinable, on_equip_function, on_unequip_function, '+ 'allowed_jobs, allowed_gender, equip_location, on_defend_function, '+ 'attack_rating, attack_range, on_attack_function '+ 'FROM itemdefinitionsequip WHERE item_definition_id=:ID'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := AnItem.ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataset.First; if NOT ADataSet.Eof then begin AnItem.Slots := ADataset.Fields[0].AsInteger; AnItem.WeaponLevel := ADataset.Fields[1].AsInteger; AnItem.Refineable := StrToBoolDef(ADataset.Fields[2].AsString, FALSE); AnItem.OnEquip := ADataSet.Fields[3].AsString; AnItem.OnDisarm := ADataset.Fields[4].AsString; AnItem.Job := ADataset.Fields[5].AsInteger; AnItem.Gender := CharToGender(ADataset.Fields[6].AsString[1]); {AnItem.Defense := ADataset.Fields[7].AsInteger;} AnItem.EquipmentLocation := BytetoEquipLocations(ADataset.Fields[7].AsInteger); AnItem.OnDefend := ADataset.Fields[8].AsString; AnItem.Attack := ADataset.Fields[9].AsInteger; AnItem.Range := ADataset.Fields[10].AsInteger; AnItem.OnAttack := ADataset.Fields[11].AsString; end; finally ADataSet.Free; end; end;//LoadDefinition //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadUseableDefinition PROCEDURE //------------------------------------------------------------------------------ // What it does- // Loads an usable item by definition ID // // Changes - // [208/07/22] Aeomin - Created. // [2008/09/19] Aeomin - Changed AQuery from var to const. // //------------------------------------------------------------------------------ procedure TItemQueries.LoadUseableDefinition( const AnItem : TUseableItem ); const AQuery = 'SELECT on_use_function FROM itemdefinitionsuseable WHERE item_definition_id=:ID'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := AnItem.ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataset.First; if NOT ADataSet.Eof then begin AnItem.OnUse := ADataset.Fields[0].AsString; end; finally ADataSet.Free; end; end;{LoadUseableDefinition} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadMiscDefinition PROCEDURE //------------------------------------------------------------------------------ // What it does- // Loads an usable item by definition ID // // Changes - // [2008/07/22] Aeomin - Created. // [2008/09/19] Aeomin - Changed AQuery from var to const. // //------------------------------------------------------------------------------ procedure TItemQueries.LoadMiscDefinition( const AnItem : TMiscItem ); const AQuery = 'SELECT on_compound_function FROM itemdefinitionsmisc WHERE item_definition_id=:ID'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := AnItem.ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataset.First; if NOT ADataSet.Eof then begin AnItem.OnCompound := ADataset.Fields[0].AsString; end; finally ADataSet.Free; end; end;{LoadMiscDefinition} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Save PROCEDURE //------------------------------------------------------------------------------ // What it does- // Save an item instance // // Changes - // [2008/09/21] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TItemQueries.Save( const AnItem : TItemInstance; const AnInventory : TInventory ); const AQuery = 'UPDATE items SET item_storage_id=:StorageID, amount=:Amount, '+ '`identified`=:Identified,`refined`:=Refined, last_x=:X, last_y=:Y, last_map_id=:MapID WHERE `id`=:ID'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := AnItem.ID; ADataSet.Params.AddParam( AParam ); //StorageID AParam := ADataset.Params.CreateParam(ftInteger, 'StorageID', ptInput); if AnInventory = nil then begin AParam.AsInteger := 0; end else begin if AnItem.Item is TUseableItem then AParam.AsInteger := AnInventory.UseID else if AnItem.Item is TEquipmentItem then AParam.AsInteger := AnInventory.EquipID else if AnItem.Item is TMiscItem then AParam.AsInteger := AnInventory.EtcID; end; ADataSet.Params.AddParam( AParam ); //Amount AParam := ADataset.Params.CreateParam(ftInteger, 'Amount', ptInput); AParam.AsInteger := AnItem.Quantity; ADataSet.Params.AddParam( AParam ); //Identified AParam := ADataset.Params.CreateParam(ftBoolean, 'Identified', ptInput); AParam.AsInteger := Byte(AnItem.Identified); ADataSet.Params.AddParam( AParam ); //Refined AParam := ADataset.Params.CreateParam(ftInteger, 'Refined', ptInput); AParam.AsInteger := AnItem.Refined; ADataSet.Params.AddParam( AParam ); //X AParam := ADataset.Params.CreateParam(ftInteger, 'X', ptInput); AParam.AsInteger := AnItem.Position.X; ADataSet.Params.AddParam( AParam ); //Y AParam := ADataset.Params.CreateParam(ftInteger, 'Y', ptInput); AParam.AsInteger := AnItem.Position.Y; ADataSet.Params.AddParam( AParam ); //MapID AParam := ADataset.Params.CreateParam(ftInteger, 'MapID', ptInput); AParam.AsInteger := AnItem.MapID; ADataSet.Params.AddParam( AParam ); QueryNoResult(ADataSet, AQuery); finally ADataSet.Free; end; end;{Save} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //New PROCEDURE //------------------------------------------------------------------------------ // What it does- // Create a new record in database // // Changes - // [2008/09/21] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TItemQueries.New( const AnItem : TItemInstance; const AnInventory : TInventory ); const AQuery = 'INSERT INTO items (`item_definition_id`,`item_storage_id`,`amount`,`identified`,`last_x`,`last_y`,`last_map_id`) VALUES '+ '(:DefinitionID, :StorageID, :Amount, :Identified, :X, :Y, :MapID);'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //DefinitionID AParam := ADataset.Params.CreateParam(ftInteger, 'DefinitionID', ptInput); AParam.AsInteger := AnItem.Item.ID; ADataSet.Params.AddParam( AParam ); //StorageID AParam := ADataset.Params.CreateParam(ftInteger, 'StorageID', ptInput); if AnInventory = nil then begin AParam.AsInteger := 0; end else begin if AnItem.Item is TUseableItem then AParam.AsInteger := AnInventory.UseID else if AnItem.Item is TEquipmentItem then AParam.AsInteger := AnInventory.EquipID else if AnItem.Item is TMiscItem then AParam.AsInteger := AnInventory.EtcID; end; ADataSet.Params.AddParam( AParam ); //Amount AParam := ADataset.Params.CreateParam(ftInteger, 'Amount', ptInput); AParam.AsInteger := AnItem.Quantity; ADataSet.Params.AddParam( AParam ); //Identified AParam := ADataset.Params.CreateParam(ftBoolean, 'Identified', ptInput); AParam.AsInteger := Byte(AnItem.Identified); ADataSet.Params.AddParam( AParam ); //X AParam := ADataset.Params.CreateParam(ftInteger, 'X', ptInput); AParam.AsInteger := AnItem.Position.X; ADataSet.Params.AddParam( AParam ); //Y AParam := ADataset.Params.CreateParam(ftInteger, 'Y', ptInput); AParam.AsInteger := AnItem.Position.Y; ADataSet.Params.AddParam( AParam ); //MapID AParam := ADataset.Params.CreateParam(ftInteger, 'MapID', ptInput); AParam.AsInteger := AnItem.MapID; ADataSet.Params.AddParam( AParam ); QueryNoResult(ADataSet, AQuery); AnItem.ID := LastID('`id`','`items`','WHERE item_definition_id='+IntToStr(AnItem.Item.ID)); finally ADataSet.Free; end; end;{New} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Delete PROCEDURE //------------------------------------------------------------------------------ // What it does- // Delete an item instance // // Changes - // [2008/10/03] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TItemQueries.Delete( const ID : LongWord ); const AQuery = 'DELETE FROM `items` WHERE id=:ID;'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := ID; ADataSet.Params.AddParam( AParam ); QueryNoResult(ADataSet, AQuery); finally ADataSet.Free; end; end;{Delete} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //FillInventory PROCEDURE //------------------------------------------------------------------------------ // What it does- // Load inventory of item // // Changes - // [2008/09/17] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TItemQueries.FillInventory( const AChara : TCharacter ); const AQuery = 'SELECT `id`,`item_definition_id`,`amount`,`identified`,`refined`,`last_x`,`last_y`,`last_map_id` '+ 'FROM items ' + 'WHERE `item_storage_id` IN (:UseID,:EquipID,:MiscID) AND `last_map_id`=0;'; var ADataSet : TZQuery; AParam : TParam; AItem : TItemInstance; APoint : TPoint; begin ADataSet := TZQuery.Create(nil); try with AChara.Inventory do begin //UseID AParam := ADataset.Params.CreateParam(ftInteger, 'UseID', ptInput); AParam.AsInteger := UseID; ADataSet.Params.AddParam( AParam ); //EquipID AParam := ADataset.Params.CreateParam(ftInteger, 'EquipID', ptInput); AParam.AsInteger := EquipID; ADataSet.Params.AddParam( AParam ); //MiscID AParam := ADataset.Params.CreateParam(ftInteger, 'MiscID', ptInput); AParam.AsInteger := EtcID; ADataSet.Params.AddParam( AParam ); end; Query(ADataSet, AQuery); ADataSet.First; while NOT ADataSet.Eof do begin AItem := TItemInstance.Create; AItem.ID := ADataSet.Fields[0].AsInteger; AItem.Item := TItem.Create; AItem.Item.ID := ADataSet.Fields[1].AsInteger; AItem.Quantity := ADataSet.Fields[2].AsInteger; AItem.Identified := Boolean(ADataSet.Fields[3].AsInteger); AItem.Refined := ADataSet.Fields[4].AsInteger; AItem.Equipped := AChara.Equipment.IsEquipped(AItem.ID); APoint.X := ADataSet.Fields[5].AsInteger; APoint.Y := ADataSet.Fields[6].AsInteger; AItem.Position := APoint; AItem.MapID := ADataSet.Fields[7].AsInteger; Load(AItem.Item); AChara.Inventory.Add( AItem, True ); ADataSet.Next; end; finally ADataSet.Free; end; end;{FillInventory} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //FillMapGround PROCEDURE //------------------------------------------------------------------------------ // What it does- // Load all items into map // // Changes - // [2008/09/30] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TItemQueries.FillMapGround( const Map:TMap ); const AQuery = 'SELECT `id`,`item_definition_id`,`amount`,`identified`,`refined`,`last_x`,`last_y`,`last_map_id` '+ 'FROM items ' + 'WHERE `last_map_id`=:MapID;'; var ADataSet : TZQuery; AParam : TParam; AItem : TItemInstance; APoint : TPoint; begin ADataSet := TZQuery.Create(nil); try //MapID AParam := ADataset.Params.CreateParam(ftInteger, 'MapID', ptInput); AParam.AsInteger := Map.ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataSet.First; while NOT ADataSet.Eof do begin AItem := TItemInstance.Create; AItem.ID := ADataSet.Fields[0].AsInteger; AItem.Item := TItem.Create; AItem.Item.ID := ADataSet.Fields[1].AsInteger; AItem.Quantity := ADataSet.Fields[2].AsInteger; AItem.Identified := Boolean(ADataSet.Fields[3].AsInteger); AItem.Refined := ADataSet.Fields[4].AsInteger;; APoint.X := ADataSet.Fields[5].AsInteger; APoint.Y := ADataSet.Fields[6].AsInteger; AItem.Position := APoint; AItem.MapID := ADataSet.Fields[7].AsInteger; AItem.MapInfo := Map; Load(AItem.Item); Map.Cell[AItem.Position.X, AItem.Position.Y].Items.AddObject( AItem.ID, AItem ); Map.ItemList.AddObject( AItem.ID, AItem ); //Add to event! AItem.Dropped; ADataSet.Next; end; finally ADataSet.Free; end; end;{FillMapGround} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Find PROCEDURE //------------------------------------------------------------------------------ // What it does- // Check if item exists // // Changes - // [2008/09/20] Aeomin - Created. // //------------------------------------------------------------------------------ function TItemQueries.Find( const ID : Word ):Boolean; const AQuery = 'SELECT id FROM itemdefinitions WHERE id=:ID'; var ADataSet : TZQuery; AParam : TParam; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataSet.First; Result := NOT ADataSet.Eof; finally ADataSet.Free; end; end;{Find} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Find PROCEDURE //------------------------------------------------------------------------------ // What it does- // Check if item exists; return zero is not found. // // Changes - // [2008/09/20] Aeomin - Created. // //------------------------------------------------------------------------------ function TItemQueries.Find( const Name : String ):Word; const AQuery = 'SELECT id FROM itemdefinitions WHERE name=:Name'; var ADataSet : TZQuery; AParam : TParam; begin Result := 0; ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput); AParam.AsString := Name; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin Result := ADataSet.Fields[0].AsInteger; end; finally ADataSet.Free; end; end;{Find} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetSpriteIDs PROCEDURE //------------------------------------------------------------------------------ // What it does- // Get sprite IDs // // Changes - // [2008/10/11] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TItemQueries.GetSpriteIDs( const AnEquipment : TEquipment ); const AQuery = 'SELECT sprite_id FROM itemdefinitions LEFT JOIN items ON itemdefinitions.id= items.item_definition_id WHERE items.id=:ID'; function DoQuery(const ID:LongWord):Word; var ADataSet : TZQuery; AParam : TParam; begin Result := 0; ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := ID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin Result := ADataSet.Fields[0].AsInteger; end; finally ADataSet.Free; end; end; var Index : Byte; begin for Index := Byte(High(TEquipLocations)) downto 0 do begin if AnEquipment.EquipmentID[TEquipLocations(Index)] > 0 then begin AnEquipment.SpriteID[TEquipLocations(Index)]:= DoQuery(AnEquipment.EquipmentID[TEquipLocations(Index)]); end; end; end;{GetSpriteIDs} //------------------------------------------------------------------------------ end.
unit GeometryHelper; interface uses sgBackendTypes, sgTypes; function LineIntersectsLines(const line: LineSegment; const lines: LinesArray): Boolean; function LinesFrom(const tri: Triangle): LinesArray; overload; function LinesFrom(const rect: Rectangle): LinesArray; overload; function VectorOverLinesFromCircle(const c: Circle; const lines: LinesArray; const velocity: Vector; out maxIdx: Longint): Vector; implementation uses sgGeometry, sgTrace, sgShared; function LineIntersectsLines(const line: LineSegment; const lines: LinesArray): Boolean; var i: Longint; pt: Point2D; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LineIntersectsLines(const line: LineSegment', ''); {$ENDIF} for i := 0 to High(lines) do begin if LineIntersectionPoint(line, lines[i], pt) and PointOnLine(pt, lines[i]) and PointOnLine(pt, line) then begin result := true; exit; end; end; result := false; {$IFDEF TRACE} TraceExit('sgGeometry', 'LineIntersectsLines(const line: LineSegment', ''); {$ENDIF} end; function LinesFrom(const tri: Triangle): LinesArray; overload; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LinesFrom(const tri: Triangle): LinesArray', ''); {$ENDIF} SetLength(result, 3); result[0] := LineFrom(tri.points[0], tri.points[1]); result[1] := LineFrom(tri.points[1], tri.points[2]); result[2] := LineFrom(tri.points[2], tri.points[0]); {$IFDEF TRACE} TraceExit('sgGeometry', 'LinesFrom(const tri: Triangle): LinesArray', ''); {$ENDIF} end; function LinesFrom(const rect: Rectangle): LinesArray; overload; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LinesFrom(const rect: Rectangle): LinesArray', ''); {$ENDIF} SetLength(result, 4); with rect do begin result[0] := LineFrom(x, y, x + width, y); result[1] := LineFrom(x, y, x, y + height); result[2] := LineFrom(x + width, y, x + width, y + height); result[3] := LineFrom(x, y + height, x + width, y + height); end; {$IFDEF TRACE} TraceExit('sgGeometry', 'LinesFrom(const rect: Rectangle): LinesArray', ''); {$ENDIF} end; // // This internal function is used to calculate the vector and determine if a hit has occurred... // function VectorOverLinesFromCircle(const c: Circle; const lines: LinesArray; const velocity: Vector; out maxIdx: Longint): Vector; type DoublePt = record ptOnCircle, ptOnLine: Point2D; end; var ptOnLine, ptOnCircle: Point2D; tmp: Array [0..3] of Point2D; chkPts: Array [0..3] of DoublePt; lineVec, normalMvmt, normalLine, toEdge, edge, ray, vOut: Vector; i, j, hits: Longint; dotProd, dist, maxDist: Single; begin {$IFDEF TRACE} TraceEnter('sgGeometry', '_VectorOverLinesFromCircle(const c: Circle', ''); {$ENDIF} // If there is no velocity then we cannot determine // the hit location etc. Return a 0,0 vector. if VectorMagnitude(velocity) = 0 then begin RaiseWarning('Attempting to determine collision with a zero/null vector.'); // velocity has no magnitude, so it can be returned result := velocity; exit; end; // Cast ray searching for points back from shape ray := InvertVector(velocity); normalMvmt := VectorNormal(velocity); vOut := VectorTo(0,0); ptOnCircle := PointAt(0,0); maxIdx := -1; maxDist := -1; // fix for tmp initialized warning for i := 0 to high(tmp) do tmp[i] := PointAt(0,0); //Search all lines for hit points for i := 0 to High(lines) do begin lineVec := LineAsVector(lines[i]); //Get the normal of the line we hit normalLine := VectorNormal(lineVec); hits := 0; //tmp 0 and tmp 1 are the widest points to detect collision with line WidestPoints(c, normalMvmt, tmp[0], tmp[1]); //tmp 2 and tmp 3 are the closest and furthest points from the line WidestPoints(c, normalLine, tmp[2], tmp[3]); // for both points... for j := 0 to 3 do begin //DrawCircle(ColorWhite, tmp[j], 2); // Cast a ray back from the test points to find line pts... out on ptOnLine if RayIntersectionPoint(tmp[j], ray, lines[i], ptOnLine) then begin //DrawCircle(ColorRed, ptOnLine, 1); //DrawLine(ColorRed, tmp[j], ptOnLine); chkPts[hits].ptOnLine := ptOnLine; chkPts[hits].ptOnCircle := tmp[j]; hits := hits + 1; end; end; // for each of the hits on this line... // search for the longest hit. for j := 0 to hits - 1 do begin //if not maxLine then DrawCircle(ColorWhite, chkPts[j].ptOnCircle, 1); toEdge := VectorFromPoints(c.center, chkPts[j].ptOnCircle); //if not maxLine then DrawLine(ColorRed, c.center, chkPts[j].ptOnCircle); dotProd := DotProduct(toEdge, normalLine); // 2d: Most distant edge pt is on a line this distance (dotProd) from the center edge := AddVectors(c.center, VectorMultiply(normalLine, dotProd)); //DrawPixel(ColorWhite, edge); // Draws pt on line to distant pt // Find the point we hit on the line... ptOnLine receives intersection point... if not LineIntersectionPoint(LineFromVector(edge, velocity), lines[i], ptOnLine) then continue; // Move back onto line segment... linePt -> closest point on line to intersect point //if not maxLine then DrawCircle(ColorRed, ptOnLine, 1); // point on line, but not necessarily the line segment //if not maxLine then DrawLine(ColorWhite, edge, ptOnLine); ptOnLine := ClosestPointOnLine(ptOnLine, lines[i]); //if not maxLine then FillCircle(ColorBlue, ptOnLine, 1); // point on segment // Find the most distant point on the circle, given the velocity vector if not DistantPointOnCircleHeading(ptOnLine, c, velocity, ptOnCircle) then continue; // if not maxLine then FillCircle(ColorBlue, ptOnCircle, 2); // point on segment // if not maxLine then DrawLine(ColorBlue, ptOnLine, ptOnCircle); dist := PointPointDistance(ptOnLine, ptOnCircle); if (dist > maxDist) or (maxIdx = -1) then begin maxDist := dist; maxIdx := i; vOut := VectorFromPoints(ptOnCircle, ptOnLine); vOut := VectorMultiply(UnitVector(vOut), VectorMagnitude(vOut) + 1.42) end; end; end; result.x := Ceiling(vOut.x); result.y := Ceiling(vOut.y); {$IFDEF TRACE} TraceExit('sgGeometry', '_VectorOverLinesFromCircle(const c: Circle', ''); {$ENDIF} end; end.
unit Magento.Category_Links; interface uses Magento.Interfaces, System.JSON; type TMagentoCategory_Links = class (TInterfacedObject, iMagentoCategory_Links) private FParent : iMagentoExtensionAttributes; FJSONArray : TJSONArray; FJSON : TJSONObject; public constructor Create(Parent : iMagentoExtensionAttributes); destructor Destroy; override; class function New(Parent : iMagentoExtensionAttributes) : iMagentoCategory_Links; function Position(value : Integer) : iMagentoCategory_Links; function Category_id(value : String) : iMagentoCategory_Links; function Continuos : iMagentoCategory_Links; function &End : iMagentoExtensionAttributes; end; implementation { TMagentoCategory_Links } uses Magento.Factory; function TMagentoCategory_Links.Category_id( value: String): iMagentoCategory_Links; begin Result := Self; FJSON.AddPair('category_id',value); end; function TMagentoCategory_Links.&End: iMagentoExtensionAttributes; begin FJSONArray.Add(FJSON); FParent.Category_Links(FJSONArray); Result := FParent; end; function TMagentoCategory_Links.Continuos: iMagentoCategory_Links; begin Result := Self; FJSONArray.Add(FJSON); FJSON := TJSONObject.Create; end; constructor TMagentoCategory_Links.Create(Parent : iMagentoExtensionAttributes); begin FParent := Parent; FJSONArray := TJSONArray.Create; FJSON := TJSONObject.Create; end; destructor TMagentoCategory_Links.Destroy; begin inherited; end; class function TMagentoCategory_Links.New(Parent : iMagentoExtensionAttributes) : iMagentoCategory_Links; begin Result := self.Create(Parent); end; function TMagentoCategory_Links.Position( value: Integer): iMagentoCategory_Links; begin Result := Self; FJSON.AddPair('position',TJSONNumber.Create(value)); end; end.
unit LrWebBrowser; interface uses SysUtils, Classes, Forms, Variants, ShDocVw; type TLrWebBrowser = class(TWebBrowser) private FCanStop: Boolean; FCanGoBack: Boolean; FOnCanDoStateChange: TNotifyEvent; FCanGoForward: Boolean; protected function GetSource: string; procedure CanDoStateChange; procedure CommandStateChange(Sender: TObject; Command: Integer; Enable: WordBool); procedure SetCanGoBack(const Value: Boolean); procedure SetCanGoForward(const Value: Boolean); procedure SetCanStop(const Value: Boolean); procedure SetSource(const Value: string); public constructor Create(AOwner: TComponent); override; function SafeStop: Boolean; function Wait: Boolean; procedure SafeBack; procedure SafeNavigate(const inUrl: string); procedure SafeRefresh; property CanGoBack: Boolean read FCanGoBack write SetCanGoBack; property CanGoForward: Boolean read FCanGoForward write SetCanGoForward; property CanStop: Boolean read FCanStop write SetCanStop; property OnCanDoStateChange: TNotifyEvent read FOnCanDoStateChange write FOnCanDoStateChange; property Source: string read GetSource write SetSource; end; implementation uses LrWebBrowserUtils; constructor TLrWebBrowser.Create(AOwner: TComponent); begin inherited; OnCommandStateChange := CommandStateChange; end; function TLrWebBrowser.GetSource: string; begin Result := LrStringFromBrowser(Self); end; procedure TLrWebBrowser.SetSource(const Value: string); begin LrStringToBrowser(Self, Value); end; procedure TLrWebBrowser.CanDoStateChange; begin if Assigned(OnCanDoStateChange) then OnCanDoStateChange(Self); end; procedure TLrWebBrowser.CommandStateChange(Sender: TObject; Command: Integer; Enable: WordBool); begin if Cardinal(Command) = CSC_NAVIGATEBACK then CanGoBack := Enable else if Cardinal(Command) = CSC_NAVIGATEFORWARD then CanGoForward := Enable else if Cardinal(Command) = CSC_UPDATECOMMANDS then CanStop := Busy; CanDoStateChange; end; { procedure TLrWebBrowser.SetParent(AParent: TWinControl); begin if (csLoading in ComponentState) or (csDestroying in ComponentState) or (AParent = nil) then inherited else begin try Stop; except end; inherited; NewBrowser; if LastUrl <> '' then Navigate(LastUrl); end; end; procedure TIEForm.NewBrowser; var w: TWebBrowser; begin w := TWebBrowser.Create(Self); w.Align := alClient; BrowserSheet.InsertControl(w); //BrowserDock.InsertControl(w); w.OnCommandStateChange := WebBrowserCommandStateChange; //w.OnDocumentComplete := WebBrowserDocumentComplete; w.OnNewWindow2 := WebBrowserNewWindow2; w.OnStatusTextChange := WebBrowserStatusTextChange; WebBrowser.Free; WebBrowser := w; end; } procedure MessagingWait; begin Sleep(100); Forms.Application.ProcessMessages; end; function TLrWebBrowser.Wait: Boolean; var i: Integer; begin try for i := 1 to 100 do if (ReadyState < READYSTATE_INTERACTIVE) then MessagingWait; Result := not (ReadyState < READYSTATE_INTERACTIVE); except Result := false; end; end; function TLrWebBrowser.SafeStop: Boolean; var i: Integer; begin try Result := Wait; if Result and Busy then begin Stop; for i := 1 to 100 do if Busy then MessagingWait; Result := not Busy; end; except Result := false; end; end; procedure TLrWebBrowser.SafeRefresh; var flags: OleVariant; begin if SafeStop then begin flags := REFRESH_COMPLETELY; Refresh2(flags); end; end; procedure TLrWebBrowser.SafeBack; begin if SafeStop then try GoBack; except end; end; procedure TLrWebBrowser.SafeNavigate(const inUrl: string); var url: OleVariant; begin if SafeStop then try url := inUrl; Navigate2(url); except end; end; { procedure TIEForm.ForceNavigate(const inUrl: string); begin Stop; NewBrowser; // if inUrl = LastUrl then // Refresh // else Navigate(inUrl); end; procedure TIEForm.WebBrowserNavigateComplete2(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant); begin UrlEdit.Text := URL; LastUrl := Url; //PreviewPagesChange(Self); end; } procedure TLrWebBrowser.SetCanGoBack(const Value: Boolean); begin FCanGoBack := Value; end; procedure TLrWebBrowser.SetCanStop(const Value: Boolean); begin FCanStop := Value; end; procedure TLrWebBrowser.SetCanGoForward(const Value: Boolean); begin FCanGoForward := Value; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmAppEvents Purpose : Originally a fix for D5 bug but is now usefull for other versions of Delphi. Date : 01-15-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmAppEvents; interface {$I CompilerDefines.INC} uses Windows, Messages, SysUtils, Classes, Forms, ActnList; type TrmCustomApplicationEvents = class(TComponent) private FOnActionExecute: TActionEvent; FOnActionUpdate: TActionEvent; FOnException: TExceptionEvent; FOnMessage: TMessageEvent; FOnHelp: THelpEvent; FOnHint: TNotifyEvent; FOnIdle: TIdleEvent; FOnDeactivate: TNotifyEvent; FOnActivate: TNotifyEvent; FOnMinimize: TNotifyEvent; FOnRestore: TNotifyEvent; FOnShortCut: TShortCutEvent; FOnShowHint: TShowHintEvent; procedure DoActionExecute(Action: TBasicAction; var Handled: Boolean); procedure DoActionUpdate(Action: TBasicAction; var Handled: Boolean); procedure DoActivate(Sender: TObject); procedure DoDeactivate(Sender: TObject); procedure DoException(Sender: TObject; E: Exception); procedure DoIdle(Sender: TObject; var Done: Boolean); function DoHelp(Command: Word; Data: Longint; var CallHelp: Boolean): Boolean; procedure DoHint(Sender: TObject); procedure DoMessage(var Msg: TMsg; var Handled: Boolean); procedure DoMinimize(Sender: TObject); procedure DoRestore(Sender: TObject); procedure DoShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: THintInfo); procedure DoShortcut(var Msg: TWMKey; var Handled: Boolean); protected property OnActionExecute: TActionEvent read FOnActionExecute write FOnActionExecute; property OnActionUpdate: TActionEvent read FOnActionUpdate write FOnActionUpdate; property OnActivate: TNotifyEvent read FOnActivate write FOnActivate; property OnDeactivate: TNotifyEvent read FOnDeactivate write FOnDeactivate; property OnException: TExceptionEvent read FOnException write FOnException; property OnIdle: TIdleEvent read FOnIdle write FOnIdle; property OnHelp: THelpEvent read FOnHelp write FOnHelp; property OnHint: TNotifyEvent read FOnHint write FOnHint; property OnMessage: TMessageEvent read FOnMessage write FOnMessage; property OnMinimize: TNotifyEvent read FOnMinimize write FOnMinimize; property OnRestore: TNotifyEvent read FOnRestore write FOnRestore; property OnShowHint: TShowHintEvent read FOnShowHint write FOnShowHint; property OnShortCut: TShortCutEvent read FOnShortCut write FOnShortCut; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TrmApplicationEvents = class(TrmCustomApplicationEvents) published property OnActionExecute; property OnActionUpdate; property OnActivate; property OnDeactivate; property OnException; property OnIdle; property OnHelp; property OnHint; property OnMessage; property OnMinimize; property OnRestore; property OnShowHint; property OnShortCut; end; implementation uses Contnrs, Consts, StdActns; { TrmCustomApplicationEvents } constructor TrmCustomApplicationEvents.Create(AOwner: TComponent); begin inherited Create(AOwner); if csdesigning in componentstate then exit; with Application do begin OnActionExecute := DoActionExecute; OnActionUpdate := DoActionUpdate; OnActivate := DoActivate; OnDeactivate := DoDeactivate; OnException := DoException; OnHelp := DoHelp; OnHint := DoHint; OnIdle := DoIdle; OnMessage := DoMessage; OnMinimize := DoMinimize; OnRestore := DoRestore; OnShowHint := DoShowHint; OnShortCut := DoShortcut; end; end; destructor TrmCustomApplicationEvents.Destroy; begin with Application do begin OnActionExecute := nil; OnActionUpdate := nil; OnActivate := nil; OnDeactivate := nil; OnException := nil; OnHelp := nil; OnHint := nil; OnIdle := nil; OnMessage := nil; OnMinimize := nil; OnRestore := nil; OnShowHint := nil; OnShortCut := nil; end; inherited; end; procedure TrmCustomApplicationEvents.DoActionExecute(Action: TBasicAction; var Handled: Boolean); begin if Assigned(FOnActionExecute) then FOnActionExecute(Action, Handled); end; procedure TrmCustomApplicationEvents.DoActionUpdate(Action: TBasicAction; var Handled: Boolean); begin if Assigned(FOnActionUpdate) then FOnActionUpdate(Action, Handled); end; procedure TrmCustomApplicationEvents.DoActivate(Sender: TObject); begin if Assigned(FOnActivate) then FOnActivate(Sender); end; procedure TrmCustomApplicationEvents.DoDeactivate(Sender: TObject); begin if Assigned(FOnDeactivate) then FOnDeactivate(Sender); end; procedure TrmCustomApplicationEvents.DoException(Sender: TObject; E: Exception); begin if Assigned(FOnException) then FOnException(Sender, E) else Application.ShowException(E); end; function TrmCustomApplicationEvents.DoHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean; begin if Assigned(FOnHelp) then Result := FOnHelp(Command, Data, CallHelp) else Result := False; end; procedure TrmCustomApplicationEvents.DoHint(Sender: TObject); begin if Assigned(FOnHint) then FOnHint(Sender) {$IFDEF D4_OR_HIGHER} else { Fire THintAction to anyone interested } with THintAction.Create(Self) do begin Hint := Application.hint; try Execute; finally Free; end; end; {$ENDIF} end; procedure TrmCustomApplicationEvents.DoIdle(Sender: TObject; var Done: Boolean); begin if Assigned(FOnIdle) then FOnIdle(Sender, Done); end; procedure TrmCustomApplicationEvents.DoMessage(var Msg: TMsg; var Handled: Boolean); begin if Assigned(FOnMessage) then FOnMessage(Msg, Handled); end; procedure TrmCustomApplicationEvents.DoMinimize(Sender: TObject); begin if Assigned(FOnMinimize) then FOnMinimize(Sender); end; procedure TrmCustomApplicationEvents.DoRestore(Sender: TObject); begin if Assigned(FOnRestore) then FOnRestore(Sender); end; procedure TrmCustomApplicationEvents.DoShortcut(var Msg: TWMKey; var Handled: Boolean); begin if Assigned(FOnShortcut) then FOnShortcut(Msg, Handled); end; procedure TrmCustomApplicationEvents.DoShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: THintInfo); begin if Assigned(FOnShowHint) then FOnShowHint(HintStr, CanShow, HintInfo); end; end.
unit Forms.Main.orig; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, AdvSmoothEdit, AdvSmoothEditButton, AdvSmoothDatePicker, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.DataSet, AdvUtil, AdvSplitter, Vcl.Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, Vcl.DBCtrls, AdvGlowButton, Vcl.ComCtrls, AdvDateTimePicker, VCL.TMSFNCGoogleMaps, Modules.Database; type TFrmMain = class(TForm) Panel1: TPanel; cbStates: TDBLookupComboBox; dsStates: TDataSource; btnShowIncidents: TAdvGlowButton; dpDate: TAdvDateTimePicker; Map: TTMSFNCGoogleMaps; procedure FormCreate(Sender: TObject); procedure btnShowIncidentsClick(Sender: TObject); private { Private declarations } procedure ShowIncidents( ADate: TDate ); public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} procedure TFrmMain.btnShowIncidentsClick(Sender: TObject); begin ShowIncidents( dpDate.Date ); end; procedure TFrmMain.FormCreate(Sender: TObject); begin dpDate.Date := EncodeDate( 2017,11,4 ); dpDate.MinDate := DBController.DateFirst; dpDate.MaxDate := DBController.DateLast; end; procedure TFrmMain.ShowIncidents(ADate: TDate); var lDateStr: String; lFormat: TFormatSettings; lRect: TTMSFNCMapsRectangle; lCoordS, lCoordE : TTMSFNCMapsCoordinateRec; lStartLat, lStartLon, lEndLat, lEndLon: Double; lMarker: TTMSFNCGoogleMapsMarker; lQuIncidents: TFDQuery; begin lFormat := TFormatSettings.Create; lFormat.ShortDateFormat := 'yyyy-mm-dd'; lDateStr := DateToStr( dpDate.Date, lFormat ); lQuIncidents := TFDQuery.Create(nil); try lQuIncidents.Connection := DBController.Connection; lQuIncidents.SQL.Text := TSQLStatements.GetIncidents; lQuIncidents.ParamByName('date').AsString := lDateStr; lQuIncidents.ParamByName('code').AsString := cbStates.KeyValue; lQuIncidents.Open; if lQuIncidents.RecordCount > 0 then begin Map.BeginUpdate; Map.Markers.Clear; Map.Rectangles.Clear; Map.Clusters.Clear; var lCluster := Map.Clusters.Add; try while not lQuIncidents.Eof do begin lStartLat := lQuIncidents.FieldByName('start_lat').AsFloat; lStartLon := lQuIncidents.FieldByName('start_lng').AsFloat; lEndLat := lQuIncidents.FieldByName('end_lat').AsFloat; lEndLon := lQuIncidents.FieldByName('end_lng').AsFloat; lCoordS := CreateCoordinate(lStartLat, lStartLon); lCoordE := CreateCoordinate(lEndLat, lEndLon); lMarker := Map.AddMarker(lCoordS) as TTMSFNCGoogleMapsMarker; lMarker.Cluster := lCluster; lMarker.DataInteger := lQuIncidents.FieldByName('id').AsInteger; if (lEndLat<>0) AND ( lEndLon <> 0) then begin // use a rectangle lRect := Map.AddRectangle( CreateBounds( lCoordS, lCoordE ) ); var lSeverity := lQuIncidents.FieldByName('severity').AsInteger; case lSeverity of 1: lRect.FillColor := clGreen; 2: lRect.FillColor := clOlive; 3: lRect.FillColor := clYellow; 4: lRect.FillColor := clRed; 5: lRect.FillColor := clPurple; else lRect.FillColor := clWhite; end; lRect.FillOpacity := 0.5; end; lQuIncidents.Next; end; finally if Map.Markers.Count > 0 then begin Map.ZoomToBounds(Map.Markers.ToCoordinateArray); end; Map.EndUpdate; end; end else begin MessageDlg( 'No accidents recorded for selected state on that day.', mtInformation, [mbOK],0); end; finally lQuIncidents.Free; end; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083054 //////////////////////////////////////////////////////////////////////////////// unit android.service.autofill.TextValueSanitizer; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os, java.util.regex.Matcher; type JTextValueSanitizer = interface; JTextValueSanitizerClass = interface(JObjectClass) ['{3859EC2B-5234-424A-819D-C26BBE93E8A6}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function init(regex : JPattern; subst : JString) : JTextValueSanitizer; cdecl;// (Ljava/util/regex/Pattern;Ljava/lang/String;)V A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 end; [JavaSignature('android/service/autofill/TextValueSanitizer')] JTextValueSanitizer = interface(JObject) ['{F27D162D-4076-48C3-A6EB-162C498F81FA}'] function describeContents : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJTextValueSanitizer = class(TJavaGenericImport<JTextValueSanitizerClass, JTextValueSanitizer>) end; implementation end.
unit uDlgAmort; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCurrencyEdit, cxCalendar, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridBandedTableView, cxGridDBBandedTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxPC, ADODB, uFrameBaseGrid, cxButtonEdit, Math; type TdlgAmort = class(TBASE_DialogForm) pcAmort: TcxPageControl; tsAmortAuto: TcxTabSheet; grdAmortAuto: TcxGrid; viewAmortAuto: TcxGridDBBandedTableView; viewAmortAuto_1: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn3: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn1: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn2: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn4: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn5: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn6: TcxGridDBBandedColumn; viewAmortAutoDBBandedColumn7: TcxGridDBBandedColumn; viewAmortAutoColumn1: TcxGridDBBandedColumn; lvAmortAuto: TcxGridLevel; bntAmortAccount: TcxButton; tsAmortUser: TcxTabSheet; grdAmortUser: TcxGrid; tvAmortUser: TcxGridDBBandedTableView; cxGridDBBandedColumn3: TcxGridDBBandedColumn; cxGridDBBandedColumn4: TcxGridDBBandedColumn; cxGridDBBandedColumn5: TcxGridDBBandedColumn; cxGridDBBandedColumn6: TcxGridDBBandedColumn; cxGridDBBandedColumn7: TcxGridDBBandedColumn; cxGridDBBandedColumn8: TcxGridDBBandedColumn; cxGridDBBandedColumn9: TcxGridDBBandedColumn; cxGridDBBandedColumn10: TcxGridDBBandedColumn; cxGridDBBandedColumn11: TcxGridDBBandedColumn; lvAmortUser: TcxGridLevel; dsAmortAuto: TDataSource; dsAmortUser: TDataSource; qryAmortAuto: TADOQuery; qryAmortUser: TADOQuery; tsAmortUserRatio: TcxTabSheet; grdRatio: TcxGrid; tvRatio: TcxGridDBBandedTableView; glRatio: TcxGridLevel; dsAmortUserRatio: TDataSource; qryAmortUserRatio: TADOQuery; tvRatio_: TcxGridDBBandedColumn; tvRatioForADOInsertCol: TcxGridDBBandedColumn; tvRatio_1: TcxGridDBBandedColumn; tvRatioDBBandedColumn: TcxGridDBBandedColumn; tvRatioDBBandedColumn1: TcxGridDBBandedColumn; tvRatioDBBandedColumn2: TcxGridDBBandedColumn; tvRatioDBBandedColumn3: TcxGridDBBandedColumn; tvRatioDBBandedColumn4: TcxGridDBBandedColumn; tvRatio_2: TcxGridDBBandedColumn; tvRatioDBBandedColumn5: TcxGridDBBandedColumn; tvRatioDBBandedColumn6: TcxGridDBBandedColumn; tvRatioDBBandedColumn7: TcxGridDBBandedColumn; tvRatio_3: TcxGridDBBandedColumn; tvRatioDBBandedColumn8: TcxGridDBBandedColumn; tvRatioDBBandedColumn9: TcxGridDBBandedColumn; tvRatioDBBandedColumn10: TcxGridDBBandedColumn; tvRatioColumn1: TcxGridDBBandedColumn; viewAmortAutoColumn2: TcxGridDBBandedColumn; viewAmortAutoColumn3: TcxGridDBBandedColumn; cxButton1: TcxButton; cmdDelAmort: TADOCommand; viewAmortAutoColumn4: TcxGridDBBandedColumn; qryCorrSum: TADOQuery; tvRatioColumn2: TcxGridDBBandedColumn; procedure cxGridDBBandedColumn7GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure bntAmortAccountClick(Sender: TObject); procedure qryAmortUserBeforePost(DataSet: TDataSet); procedure qryAmortUserAfterOpen(DataSet: TDataSet); procedure qryAmortUserAfterPost(DataSet: TDataSet); procedure qryAmortUserAfterDelete(DataSet: TDataSet); procedure qryAmortUserRatioAfterOpen(DataSet: TDataSet); procedure qryAmortUserRatioAfterPost(DataSet: TDataSet); procedure qryAmortUserRatioBeforePost(DataSet: TDataSet); procedure tvRatioDBBandedColumnGetDataText( Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: String); procedure qryAmortUserRatioBeforeDelete(DataSet: TDataSet); procedure tvRatioDBBandedColumn5PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxButton1Click(Sender: TObject); procedure qryAmortAutoBeforePost(DataSet: TDataSet); procedure qryCorrSumAfterPost(DataSet: TDataSet); procedure qryCorrSumBeforeOpen(DataSet: TDataSet); procedure FormCreate(Sender: TObject); private { Private declarations } FPrimaryKey:integer; procedure SetPrimaryKey(AValue:integer); protected procedure CheckAmortFields; virtual; procedure UpdateAmortUserMonthNumber; virtual; public WasAmortReaccount: boolean; WasAmortUserEdit: boolean; WasAmortUserRatioEdit: boolean; property PrimaryKey:integer read FPrimaryKey write SetPrimaryKey; procedure AmortAccount(FullAccount: boolean); virtual; procedure AmortAccount1(FullAccount: boolean); end; implementation uses uFrameUnitProps, uCommonUtils, DateUtils, uMain, uDlgDocument; {$R *.dfm} procedure TdlgAmort.cxButton1Click(Sender: TObject); begin inherited; if MessageBox(Handle, 'Удалить амортизационные начисления?', 'Расчет амортизации', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) <> IDYES then Exit; //CheckAmortFields; WasAmortReaccount:=true; qryAmortAuto.Open; qryAmortAuto.First; qryAmortAuto.Edit; qryAmortAuto.Post; qryAmortAuto.DisableControls; try while not qryAmortAuto.Eof do begin qryAmortAuto.Delete; end; finally qryAmortAuto.EnableControls; end; //cmdDelAmort end; procedure TdlgAmort.cxGridDBBandedColumn7GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText<>'' then atext:=DateTo_MMMMDDDD_Str(StrToDate(AText)); end; function RoundExt(AVal:double):double; begin Result := RoundTo(AVal,-2); end; procedure TdlgAmort.AmortAccount1(FullAccount: boolean); function MonthStr(d: TDate): string; begin result:=GetMonthName(MonthOf(d))+' '+IntToStr(YearOf(d)); end; function KRatio(OnDate: TDateTime): double; begin result:=1; qryAmortUserRatio.First; while not qryAmortUserRatio.Eof do begin if qryAmortUserRatio['Дата переоценки'] = OnDate then begin result:=qryAmortUserRatio['Коэффициент']; exit; end; qryAmortUserRatio.Next; end; qryAmortUserRatio.First; end; //zav function GetCorrSum(ADate:TDateTime) :Double; begin if qryCorrSum.Locate('МесяцДата', {qryAmortAuto['МесяцДата']}ADate,[]) then Result := qryCorrSum['Сумма корректировки'] else Result := 0; end; //end zav var CurDate, EndDate: TDateTime; StartPrice, CurIznos, CurIznosSumm, SummIznos, SummIznosProc, OstPrice, VostanPrice, K: Double; y, m, d: word; MonthCount: integer; //zav CorrSum, CurIznosCorr: Double; //end zav begin viewAmortAuto.DataController.Post(); if viewAmortAuto.DataController.DataSet.State in [dsInsert, dsEdit] then viewAmortAuto.DataController.DataSet.Post; CheckAmortFields; WasAmortReaccount:=true; viewAmortAuto.BeginUpdate; qryCorrSum.Tag := -1; qryAmortAuto.DisableControls; try qryAmortAuto.Open; while qryAmortAuto.RecordCount<>0 do qryAmortAuto.Delete; MonthCount:=1; CurDate:=(Owner as TFrameUnitProps).deAmortFrom.Date; CurDate:=EncodeDate(YearOf(CurDate), MonthOf(CurDate), 1); CurDate:=IncMonth(CurDate, 1); //следующий месяц за датой включения в реестр K:=KRatio(CurDate); //zav CorrSum :=GetCorrSum(CurDate); //end zav VostanPrice:=(Owner as TFrameUnitProps).cxDBCurrencyEdit2.Value; StartPrice:=(Owner as TFrameUnitProps).cxDBCurrencyEdit4.Value; //начальная стоимость CurIznos:=VostanPrice*(Owner as TFrameUnitProps).ceAmortNorm.Value/100/12; //начисленный износ {zav}CurIznosCorr := CurIznos + CorrSum {end zav}; CurIznosCorr := RoundExt(CurIznosCorr); //zav //CurIznosSumm:=CurIznos ; CurIznosSumm := CurIznosCorr; //end zav SummIznos:=((Owner as TFrameUnitProps).cxDBCurrencyEdit3.Value+CurIznosCorr); //суммарный износ - переделали в рубли SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=((Owner as TFrameUnitProps).cxDBCurrencyEdit4.Value-CurIznosSumm); //остаточная стоимость OstPrice := RoundExt(OstPrice); //zav if OstPrice<0.001 then begin CurIznosSumm:=CurIznosSumm+OstPrice; SummIznos:=SummIznos+OstPrice; SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=0; CurIznos:=StartPrice; end; //end zav CurIznos:=CurIznos*K; SummIznos:=SummIznos*K; StartPrice:=StartPrice*K; OstPrice:=OstPrice*K; VostanPrice:=VostanPrice*K; if qryAmortAuto.State in [dsEdit, dsInsert] then qryAmortAuto.Post; qryAmortAuto.Insert; qryAmortAuto['МесяцСчетчик']:=MonthCount; qryAmortAuto['МесяцДата']:=CurDate; qryAmortAuto['МесяцСтрока']:=MonthStr(CurDate); qryAmortAuto['Начальная стоимость']:=StartPrice; //zav //qryAmortAuto['Начисленный износ']:=CurIznos {zav}+ CorrSum {end zav}; qryAmortAuto['Начисленный износ']:=CurIznosCorr; //end zav qryAmortAuto['Суммарный износ']:=SummIznos; qryAmortAuto['СуммарныйИзносПроцент']:=SummIznosProc; qryAmortAuto['Остаточная стоимость']:=OstPrice; qryAmortAuto['Восстановительная стоимость']:=VostanPrice; qryAmortAuto['К переоценки']:=K; //zav if CorrSum <> 0 then qryAmortAuto['Сумма корректировки'] := CorrSum; //end zav qryAmortAuto.Post; while OstPrice>0 do begin inc(MonthCount); CurDate:=IncMonth(CurDate, 1); //следующий месяц K:=KRatio(CurDate); //zav CorrSum :=GetCorrSum(CurDate); //end zav StartPrice:=OstPrice; //начальная стоимость // CurIznos:=cxDBCurrencyEdit2.Value*ceAmortNorm.Value/100/12; //начисленный износ {zav}CurIznosCorr := CurIznos + CorrSum {end zav}; CurIznosCorr := RoundExt(CurIznosCorr); CurIznosSumm:=CurIznosSumm+CurIznosCorr; SummIznos:=SummIznos+CurIznosCorr; //суммарный износ SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=OstPrice - CurIznosCorr; //остаточная стоимость if OstPrice<0.001 then begin CurIznosSumm:=CurIznosSumm+OstPrice; SummIznos:=SummIznos+OstPrice; // if SummIznos > VostanPrice then SummIznos := VostanPrice; SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=0; CurIznosCorr:=StartPrice; end; { if SummIznosProc > 100 then begin CurIznosCorr := SummIznos SummIznos := VostanPrice; SummIznosProc := SummIznos/VostanPrice*100; end; } CurIznos:=CurIznos*K; SummIznos:=SummIznos*K; StartPrice:=StartPrice*K; OstPrice:=OstPrice*K; VostanPrice:=VostanPrice*K; qryAmortAuto.Insert; qryAmortAuto['МесяцСчетчик']:=MonthCount; qryAmortAuto['МесяцДата']:=CurDate; qryAmortAuto['МесяцСтрока']:=MonthStr(CurDate); qryAmortAuto['Начальная стоимость']:=StartPrice; qryAmortAuto['Начисленный износ']:=CurIznosCorr; qryAmortAuto['Суммарный износ']:=SummIznos; qryAmortAuto['СуммарныйИзносПроцент']:=SummIznosProc; qryAmortAuto['Остаточная стоимость']:=OstPrice; qryAmortAuto['Восстановительная стоимость']:=VostanPrice; qryAmortAuto['К переоценки']:=K; //zav if CorrSum <> 0 then qryAmortAuto['Сумма корректировки'] := CorrSum; //end zav qryAmortAuto.Post; end; finally qryCorrSum.Tag := 0; qryAmortAuto.EnableControls; viewAmortAuto.EndUpdate; end; end; procedure TdlgAmort.AmortAccount(FullAccount: boolean); function MonthStr(d: TDate): string; begin result:=GetMonthName(MonthOf(d))+' '+IntToStr(YearOf(d)); end; function KRatio(OnDate: TDateTime): double; begin result:=1; qryAmortUserRatio.First; while not qryAmortUserRatio.Eof do begin if qryAmortUserRatio['Дата переоценки'] = OnDate then begin result:=qryAmortUserRatio['Коэффициент']; exit; end; qryAmortUserRatio.Next; end; qryAmortUserRatio.First; end; //zav function GetCorrSum(ADate:TDateTime) :double; begin if qryCorrSum.Locate('МесяцДата', {qryAmortAuto['МесяцДата']}ADate,[]) then Result := qryCorrSum['Сумма корректировки'] else Result := 0; end; //end zav var CurDate, EndDate: TDateTime; StartPrice, CurIznos, CurIznosSumm, SummIznos, SummIznosProc, OstPrice, VostanPrice, K: double; y, m, d: word; MonthCount: integer; //zav CorrSum, CurIznosCorr: double; //end zav begin AmortAccount1(FullAccount); exit; viewAmortAuto.DataController.Post(); if viewAmortAuto.DataController.DataSet.State in [dsInsert, dsEdit] then viewAmortAuto.DataController.DataSet.Post; CheckAmortFields; WasAmortReaccount:=true; viewAmortAuto.BeginUpdate; qryCorrSum.Tag := -1; qryAmortAuto.DisableControls; try qryAmortAuto.Open; while qryAmortAuto.RecordCount<>0 do qryAmortAuto.Delete; MonthCount:=1; CurDate:=(Owner as TFrameUnitProps).deAmortFrom.Date; CurDate:=EncodeDate(YearOf(CurDate), MonthOf(CurDate), 1); CurDate:=IncMonth(CurDate, 1); //следующий месяц за датой включения в реестр K:=KRatio(CurDate); //zav CorrSum :=GetCorrSum(CurDate); //end zav VostanPrice:=(Owner as TFrameUnitProps).cxDBCurrencyEdit2.Value; StartPrice:=(Owner as TFrameUnitProps).cxDBCurrencyEdit4.Value; //начальная стоимость CurIznos:=VostanPrice*(Owner as TFrameUnitProps).ceAmortNorm.Value/100/12; //начисленный износ {zav}CurIznosCorr := CurIznos + CorrSum {end zav}; //zav //CurIznosSumm:=CurIznos ; CurIznosSumm := CurIznosCorr; //end zav SummIznos:=((Owner as TFrameUnitProps).cxDBCurrencyEdit3.Value+CurIznosCorr); //суммарный износ - переделали в рубли SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=((Owner as TFrameUnitProps).cxDBCurrencyEdit4.Value-CurIznosSumm); //остаточная стоимость //zav if OstPrice<0.001 then begin CurIznosSumm:=CurIznosSumm+OstPrice; SummIznos:=SummIznos+OstPrice; SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=0; CurIznos:=StartPrice; end; //end zav CurIznos:=CurIznos*K; SummIznos:=SummIznos*K; StartPrice:=StartPrice*K; OstPrice:=OstPrice*K; VostanPrice:=VostanPrice*K; if qryAmortAuto.State in [dsEdit, dsInsert] then qryAmortAuto.Post; qryAmortAuto.Insert; qryAmortAuto['МесяцСчетчик']:=MonthCount; qryAmortAuto['МесяцДата']:=CurDate; qryAmortAuto['МесяцСтрока']:=MonthStr(CurDate); qryAmortAuto['Начальная стоимость']:=StartPrice; //zav //qryAmortAuto['Начисленный износ']:=CurIznos {zav}+ CorrSum {end zav}; qryAmortAuto['Начисленный износ']:=CurIznosCorr; //end zav qryAmortAuto['Суммарный износ']:=SummIznos; qryAmortAuto['СуммарныйИзносПроцент']:=SummIznosProc; qryAmortAuto['Остаточная стоимость']:=OstPrice; qryAmortAuto['Восстановительная стоимость']:=VostanPrice; qryAmortAuto['К переоценки']:=K; //zav if CorrSum <> 0 then qryAmortAuto['Сумма корректировки'] := CorrSum; //end zav qryAmortAuto.Post; while OstPrice>0 do begin inc(MonthCount); CurDate:=IncMonth(CurDate, 1); //следующий месяц K:=KRatio(CurDate); //zav CorrSum :=GetCorrSum(CurDate); //end zav StartPrice:=OstPrice; //начальная стоимость // CurIznos:=cxDBCurrencyEdit2.Value*ceAmortNorm.Value/100/12; //начисленный износ {zav}CurIznosCorr := CurIznos + CorrSum {end zav}; CurIznosSumm:=CurIznosSumm+CurIznosCorr; SummIznos:=SummIznos+CurIznosCorr; //суммарный износ SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=OstPrice - CurIznosCorr; //остаточная стоимость if OstPrice<0.001 then begin CurIznosSumm:=CurIznosSumm+OstPrice; SummIznos:=SummIznos+OstPrice; // if SummIznos > VostanPrice then SummIznos := VostanPrice; SummIznosProc:=SummIznos/VostanPrice*100; OstPrice:=0; CurIznosCorr:=StartPrice; end; { if SummIznosProc > 100 then begin CurIznosCorr := SummIznos SummIznos := VostanPrice; SummIznosProc := SummIznos/VostanPrice*100; end; } CurIznos:=CurIznos*K; SummIznos:=SummIznos*K; StartPrice:=StartPrice*K; OstPrice:=OstPrice*K; VostanPrice:=VostanPrice*K; qryAmortAuto.Insert; qryAmortAuto['МесяцСчетчик']:=MonthCount; qryAmortAuto['МесяцДата']:=CurDate; qryAmortAuto['МесяцСтрока']:=MonthStr(CurDate); qryAmortAuto['Начальная стоимость']:=StartPrice; qryAmortAuto['Начисленный износ']:=CurIznosCorr; qryAmortAuto['Суммарный износ']:=SummIznos; qryAmortAuto['СуммарныйИзносПроцент']:=SummIznosProc; qryAmortAuto['Остаточная стоимость']:=OstPrice; qryAmortAuto['Восстановительная стоимость']:=VostanPrice; qryAmortAuto['К переоценки']:=K; //zav if CorrSum <> 0 then qryAmortAuto['Сумма корректировки'] := CorrSum; //end zav qryAmortAuto.Post; end; finally qryCorrSum.Tag := 0; qryAmortAuto.EnableControls; viewAmortAuto.EndUpdate; end; end; procedure TdlgAmort.bntAmortAccountClick(Sender: TObject); begin if qryAmortAuto.RecordCount>0 then begin if MessageBox(Handle, 'Пересчитать амортизационные начисления?', 'Расчет амортизации', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) = IDYES then AmortAccount(true); end else AmortAccount(true); end; procedure TdlgAmort.CheckAmortFields; var st: string; begin if VarIsNullMy((Owner as TFrameUnitProps).Query['Учетная единица.Дата отсчета амортизации']) then raise Exception.Create('Для расчета амортизации необходимо заполнить поле "Дата отсчета амортизации"'); if VarIsNullMy((Owner as TFrameUnitProps).Query['Учетная единица.Балансовая стоимость']) then begin if (Owner as TFrameUnitProps).IsEarthArea then st:='Кадастровая стоимость' else st:='Балансовая стоимость'; raise Exception.Create('Для расчета амортизации необходимо заполнить поле "'+st+'"'); end; if VarIsNullMy((Owner as TFrameUnitProps).Query['Учетная единица.Входящий износ']) then raise Exception.Create('Для расчета амортизации необходимо заполнить поле "Входящий износ"'); if VarIsNullMy((Owner as TFrameUnitProps).Query['Учетная единица.Входящая остаточная стоимость']) then raise Exception.Create('Для расчета амортизации необходимо заполнить поле "Входящая остаточная стоимость"'); if VarIsNullMy((Owner as TFrameUnitProps).Query['Учетная единица.Норма амортизационных отчислений']) then raise Exception.Create('Для расчета амортизации необходимо заполнить поле "Норма амортизационных отчислений"'); end; procedure TdlgAmort.UpdateAmortUserMonthNumber; var AfterPost: TDataSetNotifyEvent; b: TBookMark; i: integer; begin i:=1; AfterPost:=qryAmortUser.AfterPost; try qryAmortUser.AfterPost:=nil; b:=qryAmortUser.GetBookmark; tvAmortUser.BeginUpdate; try qryAmortUser.First; while not qryAmortUser.Eof do begin qryAmortUser.Edit; qryAmortUser['МесяцСчетчик']:=i; inc(i); qryAmortUser.Post; qryAmortUser.Next; end; qryAmortUser.GotoBookmark(b); qryAmortUser.FreeBookmark(b); finally tvAmortUser.EndUpdate; end; finally qryAmortUser.AfterPost:=AfterPost; end; end; procedure TdlgAmort.qryAmortUserBeforePost(DataSet: TDataSet); var y, m, d: word; begin if not VarIsNullMy(DataSet['МесяцДата']) then begin DecodeDate(DataSet['МесяцДата'], y, m, d); DataSet['МесяцДата']:=EncodeDate(y, m, 1); DataSet['МесяцСтрока']:=DateTo_MMMMDDDD_Str(DataSet['МесяцДата']); end else raise Exception.Create('Необходимо заполнить поле "месяц"'); end; procedure TdlgAmort.qryAmortUserAfterOpen(DataSet: TDataSet); begin qryAmortUser.Sort:='МесяцДата'; end; procedure TdlgAmort.qryAmortUserAfterPost(DataSet: TDataSet); begin UpdateAmortUserMonthNumber; WasAmortUserEdit:=true; end; procedure TdlgAmort.SetPrimaryKey(AValue:integer); begin if FPrimaryKey <> AValue then begin FPrimaryKey := AValue; //zav qryCorrSum.Close; qryCorrSum.Open; //end zav end; end; procedure TdlgAmort.qryAmortAutoBeforePost(DataSet: TDataSet); var c:boolean; //i:Integer;d:TDateTime; begin inherited; //zav if qryCorrSum.Tag = 0 then begin if qryAmortAuto.FieldByName('Сумма корректировки').AsFloat = 0 then qryAmortAuto.FieldByName('Сумма корректировки').Value := NULL; // i := qryAmortAuto['вк_Учетная единица']; // d := qryAmortAuto['МесяцДата']; c := qryCorrSum.Locate('МесяцДата', qryAmortAuto['МесяцДата'],[]) ; if not c and not qryAmortAuto.FieldByName('Сумма корректировки').IsNull then begin qryCorrSum.Insert; qryCorrSum['вк_Родитель'] := qryCorrSum.Parameters.ParamByName('@код_Учетная_единица').Value; qryCorrSum['МесяцДата'] := qryAmortAuto['МесяцДата']; qryCorrSum['Сумма корректировки'] := qryAmortAuto['Сумма корректировки']; qryCorrSum.Post; end else if c and not qryAmortAuto.FieldByName('Сумма корректировки').IsNull then begin qryCorrSum.Edit; qryCorrSum['Сумма корректировки'] := qryAmortAuto['Сумма корректировки']; qryCorrSum.Post; end else if c then begin qryCorrSum.Delete; end; end; WasAmortReaccount:=true; //end zav end; procedure TdlgAmort.qryAmortUserAfterDelete(DataSet: TDataSet); begin UpdateAmortUserMonthNumber; end; procedure TdlgAmort.qryAmortUserRatioAfterOpen(DataSet: TDataSet); begin qryAmortUserRatio.Sort:='[Дата переоценки]'; end; procedure TdlgAmort.qryAmortUserRatioAfterPost(DataSet: TDataSet); begin WasAmortUserRatioEdit:=true; end; procedure TdlgAmort.qryAmortUserRatioBeforePost(DataSet: TDataSet); var y, m, d: word; begin if not VarIsNullMy(DataSet['Дата переоценки']) then begin DecodeDate(DataSet['Дата переоценки'], y, m, d); DataSet['Дата переоценки']:=EncodeDate(y, m, 1); DataSet['Дата переоценки (строка)']:=DateTo_MMMMDDDD_Str(DataSet['Дата переоценки']); end else raise Exception.Create('Необходимо заполнить поле "Месяц переоценки"'); if VarIsNullMy(DataSet['Коэффициент']) then raise Exception.Create('Необходимо заполнить поле "Коэффициент"'); if VarIsNullMy(DataSet['код_Амортизация (коэффициенты переоценки)']) then DataSet['СтатусЗаписи']:=1 else DataSet['СтатусЗаписи']:=2 end; procedure TdlgAmort.qryCorrSumAfterPost(DataSet: TDataSet); begin inherited; //zav WasAmortUserRatioEdit:=true; //end zav end; procedure TdlgAmort.qryCorrSumBeforeOpen(DataSet: TDataSet); begin inherited; //zav qryCorrSum.Connection := frmMain.ADOConnection; // if VarIsNull(qryAmortAuto.FieldByName('вк_Учетная единица').Value) then Exit; qryCorrSum.Parameters.Refresh; // if (qryAmortAuto.RecordCount > 0) and (qryAmortAuto.Eof or qryAmortAuto.Bof ) then // qryAmortAuto.First; qryCorrSum.Parameters.ParamByName('@код_Учетная_единица').Value := PrimaryKey; // qryAmortAuto.FieldByName('вк_Учетная единица').Value; // ShowMessage(VarToStr(qryCorrSum.Parameters.ParamByName('@код_Учетная_единица').Value )); //end zav end; procedure TdlgAmort.tvRatioDBBandedColumnGetDataText( Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: String); begin inherited; if AText<>'' then atext:=DateTo_MMMMDDDD_Str(StrToDate(AText)); end; procedure TdlgAmort.qryAmortUserRatioBeforeDelete(DataSet: TDataSet); var BeforePost: TDataSetNotifyEvent; begin inherited; BeforePost:=DataSet.BeforePost; DataSet.BeforePost:=nil; try DataSet.Edit; DataSet['СтатусЗаписи']:=3; DataSet.Post; abort; finally DataSet.BeforePost:=BeforePost; end; end; procedure TdlgAmort.tvRatioDBBandedColumn5PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var frm: TdlgDocument; col: TcxGridDBBandedColumn; row: TcxCustomGridRow; GroupID: integer; qry: TAdoQuery; begin frm:=TdlgDocument.Create(nil); try // grd:=TcxButtonEdit(Sender).Parent.Parent as TcxGrid; { col:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag); row:=view.Controller.FocusedRow; qry:=Query;//view.DataController.DataSource.DataSet as TAdoQuery; if row.IsNewItemRow then begin if qry.State<>dsInsert then qry.Insert end else} qry:=qryAmortUserRatio; // if qry.State=dsEdit then begin frm.Num:=qry['Основание.Номер']; frm.Date:=qry['Основание.Дата']; frm.DocName:=qry['Основание.Наименование']; frm.DocTypeID:=qry['Основание.код_Тип документа']; frm.Link:=qry['Основание.Ссылка на файл']; frm.Comment:=qry['Основание.Примечание']; end; if frm.ShowModal<>mrOK then exit; qry.Edit; qry['Основание.Номер']:=frm.Num; qry['Основание.Дата']:=frm.Date; qry['Основание.Наименование']:=frm.DocName; qry['Основание.код_Тип документа']:=frm.DocTypeID; qry['Основание.Тип документа']:=frm.DocTypeName; qry['Основание.Ссылка на файл']:=frm.Link; qry['Основание.Примечание']:=frm.Comment; finally frm.Free; end; end; procedure TdlgAmort.FormCreate(Sender: TObject); begin inherited; qryAmortAuto.Connection:=frmMain.ADOConnection; qryAmortUser.Connection:=frmMain.ADOConnection; qryAmortUserRatio.Connection:=frmMain.ADOConnection; cmdDelAmort.Connection:=frmMain.ADOConnection; qryCorrSum.Connection:=frmMain.ADOConnection; end; end.
unit Form.TokyoInstaller; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Objekt.Ini, Vcl.StdCtrls, AdvEdit, AdvEdBtn, AdvDirectoryEdit; type TForm1 = class(TForm) Label1: TLabel; edt_TMS: TAdvDirectoryEdit; btn_Install: TButton; Label2: TLabel; edt_Optima: TAdvDirectoryEdit; Label3: TLabel; edt_Gnostice: TAdvDirectoryEdit; Label4: TLabel; edt_Mad: TAdvDirectoryEdit; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_InstallClick(Sender: TObject); private fIni: TIni; fBibliothekspfad: TStringList; fSuchpfad: TStringList; procedure Installieren; procedure SchreibeInBibliothekspfad(aValue: string); function getBibliothekspfadFromList: string; function getSuchpfadFromList: string; procedure LoescheInBibliothekspfad(aValue: string); procedure LoescheInSuchpfad(aValue: string); procedure SchreibeInSuchpfad(aValue: string); procedure MultiLoeschenInBibliothekspfad(aAV_TMS, aAV_OTPIMA: string); procedure MultiSchreibeInBibliothekspfad(a32Bit: Boolean); public end; var Form1: TForm1; implementation {$R *.dfm} uses Objekt.Global, Allgemein.System; procedure TForm1.FormCreate(Sender: TObject); begin Global := TGlobal.Create(Self); fIni := TIni.Create(Self); edt_TMS.Text := fIni.TMSPfad; edt_Optima.Text := fIni.OptimaPfad; edt_Gnostice.Text := fIni.GnosticePfad; edt_Mad.Text := fIni.MadCollectionPfad; fBibliothekspfad := TStringList.Create; fBibliothekspfad.Delimiter := ';'; fBibliothekspfad.StrictDelimiter := true; fSuchpfad := TStringList.Create; fSuchpfad.Delimiter := ';'; fSuchpfad.StrictDelimiter := true; end; procedure TForm1.FormDestroy(Sender: TObject); begin FreeAndNil(Global); FreeAndNil(fIni); FreeAndNil(fBibliothekspfad); FreeAndNil(fSuchpfad); end; procedure TForm1.btn_InstallClick(Sender: TObject); begin if Trim(edt_TMS.Text) = '' then begin ShowMessage('Bitte TMS-Pfad eintragen.'); exit; end; if Trim(edt_Optima.Text) = '' then begin ShowMessage('Bitte Optima-Komponenten-Pfad eintragen.'); exit; end; { if Trim(edt_Gnostice.Text) = '' then begin ShowMessage('Bitte Gnostice-Pfad eintragen.'); exit; end; } if Trim(edt_Mad.Text) = '' then begin ShowMessage('Bitte MadCollection-Pfad eintragen.'); exit; end; Installieren; ShowMessage('Fertig'); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin fIni.TMSPfad := IncludeTrailingPathDelimiter(edt_TMS.Text); fIni.OptimaPfad := IncludeTrailingPathDelimiter(edt_Optima.Text); fIni.GnosticePfad := IncludeTrailingPathDelimiter(edt_Gnostice.Text); fIni.MadCollectionPfad := IncludeTrailingPathDelimiter(edt_Mad.Text); end; procedure TForm1.Installieren; var AV_TMS: string; AV_OPTIMA: string; s: string; begin edt_TMS.Text := IncludeTrailingPathDelimiter(edt_TMS.Text); edt_Optima.Text := IncludeTrailingPathDelimiter(edt_Optima.Text); AV_TMS := IncludeTrailingPathDelimiter(fIni.AV_TMS); if not SameText(AV_TMS, edt_TMS.Text) then begin fIni.AV_TMS := edt_TMS.Text; AV_TMS := IncludeTrailingPathDelimiter(edt_TMS.Text); end; AV_OPTIMA := IncludeTrailingPathDelimiter(fIni.AV_OPTIMA); if not SameText(AV_OPTIMA, edt_Optima.Text) then begin fIni.AV_OPTIMA := edt_Optima.Text; AV_OPTIMA := IncludeTrailingPathDelimiter(edt_Optima.Text); end; fSuchpfad.DelimitedText := fIni.Suchpfad32; // Bibliothekspfad 32 fBibliothekspfad.DelimitedText := fIni.BibliotheksPfad32; MultiLoeschenInBibliothekspfad(AV_TMS, AV_OPTIMA); MultiSchreibeInBibliothekspfad(true); s := getBibliothekspfadFromList; fIni.BibliotheksPfad32 := s; // Bibliothekspfad 64 fBibliothekspfad.Clear; fBibliothekspfad.DelimitedText := fIni.BibliotheksPfad64; MultiLoeschenInBibliothekspfad(AV_TMS, AV_OPTIMA); MultiSchreibeInBibliothekspfad(false); s := getBibliothekspfadFromList; fIni.BibliotheksPfad64 := s; { LoescheInSuchpfad(AV_TMS + 'Delphi102Tokyo\Win32\Release\'); LoescheInSuchpfad(AV_TMS); LoescheInSuchpfad(AV_TMS + 'XlsAdapter\'); LoescheInSuchpfad(AV_OPTIMA + 'delphi-rest-client-api-master\src\'); LoescheInSuchpfad(AV_OPTIMA + 'Drag and Drop\Source\'); LoescheInSuchpfad(AV_OPTIMA + 'GridAdapter\'); LoescheInSuchpfad(AV_OPTIMA + 'logger\'); LoescheInSuchpfad(AV_OPTIMA + 'logger\log4d\'); LoescheInSuchpfad(AV_OPTIMA + 'Mail\'); LoescheInSuchpfad(AV_OPTIMA + 'RegExp\Source\'); LoescheInSuchpfad(AV_OPTIMA + 'rvSpell\'); LoescheInSuchpfad(AV_OPTIMA + 'tlb\'); LoescheInSuchpfad(AV_OPTIMA + 'Virtual-TreeView-master\Source\'); LoescheInSuchpfad(AV_OPTIMA + 'ZipMaster\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\ExecOnTime\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\LockProvider\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSButton\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSComboBox\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSDatePicker\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSEditAutoComplete\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSEditBtn\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSEditFloat\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\NFSLabel\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\ProcessQueue\'); LoescheInSuchpfad(AV_OPTIMA + 'newfrontiers\Ueberschriftenpanel\'); s := getSuchpfadFromList; fIni.Suchpfad32 := s; } end; procedure TForm1.MultiSchreibeInBibliothekspfad(a32Bit: Boolean); var GnosticePfad: String; MadPfad: string; Win: string; begin if a32Bit then Win := 'Win32' else Win := 'Win64'; GnosticePfad := IncludeTrailingPathDelimiter(edt_Gnostice.Text); MadPfad := IncludeTrailingPathDelimiter(edt_Mad.Text); SchreibeInBibliothekspfad('$(TMS)\Delphi102Tokyo\'+ Win + '\Release\'); SchreibeInBibliothekspfad('$(TMS)\'); SchreibeInBibliothekspfad('$(TMS)\XlsAdapter\'); SchreibeInBibliothekspfad('$(OPTIMA)\awrem32\'); SchreibeInBibliothekspfad('$(OPTIMA)\delphi-rest-client-api-master\src\'); SchreibeInBibliothekspfad('$(OPTIMA)\Drag and Drop\Source\'); SchreibeInBibliothekspfad('$(OPTIMA)\Drag and Drop\Demos\Outlook\MAPI\'); SchreibeInBibliothekspfad('$(OPTIMA)\GridAdapter\'); SchreibeInBibliothekspfad('$(OPTIMA)\logger\'); SchreibeInBibliothekspfad('$(OPTIMA)\logger\log4d\'); SchreibeInBibliothekspfad('$(OPTIMA)\Mail\'); SchreibeInBibliothekspfad('$(OPTIMA)\RegExp\Source\'); SchreibeInBibliothekspfad('$(OPTIMA)\rvSpell\'); SchreibeInBibliothekspfad('$(OPTIMA)\tlb\'); SchreibeInBibliothekspfad('$(OPTIMA)\Virtual-TreeView-master\Source\'); SchreibeInBibliothekspfad('$(OPTIMA)\ZipMaster\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\ExecOnTime\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\LockProvider\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSButton\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSComboBox\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSDatePicker\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSEditAutoComplete\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSEditBtn\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSEditFloat\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\NFSLabel\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\ProcessQueue\'); SchreibeInBibliothekspfad('$(OPTIMA)\newfrontiers\Ueberschriftenpanel\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Commands\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Configuration\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Database\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Entity\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Events\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.GUI\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Reflection\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Tapi\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Threading\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Utility\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Validation\'); SchreibeInBibliothekspfad('$(OPTIMA)\NfsFramework\NewFrontiers.Vcl\'); if (Length(GnosticePfad) > 1) and (DirectoryExists(GnosticePfad)) then begin SchreibeInBibliothekspfad(GnosticePfad + 'PDFtoolkit VCL\Lib\RAD10.2\' + Win + '\'); SchreibeInBibliothekspfad(GnosticePfad + 'Shared\Lib\RAD10.2\' + Win + '\'); SchreibeInBibliothekspfad(GnosticePfad + 'eDocEngine VCL\Lib\RAD10.2\' + Win + '\'); SchreibeInBibliothekspfad(GnosticePfad + 'Shared3\Lib\RAD10.2\' + Win + '\'); SchreibeInBibliothekspfad(GnosticePfad + 'eDocEngine VCL\Lib\RAD10.2\' + Win + '\ExpIntf\'); SchreibeInBibliothekspfad(GnosticePfad + 'eDocEngine VCL\Source\HtmlView\HtmlViewer Packages\'); end; SchreibeInBibliothekspfad('$(TRichViewVCL)\ThirdParty\rvHtmlViewImporter\Source'); SchreibeInBibliothekspfad(MadPfad + 'madBasic\BDS19\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madDisAsm\BDS19\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madExcept\BDS19\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madExcept\..\Plugins\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madRemote\BDS19\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madKernel\BDS19\' + Win + '\'); if a32Bit then SchreibeInBibliothekspfad(MadPfad + 'madCodeHook\BDS19\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madSecurity\BDS19\' + Win + '\'); SchreibeInBibliothekspfad(MadPfad + 'madShell\BDS19\' + Win + '\'); end; procedure TForm1.MultiLoeschenInBibliothekspfad(aAV_TMS, aAV_OTPIMA: string); begin LoescheInBibliothekspfad(aAV_TMS + 'Delphi102Tokyo\Win32\Release\'); LoescheInBibliothekspfad(aAV_TMS); LoescheInBibliothekspfad(aAV_TMS + 'XlsAdapter\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'delphi-rest-client-api-master\src\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'Drag and Drop\Source\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'Drag and Drop\Demos\Outlook\MAPI\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'GridAdapter\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'logger\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'logger\log4d\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'Mail\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'RegExp\Source\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'rvSpell\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'tlb\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'Virtual-TreeView-master\Source\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'ZipMaster\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\ExecOnTime\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\LockProvider\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSButton\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSComboBox\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSDatePicker\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSEditAutoComplete\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSEditBtn\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSEditFloat\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\NFSLabel\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\ProcessQueue\'); LoescheInBibliothekspfad(aAV_OTPIMA + 'newfrontiers\Ueberschriftenpanel\'); end; function TForm1.getBibliothekspfadFromList: string; var i1: Integer; begin Result := ''; for i1 := 0 to fBibliothekspfad.Count -1 do begin Result := Result + Trim(fBibliothekspfad.Strings[i1]) + ';'; end; end; function TForm1.getSuchpfadFromList: string; var i1: Integer; begin Result := ''; for i1 := 0 to fSuchpfad.Count -1 do begin Result := Result + Trim(fSuchpfad.Strings[i1]) + ';'; end; end; procedure TForm1.LoescheInBibliothekspfad(aValue: string); var i1: Integer; begin for i1 := fBibliothekspfad.Count -1 downto 0 do begin if SameText(aValue, IncludeTrailingPathDelimiter(fBibliothekspfad.Strings[i1])) then begin fBibliothekspfad.Delete(i1); exit; end; end; end; procedure TForm1.SchreibeInBibliothekspfad(aValue: string); var i1: Integer; s: string; begin for i1 := 0 to fBibliothekspfad.Count -1 do begin if SameText(IncludeTrailingPathDelimiter(aValue), IncludeTrailingPathDelimiter(fBibliothekspfad.Strings[i1])) then exit; end; fBibliothekspfad.Add(aValue); end; procedure TForm1.LoescheInSuchpfad(aValue: string); var i1: Integer; begin for i1 := fSuchpfad.Count -1 downto 0 do begin if SameText(aValue, IncludeTrailingPathDelimiter(fSuchpfad.Strings[i1])) then begin fSuchpfad.Delete(i1); exit; end; end; end; procedure TForm1.SchreibeInSuchpfad(aValue: string); var i1: Integer; s: string; begin for i1 := 0 to fSuchpfad.Count -1 do begin if SameText(aValue, fSuchpfad.Strings[i1]) then exit; end; fSuchpfad.Add(aValue); end; end.
unit feedNatGeo; interface uses eaterReg; type TNatGeoProcessor=class(TFeedProcessor) private FFeedURL:WideString; public function Determine(Store:IFeedStore;const FeedURL:WideString; var FeedData:WideString;const FeedDataType:WideString):boolean; override; procedure ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); override; end; implementation uses SysUtils, jsonDoc, eaterSanitize, Variants, eaterUtils, MSXML2_TLB; { TNatGeoProcessor } function TNatGeoProcessor.Determine(Store: IFeedStore; const FeedURL: WideString; var FeedData: WideString; const FeedDataType: WideString): boolean; begin Result:=Store.CheckLastLoadResultPrefix('NatGeo') and FindPrefixAndCrop(FeedData,'window\[''__natgeo__''\]='); if Result then FFeedURL:=FeedURL; end; procedure TNatGeoProcessor.ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); var jfrms,jmods,jtiles,jctas:IJSONDocArray; jdoc,jfrm,jmod,jtile,jdata,j1:IJSONDocument; itemid,itemurl:string; pubDate:TDateTime; data,title,content:WideString; frm_i,mod_i,tile_i,tag_i:integer; tags,v:Variant; r:ServerXMLHTTP60; SkipRemaining:boolean; begin jfrms:=JSONDocArray; j1:=JSON; jdoc:=JSON(['page{','meta',j1,'content{','hub{','frms',jfrms,'}}}']); try jdoc.Parse(FeedData); except on EJSONDecodeException do ;//ignore "data past end" end; itemid:=VarToStr(j1['title']); if itemid<>'' then Handler.UpdateFeedName(itemid); jmods:=JSONDocArray; jfrm:=JSON(['mods',jmods]); jtiles:=JSONDocArray; jmod:=JSON(['tiles',jtiles]); jctas:=JSONDocArray; jtile:=JSON(['ctas',jctas]); jdata:=JSON; SkipRemaining:=false; r:=CoServerXMLHTTP60.Create; for frm_i:=0 to jfrms.Count-1 do begin jfrms.LoadItem(frm_i,jfrm); for mod_i:=0 to jmods.Count-1 do begin jmods.LoadItem(mod_i,jmod); for tile_i:=0 to jtiles.Count-1 do begin jtiles.LoadItem(tile_i,jtile); if jctas.Count>0 then begin { //itemid:=jtile['cId']; itemurl:=JSON(jctas[0])['url']; itemid:=itemurl;//???!!! pubDate:=UtcNow;//???!!! if (jtile['cmsType']<>'SeriesTile') and Handler.CheckNewPost(itemid,itemurl,pubDate) then begin title:=SanitizeTitle(jtile['title']); content:=HTMLEncode(jtile['description']);//'abstract'? v:=jtile['tags']; if not(VarIsNull(v)) then begin tags:=VarArrayCreate([VarArrayLowBound(v,1),VarArrayHighBound(v,1)],varOleStr); for tag_i:=VarArrayLowBound(v,1) to VarArrayHighBound(v,1) do if VarType(v[tag_i])=varUnknown then tags[tag_i]:=JSON(v[tag_i])['name'] else tags[tag_i]:=VarToStr(v[tag_i]); Handler.PostTags('tag',tags); end; j1:=JSON(jtile['img']); content:='<img class="postthumb" referrerpolicy="no-referrer" src="'+ HTMLEncodeQ(j1['src'])+ '" alt="'+HTMLEncodeQ(VarToStr(j1['dsc']))+'" /><br />'#13#10+ content; Handler.RegisterPost(title,content); end; } itemid:='';//see below itemurl:=JSON(jctas[0])['url']; if SkipRemaining then begin //just do CheckNewPost pro forma for total load items count Handler.CheckNewPost(itemid,itemurl,0.0); end else if (jtile['cmsType']<>'SeriesTile') then begin r.open('GET',itemurl,false,EmptyParam,EmptyParam); r.send(EmptyParam); if r.status=200 then data:=r.responseText else data:=''; if FindPrefixAndCrop(data,'window\[''__natgeo__''\]=') then begin try jdata.Parse(data); except on EJSONDecodeException do ;//ignore "data past end" end; j1:=JSON(JSON(JSON(JSON(jdata['page'])['content'])['article'])['meta']); itemid:=j1['id']; try pubDate:=ConvDate1(j1['mdfdDt']); except pubDate:=UtcNow; end; if Handler.CheckNewPost(itemid,itemurl,pubDate) then begin //assert itemurl=j1['cnnicl'] title:=SanitizeTitle(j1['ttl']); content:=HTMLEncode(j1['dsc']); if not(VarIsNull(j1['sclImg'])) then content:='<img class="postthumb" referrerpolicy="no-referrer" src="'+ HTMLEncodeQ(j1['sclImg'])+ '" /><br />'#13#10+ content; v:=JSON(j1['pgTxnmy'])['sources'];//'subjects'? if not(VarIsNull(v)) then begin tags:=VarArrayCreate([VarArrayLowBound(v,1),VarArrayHighBound(v,1)],varOleStr); for tag_i:=VarArrayLowBound(v,1) to VarArrayHighBound(v,1) do tags[tag_i]:=VarToStr(v[tag_i]); Handler.PostTags('tag',tags); end; Handler.RegisterPost(title,content); end else //!! SkipRemaining:=true; end; end; end; end; end; end; Handler.ReportSuccess('NatGeo'); end; initialization RegisterFeedProcessor(TNatGeoProcessor.Create); end.
unit ideSHProxiPropEditors; interface uses DesignIntf, SysUtils, Classes, TypInfo, Controls, Graphics, ELPropInsp, SHDesignIntf; type TSHELPropEditor = class(TELPropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; TSHELStringPropEditor = class(TELStringPropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; TSHELStringsPropEditor = class(TELStringsPropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; TSHELIntegerPropEditor = class(TELIntegerPropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; TSHELClassPropEditor = class(TELClassPropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; TSHELInt64PropEditor = class(TELInt64PropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; TSHELComponentPropEditor = class(TELComponentPropEditor, ISHPropertyEditorInfo, ISHProperty) private FUserEditor: TSHPropertyEditor; FUserEditorChecked: Boolean; function GetUserEditor: TSHPropertyEditor; protected { IInterface } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { ISHPropertyEditorInfo } function ISHPropertyEditorInfo.GetInstance = IGetInstance; function IGetInstance: TObject; function ISHPropertyEditorInfo.GetPropInfo = IGetPropInfo; function IGetPropInfo: PPropInfo; function ISHPropertyEditorInfo.GetPropTypeInfo = IGetPropTypeInfo; function IGetPropTypeInfo: PTypeInfo; { ISHProperty } function ISHProperty.GetAttributes = IGetAttributes; function ISHProperty.GetValue = IGetValue; procedure ISHProperty.GetValues = IGetValues; procedure ISHProperty.SetValue = ISetValue; procedure ISHProperty.Edit = IEdit; function IGetAttributes: TPropertyAttributes; function IGetValue: string; procedure IGetValues(AValues: TStrings); procedure ISetValue(const Value: string); procedure IEdit; {override} function GetAttrs: TELPropAttrs; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property UserEditor: TSHPropertyEditor read GetUserEditor; public constructor Create(ADesigner: Pointer; APropCount: Integer); override; destructor Destroy; override; end; //Функцию необходимо использовать во всех TELInspector в событии //OnGetEditorClass, при добавлении нового класса прокси-эдитора (наследника //от нативного EL эдитра) эту функцию необходимо дорабатывать соответствующим //образом //такая необходость использования этого события вызвана невозможностью //зарегистрировать PropEditor на некоторые типы, например, множества, //простые типы function BTGetProxiEditorClass(APropertyInspector: TELPropertyInspector; AInstance: TPersistent; APropInfo: PPropInfo): TELPropEditorClass; implementation function GetUserEditorClass(AInstance: TObject; const APropertyName: string): TSHPropertyEditorClass; var I: Integer; vDesigner: ISHDesigner; ClassPtr: TClass; IntfTable: PInterfaceTable; begin if SHSupports(ISHDesigner, vDesigner) then begin ClassPtr := AInstance.ClassType; while ClassPtr <> nil do begin IntfTable := ClassPtr.GetInterfaceTable; if IntfTable <> nil then for I := Pred(IntfTable.EntryCount) downto 0 do begin Result := vDesigner.GetPropertyEditor(IntfTable.Entries[I].IID, APropertyName); if Assigned(Result) then Exit; end; ClassPtr := ClassPtr.ClassParent; end; end; Result := nil; end; function BTGetProxiEditorClass(APropertyInspector: TELPropertyInspector; AInstance: TPersistent; APropInfo: PPropInfo): TELPropEditorClass; var LTypeInfo: PTypeInfo; vIncludeProp: Boolean; begin LTypeInfo := APropInfo.PropType^; if not (((pkProperties in APropertyInspector.PropKinds) and (LTypeInfo.Kind in tkProperties)) or ((pkEvents in APropertyInspector.PropKinds) and (LTypeInfo.Kind in tkMethods))) or not Assigned(APropInfo.GetProc) or (not (pkReadOnly in APropertyInspector.PropKinds) and not Assigned(APropInfo.SetProc) and (APropInfo.PropType^.Kind <> tkClass)) then begin Result := nil; Exit; end; if Assigned(APropertyInspector.OnFilterProp) then begin vIncludeProp := True; APropertyInspector.OnFilterProp(APropertyInspector, AInstance, APropInfo, vIncludeProp); if not vIncludeProp then begin Result := nil; Exit; end; end; Result := nil; if (LTypeInfo = TypeInfo(TComponentName)) or (LTypeInfo = TypeInfo(TDate)) or (LTypeInfo = TypeInfo(TTime)) or (LTypeInfo = TypeInfo(TDateTime)) or (LTypeInfo = TypeInfo(TCaption)) or (LTypeInfo = TypeInfo(TColor)) or (LTypeInfo = TypeInfo(TCursor)) or (LTypeInfo = TypeInfo(TFontCharset)) or (LTypeInfo = TypeInfo(TFontName)) or (LTypeInfo = TypeInfo(TImeName)) or (LTypeInfo = TypeInfo(TFont)) or ((LTypeInfo.Kind = tkClass) and GetTypeData(LTypeInfo).ClassType.InheritsFrom(TFont)) or (LTypeInfo = TypeInfo(TModalResult)) or (LTypeInfo = TypeInfo(TPenStyle)) or (LTypeInfo = TypeInfo(TBrushStyle)) or (LTypeInfo = TypeInfo(TTabOrder)) or (LTypeInfo = TypeInfo(TShortCut)) then Exit; case LTypeInfo.Kind of tkInteger: Result := TSHELIntegerPropEditor; // tkChar: AEditorClass := TELCharPropEditor; // tkEnumeration: AEditorClass := TELEnumPropEditor; // tkFloat: AEditorClass := TELFloatPropEditor; tkString, tkLString, tkWString: Result := TSHELStringPropEditor; // tkSet: AEditorClass := TELSetPropEditor; tkClass: begin if (LTypeInfo = TypeInfo(TStrings)) or GetTypeData(LTypeInfo).ClassType.InheritsFrom(TStrings) then Result := TSHELStringsPropEditor else if (LTypeInfo = TypeInfo(TComponent)) or GetTypeData(LTypeInfo).ClassType.InheritsFrom(TComponent) then Result := TSHELComponentPropEditor else Result := TSHELClassPropEditor; end; tkMethod: Result := TSHELPropEditor; // tkVariant: AEditorClass := TELVariantPropEditor; tkInt64: Result := TSHELInt64PropEditor; // else // AEditorClass := TELPropEditor; end; end; { TSHELPropEditor } constructor TSHELPropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELPropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELPropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELPropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELPropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELPropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELPropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELPropEditor.IEdit; begin inherited Edit; end; function TSHELPropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELPropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELPropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELPropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELPropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELPropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELPropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELPropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELPropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELPropEditor._AddRef: Integer; begin Result := -1; end; function TSHELPropEditor._Release: Integer; begin Result := -1; end; { TSHELStringPropEditor } constructor TSHELStringPropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELStringPropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELStringPropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELStringPropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELStringPropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELStringPropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELStringPropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELStringPropEditor.IEdit; begin inherited Edit; end; function TSHELStringPropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELStringPropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELStringPropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELStringPropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELStringPropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELStringPropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELStringPropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELStringPropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELStringPropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELStringPropEditor._AddRef: Integer; begin Result := -1; end; function TSHELStringPropEditor._Release: Integer; begin Result := -1; end; { TSHELStringsPropEditor } constructor TSHELStringsPropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELStringsPropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELStringsPropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELStringsPropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELStringsPropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELStringsPropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELStringsPropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELStringsPropEditor.IEdit; begin inherited Edit; end; function TSHELStringsPropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELStringsPropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELStringsPropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELStringsPropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELStringsPropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELStringsPropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELStringsPropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELStringsPropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELStringsPropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELStringsPropEditor._AddRef: Integer; begin Result := -1; end; function TSHELStringsPropEditor._Release: Integer; begin Result := -1; end; { TSHELIntegerPropEditor } constructor TSHELIntegerPropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELIntegerPropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELIntegerPropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELIntegerPropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELIntegerPropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELIntegerPropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELIntegerPropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELIntegerPropEditor.IEdit; begin inherited Edit; end; function TSHELIntegerPropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELIntegerPropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELIntegerPropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELIntegerPropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELIntegerPropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELIntegerPropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELIntegerPropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELIntegerPropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELIntegerPropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELIntegerPropEditor._AddRef: Integer; begin Result := -1; end; function TSHELIntegerPropEditor._Release: Integer; begin Result := -1; end; { TSHELClassPropEditor } constructor TSHELClassPropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELClassPropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELClassPropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELClassPropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELClassPropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELClassPropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELClassPropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELClassPropEditor.IEdit; begin inherited Edit; end; function TSHELClassPropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELClassPropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELClassPropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELClassPropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELClassPropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELClassPropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELClassPropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELClassPropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELClassPropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELClassPropEditor._AddRef: Integer; begin Result := -1; end; function TSHELClassPropEditor._Release: Integer; begin Result := -1; end; { TSHELInt64PropEditor } constructor TSHELInt64PropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELInt64PropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELInt64PropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELInt64PropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELInt64PropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELInt64PropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELInt64PropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELInt64PropEditor.IEdit; begin inherited Edit; end; function TSHELInt64PropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELInt64PropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELInt64PropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELInt64PropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELInt64PropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELInt64PropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELInt64PropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELInt64PropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELInt64PropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELInt64PropEditor._AddRef: Integer; begin Result := -1; end; function TSHELInt64PropEditor._Release: Integer; begin Result := -1; end; { TSHELComponentPropEditor } constructor TSHELComponentPropEditor.Create(ADesigner: Pointer; APropCount: Integer); begin inherited; FUserEditorChecked := False; FUserEditor := nil; end; destructor TSHELComponentPropEditor.Destroy; begin if Assigned(FUserEditor) then FUserEditor.Free; inherited; end; procedure TSHELComponentPropEditor.Edit; begin if UserEditor <> nil then FUserEditor.Edit else inherited Edit; end; function TSHELComponentPropEditor.GetAttrs: TELPropAttrs; var UserAttributes: TPropertyAttributes; InheritedAttrs: TELPropAttrs; begin if UserEditor <> nil then begin UserAttributes := FUserEditor.GetAttributes; InheritedAttrs := (inherited GetAttrs); Result := []; if paValueList in UserAttributes then Include(Result, praValueList); if paSubProperties in UserAttributes then Include(Result, praSubProperties); if paDialog in UserAttributes then Include(Result, praDialog); if paMultiSelect in UserAttributes then Include(Result, praMultiSelect); if paAutoUpdate in UserAttributes then Include(Result, praAutoUpdate); if paSortList in UserAttributes then Include(Result, praSortList); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paVolatileSubProperties in UserAttributes then Include(Result, praVolatileSubProperties); if paNotNestable in UserAttributes then Include(Result, praNotNestable); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if paReadOnly in UserAttributes then Include(Result, praReadOnly); if praOwnerDrawValues in InheritedAttrs then Include(Result, praOwnerDrawValues); if praComponentRef in InheritedAttrs then Include(Result, praComponentRef); end else Result := inherited GetAttrs; end; function TSHELComponentPropEditor.GetUserEditor: TSHPropertyEditor; var PropertyEditorClass: TSHPropertyEditorClass; vInstance: TObject; begin Result := nil; if Assigned(FUserEditor) then Result := FUserEditor else begin vInstance := IGetInstance; if (not FUserEditorChecked) and Assigned(vInstance) then begin PropertyEditorClass := GetUserEditorClass(vInstance, GetPropName); if Assigned(PropertyEditorClass) then FUserEditor := PropertyEditorClass.Create(Self); FUserEditorChecked := True; end; end; end; function TSHELComponentPropEditor.GetValue: string; begin if UserEditor <> nil then Result := FUserEditor.GetValue else Result := inherited GetValue; end; procedure TSHELComponentPropEditor.GetValues(AValues: TStrings); begin if UserEditor <> nil then FUserEditor.GetValues(AValues) else inherited GetValues(AValues); end; procedure TSHELComponentPropEditor.IEdit; begin inherited Edit; end; function TSHELComponentPropEditor.IGetAttributes: TPropertyAttributes; var InheritedAttrs: TELPropAttrs; begin InheritedAttrs := inherited GetAttrs; Result := []; if praValueList in InheritedAttrs then Include(Result, paValueList); if praSubProperties in InheritedAttrs then Include(Result, paSubProperties); if praDialog in InheritedAttrs then Include(Result, paDialog); if praMultiSelect in InheritedAttrs then Include(Result, paMultiSelect); if praAutoUpdate in InheritedAttrs then Include(Result, paAutoUpdate); if praSortList in InheritedAttrs then Include(Result, paSortList); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praVolatileSubProperties in InheritedAttrs then Include(Result, paVolatileSubProperties); if praNotNestable in InheritedAttrs then Include(Result, paNotNestable); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); if praReadOnly in InheritedAttrs then Include(Result, paReadOnly); end; function TSHELComponentPropEditor.IGetInstance: TObject; begin Result := GetInstance(0); end; function TSHELComponentPropEditor.IGetPropInfo: PPropInfo; begin Result := GetPropInfo(0); end; function TSHELComponentPropEditor.IGetPropTypeInfo: PTypeInfo; begin Result := PropTypeInfo; end; function TSHELComponentPropEditor.IGetValue: string; begin Result := inherited GetValue; end; procedure TSHELComponentPropEditor.IGetValues(AValues: TStrings); begin inherited GetValues(AValues); end; procedure TSHELComponentPropEditor.ISetValue(const Value: string); begin inherited SetValue(Value); end; procedure TSHELComponentPropEditor.SetValue(const Value: string); begin if UserEditor <> nil then FUserEditor.SetValue(Value) else inherited SetValue(Value); end; function TSHELComponentPropEditor.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSHELComponentPropEditor._AddRef: Integer; begin Result := -1; end; function TSHELComponentPropEditor._Release: Integer; begin Result := -1; end; end.
unit MeshSetFaceColours; interface uses LOD, BasicMathsTypes; {$INCLUDE source/Global_Conditionals.inc} type TMeshSetFaceColours = class protected FLOD: TLOD; public DistanceFunction: TDistanceFunc; constructor Create(var _LOD: TLOD); virtual; procedure Execute; end; implementation uses MeshColourCalculator, GLConstants, DistanceFormulas; constructor TMeshSetFaceColours.Create(var _LOD: TLOD); begin FLOD := _LOD; DistanceFunction := GetLinearDistance; end; procedure TMeshSetFaceColours.Execute; var i: integer; Calculator: TMeshColourCalculator; begin Calculator := TMeshColourCalculator.Create; Calculator.DistanceFunction := DistanceFunction; for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin // Calculate Vertex Normals Calculator.FindMeshFaceColours(FLOD.Mesh[i]); FLOD.Mesh[i].SetColoursType(C_COLOURS_PER_FACE); FLOD.Mesh[i].SetColourGenStructure(C_COLOURS_PER_FACE); FLOD.Mesh[i].ForceRefresh; end; Calculator.Free; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Material Preview frame. } unit FRMaterialPreview; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Math.Vectors, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Media, FMX.Viewport3D, FMX.ListBox, FMX.Types3D, FMX.Controls3D, FMX.Objects3D, FMX.MaterialSources, FMX.Layers3D, VXS.Scene, VXS.BaseClasses, // VXS.SceneViewer, VXS.Material, VXS.Teapot, VXS.HUDObjects, VXS.GeomObjects, VXS.Color, VXS.Coordinates; type TRMaterialPreview = class(TFrame) CBObject: TComboBox; Camera: TCamera; Cube: TCube; Sphere: TSphere; LightSource: TLight; CBBackground: TComboBox; BackGroundSprite: TImage3D; LightMaterialSource: TLightMaterialSource; Cone: TCone; Teapot: TModel3D; World: TDummy; Light: TDummy; FireSphere: TSphere; GLSViewer: TViewport3D; procedure CBObjectChange(Sender: TObject); procedure CBBackgroundChange(Sender: TObject); procedure GLSViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure GLSViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure GLSViewerMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); procedure GLSViewerMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); private FLibMaterial: TVXAbstractLibMaterial; function GetMaterial: TVXMaterial; procedure SetMaterial(const Value: TVXMaterial); function GetLibMaterial: TVXAbstractLibMaterial; procedure SetLibMaterial(const Value: TVXAbstractLibMaterial); public IsMouseUp : Boolean; Down : TPointF; GLMaterialLibrary: TVXMaterialLibrary; constructor Create(AOwner : TComponent); override; property Material : TVXMaterial read GetMaterial write SetMaterial; property LibMaterial : TVXAbstractLibMaterial read GetLibMaterial write SetLibMaterial; end; //======================================================================= implementation //======================================================================= {$R *.fmx} var MX, MY: Integer; //-------------------------------------------------------------- { TRMaterialPreview } //-------------------------------------------------------------- constructor TRMaterialPreview.Create(AOwner: TComponent); begin inherited; BackGroundSprite.Position.X := GLSViewer.Width/2; BackGroundSprite.Position.Y := GLSViewer.Height/2; BackGroundSprite.Width := GLSViewer.Width; BackGroundSprite.Height := GLSViewer.Height; CBObject.ItemIndex:=0; CBObjectChange(Self); CBBackground.ItemIndex:=0; CBBackgroundChange(Self); end; procedure TRMaterialPreview.CBObjectChange(Sender: TObject); var i : Integer; begin i:=CBObject.ItemIndex; Cube.Visible := I = 0; Sphere.Visible := I = 1; Cone.Visible := I = 2; Teapot.Visible := I = 3; end; procedure TRMaterialPreview.CBBackgroundChange(Sender: TObject); var bgColor : TColor; begin case CBBackground.ItemIndex of 1 : bgColor := TColors.White; 2 : bgColor := TColors.Black; 3 : bgColor := TColors.Blue; 4 : bgColor := TColors.Red; 5 : bgColor := TColors.Green; else bgColor := TColors.SysNone; end; if (bgColor<>TColors.SysNone) then BackGroundSprite.Bitmap.Canvas.Fill.Color := bgColor; end; procedure TRMaterialPreview.GLSViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); begin if (ssLeft in Shift) and (ssLeft in Shift) then begin World.RotationAngle.X := World.RotationAngle.X - ((Y - Down.Y) * 0.3); World.RotationAngle.Y := World.RotationAngle.Y + ((X - Down.X) * 0.3); Down := PointF(X, Y); end; end; procedure TRMaterialPreview.GLSViewerMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin IsMouseUp := False; end; procedure TRMaterialPreview.GLSViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin Down := PointF(X, Y); IsMouseUp := True; end; procedure TRMaterialPreview.GLSViewerMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); var AVector: TVector3D; begin AVector := Vector3D(0, 0, 1); Camera.Position.Vector := Camera.Position.Vector + AVector * (WheelDelta / 120) * 0.3; end; function TRMaterialPreview.GetMaterial: TVXMaterial; begin Result := GLMaterialLibrary.Materials[0].Material; end; procedure TRMaterialPreview.SetMaterial(const Value: TVXMaterial); begin GLMaterialLibrary.Materials[0].Material.Assign(Value.GetActualPrimaryMaterial); end; function TRMaterialPreview.GetLibMaterial: TVXAbstractLibMaterial; begin Result := FLibMaterial; end; procedure TRMaterialPreview.SetLibMaterial(const Value: TVXAbstractLibMaterial); begin FLibMaterial := Value; if Assigned(FLibMaterial) then begin with GLMaterialLibrary.Materials[0] do begin Material.MaterialLibrary := FLibMaterial.MaterialLibrary; Material.LibMaterialName := FLibMaterial.Name end; end else with GLMaterialLibrary.Materials[0] do begin Material.MaterialLibrary := nil; Material.LibMaterialName := ''; end; end; end.
(* Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED Original name: 0151.PAS Description: Pentium Floating Point Division Bug Code Author: DJ MURDOCH Date: 05-26-95 23:24 *) { According to a message I just saw on Usenet, many Pentiums have a bug in their implementation of the FDIV (floating point divide) instruction. Supposedly the following program prints the value 256.0000, rather than 0.0000, on one of these: } program pentbug; var x,y,z : double; begin x := 4195835; y := 3145727; z := x - (x/y)*y; writeln('z=',z:0:4,' (should be 0.0000)'); end. { Does anyone out there have a Pentium to try this on? It prints 0.0000 on my 486DX. }
unit Role; interface uses Windows, Messages, SysUtils, Classes, IBQuery, IBSQL, IBDatabase, Db, IBStoredProc, Dbun, Variants; type TRole = class(TDbunObject) private FRoleName: string; FRoleFullName: string; FRoleID: Integer; public property RoleName: string read FRoleName write FRoleName; property RoleFullName: string read FRoleFullName write FRoleFullName; property RoleID: Integer read FRoleID write FRoleID; function FillDataBy(KeyValue: Variant): Boolean; override; procedure NewRole(Name, FullName: string; ID: Integer = -1); function DeletePermission(ObjectID, ActionID: Integer): Boolean; function AddUserToRole(UserID: Integer): Boolean; function DelUserFromRole(UserID: Integer): Boolean; function CheckPermission(ObjectID, ActionID: Integer): Boolean; function Insert: Boolean; override; function Update: Boolean; override; function Delete: Boolean; override; constructor Create(AOwner: TComponent; AConnection: TIBDatabase; Query: TIBQuery = nil); override; end; implementation { TRole } uses user; function TRole.AddUserToRole(UserID: Integer): Boolean; var theUser: TUser; begin Result := false; theUser := TUser.Create(Self, FConnection); if theUser.FillDataBy(UserID) then Result := theUser.AddUserToRole(FRoleID); theUser.Free; end; constructor TRole.Create(AOwner: TComponent; AConnection: TIBDatabase; Query: TIBQuery = nil); begin inherited; FRoleID := -1; FRoleFullName := ''; FRoleName := ''; end; function TRole.Delete: Boolean; begin Result := false; end; function TRole.DeletePermission(ObjectID, ActionID: Integer): Boolean; var sqlDelPermission: TIBSQL; sql: string; begin Result := false; sqlDelPermission := TIBSQL.Create(nil); sqlDelPermission.Database := FConnection; sqlDelPermission.Transaction := FInputTransaction; sql := 'delete from permissions where id_object = ' + IntToStr(ObjectID) + ' and id_action = ' + IntToStr(ActionID) + ' and id_role = ' + IntToStr(FRoleID); sqlDelPermission.SQL.Text := sql; StartInputTransaction; try sqlDelPermission.ExecQuery; CommitInputTransaction; except on Exception do begin RollbackInputTransaction; Exit; end; end; sqlDelPermission.Free; Result := true; end; function TRole.DelUserFromRole(UserID: Integer): Boolean; var theUser: TUser; begin Result := false; theUser := TUser.Create(Self, FConnection); if theUser.FillDataBy(UserID) then Result := theUser.DelUserFromRole(FRoleID); theUser.Free; end; function TRole.FillDataBy(KeyValue: Variant): Boolean; var sql: string; queryRes: TIBQuery; begin Result := false; if not Assigned(FDataQuery) then begin FDataQuery := TIBQuery.Create(nil); FDataQuery.Transaction := FConnection.DefaultTransaction; sql := 'select *'; sql := sql + ' from roles'; sql := sql + ' where roles.id_role = ' + VarToStr(KeyValue); FDataQuery.SQL.Text := sql; try FDataQuery.Open; except on Exception do begin // ! Exit; end; end; queryRes := FDataQuery; end else begin queryRes := FDataQuery; FDataQuery := nil; end; if queryRes.RecordCount <= 0 then begin if Assigned(FDataQuery) then begin FDataQuery.Free; FDataQuery := nil; end; Exit; end; FRoleID := KeyValue; FRoleName := queryRes.FieldByName('name').AsString; FRoleFullName := queryRes.FieldByName('full_name').AsString; // Если отбор был самостоятельный if Assigned(FDataQuery) then begin FDataQuery.Free; FDataQuery := nil; end; Result := true; end; function TRole.Insert: Boolean; var stprInsRole: TIBStoredProc; begin Result := false; stprInsRole := TIBStoredProc.Create(nil); stprInsRole.Database := FConnection; stprInsRole.Transaction := FInputTransaction; stprInsRole.StoredProcName := 'INSERT_ROLE'; StartInputTransaction; try stprInsRole.Prepare; stprInsRole.ParamByName('pname').AsString := FRoleName; stprInsRole.ParamByName('pfull_name').AsString := FRoleFullName; stprInsRole.ExecProc; CommitInputTransaction; except on Exception do begin RollbackInputTransaction; Exit; end; end; FRoleID := stprInsRole.ParamByName('pid_role').AsInteger; stprInsRole.Free; Result := true; end; function TRole.CheckPermission(ObjectID, ActionID: Integer): Boolean; var queryCheckPermission: TIBQuery; sql: string; begin Result := false; queryCheckPermission := TIBQuery.Create(nil); queryCheckPermission.Database := FConnection; queryCheckPermission.Transaction := FConnection.DefaultTransaction; sql := 'select * from permissions where id_object = ' + IntToStr(ObjectID) + ' and id_action = ' + IntToStr(ActionID) + ' and id_role = ' + IntToStr(FRoleID); queryCheckPermission.SQL.Text := sql; try queryCheckPermission.Open; except on Exception do begin //! Exit; end; end; if queryCheckPermission.RecordCount > 0 then Result := true; queryCheckPermission.Free; end; procedure TRole.NewRole(Name, FullName: string; ID: Integer); begin FRoleID := ID; FRoleName := Name; FRoleFullName := FullName; end; function TRole.Update: Boolean; var sqlUpdRole: TIBSQL; sql: string; begin Result := false; sqlUpdRole := TIBSQL.Create(nil); sqlUpdRole.Database := FConnection; sqlUpdRole.Transaction := FInputTransaction; sql := 'update roles set ' + 'name = ''' + FRoleName + ''', ' + 'full_name = ''' + FRoleFullName + ''' ' + 'where id_role = ' + IntToStr(FRoleID); sqlUpdRole.SQL.Text := sql; StartInputTransaction; try sqlUpdRole.ExecQuery; CommitInputTransaction; except on Exception do begin RollbackInputTransaction; Exit; end; end; sqlUpdRole.Free; Result := true; end; end.
object FormOptions: TFormOptions Left = 225 Top = 263 BorderStyle = bsDialog Caption = 'FormOptions' ClientHeight = 116 ClientWidth = 405 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poOwnerFormCenter PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = 0 Top = 0 Width = 405 Height = 81 Align = alTop Shape = bsFrame end object YesBtn: TcxButton Left = 208 Top = 88 Width = 91 Height = 22 Action = YesAction ParentShowHint = False ShowHint = True TabOrder = 0 LookAndFeel.Kind = lfFlat end object CancelBtn: TcxButton Left = 304 Top = 88 Width = 89 Height = 22 Action = CancelAction ParentShowHint = False ShowHint = True TabOrder = 1 LookAndFeel.Kind = lfFlat end object LabelDateForm: TcxLabel Left = 24 Top = 34 Width = 169 Height = 17 AutoSize = False ParentFont = False Properties.Alignment.Horz = taRightJustify Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clNavy Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 2 Caption = #1044#1072#1090#1072' '#1092#1086#1088#1084#1091#1074#1072#1085#1085#1103':' end object DateEdit: TcxDateEdit Left = 200 Top = 32 Width = 122 Height = 21 ParentFont = False Properties.Alignment.Horz = taRightJustify Properties.DateButtons = [btnToday] Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clGreen Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 3 end object ActionList: TActionList Left = 32 Top = 80 object YesAction: TAction Caption = 'YesAction' ShortCut = 16464 OnExecute = YesActionExecute end object CancelAction: TAction Caption = 'CancelAction' ShortCut = 27 OnExecute = CancelActionExecute end end end
unit xxmSession; interface uses xxm, Classes, DataLank; const PublicURL='http://yoy.be/home/feeder/'; type TXxmSession=class(TObject) private FID,FKey:WideString; public Name:string; UserID,DefaultBatchSize:integer; TimeBias:TDateTime; constructor Create(const ID: WideString; Context: IXxmContext); //CSRF protection by posting session cookie value function FormProtect:WideString; procedure CheckProtect(Context: IXxmContext); property ID:WideString read FID; property Key:WideString read FKey; class function Connection: TDataConnection; end; procedure SetSession(Context: IXxmContext); procedure AbandonSession; procedure AbandonConnection; procedure AuthSession(const Key,Login,Name,Email:WideString); threadvar Session: TXxmSession; implementation uses SysUtils, Windows, sha3, base64, fCommon; var SessionStore:TStringList; procedure SetSession(Context: IXxmContext); var i:integer; sid:WideString; begin if SessionStore=nil then begin SessionStore:=TStringList.Create; SessionStore.Sorted:=true; SessionStore.CaseSensitive:=true; //SessionStore.Duplicates:=dupError; end; sid:=Context.SessionID+ '|'+Context.ContextString(csUserAgent);//TODO: hash //TODO: more ways to prevent session hijacking? i:=SessionStore.IndexOf(sid); //TODO: session expiry!!! if (i<>-1) then Session:=SessionStore.Objects[i] as TXxmSession else begin //as a security measure, disallow new sessions on a first POST request if Context.ContextString(csVerb)='POST' then raise Exception.Create('Access denied.'); Session:=TXxmSession.Create(sid,Context); SessionStore.AddObject(sid,Session); end; end; //call AbandonSession to release session data (e.g. logoff) procedure AbandonSession; begin SessionStore.Delete(SessionStore.IndexOf(Session.ID)); FreeAndNil(Session); end; procedure AuthSession(const Key,Login,Name,Email:WideString); var i,tz:integer; db:TDataConnection; qr:TQueryResult; s:TXxmSession; n1,n2:string; { fn:string; f:TFileStream; fd:AnsiString; fl:integer; } begin if SessionStore=nil then raise Exception.Create('No sessions to authenticate'); i:=0; while (i<SessionStore.Count) and ((SessionStore.Objects[i] as TXxmSession).Key<>Key) do inc(i); if i<SessionStore.Count then begin s:=SessionStore.Objects[i] as TXxmSession; db:=TXxmSession.Connection; qr:=TQueryResult.Create(db,'select * from "User" where login=$1',[Login]); try if qr.EOF then begin FreeAndNil(qr); s.UserID:=db.Insert('User', ['login',Login ,'name',Name ,'email',Email ,'created',double(UtcNow) ],'id'); { //welcome message SetLength(fn,MAX_PATH); SetLength(fn,GetModuleFileName(HInstance,PChar(fn),MAX_PATH)); fn:=ExtractFilePath(fn)+'welcome.html'; if FileExists(fn) then begin //TODO: support UTF-8? f:=TFileStream.Create(fn,fmOpenRead or fmShareDenyWrite); try fl:=f.Size; SetLength(fd,fl); f.Read(fd[1],fl); finally f.Free; end; db.Insert('UserPost', ['user_id',s.UserID ,'post_id',db.Insert('Post', ['feed_id',0 ,'guid','welcome:'+IntToStr(s.UserID) ,'title','Welcome! (click here)' ,'content',fd ,'url',PublicURL+'welcome.html' ,'pubdate',double(UtcNow) ,'created',double(UtcNow) ],'id') //,'subscription_id',??? ],'id'); end; } end else begin s.UserID:=qr.GetInt('id'); tz:=qr.GetInt('timezone'); n1:=qr.GetStr('name'); n2:=qr.GetStr('email'); FreeAndNil(qr); if n1<>Name then begin db.Execute('update "User" set name=$1 where id=$2',[Name,s.UserID]); s.Name:=Name; end; if n2<>Email then begin db.Execute('update "User" set email=$1 where id=$2',[Email,s.UserID]); //?:=Email; end; //TODO: central LoadUser(qr) s.TimeBias:=(tz div 100)/24.0+(tz mod 100)/1440.0; end; finally qr.Free; end; end else raise Exception.Create('No session with that key "'+Key+'", please retry.'); end; { TxxmSession } constructor TXxmSession.Create(const ID: WideString; Context: IXxmContext); var qr:TQueryResult; s:string; tz,LogonID:integer; begin inherited Create; FID:=ID; FKey:=string(base64encode(SHA3_224(UTF8Encode(Format('[feeder]%d:%d:%d:%d:%d[%s]', [GetTickCount ,GetCurrentThreadID ,GetCurrentProcessID ,integer(pointer(Self)) ,integer(pointer(Context)) ,ID ]))))); //TODO: initiate expiry //default values Name:=''; UserID:=0; TimeBias:=0.0; DefaultBatchSize:=100; LogonID:=0; s:=Context.Cookie['feederAutoLogon']; if s<>'' then begin Connection.BeginTrans; try //TODO: more checks? hash user-agent? qr:=TQueryResult.Create(Connection,'select U.*, L.id as LogonID from "UserLogon" L inner join "User" U on U.id=L.user_id where L.key=$1',[s]); try if qr.Read then begin UserID:=qr.GetInt('id'); Name:=qr.GetStr('name'); //:=qr.GetStr('email');? tz:=qr.GetInt('timezone'); TimeBias:=(tz div 100)/24.0+(tz mod 100)/1440.0; if not qr.IsNull('batchsize') then DefaultBatchSize:=qr.GetInt('batchsize'); LogonID:=qr.GetInt('LogonID'); end; finally qr.Free; end; if UserID<>0 then begin Connection.Execute('update "UserLogon" set last=$1,address=$2,useragent=$3 where id=$4', [double(UtcNow) ,Context.ContextString(csRemoteAddress) ,Context.ContextString(csUserAgent) ,LogonID]); end; Connection.CommitTrans; except Connection.RollbackTrans; raise; end; end; end; function TXxmSession.FormProtect:WideString; begin Result:='<input type="hidden" name="XxmSessionID" value="'+HTMLEncode(FID)+'" />'; end; procedure TXxmSession.CheckProtect(Context: IXxmContext); var p:IXxmParameter; pp:IXxmParameterPost; begin if Context.ContextString(csVerb)='POST' then begin p:=Context.Parameter['XxmSessionID']; if not((p.QueryInterface(IxxmParameterPost,pp)=S_OK) and (p.Value=FID)) then raise Exception.Create('Invalid POST source detected.'); end else raise Exception.Create('xxmSession.CheckProtect only works on POST requests.'); end; threadvar WorkerThreadConnection: TDataConnection; class function TXxmSession.Connection: TDataConnection; var s:string; sl:TStringList; begin if WorkerThreadConnection=nil then begin SetLength(s,MAX_PATH); SetLength(s,GetModuleFileName(HInstance,PChar(s),MAX_PATH)); sl:=TStringList.Create; try sl.LoadFromFile(ExtractFilePath(s)+'..\feeder.ini'); WorkerThreadConnection:=TDataConnection.Create(sl.Text); finally sl.Free; end; end; Result:=WorkerThreadConnection; end; procedure AbandonConnection; begin try FreeAndNil(WorkerThreadConnection); except //log? WorkerThreadConnection:=nil; end; end; initialization SessionStore:=nil;//see SetSession finalization FreeAndNil(SessionStore); end.
unit adot.Collections.Sets; interface { TSetClass<T> TSet<T> } uses adot.Types, adot.Collections.Types, System.Generics.Collections, System.Generics.Defaults, System.StrUtils, System.SysUtils; type TSetOp = (soUnion, soIntersection, soDifference, soSymmetricDifference); { Generic class for unordered set } TSetClass<T> = class(TEnumerableExt<T>) public type { TObjectDictionary (Delphi 10.2.1) doesn't allow to change Ownership for existing objects, we can provide Ownership in constructor only. We implement own version of ObjectDictionary to fix it. } TSetObjectDictionary<TSetDictKey,TSetDictValue> = class(TDictionary<TSetDictKey,TSetDictValue>) protected OwnsKeys: boolean; procedure KeyNotify(const Key: TSetDictKey; Action: TCollectionNotification); override; end; protected var FSet: TSetObjectDictionary<T, TEmptyRec>; FComparerCopy: IEqualityComparer<T>; { FSet.Comparer is hidden in private section, so we keep copy } function GetCount: integer; function DoGetEnumerator: TEnumerator<T>; override; function GetComparer: IEqualityComparer<T>; procedure SetOwnsValues(AOwnsValues: boolean); function GetOwnsValues: boolean; public constructor Create(ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); overload; constructor Create(const AValues: TArray<T>; AComparer: IEqualityComparer<T> = nil); overload; constructor Create(const AValues: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil); overload; constructor Create(const AOperands: TArray<TSetClass<T>>; ASetOp: TSetOp; AComparer: IEqualityComparer<T> = nil); overload; destructor Destroy; override; procedure Add(const AValue: T); overload; procedure Add(const ASet: array of T); overload; procedure Add(const AValues: TEnumerable<T>); overload; procedure IncludeLogicalAnd(const A,B: TSetClass<T>); procedure IncludeLogicalOr(const A,B: TSetClass<T>); procedure IncludeLogicalXor(const A,B: TSetClass<T>); procedure Include(const AValue: T); overload; procedure Include(const ASet: array of T); overload; procedure Include(const AValues: TEnumerable<T>); overload; procedure Remove(const AValue: T); overload; procedure Remove(const ASet: array of T); overload; procedure Remove(const AValues: TEnumerable<T>); overload; function Contains(const AValue: T): boolean; overload; function Contains(const ASet: array of T): boolean; overload; function Contains(const AValues: TEnumerable<T>): boolean; overload; procedure Clear; function Empty: Boolean; function ToArray: TArray<T>; override; property Count: integer read GetCount; property Comparer: IEqualityComparer<T> read GetComparer; property OwnsValues: boolean read GetOwnsValues write SetOwnsValues; end; { Example: var a,b,c: TSet<string>; s: string; begin a := ['Mandag', 'Tirsdag', 'Fredag']; b := ['Fredag', 'LÝrdag']; c := a and b; // ['Fredag'] c := a or b; // ['Mandag', 'Tirsdag', 'Fredag', 'LÝrdag'] c := a + b - ['Mandag', 'Tirsdag']; // ['Fredag', 'LÝrdag'] if a xor b = TSet<string>.Create(['Mandag', 'Tirsdag', 'LÝrdag']) then [...] if (b in a) or ('Fredag' in a) then [...] if a>b then // "a" contains all items from "b" and at least one item extra [...] if a>=b then // "a" contains all items from "b" and maybe some items extra [...] for s in c do // enumerate all values from the set [...] c := ['En']; c.Add(['To', 'Tre']); c.Remove('To'); // ['En', 'Tre'] Assert( ('En' in c) and ('en' in c) ); // default comparer for "string" type is case insensitive c := TSet<string>.Create(['En','To'], 0,TStringComparer.Ordinal); Assert( ('En' in c) and NOT ('en' in c) ); // now we used case sensitive comparer end; } { Record type for set. Support operators for all set operations and copy-on-write. } TSet<T> = record private FSetInt: IInterfacedObject<TSetClass<T>>; procedure CreateSet(ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); function GetReadonly: TSetClass<T>; function GetReadWrite: TSetClass<T>; function GetOwnsValues: boolean; procedure SetOwnsValues(AOwnsValues: boolean); function GetCount: integer; function GetEmpty: Boolean; function GetCollection: TEnumerable<T>; property RO: TSetClass<T> read GetReadonly; property RW: TSetClass<T> read GetReadWrite; public procedure Init; overload; procedure Init(ACapacity: integer; AComparer: IEqualityComparer<T> = nil); overload; procedure Init(const V: array of T; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); overload; procedure Init(const V: TEnumerable<T>; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); overload; procedure Init(const V: array of TEnumerable<T>; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); overload; procedure Init(V: TSet<T>; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); overload; class function Create: TSet<T>; overload; static; class function Create(ACapacity: integer; AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static; class function Create(const V: array of T; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static; class function Create(const V: TEnumerable<T>; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static; class function Create(const V: array of TEnumerable<T>; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static; class function Create(V: TSet<T>; ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil): TSet<T>; overload; static; function GetEnumerator: TEnumerator<T>; procedure Add(const V: T); overload; procedure Add(const V: array of T); overload; procedure Add(const V: TEnumerable<T>); overload; procedure Add(const V: array of TEnumerable<T>); overload; procedure Add(V: TSet<T>); overload; procedure Remove(const V: T); overload; procedure Remove(const V: array of T); overload; procedure Remove(const V: TEnumerable<T>); overload; procedure Remove(const V: array of TEnumerable<T>); overload; procedure Remove(V: TSet<T>); overload; { It is prefered to use syntax "Item in SomSet" over "SomeSet.Contains(Item)", but in rare situations compiler can be confused and then "Contains" method is the only way to go } function Contains(const a: T) : Boolean; overload; function Contains(const a: TEnumerable<T>) : Boolean; overload; function Contains(a: TSet<T>) : Boolean; overload; function Copy: TSet<T>; function ToArray: TArray<T>; function ToString: string; procedure Clear; class operator In(const a: T; b: TSet<T>) : Boolean; class operator In(const a: TEnumerable<T>; b: TSet<T>) : Boolean; class operator In(a: TSet<T>; b: TSet<T>) : Boolean; class operator Implicit(const a : T) : TSet<T>; class operator Implicit(const a : TEnumerable<T>) : TSet<T>; class operator Implicit(const a : array of T) : TSet<T>; class operator Implicit(const a : TArray<T>) : TSet<T>; class operator Explicit(const a : T) : TSet<T>; class operator Explicit(const a : TEnumerable<T>) : TSet<T>; class operator Explicit(const a : array of T) : TSet<T>; class operator Explicit(const a : TArray<T>) : TSet<T>; class operator Add(a: TSet<T>; b: TSet<T>): TSet<T>; class operator Add(a: TSet<T>; const b: T): TSet<T>; class operator Add(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; class operator Add(a: TSet<T>; const b: array of T): TSet<T>; class operator Add(const a: T; b: TSet<T>): TSet<T>; class operator Add(const a: array of T; b: TSet<T>): TSet<T>; class operator Add(const a: TEnumerable<T>; b: TSet<T>): TSet<T>; class operator Subtract(a: TSet<T>; const b: T): TSet<T>; class operator Subtract(a: TSet<T>; b: TSet<T>): TSet<T>; class operator Subtract(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; class operator Subtract(a: TSet<T>; const b: array of T): TSet<T>; class operator Subtract(const a: T; b: TSet<T>): TSet<T>; class operator Subtract(const a: array of T; b: TSet<T>): TSet<T>; class operator Subtract(const a: TEnumerable<T>; b: TSet<T>): TSet<T>; class operator Equal(a: TSet<T>; b: TSet<T>) : Boolean; class operator Equal(a: TSet<T>; const b: TEnumerable<T>) : Boolean; class operator NotEqual(a: TSet<T>; b: TSet<T>): Boolean; class operator NotEqual(a: TSet<T>; const b: TEnumerable<T>) : Boolean; class operator GreaterThanOrEqual(a: TSet<T>; b: TSet<T>): Boolean; class operator GreaterThanOrEqual(a: TSet<T>; const b: TEnumerable<T>): Boolean; class operator GreaterThan(a: TSet<T>; b: TSet<T>): Boolean; class operator GreaterThan(a: TSet<T>; const b: TEnumerable<T>): Boolean; class operator LessThan(a: TSet<T>; b: TSet<T>): Boolean; class operator LessThan(a: TSet<T>; const b: TEnumerable<T>): Boolean; class operator LessThanOrEqual(a: TSet<T>; b: TSet<T>): Boolean; class operator LessThanOrEqual(a: TSet<T>; const b: TEnumerable<T>): Boolean; class operator LogicalAnd(a: TSet<T>; b: TSet<T>): TSet<T>; class operator LogicalAnd(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; class operator LogicalOr(a: TSet<T>; b: TSet<T>): TSet<T>; class operator LogicalOr(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; class operator LogicalXor(a: TSet<T>; b: TSet<T>): TSet<T>; class operator LogicalXor(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; property OwnsValues: boolean read GetOwnsValues write SetOwnsValues; property Empty: Boolean read GetEmpty; property Count: integer read GetCount; property Collection: TEnumerable<T> read GetCollection; end; implementation uses adot.Tools, adot.Strings, adot.Tools.RTTI, adot.Collections; { TSetClass<T>.TSetObjectDictionary<TSetDictKey, TSetDictValue> } procedure TSetClass<T>.TSetObjectDictionary<TSetDictKey, TSetDictValue>.KeyNotify( const Key: TSetDictKey; Action: TCollectionNotification); begin inherited; if OwnsKeys and (Action = TCollectionNotification.cnRemoved) then PObject(@Key)^.DisposeOf; end; { TSetClass<T> } constructor TSetClass<T>.Create(ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); begin inherited Create; FSet := TSetObjectDictionary<T, TEmptyRec>.Create(ACapacity, AComparer); FComparerCopy := AComparer; end; constructor TSetClass<T>.Create(const AValues: TArray<T>; AComparer: IEqualityComparer<T> = nil); begin Create(Length(AValues), AComparer); Add(AValues); end; constructor TSetClass<T>.Create(const AValues: TEnumerable<T>; AComparer: IEqualityComparer<T> = nil); begin Create(0, AComparer); Add(AValues); end; constructor TSetClass<T>.Create(const AOperands: TArray<TSetClass<T>>; ASetOp: TSetOp; AComparer: IEqualityComparer<T>); var FoundInAll: Boolean; Value: T; I,J: Integer; Found: Boolean; begin Create(0, AComparer); case ASetOp of soUnion: for I := 0 to High(AOperands) do Include(AOperands[I]); soIntersection: begin if Length(AOperands)=0 then Exit; J := 0; for I := 1 to High(AOperands) do if AOperands[I].Count<AOperands[J].Count then J := I; for Value in AOperands[J] do begin FoundInAll := True; for I := 0 to High(AOperands) do if (I<>J) and not AOperands[I].Contains(Value) then begin FoundInAll := False; Break; end; if FoundInAll then Add(Value); end; end; soDifference: begin if Length(AOperands)>0 then Add(AOperands[0]); for I := 1 to High(AOperands) do Remove(AOperands[I]); end; soSymmetricDifference: for i := 0 to High(AOperands) do for Value in AOperands[i] do begin Found := False; for j := 0 to High(AOperands) do if (i<>j) and AOperands[j].Contains(Value) then begin Found := True; Break; end; if not Found then Add(Value); end; end; end; destructor TSetClass<T>.Destroy; begin Sys.FreeAndNil(FSet); inherited; end; function TSetClass<T>.DoGetEnumerator: TEnumerator<T>; begin result := FSet.Keys.GetEnumerator; end; function TSetClass<T>.Empty: Boolean; begin result := FSet.Count=0; end; function TSetClass<T>.ToArray: TArray<T>; var i: Integer; Value: T; begin SetLength(Result, Count); i := 0; for Value in FSet.Keys do begin Result[i] := Value; inc(i); end; Assert(Count=i); end; function TSetClass<T>.GetComparer: IEqualityComparer<T>; begin result := FComparerCopy; end; function TSetClass<T>.GetCount: integer; begin result := FSet.Count; end; procedure TSetClass<T>.Remove(const ASet: array of T); var i: Integer; begin for i := Low(ASet) to High(ASet) do Remove(ASet[i]); end; procedure TSetClass<T>.Remove(const AValues: TEnumerable<T>); var Item: T; begin for Item in AValues do Remove(Item); end; function TSetClass<T>.GetOwnsValues: boolean; begin result := FSet.OwnsKeys; end; procedure TSetClass<T>.SetOwnsValues(AOwnsValues: boolean); begin if AOwnsValues and not TRttiUtils.IsInstance<T> then raise Exception.Create('Generic type is not a class.'); FSet.OwnsKeys := AOwnsValues; end; procedure TSetClass<T>.Add(const AValue: T); var R: TEmptyRec; begin FSet.Add(AValue, R); end; procedure TSetClass<T>.Add(const ASet: array of T); var i: Integer; begin for i := Low(ASet) to High(ASet) do Add(ASet[i]); end; procedure TSetClass<T>.Add(const AValues: TEnumerable<T>); var Item: T; begin for Item in AValues do Add(Item); end; procedure TSetClass<T>.IncludeLogicalAnd(const A, B: TSetClass<T>); var Value: T; begin if A.Count<=B.Count then begin for Value in A do if B.Contains(Value) then Include(Value); end else begin for Value in B do if A.Contains(Value) then Include(Value); end end; procedure TSetClass<T>.IncludeLogicalOr(const A, B: TSetClass<T>); var Value: T; begin for Value in A do Include(Value); for Value in B do Include(Value); end; procedure TSetClass<T>.IncludeLogicalXor(const A, B: TSetClass<T>); var Value: T; begin for Value in A do if not B.Contains(Value) then Include(Value); for Value in B do if not A.Contains(Value) then Include(Value); end; procedure TSetClass<T>.Include(const AValue: T); var R: TEmptyRec; begin FSet.AddOrSetValue(AValue, R); end; procedure TSetClass<T>.Include(const ASet: array of T); var i: Integer; begin for i := Low(ASet) to High(ASet) do Include(ASet[i]); end; procedure TSetClass<T>.Include(const AValues: TEnumerable<T>); var Item: T; begin for Item in AValues do Include(Item); end; procedure TSetClass<T>.Clear; begin FSet.Clear; end; function TSetClass<T>.Contains(const AValue: T): boolean; begin result := FSet.ContainsKey(AValue); end; function TSetClass<T>.Contains(const ASet: array of T): boolean; var i: Integer; begin for i := Low(ASet) to High(ASet) do if not Contains(ASet[i]) then Exit(False); result := True; end; function TSetClass<T>.Contains(const AValues: TEnumerable<T>): boolean; var Item: T; begin for Item in AValues do if not Contains(Item) then Exit(False); result := True; end; procedure TSetClass<T>.Remove(const AValue: T); begin FSet.Remove(AValue); end; { TSet<T> } procedure TSet<T>.Init; begin Self := Default(TSet<T>); end; procedure TSet<T>.Init(ACapacity: integer; AComparer: IEqualityComparer<T>); begin Self := Default(TSet<T>); CreateSet(ACapacity, AComparer); end; procedure TSet<T>.Init(const V: array of T; ACapacity: integer; AComparer: IEqualityComparer<T>); begin Self := Default(TSet<T>); CreateSet(ACapacity, AComparer); Add(v); end; procedure TSet<T>.Init(const V: TEnumerable<T>; ACapacity: integer; AComparer: IEqualityComparer<T>); begin Self := Default(TSet<T>); CreateSet(ACapacity, AComparer); Add(v); end; procedure TSet<T>.Init(const V: array of TEnumerable<T>; ACapacity: integer; AComparer: IEqualityComparer<T>); begin Self := Default(TSet<T>); CreateSet(ACapacity, AComparer); Add(v); end; procedure TSet<T>.Init(V: TSet<T>; ACapacity: integer; AComparer: IEqualityComparer<T>); begin Self := Default(TSet<T>); CreateSet(ACapacity, AComparer); Add(v); end; class function TSet<T>.Create(const V: array of T; ACapacity: integer; AComparer: IEqualityComparer<T>): TSet<T>; begin result.Init(V, ACapacity, AComparer); end; class function TSet<T>.Create(ACapacity: integer; AComparer: IEqualityComparer<T>): TSet<T>; begin result.Init(ACapacity, AComparer); end; class function TSet<T>.Create: TSet<T>; begin result.Init; end; class function TSet<T>.Create(V: TSet<T>; ACapacity: integer; AComparer: IEqualityComparer<T>): TSet<T>; begin result.Init(V, ACapacity, AComparer); end; class function TSet<T>.Create(const V: array of TEnumerable<T>; ACapacity: integer; AComparer: IEqualityComparer<T>): TSet<T>; begin result.Init(V, ACapacity, AComparer); end; class function TSet<T>.Create(const V: TEnumerable<T>; ACapacity: integer; AComparer: IEqualityComparer<T>): TSet<T>; begin result.Init(V, ACapacity, AComparer); end; procedure TSet<T>.Add(const V: T); begin RW.Include(V); end; procedure TSet<T>.Add(const V: TEnumerable<T>); var D: TSetClass<T>; Value: T; begin D := RW; for Value in V do D.Include(Value); end; procedure TSet<T>.Add(const V: array of T); var D: TSetClass<T>; Value: T; begin D := RW; for Value in V do D.Include(Value); end; procedure TSet<T>.Add(V: TSet<T>); var S,D: TSetClass<T>; Value: T; begin D := RW; S := V.RO; for Value in S do D.Include(Value); end; procedure TSet<T>.Add(const V: array of TEnumerable<T>); var D: TSetClass<T>; Enum: TEnumerable<T>; Value: T; begin D := RW; for Enum in V do for Value in Enum do D.Include(Value); end; function TSet<T>.GetEmpty: Boolean; begin result := Count = 0; end; function TSet<T>.GetEnumerator: TEnumerator<T>; begin result := RO.GetEnumerator; end; function TSet<T>.GetReadonly:TSetClass<T>; begin if FSetInt=nil then CreateSet; result := FSetInt.Data; end; function TSet<T>.GetReadWrite: TSetClass<T>; var SrcSetInt: IInterfacedObject<TSetClass<T>>; begin if FSetInt=nil then CreateSet else if FSetInt.GetRefCount<>1 then begin { Copy on write } SrcSetInt := FSetInt; CreateSet(SrcSetInt.Data.Count, SrcSetInt.Data.Comparer); FSetInt.Data.Include(SrcSetInt.Data); FSetInt.Data.OwnsValues := SrcSetInt.Data.OwnsValues; end; result := FSetInt.Data; end; procedure TSet<T>.CreateSet(ACapacity: integer = 0; AComparer: IEqualityComparer<T> = nil); var C: IEqualityComparer<T>; begin if AComparer=nil then C := TComparerUtils.DefaultEqualityComparer<T> else C := AComparer; FSetInt := TInterfacedObject<TSetClass<T>>.Create( TSetClass<T>.Create(ACapacity, C) ); end; function TSet<T>.GetOwnsValues: boolean; begin result := RO.OwnsValues; end; procedure TSet<T>.SetOwnsValues(AOwnsValues: boolean); begin RW.OwnsValues := AOwnsValues; end; function TSet<T>.Contains(const a: T) : Boolean; begin result := RO.Contains(a); end; function TSet<T>.Contains(const a: TEnumerable<T>) : Boolean; begin result := RO.Contains(a); end; function TSet<T>.Contains(a: TSet<T>) : Boolean; begin result := RO.Contains(a.RO); end; class operator TSet<T>.In(const a: TEnumerable<T>; b: TSet<T>): Boolean; begin result := b.RO.Contains(a); end; class operator TSet<T>.In(const a: T; b: TSet<T>): Boolean; begin result := b.RO.Contains(a); end; class operator TSet<T>.In(a, b: TSet<T>): Boolean; begin result := b.RO.Contains(a.RO); end; class operator TSet<T>.Implicit(const a: T): TSet<T>; begin result.FSetInt := nil; result.Add(a); end; class operator TSet<T>.Implicit(const a: TEnumerable<T>): TSet<T>; begin result.FSetInt := nil; if a<>nil then result.Add(a); end; class operator TSet<T>.Implicit(const a : array of T) : TSet<T>; begin result.FSetInt := nil; result.Add(a); end; class operator TSet<T>.Implicit(const a : TArray<T>) : TSet<T>; begin result.FSetInt := nil; result.Add(a); end; class operator TSet<T>.Explicit(const a : T) : TSet<T>; begin result.FSetInt := nil; result.Add(a); end; class operator TSet<T>.Explicit(const a : TEnumerable<T>) : TSet<T>; begin result.FSetInt := nil; if a<>nil then result.Add(a); end; class operator TSet<T>.Explicit(const a : array of T) : TSet<T>; begin result.FSetInt := nil; result.Add(a); end; class operator TSet<T>.Explicit(const a : TArray<T>) : TSet<T>; begin result.FSetInt := nil; result.Add(a); end; class operator TSet<T>.Add(a, b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Include(b.RO); end; class operator TSet<T>.Add(a: TSet<T>; const b: T): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Include(b); end; class operator TSet<T>.Add(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Include(b); end; class operator TSet<T>.Add(a: TSet<T>; const b: array of T): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Include(b); end; class operator TSet<T>.Add(const a: T; b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a); D.Include(b.RO); end; class operator TSet<T>.Add(const a: array of T; b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a); D.Include(b.RO); end; class operator TSet<T>.Add(const a: TEnumerable<T>; b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a); D.Include(b.RO); end; procedure TSet<T>.Clear; begin Self := Default(TSet<T>); end; function TSet<T>.GetCollection: TEnumerable<T>; begin result := RO; end; function TSet<T>.GetCount: integer; begin result := RO.Count; end; function TSet<T>.Copy: TSet<T>; begin if FSetInt=nil then result.FSetInt := nil else begin result.Init(Count, FSetInt.Data.Comparer); result.Add(Self); end; end; procedure TSet<T>.Remove(const V: TEnumerable<T>); begin RW.Remove(V); end; procedure TSet<T>.Remove(const V: array of T); begin RW.Remove(V); end; procedure TSet<T>.Remove(const V: T); begin RW.Remove(V); end; procedure TSet<T>.Remove(V: TSet<T>); begin RW.Remove(V.RO); end; procedure TSet<T>.Remove(const V: array of TEnumerable<T>); var i: integer; D: TSetClass<T>; begin D := RW; for i := 0 to High(v) do D.Remove(V[i]); end; class operator TSet<T>.Equal(a, b: TSet<T>): Boolean; var S,D: TSetClass<T>; begin S := a.RO; D := b.RO; result := (S.Count=D.Count) and D.Contains(S); end; class operator TSet<T>.Equal(a: TSet<T>; const b: TEnumerable<T>): Boolean; var Value: T; D: TSetClass<T>; N: Integer; begin D := a.RO; N := 0; for Value in b do if D.Contains(Value) then inc(N) else exit(False); result := N=D.Count; end; class operator TSet<T>.NotEqual(a, b: TSet<T>): Boolean; begin result := not (a=b); end; class operator TSet<T>.NotEqual(a: TSet<T>; const b: TEnumerable<T>): Boolean; begin result := not (a=b); end; class operator TSet<T>.Subtract(a: TSet<T>; const b: T): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Remove(b); end; class operator TSet<T>.Subtract(a, b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Remove(b.RO); end; class operator TSet<T>.Subtract(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Remove(b); end; class operator TSet<T>.Subtract(a: TSet<T>; const b: array of T): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Remove(b); end; class operator TSet<T>.Subtract(const a: T; b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a); D.Remove(b.RO); end; class operator TSet<T>.Subtract(const a: array of T; b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a); D.Remove(b.RO); end; class operator TSet<T>.Subtract(const a: TEnumerable<T>; b: TSet<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a); D.Remove(b.RO); end; function TSet<T>.ToArray: TArray<T>; begin result := RO.ToArray; end; function TSet<T>.ToString: string; begin result := RO.ToString; end; class operator TSet<T>.GreaterThanOrEqual(a, b: TSet<T>): Boolean; begin result := b in a; end; class operator TSet<T>.GreaterThanOrEqual(a: TSet<T>; const b: TEnumerable<T>): Boolean; begin result := b in a; end; class operator TSet<T>.GreaterThan(a, b: TSet<T>): Boolean; begin result := (a.Count>b.Count) and (b in a); end; class operator TSet<T>.GreaterThan(a: TSet<T>; const b: TEnumerable<T>): Boolean; begin result := (a<>b) and (b in a); end; class operator TSet<T>.LessThan(a, b: TSet<T>): Boolean; begin result := (a.Count<b.Count) and (a in b); end; class operator TSet<T>.LessThan(a: TSet<T>; const b: TEnumerable<T>): Boolean; begin result := (a<>b) and (a in b); end; class operator TSet<T>.LessThanOrEqual(a, b: TSet<T>): Boolean; begin result := a in b; end; class operator TSet<T>.LessThanOrEqual(a: TSet<T>; const b: TEnumerable<T>): Boolean; begin result := a in b; end; class operator TSet<T>.LogicalAnd(a, b: TSet<T>): TSet<T>; begin result.FSetInt := nil; result.RW.IncludeLogicalAnd(a.RO, b.RO); end; class operator TSet<T>.LogicalAnd(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; var S,R: TSetClass<T>; Value: T; begin result.FSetInt := nil; S := a.RO; R := result.RW; for Value in b do if S.Contains(Value) then R.Include(Value); end; class operator TSet<T>.LogicalOr(a, b: TSet<T>): TSet<T>; begin result.FSetInt := nil; result.RW.IncludeLogicalOr(a.RO, b.RO); end; class operator TSet<T>.LogicalOr(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; var D: TSetClass<T>; begin result.FSetInt := nil; D := result.RW; D.Include(a.RO); D.Include(b); end; class operator TSet<T>.LogicalXor(a, b: TSet<T>): TSet<T>; begin result.FSetInt := nil; result.RW.IncludeLogicalXor(a.RO, b.RO); end; class operator TSet<T>.LogicalXor(a: TSet<T>; const b: TEnumerable<T>): TSet<T>; begin result.FSetInt := nil; result := a xor TSet<T>(b); end; end.
unit uEntityFields; interface uses Classes, SysUtils, Windows, MConnect, ADODB; type TEntityFields = class(TObject) private FADOConn : TADOConnection; FADODateSet : TADODataSet; public constructor Create(AADOConn: TADOConnection); destructor Destroy; override; property ADOConn: TADOConnection read FADOConn write FADOConn; end; implementation { TEntityFields } constructor TEntityFields.Create(AADOConn: TADOConnection); begin FADOConn := AADOConn; FADODateSet := TADODataSet.Create(nil); FADODateSet.Connection := FADOConn; inherited Create; end; destructor TEntityFields.Destroy; begin FreeAndNil(FADODateSet); inherited Destroy; end; end.
unit OverlayImage; (* Base Component for Graphing TOverlayImage based on Renate Schaaf's code Specialty: Has methods for temporary flickerless speedy overlayed drawings like zoom rectangles or even sprites. Use the usual canvas routines with the prefix Overlay, like OverlayEllipse, OverlayRectangle, etc. Exceptions: The analog of Moveto/Lineto is as a command OverlayLine. The analog of Canvas.Draw(x,y,MyGraphic) is OvelayDraw(DestRect,MyGraphic). After finished with the overlayed (possibly compound) drawing, call ShowOverlay. The next overlayed drawing will start from scratch *) interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Clipbrd; type TOverlayImage = class(TGraphicControl) private fBitmap: TBitmap; //Bitmap for the persistant Drawing fDrawWidth, fDrawHeight: Integer; fScreenBitmap: TBitmap; //Bitmap that gets blasted to screen fLockCount: Integer; fDrawing: Boolean; fTempDrawing: Boolean; fOverlayed: Boolean; fClipRect: TRect; //ClipRect for fBitmap fTempRect: TRect; //fTempRect is fClipRect translated to screen //coordinates fClipRgn: HRgn; //corresponding region fOldRgn, fNewRgn: HRgn; //regions to optimize overlaid drawing fxoff, fyoff: Integer; (* scaling data, bmp to screen, rsp. device regions have to be given in device coordinates. if the control is not located at top=left=0 in the parent, those will be offset from the control coordinates *) fOrgFontChanged, fOrgPenChanged, fOrgBrushChanged, fOrgPaint, fOnMouseLeave, fOnMouseEnter: TNotifyEvent; fOnTempPaint: TNotifyEvent; //Something that should always be added procedure fBitmapChanged(Sender: TObject); procedure fFontChanged(Sender: TObject); procedure fPenChanged(Sender: TObject); procedure fBrushChanged(Sender: TObject); function GetCanvas: TCanvas; function GetTempCanvas: TCanvas; function GetMetafileCanvas: TCanvas; function GetFont: TFont; function GetPen: TPen; function GetBrush: TBrush; function GetTempFont: TFont; function GetTempBrush: TBrush; function GetTempPen: TPen; procedure SetFont(Value: TFont); procedure SetPen(Value: TPen); procedure SetBrush(Value: TBrush); procedure SetTempFont(Value: TFont); procedure SetTempBrush(Value: TBrush); procedure SetTempPen(Value: TPen); procedure GetOffSet; procedure fTempCanvasChanging; protected fMetaFileCanvas: TMetaFileCanvas; fMetaFile: TMetaFile; procedure Paint; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CMMouseLeave(var msg: TMessage); message CM_MouseLeave; procedure CMMouseEnter(var msg: TMessage); message CM_MouseEnter; procedure WMWindowPosChanged(var msg: TMessage); message WM_WINDOWPOSCHANGED; procedure SizeChanged; virtual; procedure Loaded; override; (* Canvas for overlaid drawings like zoom rectangles, or helper shapes which aren't part of the actual drawings. Now protected, because it can't be used properly without some specific precautions *) property OverlayCanvas: TCanvas read GetTempCanvas; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Define a new rectangular clip region. The previous region is discarded.} procedure NewClipRegion(Value: TRect); { Add a rectangle to the current clip region } procedure AddClipRegion(Value: TRect); { Subtract a rectangular region from the current clip region } procedure SubtractClipRegion(Value: TRect); {Intersect the current clip region with the region given by Value} procedure IntersectClipRegion(Value: TRect); { Call when the component is inside a scrollbox to adjust to scroll. Since the usual scrollbox has no OnScroll event, there is a derived one (<See class=TScrollEventBox>) in this same unit } procedure AdjustToScroll; { Drawing surrounded by LockUpdate and UnlockUpdate is not updated to the screen immediately. Nested calls are OK, Screen will be updated on the last UnlockUpdate. This speeds up compound drawing} procedure LockUpdate; { Drawing surrounded by LockUpdate and UnlockUpdate is not updated to the screen immediately. Nested calls are OK, Screen will be updated on the last UnlockUpdate. This speeds up compound drawing} procedure UnlockUpdate; { A call to ShowOverlay puts the current drawing on the Overlaycanvas to screen. The next Overlaycanvas call, or a call of <See method=HideOverlay> clears the canvas } procedure ShowOverlay; { Clears the overlayed canvas. Call, if no overlayed drawing is needed anymore, as this speeds up normal drawing } procedure HideOverlay; { Clears the Canvas, sets background to AColor } procedure Clear(Acanvas: TCanvas; AColor: TColor); // overload; virtual; { Saves any drawing on the <See property=MetafileCanvas> to file } procedure SaveMetafile(const filename: string); { Releases memory for metafile support } procedure EraseMetafile; { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayCopyRect(dest: TRect; Canvas: TCanvas; Source: TRect); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayDraw(dest: TRect; Graphic: TGraphic); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayFillRect(const Rect: TRect); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayFrameRect(const Rect: TRect); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayLine(x1, y1, x2, y2: Integer); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayPolygon(Points: array of TPoint); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayPolyline(Points: array of TPoint); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayEllipse(x1, y1, x2, y2: Integer); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayRectangle(x1, y1, x2, y2: Integer); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayRoundRect(x1, y1, x2, y2, X3, Y3: Integer); { For speed optimized drawings on the overlayed canvas use this analogon of the TCanvas method } procedure OverlayTextOut(x, y: Integer; const s: string); { Actually the canvas of the offscreen fbitmap } property Canvas: TCanvas read GetCanvas; { In case you'd like to draw a metafile, just use this property. It will be created, if needed } property MetafileCanvas: TCanvas read GetMetafileCanvas; { The metafile generated by drawing on <See property=MetafileCanvas> } property Metafile: TMetaFile read fMetaFile; { This Bitmap which holds the current main (not overlayed) drawing } property Bitmap: TBitmap read fBitmap; property OverlayBrush: TBrush read GetTempBrush write SetTempBrush; property OverlayPen: TPen read GetTempPen write SetTempPen; property OverlayFont: TFont read GetTempFont write SetTempFont; published property Align; { Pen, brush and font properties for the main drawing. To set the corresponding for the overlayed canvas use OverlayPen. For the Metafile canvas use MetafileCanvas.Pen, as usual } property Pen: TPen read GetPen write SetPen; { Pen, brush and font properties for the main drawing. To set the corresponding for the overlayed canvas use OverlayBrush. For the Metafile canvas use MetafileCanvas.Brush, as usual } property Brush: TBrush read GetBrush write SetBrush; { Pen, brush and font properties for the main drawing. To set the corresponding for the overlayed canvas use OverlayFont. For the Metafile canvas use MetafileCanvas.Font, as usual } property Font: TFont read GetFont write SetFont; { Events} property OnMouseDown; property OnMouseUp; property OnMouseMove; property OnResize; { If you want to see a persistent drawing on the overlayed canvas, use this event for the drawing commands } property OnOverlayPaint: TNotifyEvent read fOnTempPaint write fOnTempPaint; { Event which fires if the mouse leaves the control. Note: There must be space between the control and the boundary of the parent for this to work } property OnMouseLeave: TNotifyEvent read fOnMouseLeave write fOnMouseLeave; { Event which fires if the mouse enters the control } property OnMouseEnter: TNotifyEvent read fOnMouseEnter write fOnMouseEnter; end; (* Had to create an extra scrollbox, which fires scrollevents, because when the TOverlayImage is scrolled, the offsets for the device regions have to be recomputed. See procedure TOverlayImage.AdjustToScroll *) TScrollEventBox = class(TScrollbox) private fOnScroll: TNotifyEvent; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; published { Event fires on vertical or horizontal scroll } property OnScroll: TNotifyEvent read fOnScroll write fOnScroll; end; procedure Register; //============================================================== implementation //============================================================== constructor TOverlayImage.Create; begin inherited; if not (csDesigning in ComponentState) then ControlStyle := ControlStyle + [csOpaque]; {avoids flicker} fDrawWidth := 0; fDrawHeight := 0; fScreenBitmap := TBitmap.Create; fBitmap := TBitmap.Create; fOrgPenChanged := fBitmap.Canvas.Pen.OnChange; fOrgFontChanged := fBitmap.Canvas.Font.OnChange; fOrgBrushChanged := fBitmap.Canvas.Brush.OnChange; fBitmap.OnChange := fBitmapChanged; fLockCount := 0; fOrgPaint := nil; fMetaFileCanvas := nil; fMetaFile := nil; fClipRgn := 0; fOldRgn := 0; fNewRgn := 0; if csDesigning in ComponentState then begin Width := 50; Height := 50; end; fClipRect := Rect(0, 0, Width, Height); fTempRect := Rect(0, 0, Width, Height); fTempDrawing := False; end; destructor TOverlayImage.Destroy; begin if fBitmap <> nil then fBitmap.Free; if fBitmap <> nil then fScreenBitmap.Free; if fMetaFileCanvas <> nil then fMetaFileCanvas.Free; if fMetaFile <> nil then fMetaFile.Free; if fClipRgn <> 0 then DeleteObject(fClipRgn); if fOldRgn <> 0 then DeleteObject(fOldRgn); if fNewRgn <> 0 then DeleteObject(fNewRgn); inherited; end; procedure TOverlayImage.Paint; begin // inherited; if (csDesigning in ComponentState) then inherited Canvas.FrameRect(Rect(0, 0, Width, Height)) else begin if not fDrawing then begin fDrawing := True; try if assigned(fOnTempPaint) then begin BitBlt(fScreenBitmap.Canvas.Handle, 0, 0, fDrawWidth, fDrawHeight, fBitmap.Canvas.Handle, 0, 0, SRCCopy); fTempDrawing := True; fOnTempPaint(self); fTempDrawing := False; BitBlt(inherited Canvas.Handle, 0, 0, fDrawWidth, fDrawHeight, fScreenBitmap.Canvas.Handle, 0, 0, SRCCopy); end else if fOverlayed then BitBlt(inherited Canvas.Handle, 0, 0, fDrawWidth, fDrawHeight, fScreenBitmap.Canvas.Handle, 0, 0, SRCCopy) else BitBlt(inherited Canvas.Handle, 0, 0, fDrawWidth, fDrawHeight, fBitmap.Canvas.Handle, 0, 0, SRCCopy); finally fDrawing := False; end; end; end; end; function TOverlayImage.GetCanvas; begin SelectClipRgn(fBitmap.Canvas.Handle, fClipRgn); Result := fBitmap.Canvas; end; function TOverlayImage.GetTempCanvas; begin SelectClipRgn(fScreenBitmap.Canvas.Handle, fNewRgn); Result := fScreenBitmap.Canvas; end; procedure TOverlayImage.fTempCanvasChanging; begin if not fTempDrawing then begin fTempDrawing := True; SelectClipRgn(fScreenBitmap.Canvas.Handle, fOldRgn); BitBlt(fScreenBitmap.Canvas.Handle, 0, 0, fDrawWidth, fDrawHeight, fBitmap.Canvas.Handle, 0, 0, SRCCopy); fOverlayed := False; end; end; procedure TOverlayImage.fBitmapChanged; begin if not fDrawing then begin if fOldRgn <> 0 then begin DeleteObject(fOldRgn); fOldRgn := 0; end; fOverlayed := False; invalidate; end else update; {On each bitmap change the picture is invalidated, unless it's just being painted already and unless LockUpdate has been called} end; procedure TOverlayImage.fFontChanged(Sender: TObject); begin fOrgFontChanged(Sender); if fMetaFileCanvas <> nil then fMetaFileCanvas.Font.assign(fBitmap.Canvas.Font); end; procedure TOverlayImage.fPenChanged(Sender: TObject); begin fOrgPenChanged(Sender); if fMetaFileCanvas <> nil then fMetaFileCanvas.Pen.assign(fBitmap.Canvas.Pen); end; procedure TOverlayImage.fBrushChanged(Sender: TObject); begin fOrgBrushChanged(Sender); if fMetaFileCanvas <> nil then fMetaFileCanvas.Brush.assign(fBitmap.Canvas.Brush); end; function TOverlayImage.GetMetafileCanvas: TCanvas; begin if fMetaFileCanvas = nil then begin fMetaFile := TMetaFile.Create; fMetaFile.enhanced := True; fMetaFile.Height := fBitmap.Height; fMetaFile.Width := fBitmap.Width; fMetaFileCanvas := TMetaFileCanvas.Create(fMetaFile, 0); with fBitmap.Canvas do begin Font.OnChange := fFontChanged; Brush.OnChange := fBrushChanged; Pen.OnChange := fPenChanged; end; fFontChanged(nil); fPenChanged(nil); fBrushChanged(nil); end; SelectClipRgn(fMetaFileCanvas.Handle, fClipRgn); Result := fMetaFileCanvas; end; procedure TOverlayImage.SaveMetafile(const filename: string); begin if fMetaFileCanvas <> nil then begin fMetaFileCanvas.Free; fMetaFile.SaveToFile(filename); fMetaFileCanvas := TMetaFileCanvas.Create(fMetaFile, 0); fMetaFileCanvas.draw(0, 0, Metafile); end; end; function TOverlayImage.GetFont: TFont; begin Result := fBitmap.Canvas.Font; end; function TOverlayImage.GetPen: TPen; begin Result := fBitmap.Canvas.Pen; end; function TOverlayImage.GetBrush: TBrush; begin Result := fBitmap.Canvas.Brush; end; procedure TOverlayImage.SetFont(Value: TFont); begin fBitmap.Canvas.Font.assign(Value); end; procedure TOverlayImage.SetPen(Value: TPen); begin fBitmap.Canvas.Pen.assign(Value); end; procedure TOverlayImage.SetBrush(Value: TBrush); begin fBitmap.Canvas.Brush.assign(Value); end; procedure TOverlayImage.NewClipRegion(Value: TRect); begin if fClipRgn <> 0 then DeleteObject(fClipRgn); fClipRgn := 0; fClipRgn := CreateRectRgnIndirect(Value); end; procedure TOverlayImage.AddClipRegion(Value: TRect); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(Value); CombineRgn(fClipRgn, fClipRgn, rgn, RGN_OR); DeleteObject(rgn); end; procedure TOverlayImage.SubtractClipRegion(Value: TRect); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(Value); CombineRgn(fClipRgn, fClipRgn, rgn, RGN_DIFF); DeleteObject(rgn); end; procedure TOverlayImage.IntersectClipRegion(Value: TRect); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(Value); CombineRgn(fClipRgn, fClipRgn, rgn, RGN_And); DeleteObject(rgn); end; //------------------------------------------------------------------------ procedure TOverlayImage.WMWindowPosChanged; begin inherited; if not (csDesigning in ComponentState) then if assigned(Parent) then begin if (Width <> fDrawWidth) or (Height <> fDrawHeight) then begin fDrawWidth := Width; fDrawHeight := Height; SizeChanged; if fOldRgn <> 0 then DeleteObject(fOldRgn); fOldRgn := 0; fTempDrawing := False; fOverlayed := False; end; GetOffSet; //// ???? end; end; procedure TOverlayImage.SizeChanged; begin fScreenBitmap.Width := 0; fScreenBitmap.Width := fDrawWidth; fScreenBitmap.Height := fDrawHeight; // fBitmap.Width:=0; fBitmap.Width := fDrawWidth; fBitmap.Height := fDrawHeight; if fMetaFile <> nil then begin fMetaFileCanvas.Free; fMetaFile.Width := Width; fMetaFile.Height := Height; fMetaFileCanvas := TMetaFileCanvas.Create(fMetaFile, 0); fMetaFileCanvas.draw(0, 0, fMetaFile); end; end; procedure TOverlayImage.Loaded; begin inherited; fDrawWidth := Width; fDrawHeight := Height; Clear(Canvas, Brush.Color); end; procedure TOverlayImage.GetOffSet; var p, q: TPoint; begin if assigned(Parent) then begin with Parent do p := ClienttoScreen(Point(0, 0)); q := ClienttoScreen(Point(0, 0)); fxoff := q.x - p.x; fyoff := q.y - p.y; end; end; procedure TOverlayImage.CMMouseLeave; begin inherited; if assigned(fOnMouseLeave) then fOnMouseLeave(self); {use to get rid of stray drawing on the TempCanvas} end; procedure TOverlayImage.CMMouseEnter; begin inherited; if assigned(fOnMouseEnter) then fOnMouseEnter(self); end; procedure TOverlayImage.ShowOverlay; var DC: HDC; begin fTempDrawing := True; DC := inherited Canvas.Handle; if assigned(fOnTempPaint) then fOnTempPaint(self); if fOldRgn <> 0 then begin if fNewRgn <> 0 then begin CombineRgn(fOldRgn, fOldRgn, fNewRgn, RGN_OR); OffsetRgn(fOldRgn, fxoff, fyoff); SelectClipRgn(DC, fOldRgn); end else SelectClipRgn(DC, 0); DeleteObject(fOldRgn); end else SelectClipRgn(DC, 0); BitBlt(DC, 0, 0, fDrawWidth, fDrawHeight, fScreenBitmap.Canvas.Handle, 0, 0, SRCCopy); fOldRgn := fNewRgn; fNewRgn := 0; fTempDrawing := False; fOverlayed := True; end; procedure TOverlayImage.LockUpdate; begin fBitmap.OnChange := nil; {Don't update bitmap to screen} inc(fLockCount); end; procedure TOverlayImage.UnlockUpdate; begin dec(fLockCount); if fLockCount <= 0 then begin fLockCount := 0; {safety} fBitmap.OnChange := fBitmapChanged; fBitmapChanged(nil); end; end; procedure TOverlayImage.Clear(Acanvas: TCanvas; AColor: TColor); begin Acanvas.Brush.Color := AColor; Acanvas.FillRect(Rect(0, 0, Width, Height)); end; procedure TOverlayImage.EraseMetafile; begin if fMetaFileCanvas <> nil then fMetaFileCanvas.Free; if fMetaFile <> nil then fMetaFile.Free; fMetaFileCanvas := nil; fMetaFile := nil; with fBitmap.Canvas do begin Font.OnChange := fOrgFontChanged; Brush.OnChange := fOrgBrushChanged; Pen.OnChange := fOrgPenChanged; end; end; procedure TScrollEventBox.WMHScroll(var Message: TWMHScroll); begin inherited; if assigned(fOnScroll) then fOnScroll(self); end; procedure TScrollEventBox.WMVScroll(var Message: TWMVScroll); begin inherited; if assigned(fOnScroll) then fOnScroll(self); end; procedure TOverlayImage.AdjustToScroll; begin GetOffSet; end; procedure TOverlayImage.OverlayCopyRect(dest: TRect; Canvas: TCanvas; Source: TRect); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(dest); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn; fTempCanvasChanging; OverlayCanvas.CopyRect(dest, Canvas, Source); end; procedure TOverlayImage.OverlayDraw(dest: TRect; Graphic: TGraphic); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(dest); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.draw(dest.Left, dest.Top, Graphic); end; procedure TOverlayImage.OverlayEllipse(x1, y1, x2, y2: Integer); var rgn: HRgn; begin rgn := CreateEllipticRgnIndirect(Rect(x1 - 1, y1 - 1, x2 + 2, y2 + 2)); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.Ellipse(x1, y1, x2, y2); end; procedure TOverlayImage.OverlayFillRect(const Rect: TRect); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(Rect); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.FillRect(Rect); end; procedure TOverlayImage.OverlayFrameRect(const Rect: TRect); var rgn: HRgn; begin rgn := CreateRectRgnIndirect(Rect); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.FrameRect(Rect); end; procedure TOverlayImage.OverlayLine(x1, y1, x2, y2: Integer); var rgn: HRgn; xmin, ymin, xmax, ymax: Integer; points: array[0..2] of TPoint; begin if x1 < x2 then begin xmin := x1; xmax := x2; end else begin xmin := x2; xmax := x1; end; if y1 < y2 then begin ymin := y1; ymax := y2; end else begin ymin := y2; ymax := y1; end; rgn := CreateRectRgnIndirect(Rect(xmin - 1, ymin - 1, xmax + 1, ymax + 1)); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; Points[0]:=Point(x1,y1); Points[1]:=Point(x2,y2); Points[2]:=Points[0]; OverlayCanvas.Polyline(Points); end; procedure TOverlayImage.OverlayPolygon(Points: array of TPoint); var rgn: HRgn; begin rgn := CreatePolygonRgn(Points, High(Points) + 1, WINDING); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.Polygon(Points); end; procedure TOverlayImage.OverlayPolyline(Points: array of TPoint); var rgn: HRgn; begin rgn := CreatePolygonRgn(Points, High(Points) + 1, WINDING); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.Polyline(Points); end; procedure TOverlayImage.OverlayRectangle(x1, y1, x2, y2: Integer); var rgn: HRgn; begin rgn := CreateRectRgn(x1, y1, x2, y2); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.Rectangle(x1, y1, x2, y2); end; procedure TOverlayImage.OverlayRoundRect(x1, y1, x2, y2, X3, Y3: Integer); var rgn: HRgn; begin rgn := CreateRoundRectRgn(x1, y1, x2 + 3, y2 + 3, X3, Y3); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); fTempCanvasChanging; OverlayCanvas.RoundRect(x1, y1, x2, y2, X3, Y3); end; procedure TOverlayImage.Notification; begin //doesn't do any good tho inherited; if csDesigning in ComponentState then repaint; end; procedure TOverlayImage.HideOverlay; begin fOverlayed := False; invalidate; end; procedure TOverlayImage.OverlayTextOut(x, y: Integer; const s: string); var rgn: HRgn; w, h: Integer; begin with OverlayCanvas do begin w := TextWIdth(s); h := TextHeight(s); end; rgn := CreateRectRgn(x, y, x + w, y + h); if fNewRgn <> 0 then begin CombineRgn(fNewRgn, fNewRgn, rgn, RGN_OR); DeleteObject(rgn); end else if not fTempDrawing then fNewRgn := rgn else DeleteObject(rgn); OverlayCanvas.TextOut(x, y, s); end; function TOverlayImage.GetTempBrush: TBrush; begin Result := fScreenBitmap.Canvas.Brush; end; function TOverlayImage.GetTempFont: TFont; begin Result := fScreenBitmap.Canvas.Font; end; function TOverlayImage.GetTempPen: TPen; begin Result := fScreenBitmap.Canvas.Pen; end; procedure TOverlayImage.SetTempBrush(Value: TBrush); begin fScreenBitmap.Canvas.Brush.assign(Value); end; procedure TOverlayImage.SetTempFont(Value: TFont); begin fScreenBitmap.Canvas.Font.assign(Value); end; procedure TOverlayImage.SetTempPen(Value: TPen); begin fScreenBitmap.Canvas.Pen.assign(Value); end; procedure Register; begin RegisterComponents('MathStuff', [TOverlayImage, TScrollEventBox]); end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, XPMan, ALHintBalloon, ExtCtrls, ShellApi; type TfrmMain = class(TForm) BtnExit: TButton; XPManifest: TXPManifest; LblInfo: TLabel; Hint: TALHintBalloonControl; GbStandart: TGroupBox; BtnError: TButton; BtnWarn: TButton; BtnInfo: TButton; GbPicture: TGroupBox; BtnPict1: TButton; BtnPict2: TButton; BtnPict3: TButton; RadioButton1: TRadioButton; RadioButton2: TRadioButton; RadioButton5: TRadioButton; RadioButton6: TRadioButton; DlgOpen: TOpenDialog; LblAuthor: TLabel; LblAuthorName: TLabel; LblDemo: TLabel; LblMe: TLabel; GbArrowPos: TRadioGroup; GbAnimType: TRadioGroup; GbProps: TGroupBox; Label2: TLabel; Label7: TLabel; EdAnimSpeed: TEdit; EdDuration: TEdit; Panel1: TPanel; Label5: TLabel; procedure BtnExitClick(Sender: TObject); procedure BtnErrorClick(Sender: TObject); procedure BtnWarnClick(Sender: TObject); procedure BtnInfoClick(Sender: TObject); procedure FormClick(Sender: TObject); procedure BtnPict1Click(Sender: TObject); procedure BtnPict2Click(Sender: TObject); procedure BtnPict3Click(Sender: TObject); procedure EdAnimSpeedChange(Sender: TObject); procedure GbAnimTypeClick(Sender: TObject); procedure LblAuthorNameClick(Sender: TObject); procedure LblMeClick(Sender: TObject); private function ArrowPos: TALHintBalloonArrowPosition; end; var frmMain: TfrmMain; implementation {$R *.dfm} //////////////////////////////////////////////////////////////////////////////// /////////////////////////////// Private declarations /////////////////////////// //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ function TfrmMain.ArrowPos: TALHintBalloonArrowPosition; begin Result := TALHintBalloonArrowPosition(GbArrowPos.ItemIndex); end; //////////////////////////////////////////////////////////////////////////////// /////////////////////////////// Private declarations /////////////////////////// //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ procedure TfrmMain.BtnExitClick(Sender: TObject); begin Application.Terminate; end; //------------------------------------------------------------------------------ procedure TfrmMain.BtnErrorClick(Sender: TObject); begin Hint.ShowTextHintBalloon(bmtError, 'How is the test?', 'WHOA! Am i looking frightnng for you? :)', 300, 10, 10, BtnError, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.BtnWarnClick(Sender: TObject); begin Hint.ShowTextHintBalloon(bmtWarning, 'How is the test?', 'Oh my god! I am clicked :)', 300, 10, 10, BtnWarn, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.BtnInfoClick(Sender: TObject); begin Hint.ShowTextHintBalloon(bmtInfo, 'How is the test?', 'A am very nice hint! :)', 300, 50, 50, btnInfo, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.FormClick(Sender: TObject); begin Hint.ShowTextHintBalloon(bmtInfo, 'How is the test?', 'A am very nice hint! :)', 300, 100, 100, self, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.BtnPict1Click(Sender: TObject); begin Hint.ShowPictureHintBalloon(ExtractFilePath(ParamStr(0)) + '1.ico', 100, 100, BtnPict1, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.BtnPict2Click(Sender: TObject); begin Hint.ShowPictureHintBalloon(ExtractFilePath(ParamStr(0)) + '2.bmp', 100, 100, BtnPict2, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.BtnPict3Click(Sender: TObject); begin if DlgOpen.Execute then Hint.ShowPictureHintBalloon(dlgOpen.FileName, 100, 100, BtnPict3, ArrowPos); end; //------------------------------------------------------------------------------ procedure TfrmMain.EdAnimSpeedChange(Sender: TObject); begin if (Sender as TEdit).Text > '' then Hint.AnimationSpeed := StrToInt((Sender as TEdit).Text); end; //------------------------------------------------------------------------------ procedure TfrmMain.GbAnimTypeClick(Sender: TObject); begin Hint.AnimationType := TALHintBalloonAnimationType(GbAnimType.ItemIndex); end; procedure TfrmMain.LblAuthorNameClick(Sender: TObject); begin ShellApi.ShellExecute(Handle, 'open', 'mailto:SVanderClock@carlays.com', nil, nil, 0); end; procedure TfrmMain.LblMeClick(Sender: TObject); begin ShellApi.ShellExecute(Handle, 'open', 'mailto:quadr02005@yahoo.com', nil, nil, 0); end; end.
unit uTSFastReportFunction; interface uses SysUtils, Classes, fs_iinterpreter, DateUtils, Math; type TTSFastReportFunction = class(TfsRTTIModule) private function CallMethod(Instance: TObject; ClassType: TClass; const MethodName: String; var Params: Variant): Variant; public constructor Create(AScript: TfsScript); override; function Quot(AString : String): String; function QuotDTAwal(ATgl : TDateTime): string; function QuotDTAkhir(ATgl : TDateTime): string; function StartOfTheMonth(ATgl : TDateTime): TDateTime; function EndOfTheMonth(ATgl : TDateTime): TDateTime; Function Num2Words:String; Function Num2Let(N:Double; aRpType:Integer):String; Function Num2LetEnglish(N:Double; aRpType:Integer):String; function Num2LetEnglishDef(const ARupiah: Double): string; end; const _Kategori : string = 'TS Functions'; Ltr: array [0..19] of String = ('NOL ', 'SATU ', 'DUA ', 'TIGA ', 'EMPAT ', 'LIMA ', 'ENAM ', 'TUJUH ', 'DELAPAN ', 'SEMBILAN ', 'SEN ', 'BELAS ', 'PULUH ', 'RATUS ', 'RIBU ', 'JUTA ', 'MILYAR ', 'TRILYUN ', 'KOMA ', 'SE'); LtrEnglish: array [0..19] of String = ('Zero ', 'One ', 'Two ', 'three ', 'Four ', 'Five ', 'Six ', 'Seven ', 'Eight ', 'Nine ', 'Cent ', 'Teen ', 'Tens ', 'Hundred ', 'Thousand ', 'Million ', 'Billion ', 'Quintillion ', 'Comma ', 'ty'); SEN = 10; BELAS = 11; PULUH = 12; RATUS = 13; RIBU = 14; JUTA = 15; MILYAR = 16; TRILYUN = 17; KOMA = 18; SATU = 19; implementation { TTSFastReportFunction } constructor TTSFastReportFunction.Create; begin inherited Create(AScript); with AScript do begin AddMethod('function Quot(s: String) : String', CallMethod, _Kategori, ' Quoted Str in FR'); AddMethod('function QuotDTAwal(ATgl : TDateTime): string', CallMethod, _Kategori, ' Quoted Tanggal Awal'); AddMethod('function QuotDTAkhir(ATgl : TDateTime): string', CallMethod, _Kategori, ' Quoted Tanggal Akhir'); AddMethod('function StartOfTheMonth(ATgl : TDateTime): TDateTime', CallMethod, _Kategori, 'Start Of The Month'); AddMethod('function EndOfTheMonth(ATgl : TDateTime): TDateTime', CallMethod, _Kategori, ' End Of The Month'); AddMethod('function Num2Words : String', CallMethod, _Kategori, ' Numeric to kata2'); AddMethod('Function Num2Let(N:Double; aRpType:Integer):String', CallMethod, _Kategori, ' Numeric to Letters (ID)'); AddMethod('Function Num2LetEnglish(N:Double; aRpType:Integer):String', CallMethod, _Kategori, ' Numeric to Letters (EN)'); AddMethod('function Num2LetEnglishDef(const ARupiah: Double): string', CallMethod, _Kategori, ' Numeric to Letters (Def)'); end; end; function TTSFastReportFunction.CallMethod(Instance: TObject; ClassType: TClass; const MethodName: String; var Params: Variant): Variant; begin if MethodName = 'QUOT' then Result := Quot(Params[0]) else if MethodName = 'QUOTDTAWAL' then Result := QuotDTAwal(Params[0]) else if MethodName = 'QUOTDTAKHIR' then Result := QuotDTAkhir(Params[0]) else if MethodName = 'STARTOFTHEMONTH' then Result := StartOfTheMonth(Params[0]) else if MethodName = 'ENDOFTHEMONTH' then Result := EndOfTheMonth(Params[0]) else if MethodName = 'NUM2WORDS' then Result := Num2Words else if MethodName = 'NUM2LET' then Result := Num2Let(Params[0], Params[1]) else if MethodName = 'NUM2LETENGLISH' then Result := Num2LetEnglish(Params[0], Params[1]) else if MethodName = 'NUM2LETENGLISHDEF' then Result := Num2LetEnglishDef(Params[0]) ; end; function TTSFastReportFunction.Quot(AString : String): String; begin Result := QuotedStr(AString); end; function TTSFastReportFunction.QuotDTAkhir(ATgl : TDateTime): string; begin Result := Quot(FormatDateTime('MM/dd/yyyy 23:59:59', ATgl)); end; function TTSFastReportFunction.QuotDTAwal(ATgl : TDateTime): string; begin Result := Quot(FormatDateTime('MM/dd/yyyy 00:00:00', ATgl)); end; function TTSFastReportFunction.StartOfTheMonth(ATgl : TDateTime): TDateTime; begin Result := DateUtils.StartOfTheMonth(ATgl); end; function TTSFastReportFunction.EndOfTheMonth(ATgl : TDateTime): TDateTime; begin Result := DateUtils.EndOfTheMonth(ATgl); end; Function TTSFastReportFunction.Num2Words : String; begin Result := 'satu dua tiga empat'; end; Function SE(n:integer):String; Begin If n = 1 then SE := Ltr[SATU] else SE := Ltr[N]; End; Function u1000(n:integer):String; Var rs:String; m: Integer; Begin rs := ''; If n > 0 then Begin m := n div 100; If (m>0) then rs := SE(m)+Ltr[RATUS]; m := n mod 100; case m of 0: ; 1..9: rs := rs+Ltr[m]; 10: rs := rs+Ltr[SATU]+Ltr[PULUH]; 11..19: rs := rs+SE(m mod 10)+Ltr[BELAS]; 20..99: Begin rs := rs+Ltr[m div 10]+Ltr[PULUH]; If (m mod 10) > 0 then rs := rs + Ltr[m mod 10]; End; End; End; u1000 := rs; End; Function TTSFastReportFunction.Num2Let(N:Double; aRpType:Integer):String; Var strN, Letter, X: String; i, j, nX: integer; Begin j := 0; Letter := ''; strN := format('%.2n', [N]); i := Length(strN); While (i >= 1) do Begin X := ''; While not (CharInSet(strN[i] , [',', '.'])) and (i>=1) do Begin X := strN[i]+X; dec(i); End; dec(i); nX := StrToInt(X); if (nX > 0) or (j = 0) then Case j of 0:case aRpType of 0: Letter := Ltr[KOMA]+Ltr[ord(X[1])-ord('0')]+Ltr[ord(X[2])-ord('0')]; 1: Begin If (nX > 0) then letter := Letter + u1000(nX)+Ltr[SEN]; End; End; 1:Letter := u1000(nX)+Letter; 2:Begin If nX = 1 then Letter := 'SE'+Ltr[RIBU]+Letter Else Letter := u1000(nX)+Ltr[RIBU]+Letter; End; 3:Letter := u1000(nX)+Ltr[JUTA]+Letter; 4:Letter := u1000(nX)+Ltr[MILYAR]+Letter; 5:Letter := u1000(nX)+Ltr[TRILYUN]+Letter; End; inc(j); End; Num2Let := Letter; End; Function TTSFastReportFunction.Num2LetEnglish(N:Double; aRpType:Integer):String; Var strN, Letter, X: String; i, j, nX: integer; Begin j := 0; Letter := ''; strN := format('%.2n', [N]); i := Length(strN); While (i >= 1) do Begin X := ''; While not (CharInSet(strN[i] , [',', '.'])) and (i>=1) do Begin X := strN[i]+X; dec(i); End; dec(i); nX := StrToInt(X); if (nX > 0) or (j = 0) then Case j of 0:case aRpType of 0: Letter := LtrEnglish[KOMA]+LtrEnglish[ord(X[1])-ord('0')]+LtrEnglish[ord(X[2])-ord('0')]; 1: Begin If (nX > 0) then letter := Letter + u1000(nX)+LtrEnglish[SEN]; End; End; 1:Letter := u1000(nX)+Letter; 2:Begin If nX = 1 then Letter := 'SE'+LtrEnglish[RIBU]+Letter Else Letter := u1000(nX)+LtrEnglish[RIBU]+Letter; End; 3:Letter := u1000(nX)+LtrEnglish[JUTA]+Letter; 4:Letter := u1000(nX)+LtrEnglish[MILYAR]+Letter; 5:Letter := u1000(nX)+LtrEnglish[TRILYUN]+Letter; End; inc(j); End; Num2LetEnglish := Letter; End; function TTSFastReportFunction.Num2LetEnglishDef(const ARupiah: Double): string; var A, P: extended; N,I : integer; T : longint; NSen: integer; Str : string; const Thousands : array[0..5] of string = ('', 'Thousand ', 'Million ', 'Billion ', 'Trillion ', 'Quadrillion '); Tens : array[0..9] of string = ('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'); Ones : array[0..19] of string = ('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); function ParseRatusan(ANum: Longint): string; var I, J: integer; A,T : Longint; S : string; begin S := ''; I := 0; J := 0; Result := S; if (ANum <> 0) then begin A := ANum; T := A div 100; if (T > 0) then begin I := T; A := A - (T * 100); end; T := A div 10; if (T > 1) then begin J := T; A := A - (T * 10); end; if (I > 0) then S := Ones[I] + ' Hundred'; if (J > 0) then begin if (I > 0) then S := S + ' ' + Tens[J] else S := S + Tens[J]; end; if (A > 0) then begin if (J > 0) then S := S + '-'; if (I > 0) and (J = 0) then S := S + ' ' + Ones[A] else S := S + Ones[A]; end; Result := S; end; end; begin Result := ''; if (ARupiah < 0) then raise Exception.Create('Nilai ndak boleh < 0'); if (ARupiah > 0) then begin N := Trunc(Log10(ARupiah)); if (N > 17) then raise Exception.Create('Nilai yang akan dikonversi terlalu besar'); A := ARupiah; for I := N downto 0 do begin P := Int(Power(10.0, I*3)); T := Trunc(A/P); if (T > 0) then begin Str := ParseRatusan(T) + ' ' + Thousands[I]; if Result = '' then Result := Str else Result := Result + ' ' + Str; end; A := A - (T * P); end; NSen := Round(Frac(ARupiah) * 1000); if NSen > 0 then begin Str := 'And '+ ParseRatusan(NSen); Result := Result + Str; end; end; if (Result = '') then Result := 'Zero '; end; initialization fsRTTIModules.Add(TTSFastReportFunction); end.
{ @abstract Implements resource and locale routines that are common to VCL and FMX. The unit contains following classes: @link(TNtLanguage) and @link(TNtLanguages). They are used to store information about resource DLL languages. In addition it contains routines that are grouped into three static classes: @link(TNtBase), @link(TNtLocaleRegistry) and @link(TNtConvert). @link(TNtBase.GetAvailable) gets the available resource languages. Use it to populate the available language list in your user interface. After you have selected the language call @link(TNtTranslator.SetNew) to turn on that language. See @italic(Samples\Delphi\VCL\CustomSelect) or @italic(Samples\Delphi\FMX\CustomSelect) samples to see how to use the unit. } unit NtBase; {$I NtVer.inc} interface uses {$IFDEF AUTOREFCOUNT} System.Generics.Collections, {$ENDIF} SysUtils, Classes; const APPLICATION_RESOURCE = 'SOLULING'; APPLICATION_DIR = 'Soluling'; { Character that is used to separate country part from language part in the locale id. } LOCALE_SEPARATOR = '-'; NT_LOCALE_ALL = 0; // enumerate all named based locales { Form header. } VCL_FORM_HEADER: array[0..3] of Byte = ($54, $50, $46, $30); // 'TPF0' { The virtual folder that represents the My Documents desktop item. } NT_CSIDL_PERSONAL = $0005; {$IFNDEF MSWINDOWS} { Neutral sub language id. } SUBLANG_NEUTRAL = 0; {$ENDIF} {$IFDEF DELPHIXE} { Current locale override key (Embarcadero era) } LOCALE_OVERRIDE_KEY = 'Software\Embarcadero\Locales'; { Old locale override key (CodeGear era) } OLD_LOCALE_OVERRIDE_KEY = 'Software\CodeGear\Locales'; { Oldest locale override key (Borland era) } OLDEST_LOCALE_OVERRIDE_KEY = 'Software\Borland\Locales'; {$ELSE} {$IFDEF UNICODE} LOCALE_OVERRIDE_KEY = 'Software\CodeGear\Locales'; OLD_LOCALE_OVERRIDE_KEY = 'Software\Borland\Locales'; {$ELSE} LOCALE_OVERRIDE_KEY = 'Software\Borland\Locales'; OLD_LOCALE_OVERRIDE_KEY = ''; {$ENDIF} OLDEST_LOCALE_OVERRIDE_KEY = ''; {$ENDIF} type {$IFNDEF UNICODE} UnicodeString = WideString; RawByteString = AnsiString; {$ENDIF} { Day of the week. } TNtDayOfWeek = ( wdMonday, //< Monday wdTuesday, //< Tuesday wdWednesday, //< Wednesday wdThursday, //< Thursday wdFriday, //< Friday wdSaturday, //< Saturday wdSunday //< wdSunday ); { The first day of the week. } TNtFirstWeekOfYear = ( fwFirstPart, //< First week that has at least one day in January. fwFirstFull, //< First full week of January. fwFirst4 //< First week that has at least four days in January. ); { User interface layout. } TNtLayout = ( laLeftToRight, //< User interface layout is Western (e.g. from left to right). laRightToLeft //< User interface layout is Middle-Eastern (e.g. from right to left). ); // Specifies resource options. TNtResourceOption = ( roNoThreadLocale, //< Do not update the thread locle. roNoLocaleVariables, //< Do not update the locale variables. roNoUpdateBidiMode, //< Do not update the TApplication.BiDiMode. roFlipChildren, //< Do not flip the controls on forms. roSaveLocale //< Save the active locale. ); // Set of resource options. TNtResourceOptions = set of TNtResourceOption; { Options for extrating embedded resource files. } TExtractOption = ( eoCheckDate, //< Application check the date of exisisting resource files (if any). If the date is same or newer as the embedded file the file is not extracted. eoRemoveFiles //< Extracted files are removed after application closes. ); { Set of extracting options. } TExtractOptions = set of TExtractOption; { Specifies in what language language, country and locale names are given. } TNtLanguageName = ( lnNative, //< Language's own language is used: English, Deutsch, Franšais, ... lnLocalized, //< Language of the application is used. lnBoth, //< Native + localize is used. lnEnglish, //< English is used. lnSystem //< Lanugage of the operation system is used. ); { Specifies what case the language name should use. } TNtLanguageNameCase = ( lcDefault, //< Default case of the language name lcUpper, //< Language name starts in upper case (e.g. English) lcLower //< Language name starts in lower case (e.g. english) ); { @abstract Contains infomation about resource DLL language. } TNtLanguage = class(TObject) private FCode: String; FId: Integer; FFileName: String; FLanguageNameCase: TNtLanguageNameCase; function GetActiveCode: String; function GetName(i: TNtLanguageName): String; public { Get language name that contains both native and localized names. @param native Language name in the language itself. @param localized Language name in the current language. @return Display name. } class function GetBoth(const native, localize: String): String; { Get the display name of a language or locale. @param locale Windows language or locale id. @param languageName Specifies what kind of name is returned. @param languageNameCase Specifies what case to use in language names. @return Display name such as English or English (United States). } class function GetDisplayName( const id: String; locale: Integer = 0; languageName: TNtLanguageName = lnSystem; languageNameCase: TNtLanguageNameCase = lcDefault): String; class procedure CheckCase( var value: String; languageNameCase: TNtLanguageNameCase); property ActiveCode: String read GetActiveCode; property Code: String read FCode write FCode; //< ISO language or locale code. property Id: Integer read FId write FId; //< Windows locale id. property FileName: String read FFileName write FFileName; //< Resource DLL file name. property NativeName: String index lnNative read GetName; //< Native name. Uses language of the language itself. property LocalizedName: String index lnLocalized read GetName; //< Localized name. Uses language of the application. property EnglishName: String index lnEnglish read GetName; //< English name. property SystemName: String index lnSystem read GetName; //< System name. Uses language of the operating system. property Names[i: TNtLanguageName]: String read GetName; //< Array of names. property LanguageNameCase: TNtLanguageNameCase read FLanguageNameCase write FLanguageNameCase; end; { Specifies how the default locale is selected. } TLocaleSelect = ( lsUI, //< Locale matching the UI language of OS. This is the default behaviour in Delphi 2010 or later. lsSettings //< Locale matching the regional settings of Control Panel. This is the default behaviour in Delphi 2009 or earlier. ); { @abstract List of resource DLL languages. } TNtLanguages = class(TObject) private {$IFDEF AUTOREFCOUNT} FItems: TList<TNtLanguage>; {$ELSE} FItems: TList; {$ENDIF} function GetCount: Integer; function GetItem(i: Integer): TNtLanguage; public constructor Create; destructor Destroy; override; { Add a new language to the list. @param code Language or locale code. @param id Windows language or locale id. @param fileName Resource DLL file name. } function Add( const code: String; id: Integer = 0; const fileName: String = ''): TNtLanguage; overload; { Add a language to the list. @param language Language to be added } procedure Add(language: TNtLanguage); overload; procedure AddDefault; function FindByFile(const fileName: String): TNtLanguage; property Count: Integer read GetCount; //< Language count. property Items[i: Integer]: TNtLanguage read GetItem; default; //< Languages. end; { @abstract Static class that contains localization routines. } TNtBase = class private class procedure DeleteExtractedFiles; {$IFDEF MSWINDOWS} class function HasWriteAccess(const dir: String): Boolean; {$ENDIF} public { Checks the resource DLL count. If this is 0 raises an exception. } class procedure CheckThatDllsExist; { Check if the given locale is compatible to the system. @param locale Locale to be checked. @return @true if the locale is compatible, @false if not. On Delphi 2009 later return always @true.} class function IsLocaleCompatible(locale: Integer): Boolean; { Get a list of available resource DLL languages. @param languages Returns a list of available languages. @param exeFileName Specifies the name of the application. If empty the current application is used. @param compatibleOnly If @true only those resource DLL languages are added that are compatible to the current system settings. Not used in Delphi 2009 or later. @param checkVersions If @true only those resource DLL languages are added where the version resource of the DLL matches the EXE. @return Amount of lanugages. } class function GetAvailable( languages: TNtLanguages; exeFileName: String = ''; compatibleOnly: Boolean = False; checkVersions: Boolean = False): Integer; { Get the number of the available resource DLLs. @param exeFileName Specifies the name of the application. If empty the current application is used. @param compatibleOnly If @true only those resource DLL languages are added that are compatible to the current system settings. Not used in Delphi 2009 or later. @param checkVersions If @true only those resource DLL languages are added where the version resource of the DLL matches the EXE. @return Amount of lanugages. } class function GetAvailableCount( exeFileName: String = ''; compatibleOnly: Boolean = False; checkVersions: Boolean = False): Integer; { Get the resource DLL file for the given locale. @param fileName @param id @return Resource DLL file name. Empty if not found. } class function GetResourceFile(const fileName, id: String): String; { Check if a resource DLL file for the given locale exists. @param fileName @param id @return True if a resource file exists. } class function ResourceFileExist(const fileName, id: String): Boolean; { Set the initial locale to match the current settings in the Regional Settings of Control Panel. @param localeSelect Specifies how to select the dfault locale. @param defaultLocale Specifies the default locale. If empty the default locale is not set. } class procedure SetInitialLocale( localeSelect: TLocaleSelect; const defaultLocale: String = ''); { Sets the directory where the resource DLL file locates. @longCode(# program CustomDir; uses NtBase, Forms, Unit1 in 'Unit1.pas'; #) @param value Directory. Can be abosulte or relative to the application file. @param localeSelect Specifies how to select the dfault locale. } class procedure SetResourceDllDir(const value: String; localeSelect: TLocaleSelect = lsUI); { Load a new resource DLL file. If you call @link(TNtTranslator.SetNew) this should not be called. @param code The locale code of the resource to be loaded. @param fileName The file to be loaded. If empty then function looks the standard resource file name and location. @return The module handle of the loaded resource DLL. } class function LoadNew( code: String = ''; fileName: String = ''): HModule; { Extracts embedded resource DLLs from EXE to the application directory. If the user has write access to the directory where the EXE locates, then resource files are exteracted there. Otherwise the files are extracted to the user's personal directory. @param options Specifies the extract options @param resourceName Specifies the resource type name of the resource DLLs. If empty SOLULING is used. } class function ExtractFiles( options: TExtractOptions = [eoCheckDate]; resourceName: String = ''): Integer; { @abstract Disables the resource DLLs. If you call this application does not load any resource DLL. See Samples\Delphi\VCL\IgnoreResourceDll to see how to use this procedure. } class procedure DisableResourceDlls; { Get a special folder. @return Full path name to the folder. } class function GetFolderPath(nFolder: Integer): String; { Parse locale into language, country and variant parts. @param value Locale to be parsed. @param language Returns the language part. @param country Returns the country part. @param variant Returns the variant part. } class procedure ParseLocaleString(value: String; var language, country, variant: String); { Parse language id into language, script, country and variant parts. @param value Locale to be parsed. @param language Returns the language part. @param script Returns the script part. @param country Returns the country part. @param variant Returns the variant part. } class procedure ParseLocaleId( id: String; var language: String; var script: String; var country, variant: String); { Check if a resource DLL has been loaded. @return @true if a resource DLL has been loaded. @false if no resource DLL has been loaded and the application uses the EXE resources. } class function IsLoaded: Boolean; { Get the locale code of the currently loaded resource DLL. @return Language or locale code. This is either code of the loaded resource DLL or default language. } class function GetActiveLocale: String; { Combine primary and sub language ids into a language id. @param primaryLanguage Primary language id. @param subLanguage Sub language id. @return Language id. @seealso(LocaleToPrimary) } class function MakeLangId(primaryLanguage, subLanguage: Integer): Integer; { Get primary language id part from locale id. @param locale Language id. @return Primary language id. @seealso(MakeLangId) @seealso(LocaleToSub) } class function LocaleToPrimary(locale: Integer): Integer; { Get sub language id part from locale id. @param locale Language id. @return Sub language id. @seealso(MakeLangId) @seealso(LocaleToPrimary) } class function LocaleToSub(locale: Integer): Integer; { Get file name of the currently running application. @return Full file name of the application. } class function GetRunningFileName: String; { Get the resource file name for the given application or library file. @param exeFileName Application (.exe) or library (.dll, .bpl) file. @param code Language or locale of the resource file that is needed. @return Resource file name. } class function GetLanguageFile(const exeFileName: String; const code: String): String; { Get the currently loaded resource DLL file of the current application. @return Resource DLL file. } class function GetCurrentLanguageFile: String; { Get the resource instance. @return Resource instance. If a resource DLL has been loaded then return the resource handle of that DLL. If no resource DLL has been loaded returns the resource handle of the application itself. } class function GetResourceInstance: THandle; { Get the default language of the user. @return Language or locale id. @seealso(GetSystemLanguage) } class function GetUserLanguage: Integer; { Get the default language of the system. @return Language or locale id. @seealso(GetUserLanguage) } class function GetSystemLanguage: Integer; class function GetDefaultLanguage: String; class function GetDefaultLocale: String; { Convert locale id into locale code. @param locale Language or locale id @return Language or locale code. } class function LocaleToIsoCode(locale: Integer): String; { Convert ISO locale into locale id. @param locale Locale code. @return Locale id. } class function IsoToLocale(const locale: String): Integer; { Convert ISO language and country into locale id. @param language Language code. @param country Country code. @return Locale id. } class function IsoLanguageToLocale(const language: String; const country: String = ''): Integer; { Convert locale id into Windows language extension. This is two or three characters. @param locale Locale to be converted. @return Extension without period. } {$IFDEF MSWINDOWS} class function LocaleToExtension(locale: Integer): String; {$ENDIF} end; { @abstract Static class that contains resource routines. } TNtResources = class public class function DoesExist( resType, resName: PChar; instance: THandle = 0): Boolean; class function GetResourceStream( resType, resName: PChar; instance: THandle = 0): TResourceStream; {$IFDEF DELPHI2007} class function LoadResource( resType, resName: PChar; instance: THandle = 0): TBytes; {$ENDIF} end; { @abstract Static class that contains registry routines to manipulate locale override values. Locale override are registry key entries that specify the default locale of a Delphi application. } TNtLocaleRegistry = class public { Save the current locale of the current application as locale override. } class procedure SetCurrentDefaultLocale; { Get the locale override of the current application. @return The locale override value.} class function GetCurrentDefaultLocale: String; { Clear the locale override value of the current application in the registry. @return @true if succesful, @false if failed. } class function ClearCurrentDefaultLocale: Boolean; { Set the locale override value of the given application. @param fileName Application. @param code Locale override value.} class procedure SetDefaultLocale(const fileName: String; code: String); { Get the locale override value of the given application. @param fileName Application. @return Locale override value.} class function GetDefaultLocale(const fileName: String): String; overload; { Get the locale override value of the given application. @param fileName Application. @param keyExists @true if the locale override value exists, @false if it does not exist. @return Locale override value.} class function GetDefaultLocale(const fileName: String; out keyExists: Boolean): String; overload; { Clear the locale override value of the given application. @return @true if succesful, @false if failed. } class function ClearDefaultLocale(const fileName: String): Boolean; end; { @abstract Static class that contains routines to convert between Ansi and Unicode. } TNtConvert = class public { Converts an Ansi string into a Unicode string. @param str Ansi string to be converted. @param codePage Code page that the Ansi string uses. @return String as a Unicode string. } class function AnsiToUnicode(const str: RawByteString; codePage: Integer = 0): UnicodeString; { Converts a Unicode string into an Ansi string. @param str Unicode string to be converted. @param codePage Code page that the Ansi string uses. @return String as an Ansi string. } class function UnicodeToAnsi(const str: UnicodeString; codePage: Integer = 0): RawByteString; {$IFDEF DELPHI2007} class function BytesToUnicode(str: TBytes; codePage: Integer = 0): UnicodeString; class function UnicodeToBytes(const str: UnicodeString; codePage: Integer = 0): TBytes; class function BytesToRawByteString(bytes: TBytes): RawByteString; class function RawByteStringToBytes(str: RawByteString): TBytes; {$ENDIF} end; { @abstract Abstract extension class. } TNtExtension = class(TObject) end; { Class type of the extension class. } TNtExtensionClass = class of TNtExtension; { @abstract Class that stores installed extension. } TNtExtensions = class(TObject) private {$IFDEF AUTOREFCOUNT} FItems: TList<TNtExtension>; {$ELSE} FItems: TList; {$ENDIF} function GetCount: Integer; function GetItem(i: Integer): TNtExtension; procedure ClearItems; protected constructor Create; virtual; public destructor Destroy; override; { Registers an extension. @param extensionClass Extension class to be registered. } procedure Register(extensionClass: TNtExtensionClass); { Count of the registered extensions. } property Count: Integer read GetCount; { Array of the registered extension. } property Items[i: Integer]: TNtExtension read GetItem; default; end; {$IFDEF MSWINDOWS} const KERNEL = 'kernel32.dll'; function GetUserDefaultUILanguage: WORD; stdcall; external KERNEL name 'GetUserDefaultUILanguage'; function GetSystemDefaultUILanguage: WORD; stdcall; external KERNEL name 'GetSystemDefaultUILanguage'; {$ENDIF} var ResourceDllDir: String; // Currently loaded locale. LoadedResourceLocale: String; // Previously loaded locale. If empty the current locale is the only locale that has been loaded. PreviouslyLoadedResourceLocale: String; // Resource options. ResourceOptions: TNtResourceOptions; { Variable that stores the first day of the week of the current locale. } FirstDayOfWeek: TNtDayOfWeek; { Variable that stores the first week of the year of the current locale. } FirstWeekOfYear: TNtFirstWeekOfYear; { Variable that stores current layout of the user interface. } UiLayout: TNtLayout; { Variable that stores the original language of the application. } OriginalLanguage: String; { Variable that stores the default language of the application. } DefaultLocale: String; { Variable that stores the language of the operating system. } SystemLanguage: String; implementation uses {$IFDEF MSWINDOWS} Windows, Registry, NtWindows, {$ENDIF} {$IFDEF POSIX} Posix.Unistd, Posix.SysStat, Posix.Dlfcn, {$ENDIF} {$IFDEF MACOS} Macapi.CoreFoundation, {$ENDIF} {$IFDEF DELPHI2010} IOUtils, {$ENDIF} {$IFDEF DELPHIXE} NtResource, {$ENDIF} RTLConsts; var FExtractedResourceFiles: TStringList; // TNtLanguage function TNtLanguage.GetActiveCode: String; begin if FFileName <> '' then begin Result := ExtractFileExt(FFileName); Delete(Result, 1, 1); end else Result := FCode end; function TNtLanguage.GetName(i: TNtLanguageName): String; begin Result := GetDisplayName(FCode, FId, i, FLanguageNameCase); end; class function TNtLanguage.GetBoth(const native, localize: String): String; begin Result := Format('%s - %s', [native, localize]); end; class procedure TNtLanguage.CheckCase( var value: String; languageNameCase: TNtLanguageNameCase); begin case languageNameCase of lcUpper: value := UpperCase(Copy(value, 1, 1)) + Copy(value, 2, Length(value)); lcLower: value := LowerCase(Copy(value, 1, 1)) + Copy(value, 2, Length(value)); end; end; class function TNtLanguage.GetDisplayName( const id: String; locale: Integer; languageName: TNtLanguageName; languageNameCase: TNtLanguageNameCase): String; {$IFDEF DELPHIXE} function GetNative: String; begin if id = OriginalLanguage then Result := NtResources.Originals[id] else begin Result := NtResources.Natives[id]; if Result = '' then Result := NtResources.GetStringInLanguage(id, '', id, ''); end; CheckCase(Result, languageNameCase); end; function GetLocalized: String; begin if LoadedResourceLocale = '' then Result := NtResources.Originals[id] else begin Result := NtResources.Localizeds[id]; if Result = '' then Result := NtResources.GetString('', id, ''); end; CheckCase(Result, languageNameCase); end; function GetSystem: String; begin Result := NtResources.GetStringInLanguage(SystemLanguage, '', id, ''); if Result = '' then Result := GetNative; CheckCase(Result, languageNameCase); end; {$ENDIF} begin {$IFDEF DELPHIXE} if NtResources.Enabled then begin case languageName of lnNative: Result := GetNative; lnLocalized: Result := GetLocalized; lnBoth: Result := GetBoth(GetNative, GetLocalized); lnEnglish: Result := NtResources.Originals[id]; lnSystem: Result := GetSystem; else raise Exception.Create('Not implemented'); end; end else {$ENDIF} begin {$IFDEF MSWINDOWS} Result := TNtWindows.GetDisplayName(id, locale, languageName, languageNameCase); {$ENDIF} end; end; // TNtLanguages constructor TNtLanguages.Create; begin inherited; {$IFDEF AUTOREFCOUNT} FItems := TList<TNtLanguage>.Create; {$ELSE} FItems := TList.Create; {$ENDIF} end; destructor TNtLanguages.Destroy; begin {$IFNDEF AUTOREFCOUNT} while FItems.Count > 0 do begin TObject(FItems[0]).Free; FItems.Delete(0); end; {$ENDIF} FItems.Free; inherited; end; function TNtLanguages.GetCount: Integer; begin Result := FItems.Count; end; function TNtLanguages.GetItem(i: Integer): TNtLanguage; begin Result := FItems[i]; end; function TNtLanguages.FindByFile(const fileName: String): TNtLanguage; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if SameText(Result.FileName, fileName) then Exit; end; Result := nil; end; procedure TNtLanguages.AddDefault; begin Add(DefaultLocale); end; function TNtLanguages.Add(const code: String; id: Integer; const fileName: String): TNtLanguage; begin if FindByFile(fileName) <> nil then begin Result := nil; Exit; end; Result := TNtLanguage.Create; Result.Code := code; if id > 0 then Result.Id := id else Result.Id := TNtBase.IsoToLocale(code); Result.FileName := fileName; Add(Result); end; procedure TNtLanguages.Add(language: TNtLanguage); begin FItems.Add(language); end; // TNtBase class procedure TNtBase.DisableResourceDlls; begin LoadNew(''); end; {$IFNDEF UNICODE} function LocaleToCodePage(locale: Integer): Integer; begin if locale = LANG_CHINESE then Result := 936 else Result := StrToInt(GetLocaleStr(locale, LOCALE_IDEFAULTANSICODEPAGE, '0')); end; {$ENDIF} class function TNtBase.IsLocaleCompatible(locale: Integer): Boolean; //FI:O804 begin {$IFDEF UNICODE} Result := True; {$ELSE} Result := LocaleToCodePage(locale) = Integer(GetACP); {$ENDIF} end; class function TNtBase.GetAvailable( languages: TNtLanguages; exeFileName: String; compatibleOnly: Boolean; checkVersions: Boolean): Integer; {$IFDEF DELPHIXE} var i: Integer; {$ENDIF} begin if exeFileName = '' then exeFileName := TNtBase.GetRunningFileName; {$IFDEF DELPHIXE} if NtResources.Count > 0 then begin for i := 0 to NtResources.Count - 1 do languages.Add(NtResources[i].Id); Result := NtResources.Count; end else {$ENDIF} begin {$IFDEF MSWINDOWS} Result := TNtWindows.GetAvailable(languages, exeFileName, compatibleOnly, checkVersions); {$ENDIF} {$IFDEF POSIX} Result := 0; {$ENDIF} end; end; class function TNtBase.GetAvailableCount( exeFileName: String; compatibleOnly: Boolean; checkVersions: Boolean): Integer; var languages: TNtLanguages; begin if exeFileName = '' then exeFileName := TNtBase.GetRunningFileName; languages := TNtLanguages.Create; try GetAvailable(languages, exeFileName, compatibleOnly, checkVersions); Result := languages.Count; finally languages.Free; end; end; class procedure TNtBase.CheckThatDllsExist; begin if TNtBase.GetAvailableCount = 0 then raise Exception.Create('There is no available resource file. You must created them before switching a language'); end; class function TNtBase.GetFolderPath(nFolder: Integer): String; {$IFDEF MSWINDOWS} type TSHGetFolderPath = function(hwndOwner: HWnd; nFolder: Integer; hToken: THandle; dwFlags: DWord; lpszPath: PChar): HResult; stdcall; var handle: THandle; proc: TSHGetFolderPath; buffer: array[0..MAX_PATH] of Char; {$ENDIF} begin Result := ''; {$IFDEF MSWINDOWS} handle := LoadLibrary('shfolder.dll'); try {$IFDEF UNICODE} proc := GetProcAddress(handle, 'SHGetFolderPathW'); {$ELSE} proc := GetProcAddress(handle, 'SHGetFolderPathA'); {$ENDIF} if Assigned(proc) and (proc(0, nFolder, 0, 0, buffer) = S_OK) then Result := buffer; finally FreeLibrary(handle); end; {$ENDIF} end; class function TNtBase.GetCurrentLanguageFile: String; begin Result := GetLanguageFile(GetRunningFileName, LoadedResourceLocale); end; class function TNtBase.GetLanguageFile(const exeFileName: String; const code: String): String; begin Result := ChangeFileExt(exeFileName, '.' + code); end; class function TNtBase.GetRunningFileName: String; var len: Integer; begin SetLength(Result, MAX_PATH); len := GetModuleFileName(HInstance, PChar(Result), MAX_PATH); if len > 0 then SetLength(Result, len) else Result := ''; end; class function TNtBase.MakeLangId(primaryLanguage, subLanguage: Integer): Integer; begin Result := (subLanguage shl 10) or primaryLanguage; end; class function TNtBase.LocaleToPrimary(locale: Integer): Integer; begin Result := locale and $3FF; end; class function TNtBase.LocaleToSub(locale: Integer): Integer; begin Result := (locale shr 10) and $3F; end; class procedure TNtBase.ParseLocaleId( id: String; //FI:O801 var language: String; var script: String; var country, variant: String); function GetString: String; var p1, p2: Integer; begin p1 := Pos(LOCALE_SEPARATOR, id); p2 := Pos('_', id); if (p1 > 0) and ((p2 = 0) or (p1 < p2)) then begin Result := Copy(id, 1, p1 - 1); Delete(id, 1, p1); end else if (p2 > 0) and ((p1 = 0) or (p2 < p1)) then begin Result := Copy(id, 1, p2 - 1); Delete(id, 1, p2); end else begin Result := id; id := ''; end end; function CharUpperCase(c: Char): Char; var str: String; begin str := c; Result := UpperCase(str)[1]; end; function MakeCapital(const str: String): String; begin Result := LowerCase(str); if Length(Result) > 0 then Result[1] := CharUpperCase(Result[1]); end; var str: String; begin // la[-Scri][-CO[-variant]] language := LowerCase(GetString); str := GetString; if Length(str) = 4 then begin country := GetString; variant := GetString; script := MakeCapital(str); end else begin country := str; variant := GetString; script := ''; end; country := UpperCase(country); end; class procedure TNtBase.ParseLocaleString( value: String; //FI:O801 var language, country, variant: String); function GetString: String; var p: Integer; begin p := Pos(LOCALE_SEPARATOR, value); if p > 0 then begin Result := Copy(value, 1, p - 1); Delete(value, 1, p); end else begin Result := value; value := ''; end; end; begin language := GetString; country := GetString; variant := GetString; end; class function TNtBase.IsLoaded: Boolean; begin Result := (LibModuleList <> nil) and (LibModuleList.ResInstance <> 0) and (LibModuleList.ResInstance <> LibModuleList.Instance); end; class function TNtBase.GetActiveLocale: String; {$IFDEF MSWINDOWS} {$IFDEF DELPHI2010} var hostAppName: array [0..MAX_PATH] of Char; {$ENDIF} {$ENDIF} begin {$IFDEF DELPHIXE} if NtResources.Enabled then Result := NtResources.LanguageId else {$ENDIF} if IsLoaded then begin {$IFDEF MSWINDOWS} {$IFDEF DELPHI2010} if LoadedResourceLocale = '' then begin GetModuleFileName(0, hostAppName, Length(hostAppName)); LoadedResourceLocale := ExtractFileExt(GetResourceModuleName(hostAppName, hostAppName)); Delete(LoadedResourceLocale, 1, 1); end; {$ENDIF} {$ENDIF} Result := LoadedResourceLocale; end else Result := DefaultLocale; end; class function TNtBase.GetResourceInstance: THandle; begin if LibModuleList <> nil then Result := LibModuleList.ResInstance else Result := HInstance; end; class function TNtBase.GetDefaultLanguage: String; begin {$IFDEF MSWINDOWS} Result := GetLocaleStr(GetUserDefaultLCID, LOCALE_SISO639LANGNAME, ''); {$ELSE} Result := ''; {$ENDIF} end; class function TNtBase.GetDefaultLocale: String; begin {$IFDEF MSWINDOWS} Result := GetLocaleStr(GetUserDefaultLCID, LOCALE_SISO639LANGNAME, '') + '-' + GetLocaleStr(GetUserDefaultLCID, LOCALE_SISO3166CTRYNAME, ''); {$ELSE} Result := ''; {$ENDIF} end; class function TNtBase.GetUserLanguage: Integer; begin {$IFDEF MSWINDOWS} Result := GetUserDefaultUILanguage; {$ELSE} Result := 0; {$ENDIF} end; class function TNtBase.GetSystemLanguage: Integer; begin {$IFDEF MSWINDOWS} Result := GetSystemDefaultUILanguage; {$ELSE} Result := 0; {$ENDIF} end; class function TNtBase.LocaleToIsoCode(locale: Integer): String; begin {$IFDEF MSWINDOWS} Result := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, ''); if TNtBase.LocaleToSub(locale) <> SUBLANG_NEUTRAL then Result := Result + LOCALE_SEPARATOR + GetLocaleStr(locale, LOCALE_SISO3166CTRYNAME, ''); {$ELSE} Result := ''; {$ENDIF} end; {$IFDEF MSWINDOWS} var enumLanguage: String; enumCountry: String; enumLocale: Integer; function Iso639EnumProc(localeString: PChar): Integer; stdcall; var locale: Integer; str, language, country: String; begin str := localeString; locale := StrToInt('$' + str); Result := 1; language := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, ''); country := GetLocaleStr(locale, LOCALE_SISO3166CTRYNAME, ''); if (CompareText(language, enumLanguage) = 0) and ((enumCountry = '') or SameText(country, enumCountry)) then begin if enumCountry = '' then enumLocale := TNtBase.LocaleToPrimary(locale) else enumLocale := locale; Result := 0; end; end; {$ENDIF} class function TNtBase.IsoLanguageToLocale( const language: String; const country: String): Integer; begin {$IFDEF MSWINDOWS} enumLanguage := language; enumCountry := country; enumLocale := 0; EnumSystemLocales(@Iso639EnumProc, LCID_SUPPORTED); Result := enumLocale; {$ELSE} Result := 0; {$ENDIF} end; class function TNtBase.IsoToLocale(const locale: String): Integer; begin {$IFDEF MSWINDOWS} Result := TNtWindows.CodeToId(locale) {$ELSE} Result := 0; {$ENDIF} end; {$IFDEF MSWINDOWS} class function TNtBase.LocaleToExtension(locale: Integer): String; begin if locale = 0 then Result := '' else begin Result := GetLocaleStr(locale, LOCALE_SABBREVLANGNAME, ''); if TNtBase.LocaleToSub(locale) = SUBLANG_NEUTRAL then Delete(Result, Length(Result), 1); end; end; {$ENDIF} {$IFDEF POSIX} function LoadModule(moduleName, resModuleName: string; checkOwner: Boolean): HModule; var st1, st2: _stat; moduleFileName, resModuleFileName: UTF8String; begin Result := 0; moduleFileName := UTF8Encode(moduleName); if checkOwner and (stat(MarshaledAString(moduleFileName), st1) = -1) then Exit; resModuleFileName := UTF8Encode(resModuleName); if (not checkOwner) or ((stat(MarshaledAString(resModuleFileName), st2) <> -1) and (st1.st_uid = st2.st_uid) and (st1.st_gid = st2.st_gid)) then begin Result := HModule(dlopen(MarshaledAString(resModuleFileName), RTLD_LAZY)); end; end; {$ENDIF} class procedure TNtBase.SetResourceDllDir(const value: String; localeSelect: TLocaleSelect); begin ResourceDllDir := value; SetInitialLocale(localeSelect); end; class procedure TNtBase.SetInitialLocale( localeSelect: TLocaleSelect; const defaultLocale: String); {$IFDEF MSWINDOWS} var fileName: String; function GetString(lcType: LCTYPE): String; var len: Integer; begin SetLength(Result, 7); len := GetLocaleInfo(GetThreadLocale, lcType, @Result[1], Length(Result)); Result := Copy(Result, 1, len); while (Result <> '') and (Result[Length(Result)] = #0) do Delete(Result, Length(Result), 1); end; procedure SetLocale(const value: String); begin TNtBase.LoadNew(value); end; function ProcessLocale(const value: String): Boolean; begin if TNtBase.ResourceFileExist(fileName, value) or (value = DefaultLocale) then begin SetLocale(value); Result := True; end else Result := False; end; function ProcessLocales(const value: String): Boolean; var i: Integer; id: String; ids: TStringList; begin ids := TStringList.Create; try ids.Delimiter := ','; ids.DelimitedText := value; for i := 0 to ids.Count - 1 do begin id := ids[i]; if (id <> '') and (TNtBase.ResourceFileExist(fileName, id) or (id = DefaultLocale)) then begin SetLocale(id); Result := True; Exit; end end; Result := False; finally ids.Free; end; end; var id, language, country: String; {$ENDIF} begin //FI:C101 {$IFDEF MSWINDOWS} fileName := ParamStr(0); if defaultLocale <> '' then NtBase.DefaultLocale := defaultLocale; {$IFDEF DELPHI2010} // Check if there is a resource DLL matching the locale override. id := GetLocaleOverride(fileName); if id <> '' then begin if ResourceDllDir = '' then Exit; if ProcessLocale(id) then Exit; end; // Check if there is a resource DLL matching the default locale. if localeSelect = lsUI then begin // UI match if ProcessLocales(GetUILanguages(GetUserDefaultUILanguage)) then Exit; if ProcessLocales(GetUILanguages(GetSystemDefaultUILanguage)) then Exit; id := GetLocaleStr(GetUserDefaultUILanguage, LOCALE_SABBREVLANGNAME, ''); if ProcessLocale(id) then Exit; Delete(id, 2, 1); if ProcessLocale(id) then Exit; end else {$ENDIF} begin // Regionale settings match language := GetString(LOCALE_SISO639LANGNAME); country := GetString(LOCALE_SISO3166CTRYNAME); if ProcessLocale(language + '-' + country) then Exit; if ProcessLocale(language) then Exit; id := GetString(LOCALE_SABBREVLANGNAME); if ProcessLocale(id) then Exit; Delete(id, 3, 1); ProcessLocale(id); end; {$ENDIF} end; class function TNtBase.ResourceFileExist(const fileName, id: String): Boolean; begin Result := GetResourceFile(fileName, id) <> ''; end; class function TNtBase.GetResourceFile(const fileName, id: String): String; var ext: String; begin ext := '.' + id; // Look first from resource DLL dir (if specified) if ResourceDllDir <> '' then begin Result := ResourceDllDir + '\' + ChangeFileExt(ExtractFileName(fileName), ext); if FileExists(Result) then Exit; Result := ExtractFileDir(fileName) + '\' + ResourceDllDir + '\' + ChangeFileExt(ExtractFileName(fileName), ext); if FileExists(Result) then Exit; end; // Look then from the application or library dir Result := ChangeFileExt(fileName, ext); if FileExists(Result) then Exit; // Look finally from Soluling's personal directory such as C:\Users\<user>\Documents\Soluling {$IFDEF MSWINDOWS} Result := GetFolderPath(NT_CSIDL_PERSONAL) + '\' + APPLICATION_DIR + '\' + ChangeFileExt(ExtractFileName(fileName), ext); if FileExists(Result) then Exit; {$ENDIF} Result := ''; end; class function TNtBase.LoadNew(code: String; fileName: String): HModule; function LoadResourceDll(const fileName, ext: String): HModule; var dllFileName: String; begin dllFileName := GetResourceFile(fileName, ext); {$IFDEF MSWINDOWS} Result := LoadLibraryEx(PChar(dllFileName), 0, LOAD_LIBRARY_AS_DATAFILE); {$ENDIF} {$IFDEF POSIX} Result := LoadModule(fileName, dllFileName, True); {$ENDIF} end; var p: Integer; newInst: HMODULE; resourceFileNameGiven: Boolean; newResourceLocale: String; module: PLibModule; buffer: array[0..260] of Char; begin //FI:C101 {$IFDEF MSWINDOWS} // ResStringCleanupCache was added in Delphi 10.4.2 {$IF CompilerVersion = 34} {$IF Declared(RTLVersion1042)} ResStringCleanupCache; {$IFEND} {$IFEND} {$IFDEF DELPHI11} ResStringCleanupCache; {$ENDIF} {$ENDIF} Result := 0; module := LibModuleList; newResourceLocale := ''; while module <> nil do begin if code = '' then begin if module.ResInstance <> module.Instance then FreeLibrary(module.ResInstance); module.ResInstance := module.Instance; if Result = 0 then Result := module.Instance; end else begin if fileName = '' then begin GetModuleFileName(module.Instance, buffer, SizeOf(buffer)); fileName := buffer; resourceFileNameGiven := False; end else resourceFileNameGiven := True; if FileExists(fileName) then begin if resourceFileNameGiven then newInst := LoadResourceDll(fileName, '') else begin newInst := LoadResourceDll(fileName, code); if newInst = 0 then begin p := Pos(LOCALE_SEPARATOR, code); if p > 0 then begin Delete(code, p, Length(code)); newInst := LoadResourceDll(fileName, code); end else if Length(code) = 3 then begin Delete(code, Length(code), 1); newInst := LoadResourceDll(fileName, code); end end; end; if newInst <> 0 then begin if module.ResInstance <> module.Instance then FreeLibrary(module.ResInstance); module.ResInstance := newInst; if Result = 0 then Result := newInst; newResourceLocale := code; end else begin module.ResInstance := module.Instance; end; end; end; module := module.Next; fileName := ''; end; PreviouslyLoadedResourceLocale := LoadedResourceLocale; LoadedResourceLocale := newResourceLocale; end; function GetFileDateTime(const fileName: String): TDateTime; {$IFNDEF DELPHI2006} var time: Integer; {$ENDIF} begin {$IFDEF DELPHI2006} FileAge(fileName, Result); {$ELSE} time := FileAge(fileName); if time > 0 then Result := FileDateToDateTime(time) else Result := 0.0; {$ENDIF} end; procedure SetFileDateTime(const fileName: String; date: TDateTime); begin FileSetDate(fileName, DateTimeToFileDate(date)); end; {$IFDEF MSWINDOWS} var enumResourceFileCount: Integer; enumFileName: String; enumOptions: TExtractOptions; enumFileDate: TDateTime; function EnumExtractResourceNamesProc( instance: THandle; resType: PChar; resName: PChar; param: DWord): Bool; stdcall; //FI:O804 var size: Integer; unload: Boolean; str, fileName: String; pointer: PByte; resource: THandle; stream: TFileStream; begin str := resName; fileName := ChangeFileExt(enumFileName, '.' + str); if (not FileExists(fileName) or not (eoCheckDate in enumOptions) or (GetFileDateTime(fileName) <> enumFileDate)) then begin unload := resName = LoadedResourceLocale; if unload then TNtBase.LoadNew; resource := FindResource(instance, PChar(resName), PChar(resType)); pointer := LockResource(LoadResource(instance, resource)); size := SizeofResource(instance, resource); SysUtils.DeleteFile(fileName); stream := TFileStream.Create(fileName, fmCreate); try stream.Write(pointer^, size); finally stream.Free; end; SetFileDateTime(fileName, enumFileDate); if unload then TNtBase.LoadNew(resName); if eoRemoveFiles in enumOptions then FExtractedResourceFiles.Add(fileName); Inc(enumResourceFileCount); end; Result := True; end; {$ENDIF} class procedure TNtBase.DeleteExtractedFiles; var libModule: PLibModule; begin if (FExtractedResourceFiles <> nil) and (FExtractedResourceFiles.Count > 0) then begin libModule := LibModuleList; while libModule <> nil do begin if libModule.ResInstance <> libModule.Instance then FreeLibrary(libModule.ResInstance); libModule.ResInstance := libModule.Instance; libModule := libModule.Next; end; while FExtractedResourceFiles.Count > 0 do begin SysUtils.DeleteFile(FExtractedResourceFiles[0]); FExtractedResourceFiles.Delete(0); end; end; end; class function TNtBase.ExtractFiles( options: TExtractOptions; resourceName: String): Integer; {$IFDEF MSWINDOWS} var dir: String; {$ENDIF} begin {$IFDEF MSWINDOWS} if HasWriteAccess(ExtractFileDir(TNtBase.GetRunningFileName)) then enumFileName := TNtBase.GetRunningFileName else begin dir := TNtBase.GetFolderPath(NT_CSIDL_PERSONAL) + '\' + APPLICATION_DIR; CreateDir(dir); enumFileName := dir + '\' + ExtractFileName(TNtBase.GetRunningFileName); end; if resourceName = '' then resourceName := APPLICATION_RESOURCE; enumResourceFileCount := 0; enumFileDate := GetFileDateTime(TNtBase.GetRunningFileName); enumOptions := options; EnumResourceNames(HInstance, PChar(resourceName), @EnumExtractResourceNamesProc, 0); Result := enumResourceFileCount; {$ENDIF} {$IFDEF POSIX} Result := 0; {$ENDIF} if not TNtBase.IsLoaded or (FExtractedResourceFiles.Count > 0) then LoadNew(GetDefaultLocale); end; {$IFDEF MSWINDOWS} class function TNtBase.HasWriteAccess(const dir: String): Boolean; var f: TextFile; fileName, parentDir: String; {$IFNDEF DELPHI2010} buffer: array[0..MAX_PATH] of Char; {$ENDIF} begin try if DirectoryExists(dir) then begin {$IFDEF DELPHI2010} fileName := TPath.GetTempFileName; {$ELSE} GetTempFileName(PChar(dir), 'nt', 0, buffer); fileName := buffer; {$ENDIF} AssignFile(f, fileName); Rewrite(f); try Write(f, 10); finally Close(f); SysUtils.DeleteFile(fileName); end; end else begin parentDir := ExtractFileDir(dir); try ChDir(parentDir); CreateDir(dir); finally RemoveDir(dir); end; end; Result := True; except Result := False; end; end; {$ENDIF} // TNtResources class function TNtResources.DoesExist( resType, resName: PChar; instance: THandle): Boolean; begin if instance = 0 then instance := TNtBase.GetResourceInstance; try Result := FindResource(instance, resName, resType) <> 0; except Result := False; end; end; class function TNtResources.GetResourceStream( resType, resName: PChar; instance: THandle): TResourceStream; begin if instance = 0 then instance := TNtBase.GetResourceInstance; if DoesExist(resType, resName, instance) then Result := TResourceStream.Create(instance, resName, resType) else Result := nil; end; {$IFDEF DELPHI2007} class function TNtResources.LoadResource( resType, resName: PChar; instance: THandle = 0): TBytes; var stream: TResourceStream; begin if instance = 0 then instance := TNtBase.GetResourceInstance; if DoesExist(resType, resName, instance) then begin stream := TResourceStream.Create(instance, resName, resType); try SetLength(Result, stream.Size); stream.Read(Result[0], stream.Size); finally stream.Free; end; end else SetLength(Result, 0); end; {$ENDIF} // TNtLocaleRegistry class procedure TNtLocaleRegistry.SetCurrentDefaultLocale; var fileName: array[0..MAX_PATH] of Char; begin if GetModuleFileName(0, fileName, SizeOf(fileName)) > 0 then SetDefaultLocale(fileName, LoadedResourceLocale); end; class function TNtLocaleRegistry.GetCurrentDefaultLocale: String; var fileName: array[0..MAX_PATH] of Char; begin if GetModuleFileName(0, fileName, SizeOf(fileName)) > 0 then Result := GetDefaultLocale(fileName) else Result := ''; end; class procedure TNtLocaleRegistry.SetDefaultLocale(const fileName: String; code: String); {$IFDEF MSWINDOWS} var reg: TRegistry; {$ENDIF} begin {$IFDEF MSWINDOWS} reg := TRegistry.Create; try reg.RootKey := HKEY_CURRENT_USER; if reg.OpenKey(LOCALE_OVERRIDE_KEY, True) then begin if code = '' then code := ' '; reg.WriteString(fileName, code); end; finally reg.Free; end; {$ENDIF} end; class function TNtLocaleRegistry.GetDefaultLocale(const fileName: String): String; {$IFNDEF DELPHIXE} var keyExists: Boolean; {$ENDIF} begin {$IFDEF DELPHIXE} Result := GetLocaleOverride(fileName); {$ELSE} Result := GetDefaultLocale(fileName, keyExists); {$ENDIF} end; class function TNtLocaleRegistry.GetDefaultLocale(const fileName: String; out keyExists: Boolean): String; {$IFDEF MSWINDOWS} var reg: TRegistry; function Open(const key: String): Boolean; begin if key <> '' then begin reg.RootKey := HKEY_CURRENT_USER; Result := reg.OpenKey(key, False); if not Result then begin reg.RootKey := HKEY_LOCAL_MACHINE; Result := reg.OpenKey(key, False); end; end else Result := False; end; {$ENDIF} begin {$IFDEF MSWINDOWS} Result := ''; keyExists := False; reg := TRegistry.Create; try if Open(LOCALE_OVERRIDE_KEY) or Open(OLD_LOCALE_OVERRIDE_KEY) or Open(OLDEST_LOCALE_OVERRIDE_KEY) then begin if reg.ValueExists(fileName) then begin Result := reg.ReadString(fileName); keyExists := True; end; end; finally reg.Free; end; {$ENDIF} end; class function TNtLocaleRegistry.ClearCurrentDefaultLocale: Boolean; var fileName: array[0..MAX_PATH] of Char; begin if GetModuleFileName(0, fileName, SizeOf(fileName)) = 0 then Result := False else Result := ClearDefaultLocale(fileName); end; class function TNtLocaleRegistry.ClearDefaultLocale(const fileName: String): Boolean; {$IFDEF MSWINDOWS} var reg: TRegistry; {$ENDIF} begin Result := False; {$IFDEF MSWINDOWS} reg := TRegistry.Create; try reg.RootKey := HKEY_CURRENT_USER; if reg.OpenKey(LOCALE_OVERRIDE_KEY, False) then begin Result := reg.ValueExists(fileName); reg.DeleteValue(fileName); end; finally reg.Free; end; {$ENDIF} end; // TNtConvert class function TNtConvert.AnsiToUnicode(const str: RawByteString; codePage: Integer): UnicodeString; var len: Integer; begin {$IFDEF UNICODE} if codePage = 0 then codePage := StringCodePage(str); if codePage = 0 then codePage := DefaultSystemCodePage; {$ENDIF} if str = '' then Result := '' else begin {$IFDEF DELPHIXE3} len := UnicodeFromLocaleChars(codePage, 0, MarshaledAString(str), -1, nil, 0); {$ELSE} len := MultiByteToWideChar(codePage, 0, PAnsiChar(str), -1, nil, 0); {$ENDIF} if len > 1 then begin SetLength(Result, len - 1); {$IFDEF DELPHIXE3} UnicodeFromLocaleChars(codePage, 0, MarshaledAString(str), -1, PWideChar(Result), len); {$ELSE} MultiByteToWideChar(codePage, 0, PAnsiChar(str), -1, PWideChar(Result), len); {$ENDIF} end else Result := ''; end; end; class function TNtConvert.UnicodeToAnsi(const str: UnicodeString; codePage: Integer): RawByteString; var len: Integer; begin {$IFDEF UNICODE} if codePage = 0 then codePage := DefaultSystemCodePage; {$ENDIF} if str = '' then Result := '' else begin {$IFDEF DELPHIXE3} len := LocaleCharsFromUnicode(codePage, 0, PWideChar(str), -1, nil, 0, nil, nil); {$ELSE} len := WideCharToMultiByte(codePage, 0, PWideChar(str), -1, nil, 0, nil, nil); {$ENDIF} if len > 1 then begin SetLength(Result, len - 1); {$IFDEF DELPHIXE3} LocaleCharsFromUnicode(codePage, 0, PWideChar(str), -1, MarshaledAString(Result), len, nil, nil); {$ELSE} WideCharToMultiByte(codePage, 0, PWideChar(str), -1, PAnsiChar(Result), len, nil, nil); {$ENDIF} end else Result := ''; end; {$IFDEF UNICODE} SetCodePage(Result, codePage, False); {$ENDIF} end; {$IFDEF DELPHI2007} class function TNtConvert.BytesToRawByteString(bytes: TBytes): RawByteString; begin SetLength(Result, Length(bytes)); Move(bytes[0], Result[1], Length(bytes)); end; class function TNtConvert.RawByteStringToBytes(str: RawByteString): TBytes; begin SetLength(Result, Length(str)); Move(str[1], Result[0], Length(str)); end; class function TNtConvert.BytesToUnicode(str: TBytes; codePage: Integer = 0): UnicodeString; begin Result := AnsiToUnicode(BytesToRawByteString(str), codePage); end; class function TNtConvert.UnicodeToBytes(const str: UnicodeString; codePage: Integer = 0): TBytes; begin Result := RawByteStringToBytes(UnicodeToAnsi(str, codePage)); end; {$ENDIF} // TNtExtensions constructor TNtExtensions.Create; begin inherited; {$IFDEF AUTOREFCOUNT} FItems := TList<TNtExtension>.Create; {$ELSE} FItems := TList.Create; {$ENDIF} end; destructor TNtExtensions.Destroy; begin ClearItems; FItems.Free; inherited; end; procedure TNtExtensions.ClearItems; begin {$IFDEF AUTOREFCOUNT} FItems.Clear; {$ELSE} while FItems.Count > 0 do begin TObject(FItems[0]).Free; FItems.Delete(0); end; {$ENDIF} end; function TNtExtensions.GetCount: Integer; begin Result := FItems.Count; end; function TNtExtensions.GetItem(i: Integer): TNtExtension; begin Result := FItems[i]; end; procedure TNtExtensions.Register(extensionClass: TNtExtensionClass); var i: Integer; begin for i := 0 to Count - 1 do if Items[i].ClassType = extensionClass then Exit; FItems.Add(extensionClass.Create); end; initialization FExtractedResourceFiles := TStringList.Create; // Workaround for the resource string cache bug of Delphi 10.4.1 {$IF CompilerVersion = 34} {$IF Declared(RTLVersion1041)} {$IF not Declared(RTLVersion1042)} LoadResStringFunc := nil; {$IFEND} {$IFEND} {$IFEND} UiLayout := laLeftToRight; DefaultLocale := 'en'; OriginalLanguage := 'en'; finalization TNtBase.DeleteExtractedFiles; FExtractedResourceFiles.Free; end.
unit uVolMain; (****************************************************************** How To Detect Multimedia Devices and Set their Volume by Alex Simonetti Abreu - simonet@bhnet.com.br ******************************************************************* The purpose of the Hot-To Project is to teach Delphi developers how it is possible to detect the number and names of auxiliary multimedia devices and, optionally, set their volume using a track bar (or any other similar) component. The point why there are two applications for this project is because you cannot set a device's (for example, the CD) volume if you don't know it's device ID (for most systems, the CD player has the device ID of 2, but that can change). The method for setting the volume (basically its math) was written by me a long time ago (when I was still getting started in VB), and still has its flaws. I left it here the way it was orinally (but not in Basic, of course!) and haven't given it too much thought since then. If you find a better way for setting the correct values for the low and high words that make up the value to be passed to AuxSetVolume, please let me know. This application was tested on a Pentium with a Creative Labs Sound Blaster AWE 64 and a total of 7 devices were detected: Wave, Midi, CD, Line In, Mic, Master (for the master volume) and PC speaker. To check if it works for real (besides "hearing" the volume changes), open Windows' volume taskbar control and this application at the same time. By changing the volume in the application, you'll see how Windows reacts to those changes. Best regards. Alex Simonetti Abreu Belo Horizonte, MG, Brazil August, 1998 *) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls; type TFrmMMVolMain = class(TForm) RadioGroup1: TRadioGroup; Panel1: TPanel; GroupBox5: TGroupBox; lbName: TLabel; tbVolLeft: TTrackBar; tbVolRight: TTrackBar; cblock: TCheckBox; Label1: TLabel; Label2: TLabel; Button1: TButton; Panel2: TPanel; Label3: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; procedure FormCreate(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SetVolume(Sender : TObject); procedure Label6Click(Sender: TObject); procedure Label7Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmMMVolMain: TFrmMMVolMain; implementation uses ShellAPI, MMSystem; {$R *.DFM} procedure TFrmMMVolMain.FormCreate(Sender: TObject); var cct, NumAux : shortint; AuxCaps : TAuxCaps; begin // This will list all multimedia devices and add their names to the // radio group that allows for multimedia device selection. // Only Auxiliary devices will be displayed (not the main ones). NumAux := AuxGetNumDevs; if (NumAux <= 0) then begin application.messagebox('No multimedia devices are present', 'Multimedia Volume', MB_ICONHAND + MB_OK); exit; end; RadioGroup1.items.beginupdate; RadioGroup1.items.clear; for cct:= 0 to (NumAux-1) do begin auxGetDevCaps(cct, @AuxCaps, sizeof(AuxCaps)); RadioGroup1.items.add(AuxCaps.szPname); end; RadioGroup1.items.EndUpdate; RAdioGroup1.itemindex := 0; end; procedure TFrmMMVolMain.RadioGroup1Click(Sender: TObject); var NumAux : longint; AuxCaps : TAuxCaps; begin NumAux := RadioGroup1.itemindex; // Read the device capabilities for the selected device auxGetDevCaps(NumAux, @AuxCaps, sizeof(AuxCaps)); with AuxCaps do begin if (dwSupport and AUXCAPS_LRVOLUME) > 0 then begin // This device supports Left & Right volume control cbLock.enabled := true; end else begin cbLock.checked := true; cbLock.enabled := false; end; if (dwSupport and AUXCAPS_VOLUME) > 0 then begin // This device supports volume control GroupBox5.enabled := true; lbName.caption := RadioGroup1.items[RadioGroup1.itemindex]; end else begin GroupBox5.enabled := false; lbName.caption := 'Volume control not supported'; end; end; end; procedure TFrmMMVolMain.Button1Click(Sender: TObject); begin Close; end; procedure TFrmMMVolMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmMMVolMain.SetVolume(Sender : TObject); var xlow, xhigh : longint; vol : DWORD; begin // This is the routine that actually sets the volume of the // multimedia device selected. // I already planned for the DeviceID of the aux device to be // the same as its index in the RadioGroupBox (see the form's OnCreate event). if cblock.checked then begin if sender = tbVolLeft then tbVolRight.Position := tbVolLeft.Position; if sender = tbVolRight then tbVolLeft.position := tbVolRight.Position; end; // The left volume is in the low order word of the value passed to // AuxSetVolume, and the right volume word is in the high order word. xlow := abs(tbVolLeft.position+1)*4096 - 1; xhigh := abs(tbVolRight.position+1)*4096 shl 16 - 1; if abs(tbVolLeft.position)=0 then xlow:=0; if abs(tbVolRight.position)=0 then xhigh:=0; if abs(tbVolRight.position)=15 then xhigh:=$FFFF0000; if abs(tbVolLeft.position)=15 then xlow:=$FFFF; vol := xlow + xhigh; auxsetvolume(RadioGroup1.ItemIndex, vol); end; procedure TFrmMMVolMain.Label6Click(Sender: TObject); begin // Bonus tip: // How to send e-mail using Delphi without using MAPI. // The line below will open the default e-mail program with a new messge addresses to // me (simonet@bhnet.com.br) and a subject of "Thanks for the Multimedia project" ShellExecute(handle, 'open', 'mailto:simonet@bhnet.com.br?Subject=Thanks for the Multimedia project ', nil, nil, SW_SHOWNORMAL); end; procedure TFrmMMVolMain.Label7Click(Sender: TObject); begin // Bonus tip: // The line below will open the default Internet browser in the selected page // if there's not default application registered to process http: calls, // nothing (or maybe an error) will happen ShellExecute(handle, 'open', 'http://www.bhnet.com.br/~simonet', nil, nil, SW_SHOWNORMAL); end; end.
{ *********************************************************************** } { } { AriaNg WKE 自动化浏览器项目单元 } { } { 设计:Lsuper 2017.09.11 } { 备注: } { 审核: } { } { Copyright (c) 1998-2019 Super Studio } { } { *********************************************************************** } unit Aria2ControlFrm; interface uses System.SysUtils, Vcl.Forms, Langji.Wke.Webbrowser; type TAria2ControlForm = class(TForm) procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private FWebBrowser: TWkeWebBrowser; private procedure ExtractWebIndexFile(const AFile: string); private procedure WkeWebBrowser1TitleChange(Sender: TObject; sTitle: string); end; var Aria2ControlForm: TAria2ControlForm; implementation {$R *.dfm} {$R *.res} { index.html } uses System.Classes, System.Types, Vcl.Controls, Langji.Wke.Lib; { TAria2ControlForm } procedure TAria2ControlForm.ExtractWebIndexFile(const AFile: string); var F: string; S: TResourceStream; begin F := ExtractFileDir(AFile); if not DirectoryExists(F) then ForceDirectories(F); if not DirectoryExists(F) then Exit; S := TResourceStream.Create(HInstance, 'INDEX', RT_RCDATA); with TFileStream.Create(AFile, fmCreate) do try CopyFrom(S, S.Size); finally Free; S.Free; end; end; procedure TAria2ControlForm.FormCreate(Sender: TObject); const defLocalStoragePathFmt = '%s\LocalStorage'; var S: string; begin S := GetModuleName(0); S := ExtractFileDir(S); wkeLibFileName := Format('%s\WKE.dll', [S]); FWebBrowser := TWkeWebBrowser.Create(Self); FWebBrowser.Parent := Self; FWebBrowser.Align := alClient; S := Format(defLocalStoragePathFmt, [S]); if not DirectoryExists(S) then ForceDirectories(S); FWebBrowser.CookiePath := S; FWebBrowser.CookieEnabled := True; FWebBrowser.LocalStoragePath := S; FWebBrowser.OnTitleChange := WkeWebBrowser1TitleChange; end; procedure TAria2ControlForm.FormShow(Sender: TObject); var F: string; begin F := GetModuleName(0); F := ExtractFilePath(F); F := F + 'App\index.html'; if not FileExists(F) then ExtractWebIndexFile(F); if FileExists(F) then FWebBrowser.LoadFile(F); FWebBrowser.ZoomFactor := Screen.PixelsPerInch / 96; end; procedure TAria2ControlForm.WkeWebBrowser1TitleChange(Sender: TObject; sTitle: string); begin Caption := sTitle; end; end.
unit uArrayListOfPoint; interface uses uArrayList, uPoint; { Automatic dynamic points array } type ArrayListOfPoint = class(ArrayList) public procedure add(p: Point); overload; procedure put(p: Point; index: integer); overload; function remove(index: integer): Point; overload; procedure remove(p: Point); overload; function get(index: integer): Point; overload; function find(p: Point): integer; overload; end; implementation // ArrayListOfPoint procedure ArrayListOfPoint.add(p: Point); begin inherited add(p); end; // ArrayListOfPoint procedure ArrayListOfPoint.put(p: Point; index: integer); begin inherited put(p, index); end; // ArrayListOfPoint function ArrayListOfPoint.remove(index: integer): Point; begin remove := inherited remove(index) as Point; end; // ArrayListOfPoint procedure ArrayListOfPoint.remove(p: Point); var i: integer; begin for i := 0 to size() - 1 do begin if (arr[i] as Point) = p then begin remove(i); break; end; end; end; // ArrayListOfPoint function ArrayListOfPoint.get(index: integer): Point; begin get := inherited get(index) as Point; end; // ArrayListOfPoint function ArrayListOfPoint.find(p: Point): integer; var i: integer; begin find := -1; for i := 0 to len - 1 do if p = get(i) then begin find := i; break; end; end; end.
unit uFrmSobre; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, jpeg, ExtCtrls, IniFiles; type TfrmSobre = class(TForm) Memo1: TMemo; Image1: TImage; procedure FormCreate(Sender: TObject); private { Private declarations } function GetBuildInfo(prog: String): String; function DSiFileSize(const fileName: string): int64; public { Public declarations } end; var frmSobre: TfrmSobre; implementation {$R *.dfm} procedure TfrmSobre.FormCreate(Sender: TObject); begin Memo1.Lines.Add('ServiSoft Informática Ltda.'); Memo1.Lines.Add('Fone: (51) 3598-6584'); Memo1.Lines.Add(''); Memo1.Lines.Add('Suporte:'); Memo1.Lines.Add(' Cleomar - Cel.: (51) 3598-6584 / 9942-0952'); Memo1.Lines.Add('Skype: cleomar_pacheco@hotmail.com'); Memo1.Lines.Add('Email: cleomar@servisoft.com.br'); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add('Versão para SQL Server'); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add('Versão: ' + GetBuildInfo(GetCurrentDir + '\CEBI.EXE')); end; function TfrmSobre.DSiFileSize(const fileName: string): int64; var fHandle: DWORD; begin fHandle := CreateFile(PChar(fileName), 0, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if fHandle = INVALID_HANDLE_VALUE then Result := -1 else try Int64Rec(Result).Lo := GetFileSize(fHandle, @Int64Rec(Result).Hi); finally CloseHandle(fHandle); end; end; function TfrmSobre.GetBuildInfo(prog: String): String; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; V1, V2, V3, V4: Word; begin VerInfoSize := GetFileVersionInfoSize(PChar(prog),Dummy); GetMem(VerInfo,VerInfoSize); GetFileVersionInfo(PChar(prog),0,VerInfoSize,VerInfo); VerQueryValue(VerInfo,'',Pointer(VerValue),VerValueSize); with VerValue^ do begin V1 := dwFileVersionMS shr 16; V2 := dwFileVersionMS and $FFFF; V3 := dwFileVersionLS shr 16; V4 := dwFileVersionLS and $FFFF; end; FreeMem(VerInfo,VerInfoSize); result := Copy(IntToStr(100 + v1),3,2) + '.' + Copy(IntToStr(100 + V2),2,2) + '.' + Copy(IntToStr(100 + V3),2,2) + '.' + Copy(IntToStr(100 + V4),2,2); end; end.
unit ufrmSerialNumberHistory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uDialogParent, siComp, siLangRT, StdCtrls, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, Buttons, CheckLst, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ComCtrls, ADODB; type TviewSerialNumberHistory = class(TDialogParent) Panel3: TPanel; pgSerial: TPageControl; tsOnSale: TTabSheet; Panel4: TPanel; tsInventory: TTabSheet; grdInvSerial: TcxGrid; grdInvSerialDBTableView: TcxGridDBTableView; grdInvSerialDBTableViewName: TcxGridDBColumn; grdInvSerialDBTableViewSerial: TcxGridDBColumn; grdInvSerialLevel: TcxGridLevel; tsTransfer: TTabSheet; Label4: TLabel; clbSerial: TCheckListBox; Panel5: TPanel; Panel6: TPanel; Panel7: TPanel; Panel8: TPanel; Panel9: TPanel; Panel10: TPanel; btRemove: TSpeedButton; gridSerialOnSale: TcxGrid; gridSerialOnSaleDBTableView: TcxGridDBTableView; gridSerialOnSaleDBTableViewSerialNumber: TcxGridDBColumn; gridSerialOnSaleDBTableViewIdentificationNumber: TcxGridDBColumn; gridSerialOnSaleLevel: TcxGridLevel; gridSerialNumber: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridDBColumn2: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; dsSerialCurrent: TDataSource; dsSerialNumber: TDataSource; procedure dsSerialCurrentDataChange(Sender: TObject; Field: TField); procedure AplicarClick(Sender: TObject); procedure dsSerialNumberDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } function start(id_preinventory: Integer): Boolean; end; implementation uses uDm, uDMParent, SerialNumberCls; {$R *.dfm} { TviewSerialNumberHistory } function TviewSerialNumberHistory.start(id_preinventory: Integer): Boolean; var objSerialNumber: TSerialNumberFromPreSale; begin objSerialNumber := TSerialNumberFromPreSale.Create(-1, dm.fStore.ID, id_preinventory, 1); objSerialNumber.Connection := dm.ADODBConnect; dsSerialCurrent.DataSet := objSerialNumber.getSerial(id_preinventory); dsSerialNumber.DataSet := objSerialNumber.getserialRecorded; result := ( showModal = mrOK ); end; procedure TviewSerialNumberHistory.dsSerialCurrentDataChange( Sender: TObject; Field: TField); begin inherited; btRemove.Enabled := true; end; procedure TviewSerialNumberHistory.AplicarClick(Sender: TObject); begin inherited; close; end; procedure TviewSerialNumberHistory.dsSerialNumberDataChange( Sender: TObject; Field: TField); begin inherited; btRemove.Enabled := false; end; end.