text
stringlengths
14
6.51M
{ This file is part of DBGP Plugin for Notepad++ Copyright (C) 2007 Damjan Zobo Cvetko 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. } unit NppForms; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Forms, Vcl.Dialogs, NppPlugin; type TNppForm = class(TForm) private { Private declarations } protected procedure DoClose(var Action: TCloseAction); override; public { Public declarations } Npp: TNppPlugin; DefaultCloseAction: TCloseAction; constructor Create(NppParent: TNppPlugin); overload; constructor Create(AOwner: TNppForm); overload; function Confirmed(const ACaption,ATitle: nppString): boolean; procedure MessageWarning(const ATitle, ACaption: nppString); procedure MessageError(const ATitle,ACaption: nppString); procedure MessageSimple(const ATitle,ACaption: nppString); destructor Destroy; override; end; var NppForm: TNppForm; implementation {$R *.dfm} { TNppForm } constructor TNppForm.Create(NppParent: TNppPlugin); begin Npp := NppParent; DefaultCloseAction := caNone; inherited Create(nil); // We figure right now this does more damage than good. // So let the main transalte and dispatch do it's thing instead of isdialogmessage Npp.RegisterAsDialog(Handle); end; function TNppForm.Confirmed(const ACaption, ATitle: nppString): boolean; begin Result := False; if Assigned(Application) then Result := (Application.MessageBox(nppPChar(ACaption),nppPChar(ATitle), MB_ICONQUESTION + MB_YESNO) = IDYES); end; constructor TNppForm.Create(AOwner: TNppForm); begin Npp := AOwner.Npp; DefaultCloseAction := caNone; inherited Create(AOwner); Npp.RegisterAsDialog(Handle); end; destructor TNppForm.Destroy; begin if (self.HandleAllocated) then Npp.UnRegisterAsDialog(Handle); inherited; end; procedure TNppForm.DoClose(var Action: TCloseAction); begin if (self.DefaultCloseAction <> caNone) then Action := self.DefaultCloseAction; inherited; end; procedure TNppForm.MessageError(const ATitle, ACaption: nppString); begin if Assigned(Application) then Application.MessageBox(nppPChar(ATitle),nppPChar(ACaption),MB_ICONSTOP + MB_OK); end; procedure TNppForm.MessageSimple(const ATitle, ACaption: nppString); begin if Assigned(Application) then Application.MessageBox(nppPChar(ATitle),nppPChar(ACaption),MB_OK); end; procedure TNppForm.MessageWarning(const ATitle, ACaption: nppString); begin if Assigned(Application) then Application.MessageBox(nppPChar(ATitle),nppPChar(ACaption),MB_ICONWARNING + MB_OK); end; end.
UNIT GUI_Pokedex; {$mode objfpc}{$H+} INTERFACE USES Crt, DT_Pokedex, DT_Especie, DT_TipoElemental, Utilidades; (*Dibuja en pantalla los datos de la especie seleccionada, tal como se describe en los documentos.*) PROCEDURE DrawPokedex(p: DatosPokedex); (*Dibuja el fondo de la pokedex*) PROCEDURE DrawPokedexBackground(); IMPLEMENTATION CONST XDatos= 39; //Línea inicial para describir los datos. MAX_LEN_NAME = 20; //Longitud maxima del nombre de un pokemon. MAX_LEN_TYPE = 20; //Longitud maxima en pantalla de ambos tipos de un pokemon. (*Dibuja el fondo de la pokedex*) PROCEDURE DrawPokedexBackground(); Begin TextBackground(Black); ClrScr; //Limpiamos la pantalla. TextColor(Cyan); GoToXY(XDatos,14); WriteLn('**************************************'); GoToXY(XDatos,15); WriteLn(' LISTADO DE ESPECIES '); GoToXY(XDatos,16); WriteLn('**************************************'); GoToXY(XDatos,24); WriteLn('**************************************'); GoToXY(XDatos,17); Write('|'); GoToXY(XDatos,18); Write('|'); GoToXY(XDatos,19); Write('|'); GoToXY(XDatos,20); Write('|'); GoToXY(XDatos,21); Write('|'); GoToXY(XDatos,22); Write('|'); GoToXY(XDatos,23); Write('|'); GoToXY(XDatos+38,17); Write('|'); GoToXY(XDatos+38,18); Write('|'); GoToXY(XDatos+38,19); Write('|'); GoToXY(XDatos+38,20); Write('|'); GoToXY(XDatos+38,21); Write('|'); GoToXY(XDatos+38,22); Write('|'); GoToXY(XDatos+38,23); Write('|'); //Escribimos las estadísticas base. TextColor(DarkGray); GoToXY(XDatos,3); Write('==========ESTADISTICAS BASE==========='); GoToXY(XDatos,4); Write('PS='); GoToXY(XDatos+9,4); Write('ATK='); GoToXY(XDatos+19,4); Write('DEF='); GoToXY(XDatos+29,4); Write('VEL='); GoToXY(XDatos,5); Write('ATKSp='); GoToXY(XDatos+12,5); Write('DEFSp='); GoToXY(XDatos+24,5); Write('AMISTAD='); GoToXY(XDatos,6); Write('EXP='); GoToXY(XDatos+10,6); Write('RATIO='); //Escribimos los datos de puntos de efuerzo. GoToXY(XDatos,8); Write('==========PUNTOS DE ESFUERZO=========='); GoToXY(XDatos,9); Write('PS='); GoToXY(XDatos+8,9); Write('ATK='); GoToXY(XDatos+17,9); Write('DEF='); GoToXY(XDatos+26,9); Write('VEL='); GoToXY(XDatos,10); Write('ATKSp='); GoToXY(XDatos+11,10); Write('DEFSp='); //Escribimos el tipo de crecimiento. GoToXY(XDatos,12); Write('CREMIENTO:'); end; (*Asigna el color correspondiente al tipo para dibujar el pokémon.*) PROCEDURE ColorTipoElemental(tipo: STRING; VAR c: INTEGER); Begin IF tipo='Acero' THEN c:= LightGray ELSE IF tipo='Agua' THEN c:= LightBlue ELSE IF tipo='Bicho' THEN c:= LightGreen ELSE IF tipo='Dragon' THEN c:= Red ELSE IF tipo='Electrico' THEN c:= Yellow ELSE IF tipo='Fantasma' THEN c:= DarkGray ELSE IF tipo='Fuego' THEN c:= LightRed ELSE IF tipo='Hada' THEN c:= LightMagenta ELSE IF tipo='Hielo' THEN c:= Cyan ELSE IF tipo='Lucha' THEN c:= Brown ELSE IF tipo='Normal' THEN c:= White ELSE IF tipo='Planta' THEN c:= Green ELSE IF tipo='Psiquico' THEN c:= Magenta ELSE IF tipo='Roca' THEN c:= LightGray ELSE IF tipo='Siniestro' THEN c:= Blue ELSE IF tipo='Tierra' THEN c:= Brown ELSE IF tipo='Veneno' THEN c:= Magenta ELSE IF tipo='Volador' THEN c:= LightGray ELSE IF tipo='NULL' THEN c:= DarkGray ELSE IF tipo='???' THEN c:= White; end; (*Dibuja el pokemon dado por el numero, con el color asignado.*) PROCEDURE DrawPokemon(numero: STRING; colorTipo: INTEGER); VAR i: INTEGER; imagen: Text; lineaDibujo: String; Begin assign(imagen, 'Images\'+numero+'.txt' ); {$I-} reset(imagen); {$I+} IF IOResult<> 0 THEN BEGIN WriteLn('El archivo "'+'Images\'+numero+'.txt'+'" no existe.'); WriteLn('Presiona ENTER para continuar.'); ReadLn; end ELSE Begin TextColor(colorTipo); i:= 1; WHILE NOT EOF(imagen) DO Begin GoToXY(1,i); ReadLn(imagen,lineaDibujo); Write(lineaDibujo); i:= i+1; end; Close(imagen); end; end; PROCEDURE DrawList(currentInd: INTEGER; l: ListaEspecies); CONST spc = ' '; Begin IF currentInd<=3 THEN Begin IF currentInd=1 THEN TextColor(LightCyan) ELSE TextColor(LightBlue); GoToXY(XDatos+1,17); Write(NombreEspecie(EspecieListaEspecies(1,l)) + spc); IF currentInd=2 THEN TextColor(LightCyan) ELSE TextColor(LightBlue); GoToXY(XDatos+1,18); Write(NombreEspecie(EspecieListaEspecies(2,l)) + spc); IF currentInd=3 THEN TextColor(LightCyan) ELSE TextColor(LightBlue); GoToXY(XDatos+1,19); Write(NombreEspecie(EspecieListaEspecies(3,l)) + spc); TextColor(LightBlue); GoToXY(XDatos+1,20); Write(NombreEspecie(EspecieListaEspecies(4,l)) + spc); GoToXY(XDatos+1,21); Write(NombreEspecie(EspecieListaEspecies(5,l)) + spc); GoToXY(XDatos+1,22); Write(NombreEspecie(EspecieListaEspecies(6,l)) + spc); GoToXY(XDatos+1,23); Write(NombreEspecie(EspecieListaEspecies(7,l)) + spc); end else begin TextColor(Blue); GoToXY(XDatos+1,17); Write(NombreEspecie(EspecieListaEspecies(currentInd-3,l)) + spc); GoToXY(XDatos+1,18); Write(NombreEspecie(EspecieListaEspecies(currentInd-2,l)) + spc); GoToXY(XDatos+1,19); Write(NombreEspecie(EspecieListaEspecies(currentInd-1,l)) + spc); TextColor(LightCyan); GoToXY(XDatos+1,20); Write(NombreEspecie(EspecieListaEspecies(currentInd,l)) + spc); TextColor(LightBlue); GoToXY(XDatos+1,21); Write(NombreEspecie(EspecieListaEspecies(currentInd+1,l)) + spc); GoToXY(XDatos+1,22); Write(NombreEspecie(EspecieListaEspecies(currentInd+2,l)) + spc); GoToXY(XDatos+1,23); Write(NombreEspecie(EspecieListaEspecies(currentInd+3,l)) + spc); end; end; (*Dibuja en pantalla los datos de la especie seleccionada, tal como se describe en los documentos.*) PROCEDURE DrawPokedex(p: DatosPokedex); VAR colorActual: INTEGER; especieActual: Especie; tipo1, tipo2, name: STRING; BEGIN especieActual:= EspecieSeleccionada(p); //Dibujamos la especie actual con el color adecuado según su tipo primario. tipo1:= NombreTipoElemental(ObtenerTipoElemental(TipoEspecie(1,especieActual),p)); tipo2:= NombreTipoElemental(ObtenerTipoElemental(TipoEspecie(2,especieActual),p)); ColorTipoElemental(tipo1,colorActual); DrawPokemon(NumeroEspecie(especieActual),colorActual); //Escribimos los datos específicos de esta especie. TextColor(White); GoToXY(XDatos,1); Write('#' + NumeroEspecie(especieActual) + ' '); GoToXY(XDatos+7,1); name := NombreEspecie(especieActual); Write(name + stringOfChar(' ', MAX_LEN_NAME - length(name))); GoToXY(XDatos+24,1); Write(tipo1); IF tipo2<>'NULL' THEN Begin Write('/'+tipo2); end; Write(stringOfChar(' ', MAX_LEN_NAME - length(tipo1) - length(tipo2) + 5)); TextColor(White); //Escribimos las estadísticas base. GoToXY(XDatos+4,4); Write(EstadisticaEspecie(PS_Base,especieActual), ' '); GoToXY(XDatos+14,4); Write(EstadisticaEspecie(ATK_Base,especieActual), ' '); GoToXY(XDatos+24,4); Write(EstadisticaEspecie(DEF_Base,especieActual), ' '); GoToXY(XDatos+34,4); Write(EstadisticaEspecie(VEL_Base,especieActual), ' '); GoToXY(XDatos+7,5); Write(EstadisticaEspecie(ATKSp_Base,especieActual), ' '); GoToXY(XDatos+19,5); Write(EstadisticaEspecie(DEFSp_Base,especieActual), ' '); GoToXY(XDatos+33,5); Write(EstadisticaEspecie(AMISTAD_Base,especieActual), ' '); GoToXY(XDatos+5,6); Write(EstadisticaEspecie(EXP_Base,especieActual), ' '); GoToXY(XDatos+17,6); Write(EstadisticaEspecie(RatioCaptura,especieActual), ' '); //Escribimos los datos de puntos de efuerzo. GoToXY(XDatos+4,9); Write(EstadisticaEspecie(PS_Esfuerzo,especieActual), ' '); GoToXY(XDatos+13,9); Write(EstadisticaEspecie(ATK_Esfuerzo,especieActual), ' '); GoToXY(XDatos+22,9); Write(EstadisticaEspecie(DEF_Esfuerzo,especieActual), ' '); GoToXY(XDatos+31,9); Write(EstadisticaEspecie(VEL_Esfuerzo,especieActual), ' '); GoToXY(XDatos+7,10); Write(EstadisticaEspecie(ATKSp_Esfuerzo,especieActual), ' '); GoToXY(XDatos+18,10); Write(EstadisticaEspecie(DEFSp_Esfuerzo,especieActual), ' '); //Escribimos el tipo de crecimiento. GoToXY(XDatos+23,12); Write(CrecimientoEspecie(especieActual), ' '); //Dibujamos la lista de selección. DrawList(IndiceEspecieSeleccionada(p),ListaDeEspecies(p)); GoToXY(1,22); TextBackground(Blue); TextColor(Yellow); Write(' Presiona '); TextColor(white); Write('B'); TextColor(Yellow); Write(' para buscar una especie '); GoToXY(1,23); Write(' '); TextBackground(black); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Connection classes } { } { Copyright (c) 1998 Inprise Corporation } { } {*******************************************************} unit CorbaCon; interface uses Messages, Windows, SysUtils, CorbaObj, CorbaStd, Classes, StdVcl, DBClient; type { TCorbaConnection } TRepositoryId = type string; TCancelEvent = procedure (Sender: TObject; var Cancel: Boolean; var DialogMessage: string) of object; TCorbaConnection = class(TCustomRemoteServer) private FRepositoryId: TRepositoryId; FObjectName: string; FHostName: string; FAppServer: Variant; FOnCancel: TCancelEvent; FConnecting: Boolean; FCancelable: Boolean; procedure ThreadTimeout(var DialogMessage: string; var Cancel: Boolean); procedure SetRepositoryId(const Value: TRepositoryId); procedure SetObjectName(const Value: string); procedure SetHostName(const Value: string); protected function GetAppServer: Variant; virtual; procedure SetAppServer(Value: Variant); virtual; procedure DoConnect; override; procedure DoDisconnect; override; function GetConnected: Boolean; override; procedure SetConnected(Value: Boolean); override; procedure GetProviderNames(Proc: TGetStrProc); override; public constructor Create(AOwner: TComponent); override; function GetProvider(const ProviderName: string): IProvider; override; property AppServer: Variant read GetAppServer; published property Cancelable: Boolean read FCancelable write FCancelable default False; property Connected; property RepositoryId: TRepositoryId read FRepositoryId write SetRepositoryId; property ObjectName: string read FObjectName write SetObjectName; property HostName: string read FHostName write SetHostName; property AfterConnect; property AfterDisconnect; property BeforeConnect; property BeforeDisconnect; property OnCancel: TCancelEvent read FOnCancel write FOnCancel; end; implementation uses ActiveX, ComObj, Forms, Registry, MidConst, DBLogDlg, OrbPas, Dialogs; resourcestring sConnecting = 'Connecting to CORBA server...'; { TCorbaBindThread } type PIObject = ^IObject; TCorbaBindThread = class(TThread) private FRepId: string; FFactoryId: string; FInstanceName: string; FHostName: string; FIID: TGUID; FObjectPtr: PIObject; FLock: TRTLCriticalSection; FCanFree: THandle; FCallComplete: THandle; FException: TObject; FFinished: Boolean; FDialogHandle: HWND; procedure SetDialogHandle(const Value: HWND); public constructor Create(const RepId, FactoryId, InstanceName, HostName: string; IID: TGUID; var Obj: IObject); destructor Destroy; override; procedure Cancel; procedure Execute; override; procedure MarkFreeable; property CallCompleteEvent: THandle read FCallComplete; property Exception: TObject read FException write FException; property Finished: Boolean read FFinished; property DialogHandle: HWND read FDialogHandle write SetDialogHandle; end; { TCorbaBindThread } constructor TCorbaBindThread.Create(const RepId, FactoryId, InstanceName, HostName: string; IID: TGUID; var Obj: IObject); begin FRepId := RepId; FFactoryId := FactoryId; FInstanceName := InstanceName; FHostName := HostName; FIID := IID; FObjectPtr := @Obj; FreeOnTerminate := True; InitializeCriticalSection(FLock); FCanFree := CreateEvent(nil, True, False, nil); FCallComplete := CreateEvent(nil, True, False, nil); inherited Create(False); end; destructor TCorbaBindThread.Destroy; begin DeleteCriticalSection(FLock); CloseHandle(FCanFree); CloseHandle(FCallComplete); FException.Free; inherited Destroy; end; procedure TCorbaBindThread.Cancel; begin EnterCriticalSection(FLock); try FObjectPtr := nil; FDialogHandle := 0; finally LeaveCriticalSection(FLock); end; end; type PRaiseFrame = ^TRaiseFrame; TRaiseFrame = record NextRaise: PRaiseFrame; ExceptAddr: Pointer; ExceptObject: TObject; ExceptionRecord: PExceptionRecord; end; procedure TCorbaBindThread.Execute; var Obj: IObject; begin FException:= nil; try Obj := CORBAFactoryCreateStub(FRepID, FFactoryID, FInstanceName, FHostName, FIID); EnterCriticalSection(FLock); try if FObjectPtr <> nil then FObjectPtr^ := Obj; finally LeaveCriticalSection(FLock); end; except if RaiseList <> nil then begin FException := PRaiseFrame(RaiseList)^.ExceptObject; PRaiseFrame(RaiseList)^.ExceptObject := nil; end; end; EnterCriticalSection(FLock); try if FDialogHandle <> 0 then PostMessage(FDialogHandle, WM_CLOSE, 0, 0); finally LeaveCriticalSection(FLock); end; FFinished := True; ResetEvent(FCallComplete); WaitForSingleObject(FCanFree, INFINITE); end; procedure TCorbaBindThread.MarkFreeable; begin ResetEvent(FCanFree); end; procedure TCorbaBindThread.SetDialogHandle(const Value: HWND); begin EnterCriticalSection(FLock); try FDialogHandle := Value; finally LeaveCriticalSection(FLock); end; end; type TTimedOutEvent = procedure (var Msg: string; var Cancel: Boolean) of object; function ThreadedBind(const RepId, FactoryId, InstanceName, HostName: string; IID: TGUID; Timeout: DWORD; TimedOut: TTimedOutEvent): IObject; var Thread: TCorbaBindThread; CompleteEvent: THandle; WaitResult: DWORD; Cancel: Boolean; TickCount: DWORD; WaitTicks: DWORD; CurTicks: DWORD; ConnectMessage: string; Exception: TObject; procedure ShowConnectDialog(const Msg: string); var MsgDialog: TForm; begin MsgDialog := CreateMessageDialog(Msg, mtInformation, [mbCancel]); Thread.DialogHandle := MsgDialog.Handle; MsgDialog.ShowModal; end; begin Thread := TCorbaBindThread.Create(RepId, FactoryId, InstanceName, HostName, IID, Result); try CompleteEvent := Thread.CallCompleteEvent; TickCount := GetTickCount; WaitTicks := Timeout; while not Thread.Finished do begin WaitResult := MsgWaitForMultipleObjects(1, CompleteEvent, False, WaitTicks, QS_ALLINPUT); case WaitResult of WAIT_TIMEOUT: begin Cancel := False; ConnectMessage := sConnecting; if Assigned(TimedOut) then TimedOut(ConnectMessage, Cancel); if not Thread.Finished and not Cancel and (ConnectMessage <> '') then begin ShowConnectDialog(ConnectMessage); Cancel := True; end; if Cancel and not Thread.Finished then begin Thread.Cancel; Result := nil; Abort; end; TickCount := GetTickCount; WaitTicks := Timeout; end; $FFFFFFFF: RaiseLastWin32Error; else if Thread.Finished then Break; Application.ProcessMessages; CurTicks := GetTickCount; if TickCount + TimeOut > CurTicks then WaitTicks := TickCount + TimeOut - CurTicks else WaitTicks := 0; end; end; if Thread.Exception <> nil then begin Exception := Thread.Exception; Thread.Exception := nil; raise Exception; end; finally Thread.MarkFreeable; end; end; { TCorbaConnection } constructor TCorbaConnection.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TCorbaConnection.SetRepositoryId(const Value: TRepositoryId); begin if Value <> FRepositoryId then begin if not (csLoading in ComponentState) then begin SetConnected(False); end; FRepositoryId := Value; end; end; procedure TCorbaConnection.SetObjectName(const Value: string); begin if Value <> FObjectName then begin if not (csLoading in ComponentState) then begin SetConnected(False); end; FObjectName := Value; end; end; procedure TCorbaConnection.SetHostName(const Value: string); begin if Value <> FHostName then begin if not (csLoading in ComponentState) then begin SetConnected(False); end; FHostName := Value; end; end; function TCorbaConnection.GetConnected: Boolean; begin Result := (not VarIsNull(AppServer) and (IUnknown(AppServer) <> nil)); end; procedure TCorbaConnection.SetConnected(Value: Boolean); begin if (not (csReading in ComponentState)) and (Value and not Connected) and (FRepositoryId = '') then raise Exception.CreateFmt(SRepositoryIdBlank, [Name]); inherited SetConnected(Value); end; procedure TCorbaConnection.DoDisconnect; begin SetAppServer(NULL); end; function TCorbaConnection.GetAppServer: Variant; begin Result := FAppServer; end; procedure TCorbaConnection.SetAppServer(Value: Variant); begin FAppServer := Value; end; function TCorbaConnection.GetProvider(const ProviderName: string): IProvider; var Stub: IStub; OutBuf: IMarshalOutBuffer; InBuf: IMarshalInBuffer; begin Connected := True; (IUnknown(AppServer) as IStubObject).GetStub(Stub); Stub.CreateRequest(PChar('Get_' + ProviderName), True, OutBuf); Stub.Invoke(OutBuf, InBuf); Result := UnmarshalObject(InBuf, IProvider) as IProvider; end; procedure TCorbaConnection.GetProviderNames(Proc: TGetStrProc); var List: Variant; I: Integer; begin Connected := True; VarClear(List); try List := (IUnknown(AppServer) as IDataBroker).GetProviderNames; except { Assume any errors means the list is not available. } end; if VarIsArray(List) and (VarArrayDimCount(List) = 1) then for I := VarArrayLowBound(List, 1) to VarArrayHighBound(List, 1) do Proc(List[I]); end; procedure TCorbaConnection.DoConnect; const SPrefix = 'IDL:'; // Do not localize PrefixLength = Length(SPrefix); SFactory = 'Factory'; var Intf: IUnknown; FactoryId, ObjectId: string; IID: TGuid; P: Integer; begin if FConnecting then Exit; FConnecting := True; try CorbaInitialize; if (Length(RepositoryId) <= PrefixLength) or (AnsiCompareStr(Copy(RepositoryId, 1, PrefixLength), SPrefix) <> 0) then begin FactoryId := Format('%s%s%s:1.0', [SPrefix, RepositoryId, SFactory]); ObjectId := Format('%s%s:1.0', [SPrefix, RepositoryId]); end else begin FactoryId := RepositoryId; ObjectId := RepositoryId; P := Pos(SFactory+':', ObjectId); if P > 0 then Delete(ObjectId, P, Length(SFactory)); end; if not CorbaInterfaceIDManager.SearchGuid(ObjectId, IID) then IID := IDataBroker; if FCancelable or (csDesigning in ComponentState) then Intf := ThreadedBind(FactoryId, ObjectName, '', HostName, IID, 1000, ThreadTimeout) else Intf := CORBAFactoryCreateStub(FactoryId, ObjectName, '', HostName, IID); if Intf <> nil then SetAppServer(Intf); finally FConnecting := False; end; end; procedure TCorbaConnection.ThreadTimeout(var DialogMessage: string; var Cancel: Boolean); begin if Assigned(FOnCancel) then FOnCancel(Self, Cancel, DialogMessage); end; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program CHEER; Uses Math; Const maxN =10000; maxM =100000; Type TEdge =Record u,v,c :SmallInt; end; Var n :SmallInt; m :LongInt; A,Lab :Array[1..maxN] of SmallInt; E :Array[1..maxM] of TEdge; res :Int64; procedure Enter; var i :LongInt; begin Read(n,m); for i:=1 to n do Read(A[i]); for i:=1 to m do with (E[i]) do begin Read(u,v,c); c:=2*c+A[u]+A[v]; end; end; procedure Init; var i :SmallInt; begin for i:=1 to n do Lab[i]:=-1; end; function GetRoot(x :SmallInt) :SmallInt; begin while (Lab[x]>0) do x:=Lab[x]; Exit(x); end; procedure Union(r1,r2 :SmallInt); var x :SmallInt; begin x:=Lab[r1]+Lab[r2]; if (Lab[r1]>Lab[r2]) then begin Lab[r1]:=r2; Lab[r2]:=x; end else begin Lab[r1]:=x; Lab[r2]:=r1; end; end; procedure DownHeap(root,leaf :LongInt); var Key :TEdge; child :LongInt; begin Key:=E[root]; while (root*2<=leaf) do begin child:=root*2; if (child<leaf) and (E[child].c>E[child+1].c) then Inc(child); if (Key.c<=E[child].c) then Break; E[root]:=E[child]; root:=child; end; E[root]:=Key; end; procedure Greedy; var Tmp :TEdge; i,count :LongInt; r1,r2 :SmallInt; begin for i:=m div 2 downto 1 do DownHeap(i,m); count:=0; res:=0; for i:=m-1 downto 0 do begin Tmp:=E[1]; E[1]:=E[i+1]; E[i+1]:=Tmp; DownHeap(1,i); r1:=GetRoot(E[i+1].u); r2:=GetRoot(E[i+1].v); if (r1<>r2) then begin Inc(count); Inc(res,E[i+1].c); if (count=n-1) then Break; Union(r1,r2); end; end; end; procedure Escape; var i,minV :SmallInt; begin minV:=A[1]; for i:=2 to n do minV:=Min(minV,A[i]); Write(res+minV); end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Init; Greedy; Escape; Close(Input); Close(Output); End.
unit MgShapes; interface uses Classes; type TMgGeometricShape = class(TPersistent) private FOnChange : TNotifyEvent; protected procedure AssignTo(Dest: TPersistent); override; procedure Changed; virtual; public constructor Create; virtual; abstract; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TMgSimpleShapes = class(TMgGeometricShape) end; (* TMgVerticalLine = class(TMgSimpleShapes) public property Y: TFixed24Dot8 read FY write SetY; property X1: TFixed24Dot8 read FX1 write SetX1; property X2: TFixed24Dot8 read FX2 write SetX2; end; TMgHorizontalLine = class(TMgSimpleShapes) public property Y: TFixed24Dot8 read FY write SetY; property X1: TFixed24Dot8 read FX1 write SetX1; property X2: TFixed24Dot8 read FX2 write SetX2; end; *) implementation { TMgGeometricShape } procedure TMgGeometricShape.AssignTo(Dest: TPersistent); begin if Dest is TMgGeometricShape then with TMgGeometricShape(Dest) do begin FOnChange := Self.FOnChange; end else inherited; end; procedure TMgGeometricShape.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; end.
unit uGameManager; /// ключевой модуль реализации логики игры и управление интерфейсом /// что делается контролем подчиненных специализированных менеджеров interface uses uTypes; type TGameManager = class private fJumpAbility: TJumpAbility; public procedure Init; /// метод инициализирует и настраивает все вспомогательные менеджеры procedure LoadDataFromDB; /// загружает данные из базы данных в рабочие объекты и массивы // procedure LoadState; /// загружает автосохранение (состояние игрв нв момент выхода с /// последней посещенной точки (локации) // procedure NewGame; /// при отсутствии автосохранения или по инициативе игрока, запускет /// новую игру // procedure Run; /// проводит необходимую работу и запускает игру, загруженную из автосейва /// или запущенную заново // procedure SaveState; /// производит автосохранение текущего состояния игры procedure OnCooldownTick; /// обрабатывает логику кулдаунов procedure DoJump; end; var mngGame : TGameManager; implementation { TGameManager } uses uInterfaceManager, uConstants, DB; procedure TGameManager.DoJump; begin // если способность не в откате, активируем if not fJumpAbility.InCooldown then begin fJumpAbility.currentCooldown := 0; fJumpAbility.InCooldown := true; end; end; procedure TGameManager.Init; /// базовая инициализация и запуск игры begin // устанавливаем параметры мопонентов всех панелей на базовые настройки // (цвета, картинки, видимость и т.п.) // подразумевается, что все компоненты уже привязаны к менеджеру интерфейса mngInterface.Init; // загружаем исходные данные LoadDataFromDB; end; procedure TGameManager.LoadDataFromDB; begin // способность прыжка fJumpAbility.baseJumpDistance := ABILITY_JUMP_DISTANCE; fJumpAbility.fullJumpDistance := ABILITY_JUMP_DISTANCE; fJumpAbility.baseCooldownLength := ABILITY_JUMP_COOLDOWN; fJumpAbility.fullCooldownLength := ABILITY_JUMP_COOLDOWN; fJumpAbility.currentCooldown := 0; fJumpAbility.InCooldown := false; // end; procedure TGameManager.OnCooldownTick; /// обрабатывает все имеющиеся в игре откаты /// генерит соответствующие события при их завершении begin // способность "Прыжок" if fJumpAbility.InCooldown then begin fJumpAbility.currentCooldown := fJumpAbility.currentCooldown + TIMER_COOLDOWN_INTERVAL; if fJumpAbility.currentCooldown >= fJumpAbility.fullCooldownLength then begin fJumpAbility.currentCooldown := fJumpAbility.fullCooldownLength; fJumpAbility.InCooldown := false; end; // обновляем прогресс в интерфейсе mngInterface.SetKindProgress( KIND_PROGRESS_JUMP, fJumpAbility.currentCooldown / fJumpAbility.fullCooldownLength, fJumpAbility.InCooldown ); end; end; initialization mngGame := TGameManager.Create; finalization mngGame.Free; end.
unit CORBAServerImpl; { This is the Implementation Unit of the CORBA Server. In the initialization section of this unit, the wizard writes a call to CORBAFactory constructor which creates an instance of the Object DemoCORBA. The third parameter to the method is the Repository ID and is of the format 'IDL:ProjectName/ClassNameFactory:1.0' This is what any CORBA client uses to connect to any CORBA Server. In order to view the IDL file, use the 'Export to CORBA IDL' button on the Type Library Form. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComObj, VCLCom, StdVcl, BdeProv, DataBkr, CorbaRdm, CorbaObj, CORBAServer_TLB, Db, DBTables; type TDemoCORBA = class(TCorbaDataModule, IDemoCORBA) CustomerTable: TTable; CustomerSource: TDataSource; OrderTable: TTable; procedure DemoCORBACreate(Sender: TObject); procedure DemoCORBADestroy(Sender: TObject); private { Private declarations } public { Public declarations } protected function Get_CustomerTable: IProvider; safecall; end; var DemoCORBA: TDemoCORBA; implementation {$R *.DFM} uses CorbInit, CorbaVcl, CORBAServerForm; { This method was generated using the "export from datamodule" option on the local menu of any TQuery, Table, or TProvider component. It returns the IProvider interface used by the client. } function TDemoCORBA.Get_CustomerTable: IProvider; begin Result := CustomerTable.Provider; end; { These Create/Destroy methods are optional. These are here for the purpose of counting the clients connected to the CORBA Server Disabling IDE debugger would allow running multiple copies of the client.} procedure TDemoCORBA.DemoCORBACreate(Sender: TObject); begin MainServerForm.UpdateClientCount(1); end; procedure TDemoCORBA.DemoCORBADestroy(Sender: TObject); begin MainServerForm.UpdateClientCount(-1); end; initialization TCorbaVclComponentFactory.Create('DemoCORBAFactory', 'DemoCORBA', 'IDL:CORBAServer/DemoCORBAFactory:1.0', IDemoCORBA, TDemoCORBA, iMultiInstance, tmSingleThread); end.
unit inifileunit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, regexpr; type TIniFile = class public List: TStringList; FileName: string; constructor Create(filePath: string = ''); destructor Destroy; procedure Free(); function Load(filePath: string = ''): Boolean; function Get(key: string; defaultValue: string = ''): string; overload; function Get(section: string; key: string; defaultValue: string): string; overload; end; implementation constructor TIniFile.Create(filePath: string = ''); begin List := TStringList.Create; List.Sorted := True; List.Duplicates := dupIgnore; if filePath <> '' then Load(filePath); end; destructor TIniFile.Destroy; begin List.Free; Inherited Destroy; end; procedure TIniFile.Free(); begin if Self <> Nil then Destroy; end; function TIniFile.Load(filePath: string = ''): Boolean; var fileLines : TStringList; sectionRegex, nameValueRegex : TRegExpr; i : integer; line, section : string; begin if filePath <> '' then FileName := filePath; Result := False; fileLines := TStringList.Create; try fileLines.LoadFromFile(filePath); if fileLines.Count > 0 then begin List.Clear; sectionRegex := TRegExpr.Create; sectionRegex.Expression := '\[(.+)\]'; nameValueRegex := TRegExpr.Create; nameValueRegex.Expression := '([\w/]+)\s*=\s*(.*)'; section := ''; for i := 0 to (fileLines.Count - 1) do begin line := Trim(fileLines[i]); if (Pos(';', line) = 1) or (Pos('#', line) = 1) then continue; if sectionRegex.Exec(line) then begin section := sectionRegex.Match[1]; end else if nameValueRegex.Exec(line) then begin List.Values[section + '/' + nameValueRegex.Match[1]] := nameValueRegex.Match[2]; end; end; sectionRegex.Free; nameValueRegex.Free; Result := True; end; except end; fileLines.Free; end; function TIniFile.Get(key: string; defaultValue: string = ''): string; overload; var commentIndex: integer; begin Result := List.Values[key]; commentIndex := Pos('#', Result); if commentIndex > 0 then Result := copy(Result, 1, commentIndex - 1); Result := Trim(Result); if Result = '' then Result := defaultValue; end; function TIniFile.Get(section: string; key: string; defaultValue: string): string; overload; var commentIndex: integer; begin Result := List.Values[section + '/' + key]; commentIndex := Pos('#', Result); if commentIndex > 0 then Result := copy(Result, 1, commentIndex - 1); Result := Trim(Result); if Result = '' then Result := defaultValue; end; end.
{ This file is part of the Free Pascal run time library. Copyright (c) 2003 by the Free Pascal development team CustomApplication class. Port to pas2js by Mattias Gaertner mattias@freepascal.org See the file COPYING.FPC, included in this distribution, for details about the copyright. 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. **********************************************************************} unit CustApp; {$mode objfpc} interface uses Classes, SysUtils, Types, JS; Const SErrInvalidOption: String = 'Invalid option at position %s: "%s"'; SErrNoOptionAllowed: String = 'Option at position %s does not allow an argument: %s'; SErrOptionNeeded: String = 'Option at position %s needs an argument : %s'; Type TExceptionEvent = procedure (Sender : TObject; E : Exception) of object; TEventLogTypes = set of TEventType; { TCustomApplication } TCustomApplication = Class(TComponent) Private FEventLogFilter: TEventLogTypes; FExceptObjectJS: JSValue; FOnException: TExceptionEvent; FTerminated: Boolean; FTitle: String; FOptionChar: Char; FCaseSensitiveOptions: Boolean; FStopOnException: Boolean; FExceptionExitCode: Integer; FExceptObject: Exception; Protected function GetEnvironmentVar(VarName: String): String; virtual; function GetExeName: string; virtual; function GetLocation: String; virtual; abstract; function GetOptionAtIndex(AIndex: Integer; IsLong: Boolean): String; procedure SetTitle(const AValue: string); virtual; function GetConsoleApplication: boolean; virtual; abstract; procedure DoRun; virtual; abstract; function GetParams(Index: Integer): String; virtual; function GetParamCount: Integer; virtual; procedure DoLog(EventType: TEventType; const Msg: String); virtual; Public constructor Create(AOwner: TComponent); override; // Some Delphi methods. procedure HandleException(Sender: TObject); virtual; procedure Initialize; virtual; procedure Run; procedure ShowException(E: Exception); virtual; abstract; procedure Terminate; virtual; procedure Terminate(AExitCode: Integer); virtual; // Extra methods. function FindOptionIndex(Const S: String; var Longopt: Boolean; StartAt: Integer = -1): Integer; function GetOptionValue(Const S: String): String; function GetOptionValue(Const C: Char; Const S: String): String; function GetOptionValues(Const C: Char; Const S: String): TStringDynArray; function HasOption(Const S: String) : Boolean; function HasOption(Const C: Char; Const S: String): Boolean; function CheckOptions(Const ShortOptions: String; Const Longopts: TStrings; Opts,NonOpts: TStrings; AllErrors: Boolean = False): String; function CheckOptions(Const ShortOptions: String; Const Longopts: Array of string; Opts,NonOpts: TStrings; AllErrors: Boolean = False): String; function CheckOptions(Const ShortOptions: String; Const Longopts: TStrings; AllErrors: Boolean = False): String; function CheckOptions(Const ShortOptions: String; Const LongOpts: Array of string; AllErrors: Boolean = False): String; function CheckOptions(Const ShortOptions: String; Const LongOpts: String; AllErrors: Boolean = False): String; function GetNonOptions(Const ShortOptions: String; Const Longopts: Array of string): TStringDynArray; procedure GetNonOptions(Const ShortOptions: String; Const Longopts: Array of string; NonOptions: TStrings); procedure GetEnvironmentList(List: TStrings; NamesOnly: Boolean); virtual; abstract; procedure GetEnvironmentList(List: TStrings); virtual; procedure Log(EventType: TEventType; const Msg: String); procedure Log(EventType: TEventType; const Fmt: String; const Args: Array of string); // Delphi properties property ExeName: string read GetExeName; property Terminated: Boolean read FTerminated; property Title: string read FTitle write SetTitle; property OnException: TExceptionEvent read FOnException write FOnException; // Extra properties property ConsoleApplication: Boolean Read GetConsoleApplication; property Location: String Read GetLocation; property Params[Index: integer]: String Read GetParams; property ParamCount: Integer Read GetParamCount; property EnvironmentVariable[EnvName: String]: String Read GetEnvironmentVar; property OptionChar: Char Read FoptionChar Write FOptionChar; property CaseSensitiveOptions: Boolean Read FCaseSensitiveOptions Write FCaseSensitiveOptions; property StopOnException: Boolean Read FStopOnException Write FStopOnException; property ExceptionExitCode: Longint Read FExceptionExitCode Write FExceptionExitCode; property ExceptObject: Exception read FExceptObject write FExceptObject; property ExceptObjectJS: JSValue read FExceptObjectJS write FExceptObjectJS; property EventLogFilter: TEventLogTypes Read FEventLogFilter Write FEventLogFilter; end; var CustomApplication: TCustomApplication = nil; implementation { TCustomApplication } function TCustomApplication.GetEnvironmentVar(VarName: String): String; begin Result:=GetEnvironmentVariable(VarName); end; function TCustomApplication.GetExeName: string; begin Result:=ParamStr(0); end; function TCustomApplication.GetOptionAtIndex(AIndex: Integer; IsLong: Boolean ): String; Var P : Integer; O : String; begin Result:=''; If AIndex=-1 then Exit; If IsLong then begin // Long options have form --option=value O:=Params[AIndex]; P:=Pos('=',O); If P=0 then P:=Length(O); Delete(O,1,P); Result:=O; end else begin // short options have form '-o value' If AIndex<ParamCount then if Copy(Params[AIndex+1],1,1)<>'-' then Result:=Params[AIndex+1]; end; end; procedure TCustomApplication.SetTitle(const AValue: string); begin FTitle:=AValue; end; function TCustomApplication.GetParams(Index: Integer): String; begin Result:=ParamStr(Index); end; function TCustomApplication.GetParamCount: Integer; begin Result:=System.ParamCount; end; procedure TCustomApplication.DoLog(EventType: TEventType; const Msg: String); begin // Do nothing, override in descendants if EventType=etCustom then ; if Msg='' then ; end; constructor TCustomApplication.Create(AOwner: TComponent); begin inherited Create(AOwner); FOptionChar:='-'; FCaseSensitiveOptions:=True; FStopOnException:=False; end; procedure TCustomApplication.HandleException(Sender: TObject); begin ShowException(ExceptObject); if FStopOnException then Terminate(ExceptionExitCode); if Sender=nil then ; end; procedure TCustomApplication.Initialize; begin FTerminated:=False; end; procedure TCustomApplication.Run; begin Repeat ExceptObject:=nil; ExceptObjectJS:=nil; Try DoRun; except on E: Exception do begin ExceptObject:=E; ExceptObjectJS:=E; HandleException(Self); end else begin ExceptObject:=nil; ExceptObjectJS := JS.JSExceptValue; end; end; break; Until FTerminated; end; procedure TCustomApplication.Terminate; begin Terminate(ExitCode); end; procedure TCustomApplication.Terminate(AExitCode: Integer); begin FTerminated:=True; ExitCode:=AExitCode; end; function TCustomApplication.FindOptionIndex(const S: String; var Longopt: Boolean; StartAt: Integer): Integer; Var SO,O : String; I,P : Integer; begin If Not CaseSensitiveOptions then SO:=UpperCase(S) else SO:=S; Result:=-1; I:=StartAt; if I=-1 then I:=ParamCount; While (Result=-1) and (I>0) do begin O:=Params[i]; // - must be seen as an option value If (Length(O)>1) and (O[1]=FOptionChar) then begin Delete(O,1,1); LongOpt:=(Length(O)>0) and (O[1]=FOptionChar); If LongOpt then begin Delete(O,1,1); P:=Pos('=',O); If (P<>0) then O:=Copy(O,1,P-1); end; If Not CaseSensitiveOptions then O:=UpperCase(O); If (O=SO) then Result:=i; end; Dec(i); end; end; function TCustomApplication.GetOptionValue(const S: String): String; begin Result:=GetOptionValue(' ',S); end; function TCustomApplication.GetOptionValue(const C: Char; const S: String ): String; Var B : Boolean; I : integer; begin Result:=''; I:=FindOptionIndex(C,B); If I=-1 then I:=FindOptionIndex(S,B); If I<>-1 then Result:=GetOptionAtIndex(I,B); end; function TCustomApplication.GetOptionValues(const C: Char; const S: String ): TStringDynArray; Var I,Cnt : Integer; B : Boolean; begin SetLength(Result,ParamCount); Cnt:=0; Repeat I:=FindOptionIndex(C,B,I); If I<>-1 then begin Inc(Cnt); Dec(I); end; Until I=-1; Repeat I:=FindOptionIndex(S,B,I); If I<>-1 then begin Inc(Cnt); Dec(I); end; Until I=-1; SetLength(Result,Cnt); Cnt:=0; I:=-1; Repeat I:=FindOptionIndex(C,B,I); If (I<>-1) then begin Result[Cnt]:=GetOptionAtIndex(I,False); Inc(Cnt); Dec(i); end; Until (I=-1); I:=-1; Repeat I:=FindOptionIndex(S,B,I); If I<>-1 then begin Result[Cnt]:=GetOptionAtIndex(I,True); Inc(Cnt); Dec(i); end; Until (I=-1); end; function TCustomApplication.HasOption(const S: String): Boolean; Var B : Boolean; begin Result:=FindOptionIndex(S,B)<>-1; end; function TCustomApplication.HasOption(const C: Char; const S: String): Boolean; Var B : Boolean; begin Result:=(FindOptionIndex(C,B)<>-1) or (FindOptionIndex(S,B)<>-1); end; function TCustomApplication.CheckOptions(const ShortOptions: String; const Longopts: TStrings; Opts, NonOpts: TStrings; AllErrors: Boolean ): String; Var I,J,L,P : Integer; O,OV,SO : String; UsedArg,HaveArg : Boolean; Function FindLongOpt(S : String) : boolean; Var I : integer; begin Result:=Assigned(LongOpts); if Not Result then exit; If CaseSensitiveOptions then begin I:=LongOpts.Count-1; While (I>=0) and (LongOpts[i]<>S) do Dec(i); end else begin S:=UpperCase(S); I:=LongOpts.Count-1; While (I>=0) and (UpperCase(LongOpts[i])<>S) do Dec(i); end; Result:=(I<>-1); end; Procedure AddToResult(Const Msg : string); begin If (Result<>'') then Result:=Result+sLineBreak; Result:=Result+Msg; end; begin If CaseSensitiveOptions then SO:=Shortoptions else SO:=LowerCase(Shortoptions); Result:=''; I:=1; While (I<=ParamCount) and ((Result='') or AllErrors) do begin O:=Paramstr(I); If (Length(O)=0) or (O[1]<>FOptionChar) then begin If Assigned(NonOpts) then NonOpts.Add(O); end else begin If (Length(O)<2) then AddToResult(Format(SErrInvalidOption,[IntToStr(I),O])) else begin HaveArg:=False; OV:=''; // Long option ? If (O[2]=FOptionChar) then begin Delete(O,1,2); J:=Pos('=',O); If J<>0 then begin HaveArg:=true; OV:=O; Delete(OV,1,J); O:=Copy(O,1,J-1); end; // Switch Option If FindLongopt(O) then begin If HaveArg then AddToResult(Format(SErrNoOptionAllowed,[IntToStr(I),O])); end else begin // Required argument If FindLongOpt(O+':') then begin If Not HaveArg then AddToResult(Format(SErrOptionNeeded,[IntToStr(I),O])); end else begin // Optional Argument. If not FindLongOpt(O+'::') then AddToResult(Format(SErrInvalidOption,[IntToStr(I),O])); end; end; end else // Short Option. begin HaveArg:=(I<ParamCount) and (Length(ParamStr(I+1))>0) and (ParamStr(I+1)[1]<>FOptionChar); UsedArg:=False; If Not CaseSensitiveOptions then O:=LowerCase(O); L:=Length(O); J:=2; While ((Result='') or AllErrors) and (J<=L) do begin P:=Pos(O[J],SO); If (P=0) or (O[j]=':') then AddToResult(Format(SErrInvalidOption,[IntToStr(I),O[J]])) else begin If (P<Length(SO)) and (SO[P+1]=':') then begin // Required argument If ((P+1)=Length(SO)) or (SO[P+2]<>':') Then If (J<L) or not haveArg then // Must be last in multi-opt !! begin AddToResult(Format(SErrOptionNeeded,[IntToStr(I),O[J]])); end; O:=O[j]; // O is added to arguments. UsedArg:=True; end; end; Inc(J); end; HaveArg:=HaveArg and UsedArg; If HaveArg then begin Inc(I); // Skip argument. OV:=Paramstr(I); end; end; If HaveArg and ((Result='') or AllErrors) then If Assigned(Opts) then Opts.Add(O+'='+OV); end; end; Inc(I); end; end; function TCustomApplication.CheckOptions(const ShortOptions: String; const Longopts: array of string; Opts, NonOpts: TStrings; AllErrors: Boolean ): String; Var L : TStringList; I : Integer; begin L:=TStringList.Create; try For I:=0 to High(LongOpts) do L.Add(LongOpts[i]); Result:=CheckOptions(ShortOptions,L,Opts,NonOpts,AllErrors); finally L.Destroy; end; end; function TCustomApplication.CheckOptions(const ShortOptions: String; const Longopts: TStrings; AllErrors: Boolean): String; begin Result:=CheckOptions(ShortOptions,LongOpts,Nil,Nil,AllErrors); end; function TCustomApplication.CheckOptions(const ShortOptions: String; const LongOpts: array of string; AllErrors: Boolean): String; Var L : TStringList; I : Integer; begin L:=TStringList.Create; Try For I:=0 to High(LongOpts) do L.Add(LongOpts[i]); Result:=CheckOptions(ShortOptions,L,AllErrors); Finally L.Destroy; end; end; function TCustomApplication.CheckOptions(const ShortOptions: String; const LongOpts: String; AllErrors: Boolean): String; Const SepChars = ' '#10#13#9; Var L : TStringList; Len,I,J : Integer; begin L:=TStringList.Create; Try I:=1; Len:=Length(LongOpts); While I<=Len do begin While Isdelimiter(SepChars,LongOpts,I) do Inc(I); J:=I; While (J<=Len) and Not IsDelimiter(SepChars,LongOpts,J) do Inc(J); If (I<=J) then L.Add(Copy(LongOpts,I,(J-I))); I:=J+1; end; Result:=CheckOptions(Shortoptions,L,AllErrors); Finally L.Destroy; end; end; function TCustomApplication.GetNonOptions(const ShortOptions: String; const Longopts: array of string): TStringDynArray; Var NO : TStrings; I : Integer; begin No:=TStringList.Create; try GetNonOptions(ShortOptions,LongOpts,No); SetLength(Result,NO.Count); For I:=0 to NO.Count-1 do Result[I]:=NO[i]; finally NO.Destroy; end; end; procedure TCustomApplication.GetNonOptions(const ShortOptions: String; const Longopts: array of string; NonOptions: TStrings); Var S : String; begin S:=CheckOptions(ShortOptions,LongOpts,Nil,NonOptions,true); if (S<>'') then Raise EListError.Create(S); end; procedure TCustomApplication.GetEnvironmentList(List: TStrings); begin GetEnvironmentList(List,False); end; procedure TCustomApplication.Log(EventType: TEventType; const Msg: String); begin If (FEventLogFilter=[]) or (EventType in FEventLogFilter) then DoLog(EventType,Msg); end; procedure TCustomApplication.Log(EventType: TEventType; const Fmt: String; const Args: array of string); begin try Log(EventType, Format(Fmt, Args)); except On E: Exception do Log(etError,Format('Error formatting message "%s" with %d arguments: %s', [Fmt,IntToStr(Length(Args)),E.Message])); end end; end.
PROGRAM PrimeNumbers(INPUT, OUTPUT); CONST Max = 100; Min = 2; TYPE SetOfNumbers = SET OF Min..Max; VAR LotsOfNumbers: SetOfNumbers; Current, Number, Prime: INTEGER; BEGIN LotsOfNumbers := [Min..Max]; Current := Min; WHILE (Current <= Max) DO BEGIN Number := Current; IF Number IN LotsOfNumbers THEN BEGIN WRITE(Number, ' '); Prime := Number; Number := Number + Prime; WHILE Number <= Max DO BEGIN LotsOfNumbers := LotsOfNumbers - [Number]; Number := Number + Prime; END; END; Current := Current + 1; END; END.
unit UIRegisterController; interface type IRegisterController = interface procedure RegisterClose; procedure RegisterSave; procedure RegisterCancel; end; implementation end.
unit FC.Trade.TraderCollection; interface uses SysUtils, BaseUtils, Classes, StockChart,Serialization, FC.Definitions; type { TSCOrderCollection } //Self Destruct | Not Self Destruct TStockOrderCollection = class (TInterfaceProvider,IStockTraderCollection) private FList: TInterfaceList; public // IStockTraderCollection function GetItem(Index: Integer): IStockTrader; procedure Delete(index: integer); procedure Clear; function Add(const aTrader: IStockTrader): integer; function Count: integer; property Items[Index: Integer]: IStockTrader read GetItem; default; constructor Create(aSelfDestruct: boolean=true); destructor Destroy; override; end; implementation { TStockTraderCollection } function TStockTraderCollection.Add(const aTrader: IStockTrader): integer; begin result:=FList.Add(aTrader); end; function TStockTraderCollection.Count: integer; begin result:=FList.Count; end; function TStockTraderCollection.GetItem(Index: Integer): IStockTrader; begin result:=FList[index] as IStockTrader; end; procedure TStockTraderCollection.Delete(index: integer); begin FList.Delete(index); end; procedure TStockTraderCollection.Clear; begin FList.Clear; end; constructor TStockTraderCollection.Create(aSelfDestruct: boolean); begin inherited CReate; FSelfDestruct:=aSelfDestruct; FList:=TInterfaceList.Create; end; destructor TStockTraderCollection.Destroy; begin FreeAndNil(FList); inherited; end; end.
{*************************************************************** * * Project : UDPClient * Unit Name: ClientMainForm * Purpose : UDP Chargen and Echo demo - client project * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:42:02 * Author : <unknown> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit ClientMainForm; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QStdCtrls, QDialogs, {$ELSE} windows, messages, graphics, controls, forms, dialogs, stdctrls, {$ENDIF} SysUtils, Classes, IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient; type TfrmMain = class(TForm) Button1: TButton; IdUDPClient1: TIdUDPClient; IdUDPClient2: TIdUDPClient; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure Test(IdUDPClient: TIdUDPClient); public { Public declarations } end; var frmMain: TfrmMain; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} uses IdException, IdStackConsts; procedure TfrmMain.Button1Click(Sender: TObject); begin Test(IdUDPClient1); end; procedure TfrmMain.Button2Click(Sender: TObject); begin Test(IdUDPClient2); end; procedure TfrmMain.Test(IdUDPClient: TIdUDPClient); var s, peer: string; port: integer; counter: integer; begin counter := 1; Screen.Cursor := crHourGlass; try IdUDPClient.Send(Format('test #%d', [counter])); repeat try s := IdUDPClient.ReceiveString(peer, port); except on E: EIdSocketError do if E.LastError <> 10040 then raise; end; if s <> '' then ShowMessage(Format('%s:%d said'#13'%s', [peer, port, s])); until s = ''; finally Screen.Cursor := crDefault; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin // enable broadcast support in TIdUDPClient IdUDPClient1.BroadcastEnabled := True; IdUDPClient2.BroadcastEnabled := True; end; end.
unit Winapi.WinUser; {$MINENUMSIZE 4} interface uses Winapi.WinNt, Winapi.WinBase; const user32 = 'user32.dll'; // 371 SW_HIDE = 0; SW_SHOWNORMAL = 1; SW_SHOWMINIMIZED = 2; SW_SHOWMAXIMIZED = 3; SW_SHOWNOACTIVATE = 4; // 1353 DESKTOP_READOBJECTS = $0001; DESKTOP_CREATEWINDOW = $0002; DESKTOP_CREATEMENU = $0004; DESKTOP_HOOKCONTROL = $0008; DESKTOP_JOURNALRECORD = $0010; DESKTOP_JOURNALPLAYBACK = $0020; DESKTOP_ENUMERATE = $0040; DESKTOP_WRITEOBJECTS = $0080; DESKTOP_SWITCHDESKTOP = $0100; DESKTOP_ALL_ACCESS = $01FF or STANDARD_RIGHTS_REQUIRED; DesktopAccessMapping: array [0..8] of TFlagName = ( (Value: DESKTOP_READOBJECTS; Name: 'Read objects'), (Value: DESKTOP_CREATEWINDOW; Name: 'Create window'), (Value: DESKTOP_CREATEMENU; Name: 'Create menu'), (Value: DESKTOP_HOOKCONTROL; Name: 'Hook control'), (Value: DESKTOP_JOURNALRECORD; Name: 'Journal record'), (Value: DESKTOP_JOURNALPLAYBACK; Name: 'Journal playback'), (Value: DESKTOP_ENUMERATE; Name: 'Enumerate'), (Value: DESKTOP_WRITEOBJECTS; Name: 'Write objects'), (Value: DESKTOP_SWITCHDESKTOP; Name: 'Switch desktop') ); DesktopAccessType: TAccessMaskType = ( TypeName: 'desktop'; FullAccess: DESKTOP_ALL_ACCESS; Count: Length(DesktopAccessMapping); Mapping: PFlagNameRefs(@DesktopAccessMapping); ); // 1533 WINSTA_ENUMDESKTOPS = $0001; WINSTA_READATTRIBUTES = $0002; WINSTA_ACCESSCLIPBOARD = $0004; WINSTA_CREATEDESKTOP = $0008; WINSTA_WRITEATTRIBUTES = $0010; WINSTA_ACCESSGLOBALATOMS = $0020; WINSTA_EXITWINDOWS = $0040; WINSTA_ENUMERATE = $0100; WINSTA_READSCREEN = $0200; WINSTA_ALL_ACCESS = $037F or STANDARD_RIGHTS_REQUIRED; WinStaAccessMapping: array [0..8] of TFlagName = ( (Value: WINSTA_ENUMDESKTOPS; Name: 'Enumerate desktops'), (Value: WINSTA_READATTRIBUTES; Name: 'Read attributes'), (Value: WINSTA_ACCESSCLIPBOARD; Name: 'Access clipboard'), (Value: WINSTA_CREATEDESKTOP; Name: 'Create desktop'), (Value: WINSTA_WRITEATTRIBUTES; Name: 'Write attributes'), (Value: WINSTA_ACCESSGLOBALATOMS; Name: 'Access global atoms'), (Value: WINSTA_EXITWINDOWS; Name: 'Exit Windows'), (Value: WINSTA_ENUMERATE; Name: 'Enumerate'), (Value: WINSTA_READSCREEN; Name: 'Read screen') ); WinStaAccessType: TAccessMaskType = ( TypeName: 'window station'; FullAccess: WINSTA_ALL_ACCESS; Count: Length(WinStaAccessMapping); Mapping: PFlagNameRefs(@WinStaAccessMapping); ); // 8897 MB_OK = $00000000; MB_OKCANCEL = $00000001; MB_ABORTRETRYIGNORE = $00000002; MB_YESNOCANCEL = $00000003; MB_YESNO = $00000004; MB_RETRYCANCEL = $00000005; MB_CANCELTRYCONTINUE = $00000006; MB_ICONHAND = $00000010; MB_ICONQUESTION = $00000020; MB_ICONEXCLAMATION = $00000030; MB_ICONASTERISK = $00000040; MB_ICONWARNING = MB_ICONEXCLAMATION; MB_ICONERROR = MB_ICONHAND; MB_ICONINFORMATION = MB_ICONASTERISK; MB_ICONSTOP = MB_ICONHAND; // 10853 IDOK = 1; IDCANCEL = 2; IDABORT = 3; IDRETRY = 4; IDIGNORE = 5; IDYES = 6; IDNO = 7; IDCLOSE = 8; IDHELP = 9; IDTRYAGAIN = 10; IDCONTINUE = 11; IDTIMEOUT = 32000; type HWND = NativeUInt; HICON = NativeUInt; HDESK = THandle; HWINSTA = THandle; WPARAM = NativeUInt; LPARAM = NativeInt; TStringEnumProcW = function (Name: PWideChar; var Context: TArray<String>): LongBool; stdcall; // 1669 TUserObjectInfoClass = ( UserObjectReserved = 0, UserObjectFlags = 1, // q, s: TUserObjectFlags UserObjectName = 2, // q: PWideChar UserObjectType = 3, // q: PWideChar UserObjectUserSid = 4, // q: PSid UserObjectHeapSize = 5, // q: Cardinal UserObjectIO = 6 // q: LongBool ); // 1682 TUserObjectFlags = record fInherit: LongBool; fReserved: LongBool; dwFlags: Cardinal; end; PUserObjectFlags = ^TUserObjectFlags; // windef.154 TRect = record left: Integer; top: Integer; right: Integer; bottom: Integer; end; // 14281 TGuiThreadInfo = record cbSize: Cardinal; flags: Cardinal; hwndActive: HWND; hwndFocus: HWND; hwndCapture: HWND; hwndMenuOwner: HWND; hwndMoveSize: HWND; hwndCaret: HWND; rcCaret: TRect; end; // Desktops // 1387 function CreateDesktopW(lpszDesktop: PWideChar; lpszDevice: PWideChar; pDevmode: Pointer; dwFlags: Cardinal; dwDesiredAccess: TAccessMask; lpsa: PSecurityAttributes): HDESK; stdcall; external user32; // 1450 function OpenDesktopW(pszDesktop: PWideChar; dwFlags: Cardinal; fInherit: LongBool; DesiredAccess: TAccessMask): HDESK; stdcall; external user32; // 1480 function EnumDesktopsW(hWinStation: HWINSTA; lpEnumFunc: TStringEnumProcW; var Context: TArray<String>): LongBool; stdcall; external user32; // 1502 function SwitchDesktop(hDesktop: HDESK): LongBool; stdcall; external user32; // rev function SwitchDesktopWithFade(hDesktop: HDESK; dwFadeTime: Cardinal): LongBool; stdcall; external user32; // 1509 function SetThreadDesktop(hDesktop: HDESK): LongBool; stdcall; external user32; // 1515 function CloseDesktop(hDesktop: HDESK): LongBool; stdcall; external user32; // 1521 function GetThreadDesktop(dwThreadId: Cardinal): HDESK; stdcall; external user32; // Window Stations // 1571 function CreateWindowStationW(lpwinsta: PWideChar; dwFlags: Cardinal; dwDesiredAccess: TAccessMask; lpsa: PSecurityAttributes): HWINSTA; stdcall; external user32; // 1592 function OpenWindowStationW(pszWinSta: PWideChar; fInherit: LongBool; DesiredAccess: TAccessMask): HWINSTA; stdcall; external user32; // 1611 function EnumWindowStationsW(lpEnumFunc: TStringEnumProcW; var Context: TArray<String>): LongBool; stdcall; external user32; // 1623 function CloseWindowStation(hWinStation: HWINSTA): LongBool; stdcall; external user32; // 1629 function SetProcessWindowStation(hWinSta: HWINSTA): LongBool; stdcall; external user32; // 1635 function GetProcessWindowStation: HWINSTA; stdcall; external user32; // rev function LockWindowStation(hWinStation: HWINSTA): LongBool; stdcall; external user32; // rev function UnlockWindowStation(hWinStation: HWINSTA): LongBool; stdcall; external user32; // rev function SetWindowStationUser(hWinStation: HWINSTA; var Luid: TLuid; Sid: PSid; SidLength: Cardinal): LongBool; stdcall; external user32; // User objects // 1700 function GetUserObjectInformationW(hObj: THandle; InfoClass: TUserObjectInfoClass; pvInfo: Pointer; nLength: Cardinal; pnLengthNeeded: PCardinal): LongBool; stdcall; external user32; // 1723 function SetUserObjectInformationW(hObj: THandle; InfoClass: TUserObjectInfoClass; pvInfo: Pointer; nLength: Cardinal): LongBool; stdcall; external user32; // Other // 4058 function WaitForInputIdle(hProcess: THandle; dwMilliseconds: Cardinal): Cardinal; stdcall; external user32; // 10618 function DestroyIcon(Icon: HICON): LongBool stdcall; external user32; // 14316 function GetGUIThreadInfo(idThread: Cardinal; var gui: TGuiThreadInfo): LongBool; stdcall; external 'user32.dll'; implementation end.
unit aggform; { This project demonstrates the use of maintained aggregates on clientdatasets. The Customer and Orders tables from DBDEMOS are used to create a master-detail relationanship. The data is transfered through the provider. On the "client" side, two aggregate fields are set up on the orders clientdataset. One is a "global" aggregate ( the grouping level of the aggregate field is zero ). The other is a grouped aggregate defined on an an index that is created on the 'ShipVIA' field. When the datasets are first opened, only the global aggregate is displayed. As you navigate through the customer dataset, the new value for that customer is displayed. If you add, delete or modify any records in the detail set the new value for the aggregate is automatically updated. If you press the 'GroupByShipVIA' button the 'ShipVIA' index is activated on the details. This also activates any non-global aggregates ( Agg.GroupingLeve > 0 ) that use this index, and now the sub-total for each shipping method is displayed. As you navigate among the detail set, if you move to a different shipping method, the aggregate value will change. Any updates to the detail dataset will force updates to the aggregate values. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, DBCtrls, Grids, DBGrids, DBClient, Provider, Db, DBTables, ExtCtrls; type TForm1 = class(TForm) CustDataSource: TDataSource; CustQuery: TQuery; OrderQuery: TQuery; Provider1: TDataSetProvider; CustOrders: TClientDataSet; DBGrid1: TDBGrid; DBEdit1: TDBEdit; CustOrdersDataSource: TDataSource; DBNavigator1: TDBNavigator; CustOrdersCustNo: TFloatField; CustOrdersCompany: TStringField; CustOrdersAddr1: TStringField; CustOrdersAddr2: TStringField; CustOrdersCity: TStringField; CustOrdersState: TStringField; CustOrdersZip: TStringField; CustOrdersCountry: TStringField; CustOrdersPhone: TStringField; CustOrdersFAX: TStringField; CustOrdersTaxRate: TFloatField; CustOrdersContact: TStringField; CustOrdersLastInvoiceDate: TDateTimeField; CustOrdersOrderQuery: TDataSetField; OrderDSDataSource: TDataSource; OrderDS: TClientDataSet; OrderDSTotalPerCustomer: TAggregateField; Button1: TButton; CustQueryCustNo: TFloatField; CustQueryCompany: TStringField; CustQueryAddr1: TStringField; CustQueryAddr2: TStringField; CustQueryCity: TStringField; CustQueryState: TStringField; CustQueryZip: TStringField; CustQueryCountry: TStringField; CustQueryPhone: TStringField; CustQueryFAX: TStringField; CustQueryTaxRate: TFloatField; CustQueryContact: TStringField; CustQueryLastInvoiceDate: TDateTimeField; DBEdit2: TDBEdit; Label1: TLabel; DBNavigator2: TDBNavigator; OrderDSOrderTotalPerShipMethod: TAggregateField; DBEdit3: TDBEdit; Button2: TButton; DBTextShipMethod: TDBEdit; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin CustOrders.Active := True; OrderDS.Active := True; end; procedure TForm1.Button2Click(Sender: TObject); begin OrderDS.IndexName := 'ShipVIA'; DBTextShipMethod.DataField := 'ShipVIA'; CustOrders.First; end; end.
unit ServData; { This is the remote datamodule for this demo. It contains the implementaion of the OLE automation object that the client application talks to. The client project contains the code which calls the SetParams method of the IProvider interface. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComServ, ComObj, VCLCom, StdVcl, DataBkr, Serv_TLB, Db, DBTables, Provider; type TSetParamDemo = class(TRemoteDataModule, ISetParamDemo) Events: TQuery; EventProvider: TDataSetProvider; procedure SetParamDemoCreate(Sender: TObject); procedure SetParamDemoDestroy(Sender: TObject); procedure EventsAfterOpen(DataSet: TDataSet); protected class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override; end; var SetParamDemo: TSetParamDemo; implementation {$R *.dfm} uses ServMain; procedure TSetParamDemo.SetParamDemoCreate(Sender: TObject); begin { Update the client counter } MainForm.UpdateClientCount(1); end; procedure TSetParamDemo.SetParamDemoDestroy(Sender: TObject); begin { Update the client counter } MainForm.UpdateClientCount(-1); end; procedure TSetParamDemo.EventsAfterOpen(DataSet: TDataSet); begin { Update the query counter } MainForm.IncQueryCount; end; class procedure TSetParamDemo.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); begin if Register then begin inherited UpdateRegistry(Register, ClassID, ProgID); EnableSocketTransport(ClassID); EnableWebTransport(ClassID); end else begin DisableSocketTransport(ClassID); DisableWebTransport(ClassID); inherited UpdateRegistry(Register, ClassID, ProgID); end; end; initialization TComponentFactory.Create(ComServer, TSetParamDemo, Class_SetParamDemo, ciMultiInstance); end.
unit uRange; interface uses Generics.Collections, uRangeElement; type TRange = class(TObject) private FRange_ID: Integer; FDescription: string; FRangeElementList: TDictionary<Integer, TRangeElement>; public constructor Create(aRange_ID: Integer; aDescription: string); function GetPlannedQuantity: Integer; procedure AddRangeElement(const aRangeElement: TRangeElement); function GetElementByID(aElement_ID: Integer) : TRangeElement; procedure RemoveElementById(aElement_ID: Integer); published property Range_ID: Integer read FRange_ID; property Description: string read FDescription write FDescription; property PlannedQuantity: Integer read GetPlannedQuantity; property Elements: TDictionary<Integer, TRangeElement> read FRangeElementList; end; implementation constructor TRange.Create(aRange_ID: Integer; aDescription: string); begin FRange_ID := aRange_ID; FDescription := aDescription; FRangeElementList := TDictionary<Integer, TRangeElement>.Create; end; function TRange.GetPlannedQuantity: Integer; var key: Integer; begin result:= 0; for key in FRangeElementList.keys do begin result := result + FRangeElementList.Items[key].GetPlannedQuantity; end; end; procedure TRange.AddRangeElement(const aRangeElement: TRangeElement); begin FRangeElementList.Add(aRangeElement.Element_ID, aRangeElement); end; function TRange.GetElementByID(aElement_ID: Integer): TRangeElement; begin Result := nil; if FRangeElementList.ContainsKey(aElement_ID) then result := FRangeElementList.Items[aElement_ID]; end; procedure TRange.RemoveElementById(aElement_ID: Integer); begin if FRangeElementList.ContainsKey(aElement_ID) then FRangeElementList.Remove(aElement_ID); end; end.
//Description: Text converter //Author: George Birbilis (birbilis@kagi.com) //Version: 30Aug2006 unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, SynEdit, SynMemo; type TForm1 = class(TForm) Label2: TLabel; txtFrom: TEdit; Label1: TLabel; txtTo: TEdit; Button1: TButton; Button2: TButton; txtSource: TSynMemo; txtTarget: TSynMemo; procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); protected procedure msgDifferentLayout; procedure msgNonReversibleMapping(const cFrom,cTo,cOther:WideChar); public procedure UpdateMapping; procedure Convert; end; var Form1: TForm1; implementation {$R *.dfm} //Messages// procedure TForm1.msgDifferentLayout; begin ShowMessage('Source and Target must have identical layout to resync the mapping'); end; procedure TForm1.msgNonReversibleMapping(const cFrom,cTo,cOther:WideChar); begin ShowMessage('Char ['+cTo+'] is already in "To" field, but mapped to char ['+cOther+'] at the "From" field. Added again to map to ['+cFrom+']. This is a non reversible (1-1) mapping'); end; //Actions// procedure TForm1.UpdateMapping; procedure UpdateWideCharMapping(const cFrom,cTo:WideChar); var p:integer; begin if pos(cFrom,txtFrom.Text)=0 then begin txtFrom.Text:=txtFrom.Text+cFrom; p:=pos(cTo,txtTo.Text); if (p<>0) then msgNonReversibleMapping(cFrom,cTo,WideChar(txtFrom.Text[p])); txtTo.Text:=txtTo.Text+cTo; end; end; var i:integer; s1,s2:WideString; begin s1:=txtSource.Text; s2:=txtTarget.Text; if (txtSource.Lines.Count<>txtTarget.Lines.Count) or (length(s1)<>length(s2)) then MsgDifferentLayout Else for i:=1 to length(s1) do updateWideCharMapping(s1[i],s2[i]); end; function convertWideChars(const s,fromChars,toChars:WideString):string; var i,p:integer; c:WideChar; begin result:=''; for i:=1 to length(s) do begin c:=s[i]; p:=pos(c,fromChars); if p=0 then result:=result+c else result:=result+toChars[p]; end; end; procedure TForm1.Convert; begin txtTarget.text:=convertWideChars(txtSource.text,txtFrom.Text,txtTo.Text); end; //Event handlers// procedure TForm1.Button2Click(Sender: TObject); begin UpdateMapping; end; procedure TForm1.Button1Click(Sender: TObject); begin Convert; end; end.
unit ANU_Base; (************************************************************************* DESCRIPTION : Anubis (tweaked) basic routines REQUIREMENTS : TP5-7, D1-D7/D9-D12/D17-D18/D25S, FPC, VP, WDOSX EXTERNAL DATA : --- MEMORY USAGE : 6.5 KB static data DISPLAY MODE : --- REFERENCES : [1] http://www.larc.usp.br/~pbarreto/AnubisPage.html [2] Tweaked version of Anubis, all zips from [1] Docs: anubis-tweak.zip C source: anubis-tweak-c.zip Test vectors: anubis-tweak-test-vectors.zip [3] The original definition of Anubis as submitted to NESSIE http://www.larc.usp.br/~pbarreto/anubis.zip REMARKS : With BASM16 the tables T0 .. T5) and the used context should be dword aligned to get optimal speed. If ANU_A4 is defined a dummy 16 bit integer is placed before T0, use the function ANU_T0Ofs to get the ofs(T0) mod 15. Since only one round key array is used, it is essential that the correct key setup is done for encryption and decryption. The block modes units check for correct setup and return error codes. The procedures ANU_Encrypt and ANU_Decrypt normally do no such checks! If the symbol debug is defined, RTE 210 is generated if the check fails. So be careful if you call these routines directly. Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.01 02.08.08 W.Ehrhardt Initial BP7 ANU_Init/RKEnc 0.02 02.08.08 we core routine, D4+ compatible 0.03 02.08.08 we ANU_Init/RKDec, TP5-6 compatible 0.04 03.08.08 we Decrypt byte in context 0.05 03.08.08 we ANU_Init2, ANU_Init_Enc, ANU_Init_Dec 0.06 05.08.08 we Names analog to AES: ANU_Init_Encr, ANU_Init_Decr 0.07 09.08.08 we Crypt BIT16 with byte vectors: speed factor 7 0.08 09.08.08 we Init2/BIT16 with byte vector typecasts 0.09 09.08.08 we Init2/BIT16 kv: byte vector absolute kappa 0.10 09.08.08 we Byte size sbox SB for inverse key setup 0.11 09.08.08 we Unroll init/final RB loops in crypt 0.12 11.08.08 we Crypt with BASM16 (speed doubled for Pentium 4) 0.13 11.08.08 we ANU_T0Ofs for BASM16, cyrpt is 60 faster if ofs(T0)=0 0.14 11.08.08 we If ANU_A4 is defined a dummy integer is placed before T0 0.15 12.08.08 we BASM16: force inter/state in crypt to be dword aligned when called from ANU_Encrypt/Decrypt 0.16 14.08.08 we Debug: Generate RTE 210 if wrong key setup detected 0.17 14.08.08 we Avoid FPC2.2.2 warning in ANU_T0Ofs: cardinal typecast $ifdef HAS_XTYPES 0.18 16.08.08 we Removed ANU_Reset 0.19 24.11.08 we Uses BTypes 0.20 09.12.08 we Updated URLs 0.21 01.08.10 we ANU_Err_CTR_SeekOffset, ANU_Err_Invalid_16Bit_Length 0.23 22.07.12 we 64-bit compatibility 0.24 25.12.12 we {$J+} if needed 0.25 19.11.17 we RB for CPUARM **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2008-2017 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i std.inc} interface const ANU_Err_Invalid_Key_Size = -1; {Key size in bits not 128, 192, or 256} ANU_Err_Invalid_Mode = -2; {Encr/Decr with Init for Decr/Encr} ANU_Err_Invalid_Length = -3; {No full block for cipher stealing} ANU_Err_Data_After_Short_Block = -4; {Short block must be last} ANU_Err_MultipleIncProcs = -5; {More than one IncProc Setting} ANU_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length} ANU_Err_EAX_Inv_Text_Length = -7; {More than 64K text length in EAX all-in-one for 16 Bit} ANU_Err_EAX_Inv_TAG_Length = -8; {EAX all-in-one tag length not 0..16} ANU_Err_EAX_Verify_Tag = -9; {EAX all-in-one tag does not compare} ANU_Err_CTR_SeekOffset = -15; {Negative offset in ANU_CTR_Seek} ANU_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code} type TANURndKey = packed array[0..18,0..3] of longint; {Round key schedule} TANUBlock = packed array[0..15] of byte; {128 bit block} PANUBlock = ^TANUBlock; type TANUIncProc = procedure(var CTR: TANUBlock); {user supplied IncCTR proc} {$ifdef DLL} stdcall; {$endif} type TANUContext = packed record IV : TANUBlock; {IV or CTR } buf : TANUBlock; {Work buffer } bLen : word; {Bytes used in buf } Rounds : word; {Number of rounds } KeyBits : word; {Number of bits in key } Decrypt : byte; {<>0 if decrypting key } Flag : byte; {Bit 1: Short block } IncProc : TANUIncProc; {Increment proc CTR-Mode} RK : TANURndKey; {Encr/Decr round keys } end; const ANUBLKSIZE = sizeof(TANUBlock); {Anubis block size in bytes} {$ifdef CONST} function ANU_Init2(const Key; KeyBits: word; var ctx: TANUContext; decr: byte): integer; {-Anubis context/round key initialization, Inverse key if decr<>0} {$ifdef DLL} stdcall; {$endif} function ANU_Init_Encr(const Key; KeyBits: word; var ctx: TANUContext): integer; {-Anubis context/round key initialization for encrytion} {$ifdef DLL} stdcall; {$endif} function ANU_Init_Decr(const Key; KeyBits: word; var ctx: TANUContext): integer; {-Anubis context/round key initialization for decr<ptionn} {$ifdef DLL} stdcall; {$endif} procedure ANU_Encrypt(var ctx: TANUContext; const BI: TANUBlock; var BO: TANUBlock); {-encrypt one block (in ECB mode)} {$ifdef DLL} stdcall; {$endif} procedure ANU_Decrypt(var ctx: TANUContext; const BI: TANUBlock; var BO: TANUBlock); {-decrypt one block (in ECB mode)} {$ifdef DLL} stdcall; {$endif} procedure ANU_XorBlock(const B1, B2: TANUBlock; var B3: TANUBlock); {-xor two blocks, result in third} {$ifdef DLL} stdcall; {$endif} {$else} function ANU_Init2(var Key; KeyBits: word; var ctx: TANUContext; decr: byte): integer; {-Anubis context/round key initialization, Inverse key if decr<>0} function ANU_Init_Encr(var Key; KeyBits: word; var ctx: TANUContext): integer; {-Anubis context/round key initialization for encrytion} function ANU_Init_Decr(var Key; KeyBits: word; var ctx: TANUContext): integer; {-Anubis context/round key initialization for decr<ptionn} procedure ANU_Encrypt(var ctx: TANUContext; var BI: TANUBlock; var BO: TANUBlock); {-encrypt one block (in ECB mode)} procedure ANU_Decrypt(var ctx: TANUContext; var BI: TANUBlock; var BO: TANUBlock); {-decrypt one block (in ECB mode)} procedure ANU_XorBlock(var B1, B2: TANUBlock; var B3: TANUBlock); {-xor two blocks, result in third} {$endif} procedure ANU_SetFastInit(value: boolean); {-set FastInit variable} {$ifdef DLL} stdcall; {$endif} function ANU_GetFastInit: boolean; {-Returns FastInit variable} {$ifdef DLL} stdcall; {$endif} function ANU_T0Ofs: byte; {-Return offset of Table T0 mod 15, used to optimize BASM16 32 bit access} implementation uses BTypes; type TXSBox = packed array[0..255] of longint; {Extended S-box} TWA4 = packed array[0..3] of longint; {Block as array of longint} {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9+ errors!} {$endif} const {$ifdef BIT16} {$ifdef ANU_A4} dummy: integer = 0; {dummy integer to dword align T0 and T1..T5} {$endif} {$endif} T0: TXSBox = ($ba69d2bb, $54a84de5, $2f5ebce2, $74e8cd25, $53a651f7, $d3bb6bd0, $d2b96fd6, $4d9a29b3, $50a05dfd, $ac458acf, $8d070e09, $bf63c6a5, $70e0dd3d, $52a455f1, $9a29527b, $4c982db5, $eac98f46, $d5b773c4, $97336655, $d1bf63dc, $3366ccaa, $51a259fb, $5bb671c7, $a651a2f3, $dea15ffe, $48903dad, $a84d9ad7, $992f5e71, $dbab4be0, $3264c8ac, $b773e695, $fce5d732, $e3dbab70, $9e214263, $913f7e41, $9b2b567d, $e2d9af76, $bb6bd6bd, $4182199b, $6edca579, $a557aef9, $cb8b0b80, $6bd6b167, $95376e59, $a15fbee1, $f3fbeb10, $b17ffe81, $0204080c, $cc851792, $c49537a2, $1d3a744e, $14285078, $c39b2bb0, $63c69157, $daa94fe6, $5dba69d3, $5fbe61df, $dca557f2, $7dfae913, $cd871394, $7ffee11f, $5ab475c1, $6cd8ad75, $5cb86dd5, $f7f3fb08, $264c98d4, $ffe3db38, $edc79354, $e8cd874a, $9d274e69, $6fdea17f, $8e010203, $19326456, $a05dbae7, $f0fde71a, $890f1e11, $0f1e3c22, $070e1c12, $af4386c5, $fbebcb20, $08102030, $152a547e, $0d1a342e, $04081018, $01020406, $64c88d45, $dfa35bf8, $76ecc529, $79f2f90b, $dda753f4, $3d7af48e, $162c5874, $3f7efc82, $376edcb2, $6ddaa973, $3870e090, $b96fdeb1, $73e6d137, $e9cf834c, $356ad4be, $55aa49e3, $71e2d93b, $7bf6f107, $8c050a0f, $72e4d531, $880d1a17, $f6f1ff0e, $2a54a8fc, $3e7cf884, $5ebc65d9, $274e9cd2, $468c0589, $0c183028, $65ca8943, $68d0bd6d, $61c2995b, $03060c0a, $c19f23bc, $57ae41ef, $d6b17fce, $d9af43ec, $58b07dcd, $d8ad47ea, $66cc8549, $d7b37bc8, $3a74e89c, $c88d078a, $3c78f088, $fae9cf26, $96316253, $a753a6f5, $982d5a77, $ecc59752, $b86ddab7, $c7933ba8, $ae4182c3, $69d2b96b, $4b9631a7, $ab4b96dd, $a94f9ed1, $67ce814f, $0a14283c, $478e018f, $f2f9ef16, $b577ee99, $224488cc, $e5d7b364, $eec19f5e, $be61c2a3, $2b56acfa, $811f3e21, $1224486c, $831b362d, $1b366c5a, $0e1c3824, $23468cca, $f5f7f304, $458a0983, $214284c6, $ce811f9e, $499239ab, $2c58b0e8, $f9efc32c, $e6d1bf6e, $b671e293, $2850a0f0, $172e5c72, $8219322b, $1a34685c, $8b0b161d, $fee1df3e, $8a09121b, $09122436, $c98f038c, $87132635, $4e9c25b9, $e1dfa37c, $2e5cb8e4, $e4d5b762, $e0dda77a, $ebcb8b40, $903d7a47, $a455aaff, $1e3c7844, $85172e39, $60c09d5d, $00000000, $254a94de, $f4f5f702, $f1ffe31c, $94356a5f, $0b162c3a, $e7d3bb68, $75eac923, $efc39b58, $3468d0b8, $3162c4a6, $d4b577c2, $d0bd67da, $86112233, $7efce519, $ad478ec9, $fde7d334, $2952a4f6, $3060c0a0, $3b76ec9a, $9f234665, $f8edc72a, $c6913fae, $13264c6a, $060c1814, $050a141e, $c59733a4, $11224466, $77eec12f, $7cf8ed15, $7af4f501, $78f0fd0d, $366cd8b4, $1c387048, $3972e496, $59b279cb, $18306050, $56ac45e9, $b37bf68d, $b07dfa87, $244890d8, $204080c0, $b279f28b, $9239724b, $a35bb6ed, $c09d27ba, $44880d85, $62c49551, $10204060, $b475ea9f, $84152a3f, $43861197, $933b764d, $c2992fb6, $4a9435a1, $bd67cea9, $8f030605, $2d5ab4ee, $bc65caaf, $9c254a6f, $6ad4b561, $40801d9d, $cf831b98, $a259b2eb, $801d3a27, $4f9e21bf, $1f3e7c42, $ca890f86, $aa4992db, $42841591); T1: TXSBox = ($69babbd2, $a854e54d, $5e2fe2bc, $e87425cd, $a653f751, $bbd3d06b, $b9d2d66f, $9a4db329, $a050fd5d, $45accf8a, $078d090e, $63bfa5c6, $e0703ddd, $a452f155, $299a7b52, $984cb52d, $c9ea468f, $b7d5c473, $33975566, $bfd1dc63, $6633aacc, $a251fb59, $b65bc771, $51a6f3a2, $a1defe5f, $9048ad3d, $4da8d79a, $2f99715e, $abdbe04b, $6432acc8, $73b795e6, $e5fc32d7, $dbe370ab, $219e6342, $3f91417e, $2b9b7d56, $d9e276af, $6bbbbdd6, $82419b19, $dc6e79a5, $57a5f9ae, $8bcb800b, $d66b67b1, $3795596e, $5fa1e1be, $fbf310eb, $7fb181fe, $04020c08, $85cc9217, $95c4a237, $3a1d4e74, $28147850, $9bc3b02b, $c6635791, $a9dae64f, $ba5dd369, $be5fdf61, $a5dcf257, $fa7d13e9, $87cd9413, $fe7f1fe1, $b45ac175, $d86c75ad, $b85cd56d, $f3f708fb, $4c26d498, $e3ff38db, $c7ed5493, $cde84a87, $279d694e, $de6f7fa1, $018e0302, $32195664, $5da0e7ba, $fdf01ae7, $0f89111e, $1e0f223c, $0e07121c, $43afc586, $ebfb20cb, $10083020, $2a157e54, $1a0d2e34, $08041810, $02010604, $c864458d, $a3dff85b, $ec7629c5, $f2790bf9, $a7ddf453, $7a3d8ef4, $2c167458, $7e3f82fc, $6e37b2dc, $da6d73a9, $703890e0, $6fb9b1de, $e67337d1, $cfe94c83, $6a35bed4, $aa55e349, $e2713bd9, $f67b07f1, $058c0f0a, $e47231d5, $0d88171a, $f1f60eff, $542afca8, $7c3e84f8, $bc5ed965, $4e27d29c, $8c468905, $180c2830, $ca654389, $d0686dbd, $c2615b99, $06030a0c, $9fc1bc23, $ae57ef41, $b1d6ce7f, $afd9ec43, $b058cd7d, $add8ea47, $cc664985, $b3d7c87b, $743a9ce8, $8dc88a07, $783c88f0, $e9fa26cf, $31965362, $53a7f5a6, $2d98775a, $c5ec5297, $6db8b7da, $93c7a83b, $41aec382, $d2696bb9, $964ba731, $4babdd96, $4fa9d19e, $ce674f81, $140a3c28, $8e478f01, $f9f216ef, $77b599ee, $4422cc88, $d7e564b3, $c1ee5e9f, $61bea3c2, $562bfaac, $1f81213e, $24126c48, $1b832d36, $361b5a6c, $1c0e2438, $4623ca8c, $f7f504f3, $8a458309, $4221c684, $81ce9e1f, $9249ab39, $582ce8b0, $eff92cc3, $d1e66ebf, $71b693e2, $5028f0a0, $2e17725c, $19822b32, $341a5c68, $0b8b1d16, $e1fe3edf, $098a1b12, $12093624, $8fc98c03, $13873526, $9c4eb925, $dfe17ca3, $5c2ee4b8, $d5e462b7, $dde07aa7, $cbeb408b, $3d90477a, $55a4ffaa, $3c1e4478, $1785392e, $c0605d9d, $00000000, $4a25de94, $f5f402f7, $fff11ce3, $35945f6a, $160b3a2c, $d3e768bb, $ea7523c9, $c3ef589b, $6834b8d0, $6231a6c4, $b5d4c277, $bdd0da67, $11863322, $fc7e19e5, $47adc98e, $e7fd34d3, $5229f6a4, $6030a0c0, $763b9aec, $239f6546, $edf82ac7, $91c6ae3f, $26136a4c, $0c061418, $0a051e14, $97c5a433, $22116644, $ee772fc1, $f87c15ed, $f47a01f5, $f0780dfd, $6c36b4d8, $381c4870, $723996e4, $b259cb79, $30185060, $ac56e945, $7bb38df6, $7db087fa, $4824d890, $4020c080, $79b28bf2, $39924b72, $5ba3edb6, $9dc0ba27, $8844850d, $c4625195, $20106040, $75b49fea, $15843f2a, $86439711, $3b934d76, $99c2b62f, $944aa135, $67bda9ce, $038f0506, $5a2deeb4, $65bcafca, $259c6f4a, $d46a61b5, $80409d1d, $83cf981b, $59a2ebb2, $1d80273a, $9e4fbf21, $3e1f427c, $89ca860f, $49aadb92, $84429115); T2: TXSBox = ($d2bbba69, $4de554a8, $bce22f5e, $cd2574e8, $51f753a6, $6bd0d3bb, $6fd6d2b9, $29b34d9a, $5dfd50a0, $8acfac45, $0e098d07, $c6a5bf63, $dd3d70e0, $55f152a4, $527b9a29, $2db54c98, $8f46eac9, $73c4d5b7, $66559733, $63dcd1bf, $ccaa3366, $59fb51a2, $71c75bb6, $a2f3a651, $5ffedea1, $3dad4890, $9ad7a84d, $5e71992f, $4be0dbab, $c8ac3264, $e695b773, $d732fce5, $ab70e3db, $42639e21, $7e41913f, $567d9b2b, $af76e2d9, $d6bdbb6b, $199b4182, $a5796edc, $aef9a557, $0b80cb8b, $b1676bd6, $6e599537, $bee1a15f, $eb10f3fb, $fe81b17f, $080c0204, $1792cc85, $37a2c495, $744e1d3a, $50781428, $2bb0c39b, $915763c6, $4fe6daa9, $69d35dba, $61df5fbe, $57f2dca5, $e9137dfa, $1394cd87, $e11f7ffe, $75c15ab4, $ad756cd8, $6dd55cb8, $fb08f7f3, $98d4264c, $db38ffe3, $9354edc7, $874ae8cd, $4e699d27, $a17f6fde, $02038e01, $64561932, $bae7a05d, $e71af0fd, $1e11890f, $3c220f1e, $1c12070e, $86c5af43, $cb20fbeb, $20300810, $547e152a, $342e0d1a, $10180408, $04060102, $8d4564c8, $5bf8dfa3, $c52976ec, $f90b79f2, $53f4dda7, $f48e3d7a, $5874162c, $fc823f7e, $dcb2376e, $a9736dda, $e0903870, $deb1b96f, $d13773e6, $834ce9cf, $d4be356a, $49e355aa, $d93b71e2, $f1077bf6, $0a0f8c05, $d53172e4, $1a17880d, $ff0ef6f1, $a8fc2a54, $f8843e7c, $65d95ebc, $9cd2274e, $0589468c, $30280c18, $894365ca, $bd6d68d0, $995b61c2, $0c0a0306, $23bcc19f, $41ef57ae, $7fced6b1, $43ecd9af, $7dcd58b0, $47ead8ad, $854966cc, $7bc8d7b3, $e89c3a74, $078ac88d, $f0883c78, $cf26fae9, $62539631, $a6f5a753, $5a77982d, $9752ecc5, $dab7b86d, $3ba8c793, $82c3ae41, $b96b69d2, $31a74b96, $96ddab4b, $9ed1a94f, $814f67ce, $283c0a14, $018f478e, $ef16f2f9, $ee99b577, $88cc2244, $b364e5d7, $9f5eeec1, $c2a3be61, $acfa2b56, $3e21811f, $486c1224, $362d831b, $6c5a1b36, $38240e1c, $8cca2346, $f304f5f7, $0983458a, $84c62142, $1f9ece81, $39ab4992, $b0e82c58, $c32cf9ef, $bf6ee6d1, $e293b671, $a0f02850, $5c72172e, $322b8219, $685c1a34, $161d8b0b, $df3efee1, $121b8a09, $24360912, $038cc98f, $26358713, $25b94e9c, $a37ce1df, $b8e42e5c, $b762e4d5, $a77ae0dd, $8b40ebcb, $7a47903d, $aaffa455, $78441e3c, $2e398517, $9d5d60c0, $00000000, $94de254a, $f702f4f5, $e31cf1ff, $6a5f9435, $2c3a0b16, $bb68e7d3, $c92375ea, $9b58efc3, $d0b83468, $c4a63162, $77c2d4b5, $67dad0bd, $22338611, $e5197efc, $8ec9ad47, $d334fde7, $a4f62952, $c0a03060, $ec9a3b76, $46659f23, $c72af8ed, $3faec691, $4c6a1326, $1814060c, $141e050a, $33a4c597, $44661122, $c12f77ee, $ed157cf8, $f5017af4, $fd0d78f0, $d8b4366c, $70481c38, $e4963972, $79cb59b2, $60501830, $45e956ac, $f68db37b, $fa87b07d, $90d82448, $80c02040, $f28bb279, $724b9239, $b6eda35b, $27bac09d, $0d854488, $955162c4, $40601020, $ea9fb475, $2a3f8415, $11974386, $764d933b, $2fb6c299, $35a14a94, $cea9bd67, $06058f03, $b4ee2d5a, $caafbc65, $4a6f9c25, $b5616ad4, $1d9d4080, $1b98cf83, $b2eba259, $3a27801d, $21bf4f9e, $7c421f3e, $0f86ca89, $92dbaa49, $15914284); T3: TXSBox = ($bbd269ba, $e54da854, $e2bc5e2f, $25cde874, $f751a653, $d06bbbd3, $d66fb9d2, $b3299a4d, $fd5da050, $cf8a45ac, $090e078d, $a5c663bf, $3ddde070, $f155a452, $7b52299a, $b52d984c, $468fc9ea, $c473b7d5, $55663397, $dc63bfd1, $aacc6633, $fb59a251, $c771b65b, $f3a251a6, $fe5fa1de, $ad3d9048, $d79a4da8, $715e2f99, $e04babdb, $acc86432, $95e673b7, $32d7e5fc, $70abdbe3, $6342219e, $417e3f91, $7d562b9b, $76afd9e2, $bdd66bbb, $9b198241, $79a5dc6e, $f9ae57a5, $800b8bcb, $67b1d66b, $596e3795, $e1be5fa1, $10ebfbf3, $81fe7fb1, $0c080402, $921785cc, $a23795c4, $4e743a1d, $78502814, $b02b9bc3, $5791c663, $e64fa9da, $d369ba5d, $df61be5f, $f257a5dc, $13e9fa7d, $941387cd, $1fe1fe7f, $c175b45a, $75add86c, $d56db85c, $08fbf3f7, $d4984c26, $38dbe3ff, $5493c7ed, $4a87cde8, $694e279d, $7fa1de6f, $0302018e, $56643219, $e7ba5da0, $1ae7fdf0, $111e0f89, $223c1e0f, $121c0e07, $c58643af, $20cbebfb, $30201008, $7e542a15, $2e341a0d, $18100804, $06040201, $458dc864, $f85ba3df, $29c5ec76, $0bf9f279, $f453a7dd, $8ef47a3d, $74582c16, $82fc7e3f, $b2dc6e37, $73a9da6d, $90e07038, $b1de6fb9, $37d1e673, $4c83cfe9, $bed46a35, $e349aa55, $3bd9e271, $07f1f67b, $0f0a058c, $31d5e472, $171a0d88, $0efff1f6, $fca8542a, $84f87c3e, $d965bc5e, $d29c4e27, $89058c46, $2830180c, $4389ca65, $6dbdd068, $5b99c261, $0a0c0603, $bc239fc1, $ef41ae57, $ce7fb1d6, $ec43afd9, $cd7db058, $ea47add8, $4985cc66, $c87bb3d7, $9ce8743a, $8a078dc8, $88f0783c, $26cfe9fa, $53623196, $f5a653a7, $775a2d98, $5297c5ec, $b7da6db8, $a83b93c7, $c38241ae, $6bb9d269, $a731964b, $dd964bab, $d19e4fa9, $4f81ce67, $3c28140a, $8f018e47, $16eff9f2, $99ee77b5, $cc884422, $64b3d7e5, $5e9fc1ee, $a3c261be, $faac562b, $213e1f81, $6c482412, $2d361b83, $5a6c361b, $24381c0e, $ca8c4623, $04f3f7f5, $83098a45, $c6844221, $9e1f81ce, $ab399249, $e8b0582c, $2cc3eff9, $6ebfd1e6, $93e271b6, $f0a05028, $725c2e17, $2b321982, $5c68341a, $1d160b8b, $3edfe1fe, $1b12098a, $36241209, $8c038fc9, $35261387, $b9259c4e, $7ca3dfe1, $e4b85c2e, $62b7d5e4, $7aa7dde0, $408bcbeb, $477a3d90, $ffaa55a4, $44783c1e, $392e1785, $5d9dc060, $00000000, $de944a25, $02f7f5f4, $1ce3fff1, $5f6a3594, $3a2c160b, $68bbd3e7, $23c9ea75, $589bc3ef, $b8d06834, $a6c46231, $c277b5d4, $da67bdd0, $33221186, $19e5fc7e, $c98e47ad, $34d3e7fd, $f6a45229, $a0c06030, $9aec763b, $6546239f, $2ac7edf8, $ae3f91c6, $6a4c2613, $14180c06, $1e140a05, $a43397c5, $66442211, $2fc1ee77, $15edf87c, $01f5f47a, $0dfdf078, $b4d86c36, $4870381c, $96e47239, $cb79b259, $50603018, $e945ac56, $8df67bb3, $87fa7db0, $d8904824, $c0804020, $8bf279b2, $4b723992, $edb65ba3, $ba279dc0, $850d8844, $5195c462, $60402010, $9fea75b4, $3f2a1584, $97118643, $4d763b93, $b62f99c2, $a135944a, $a9ce67bd, $0506038f, $eeb45a2d, $afca65bc, $6f4a259c, $61b5d46a, $9d1d8040, $981b83cf, $ebb259a2, $273a1d80, $bf219e4f, $427c3e1f, $860f89ca, $db9249aa, $91158442); T4: TXSBox = ($babababa, $54545454, $2f2f2f2f, $74747474, $53535353, $d3d3d3d3, $d2d2d2d2, $4d4d4d4d, $50505050, $acacacac, $8d8d8d8d, $bfbfbfbf, $70707070, $52525252, $9a9a9a9a, $4c4c4c4c, $eaeaeaea, $d5d5d5d5, $97979797, $d1d1d1d1, $33333333, $51515151, $5b5b5b5b, $a6a6a6a6, $dededede, $48484848, $a8a8a8a8, $99999999, $dbdbdbdb, $32323232, $b7b7b7b7, $fcfcfcfc, $e3e3e3e3, $9e9e9e9e, $91919191, $9b9b9b9b, $e2e2e2e2, $bbbbbbbb, $41414141, $6e6e6e6e, $a5a5a5a5, $cbcbcbcb, $6b6b6b6b, $95959595, $a1a1a1a1, $f3f3f3f3, $b1b1b1b1, $02020202, $cccccccc, $c4c4c4c4, $1d1d1d1d, $14141414, $c3c3c3c3, $63636363, $dadadada, $5d5d5d5d, $5f5f5f5f, $dcdcdcdc, $7d7d7d7d, $cdcdcdcd, $7f7f7f7f, $5a5a5a5a, $6c6c6c6c, $5c5c5c5c, $f7f7f7f7, $26262626, $ffffffff, $edededed, $e8e8e8e8, $9d9d9d9d, $6f6f6f6f, $8e8e8e8e, $19191919, $a0a0a0a0, $f0f0f0f0, $89898989, $0f0f0f0f, $07070707, $afafafaf, $fbfbfbfb, $08080808, $15151515, $0d0d0d0d, $04040404, $01010101, $64646464, $dfdfdfdf, $76767676, $79797979, $dddddddd, $3d3d3d3d, $16161616, $3f3f3f3f, $37373737, $6d6d6d6d, $38383838, $b9b9b9b9, $73737373, $e9e9e9e9, $35353535, $55555555, $71717171, $7b7b7b7b, $8c8c8c8c, $72727272, $88888888, $f6f6f6f6, $2a2a2a2a, $3e3e3e3e, $5e5e5e5e, $27272727, $46464646, $0c0c0c0c, $65656565, $68686868, $61616161, $03030303, $c1c1c1c1, $57575757, $d6d6d6d6, $d9d9d9d9, $58585858, $d8d8d8d8, $66666666, $d7d7d7d7, $3a3a3a3a, $c8c8c8c8, $3c3c3c3c, $fafafafa, $96969696, $a7a7a7a7, $98989898, $ecececec, $b8b8b8b8, $c7c7c7c7, $aeaeaeae, $69696969, $4b4b4b4b, $abababab, $a9a9a9a9, $67676767, $0a0a0a0a, $47474747, $f2f2f2f2, $b5b5b5b5, $22222222, $e5e5e5e5, $eeeeeeee, $bebebebe, $2b2b2b2b, $81818181, $12121212, $83838383, $1b1b1b1b, $0e0e0e0e, $23232323, $f5f5f5f5, $45454545, $21212121, $cececece, $49494949, $2c2c2c2c, $f9f9f9f9, $e6e6e6e6, $b6b6b6b6, $28282828, $17171717, $82828282, $1a1a1a1a, $8b8b8b8b, $fefefefe, $8a8a8a8a, $09090909, $c9c9c9c9, $87878787, $4e4e4e4e, $e1e1e1e1, $2e2e2e2e, $e4e4e4e4, $e0e0e0e0, $ebebebeb, $90909090, $a4a4a4a4, $1e1e1e1e, $85858585, $60606060, $00000000, $25252525, $f4f4f4f4, $f1f1f1f1, $94949494, $0b0b0b0b, $e7e7e7e7, $75757575, $efefefef, $34343434, $31313131, $d4d4d4d4, $d0d0d0d0, $86868686, $7e7e7e7e, $adadadad, $fdfdfdfd, $29292929, $30303030, $3b3b3b3b, $9f9f9f9f, $f8f8f8f8, $c6c6c6c6, $13131313, $06060606, $05050505, $c5c5c5c5, $11111111, $77777777, $7c7c7c7c, $7a7a7a7a, $78787878, $36363636, $1c1c1c1c, $39393939, $59595959, $18181818, $56565656, $b3b3b3b3, $b0b0b0b0, $24242424, $20202020, $b2b2b2b2, $92929292, $a3a3a3a3, $c0c0c0c0, $44444444, $62626262, $10101010, $b4b4b4b4, $84848484, $43434343, $93939393, $c2c2c2c2, $4a4a4a4a, $bdbdbdbd, $8f8f8f8f, $2d2d2d2d, $bcbcbcbc, $9c9c9c9c, $6a6a6a6a, $40404040, $cfcfcfcf, $a2a2a2a2, $80808080, $4f4f4f4f, $1f1f1f1f, $cacacaca, $aaaaaaaa, $42424242); T5: TXSBox = ($00000000, $01020608, $02040c10, $03060a18, $04081820, $050a1e28, $060c1430, $070e1238, $08103040, $09123648, $0a143c50, $0b163a58, $0c182860, $0d1a2e68, $0e1c2470, $0f1e2278, $10206080, $11226688, $12246c90, $13266a98, $142878a0, $152a7ea8, $162c74b0, $172e72b8, $183050c0, $193256c8, $1a345cd0, $1b365ad8, $1c3848e0, $1d3a4ee8, $1e3c44f0, $1f3e42f8, $2040c01d, $2142c615, $2244cc0d, $2346ca05, $2448d83d, $254ade35, $264cd42d, $274ed225, $2850f05d, $2952f655, $2a54fc4d, $2b56fa45, $2c58e87d, $2d5aee75, $2e5ce46d, $2f5ee265, $3060a09d, $3162a695, $3264ac8d, $3366aa85, $3468b8bd, $356abeb5, $366cb4ad, $376eb2a5, $387090dd, $397296d5, $3a749ccd, $3b769ac5, $3c7888fd, $3d7a8ef5, $3e7c84ed, $3f7e82e5, $40809d3a, $41829b32, $4284912a, $43869722, $4488851a, $458a8312, $468c890a, $478e8f02, $4890ad7a, $4992ab72, $4a94a16a, $4b96a762, $4c98b55a, $4d9ab352, $4e9cb94a, $4f9ebf42, $50a0fdba, $51a2fbb2, $52a4f1aa, $53a6f7a2, $54a8e59a, $55aae392, $56ace98a, $57aeef82, $58b0cdfa, $59b2cbf2, $5ab4c1ea, $5bb6c7e2, $5cb8d5da, $5dbad3d2, $5ebcd9ca, $5fbedfc2, $60c05d27, $61c25b2f, $62c45137, $63c6573f, $64c84507, $65ca430f, $66cc4917, $67ce4f1f, $68d06d67, $69d26b6f, $6ad46177, $6bd6677f, $6cd87547, $6dda734f, $6edc7957, $6fde7f5f, $70e03da7, $71e23baf, $72e431b7, $73e637bf, $74e82587, $75ea238f, $76ec2997, $77ee2f9f, $78f00de7, $79f20bef, $7af401f7, $7bf607ff, $7cf815c7, $7dfa13cf, $7efc19d7, $7ffe1fdf, $801d2774, $811f217c, $82192b64, $831b2d6c, $84153f54, $8517395c, $86113344, $8713354c, $880d1734, $890f113c, $8a091b24, $8b0b1d2c, $8c050f14, $8d07091c, $8e010304, $8f03050c, $903d47f4, $913f41fc, $92394be4, $933b4dec, $94355fd4, $953759dc, $963153c4, $973355cc, $982d77b4, $992f71bc, $9a297ba4, $9b2b7dac, $9c256f94, $9d27699c, $9e216384, $9f23658c, $a05de769, $a15fe161, $a259eb79, $a35bed71, $a455ff49, $a557f941, $a651f359, $a753f551, $a84dd729, $a94fd121, $aa49db39, $ab4bdd31, $ac45cf09, $ad47c901, $ae41c319, $af43c511, $b07d87e9, $b17f81e1, $b2798bf9, $b37b8df1, $b4759fc9, $b57799c1, $b67193d9, $b77395d1, $b86db7a9, $b96fb1a1, $ba69bbb9, $bb6bbdb1, $bc65af89, $bd67a981, $be61a399, $bf63a591, $c09dba4e, $c19fbc46, $c299b65e, $c39bb056, $c495a26e, $c597a466, $c691ae7e, $c793a876, $c88d8a0e, $c98f8c06, $ca89861e, $cb8b8016, $cc85922e, $cd879426, $ce819e3e, $cf839836, $d0bddace, $d1bfdcc6, $d2b9d6de, $d3bbd0d6, $d4b5c2ee, $d5b7c4e6, $d6b1cefe, $d7b3c8f6, $d8adea8e, $d9afec86, $daa9e69e, $dbabe096, $dca5f2ae, $dda7f4a6, $dea1febe, $dfa3f8b6, $e0dd7a53, $e1df7c5b, $e2d97643, $e3db704b, $e4d56273, $e5d7647b, $e6d16e63, $e7d3686b, $e8cd4a13, $e9cf4c1b, $eac94603, $ebcb400b, $ecc55233, $edc7543b, $eec15e23, $efc3582b, $f0fd1ad3, $f1ff1cdb, $f2f916c3, $f3fb10cb, $f4f502f3, $f5f704fb, $f6f10ee3, $f7f308eb, $f8ed2a93, $f9ef2c9b, $fae92683, $fbeb208b, $fce532b3, $fde734bb, $fee13ea3, $ffe338ab); SB: array[byte] of byte = ($ba,$54,$2f,$74,$53,$d3,$d2,$4d,$50,$ac,$8d,$bf,$70,$52,$9a,$4c, $ea,$d5,$97,$d1,$33,$51,$5b,$a6,$de,$48,$a8,$99,$db,$32,$b7,$fc, $e3,$9e,$91,$9b,$e2,$bb,$41,$6e,$a5,$cb,$6b,$95,$a1,$f3,$b1,$02, $cc,$c4,$1d,$14,$c3,$63,$da,$5d,$5f,$dc,$7d,$cd,$7f,$5a,$6c,$5c, $f7,$26,$ff,$ed,$e8,$9d,$6f,$8e,$19,$a0,$f0,$89,$0f,$07,$af,$fb, $08,$15,$0d,$04,$01,$64,$df,$76,$79,$dd,$3d,$16,$3f,$37,$6d,$38, $b9,$73,$e9,$35,$55,$71,$7b,$8c,$72,$88,$f6,$2a,$3e,$5e,$27,$46, $0c,$65,$68,$61,$03,$c1,$57,$d6,$d9,$58,$d8,$66,$d7,$3a,$c8,$3c, $fa,$96,$a7,$98,$ec,$b8,$c7,$ae,$69,$4b,$ab,$a9,$67,$0a,$47,$f2, $b5,$22,$e5,$ee,$be,$2b,$81,$12,$83,$1b,$0e,$23,$f5,$45,$21,$ce, $49,$2c,$f9,$e6,$b6,$28,$17,$82,$1a,$8b,$fe,$8a,$09,$c9,$87,$4e, $e1,$2e,$e4,$e0,$eb,$90,$a4,$1e,$85,$60,$00,$25,$f4,$f1,$94,$0b, $e7,$75,$ef,$34,$31,$d4,$d0,$86,$7e,$ad,$fd,$29,$30,$3b,$9f,$f8, $c6,$13,$06,$05,$c5,$11,$77,$7c,$7a,$78,$36,$1c,$39,$59,$18,$56, $b3,$b0,$24,$20,$b2,$92,$a3,$c0,$44,$62,$10,$b4,$84,$43,$93,$c2, $4a,$bd,$8f,$2d,$bc,$9c,$6a,$40,$cf,$a2,$80,$4f,$1f,$ca,$aa,$42); RC: array[0..18] of longint = ($ba542f74, $53d3d24d, $50ac8dbf, $70529a4c, $ead597d1, $33515ba6, $de48a899, $db32b7fc, $e39e919b, $e2bb416e, $a5cb6b95, $a1f3b102, $ccc41d14, $c363da5d, $5fdc7dcd, $7f5a6c5c, $f726ffed, $e89d6f8e, $19a0f089); const X000000ff = longint($000000ff); {Avoid D4+ warnings} X0000ff00 = longint($0000ff00); X00ff0000 = longint($00ff0000); Xff000000 = longint($ff000000); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} {$ifdef D4Plus} var {$else} {$ifdef J_OPT} {$J+} {$endif} const {$endif} FastInit : boolean = true; {Clear only necessary context data at init} {IV and buf remain uninitialized} {$ifndef BIT16} {------- 32/64-bit code --------} {$ifdef BIT64} {---------------------------------------------------------------------------} function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-reverse byte order in longint} begin RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24); end; {$else} {$ifdef CPUARM} {---------------------------------------------------------------------------} function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-reverse byte order in longint} begin RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24); end; {$else} {---------------------------------------------------------------------------} function RB(A: longint): longint; assembler; {&frame-} {-reverse byte order in longint} asm {$ifdef LoadArgs} mov eax,[A] {$endif} xchg al,ah rol eax,16 xchg al,ah end; {$endif} {$endif} {$else} {---------------------------------------------------------------------------} function RB(A: longint): longint; {-reverse byte order in longint} inline( $58/ {pop ax } $5A/ {pop dx } $86/$C6/ {xchg dh,al} $86/$E2); {xchg dl,ah} {$endif} {$ifdef BASM16} {---------------------------------------------------------------------------} procedure ANU_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TANUBlock; var B3: TANUBlock); {-xor two blocks, result in third} begin asm mov di,ds lds si,[B1] db $66; mov ax,[si] db $66; mov bx,[si+4] db $66; mov cx,[si+8] db $66; mov dx,[si+12] lds si,[B2] db $66; xor ax,[si] db $66; xor bx,[si+4] db $66; xor cx,[si+8] db $66; xor dx,[si+12] lds si,[B3] db $66; mov [si],ax db $66; mov [si+4],bx db $66; mov [si+8],cx db $66; mov [si+12],dx mov ds,di end; end; {$else} {---------------------------------------------------------------------------} procedure ANU_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TANUBlock; var B3: TANUBlock); {-xor two blocks, result in third} var a1: TWA4 absolute B1; a2: TWA4 absolute B2; a3: TWA4 absolute B3; begin a3[0] := a1[0] xor a2[0]; a3[1] := a1[1] xor a2[1]; a3[2] := a1[2] xor a2[2]; a3[3] := a1[3] xor a2[3]; end; {$endif BASM16} {---------------------------------------------------------------------------} procedure ANU_SetFastInit(value: boolean); {-set FastInit variable} begin FastInit := value; end; {---------------------------------------------------------------------------} function ANU_GetFastInit: boolean; {-Returns FastInit variable} begin ANU_GetFastInit := FastInit; end; {$ifndef BIT16} {---------------------------------------------------------------------------} function ANU_Init2(const Key; KeyBits: word; var ctx: TANUContext; decr: byte): integer; {-Anubis context/round key initialization, decrypt if decr<>0} var kappa,inter: array[0..9] of longint; i,j,N,N1,r: integer; K0,K1,K2,K3: longint; RKEnc: TANURndKey; begin if (KeyBits and $1F <> 0) or (KeyBits<128) or (KeyBits>320) then begin ANU_Init2 := ANU_Err_Invalid_Key_Size; exit; end; ANU_Init2 := 0; if FastInit then with ctx do begin {Clear only the necessary context data at init. IV and buf} {remain uninitialized, other fields are initialized below.} bLen :=0; Flag :=0; IncProc := nil; end else fillchar(ctx, sizeof(ctx), 0); N := KeyBits shr 5; N1 := pred(N); ctx.Rounds := 8 + N; ctx.Keybits := KeyBits; ctx.Decrypt := decr; {map cipher key to initial key state} for i:=0 to N1 do kappa[i] := RB(TXSBox(Key)[i]); {generate Rounds + 1 round keys} for r:=0 to ctx.Rounds do begin K0 := T4[kappa[N1] shr 24]; K1 := T4[kappa[N1] shr 16 and $ff]; K2 := T4[kappa[N1] shr 8 and $ff]; K3 := T4[kappa[N1] and $ff]; for i:=N-2 downto 0 do begin K0 := T4[kappa[i] shr 24] xor (T5[K0 shr 24 ] and Xff000000) xor (T5[K0 shr 16 and $ff] and X00ff0000) xor (T5[K0 shr 8 and $ff] and X0000ff00) xor (T5[K0 and $ff] and X000000ff); K1 := T4[kappa[i] shr 16 and $ff] xor (T5[K1 shr 24 ] and Xff000000) xor (T5[K1 shr 16 and $ff] and X00ff0000) xor (T5[K1 shr 8 and $ff] and X0000ff00) xor (T5[K1 and $ff] and X000000ff); K2 := T4[kappa[i] shr 8 and $ff] xor (T5[K2 shr 24 ] and Xff000000) xor (T5[K2 shr 16 and $ff] and X00ff0000) xor (T5[K2 shr 8 and $ff] and X0000ff00) xor (T5[K2 and $ff] and X000000ff); K3 := T4[kappa[i] and $ff] xor (T5[K3 shr 24 ] and Xff000000) xor (T5[K3 shr 16 and $ff] and X00ff0000) xor (T5[K3 shr 8 and $ff] and X0000ff00) xor (T5[K3 and $ff] and X000000ff); end; {for i} ctx.RK[r][0] := K0; ctx.RK[r][1] := K1; ctx.RK[r][2] := K2; ctx.RK[r][3] := K3; if r<ctx.Rounds then begin for i:=0 to N1 do begin j := i; inter[i] := T0[kappa[j] shr 24]; if j=0 then j:=N1 else dec(j); inter[i] := inter[i] xor T1[kappa[j] shr 16 and $ff]; if j=0 then j:=N1 else dec(j); inter[i] := inter[i] xor T2[kappa[j] shr 8 and $ff]; if j=0 then j:=N1 else dec(j); inter[i] := inter[i] xor T3[kappa[j] and $ff]; end; kappa[0] := inter[0] xor RC[r]; for i:=1 to pred(N) do kappa[i] := inter[i]; end; end; {generate inverse key schedule} if decr<>0 then with ctx do begin RKEnc := RK; j := Rounds; for i:=0 to 3 do begin RK[0][i] := RKEnc[j][i]; RK[j][i] := RKEnc[0][i]; end; for r:=1 to pred(j) do begin for i:=0 to 3 do begin K0 := RKEnc[j-r][i]; RK[r][i] := T0[SB[K0 shr 24 ]] xor T1[SB[K0 shr 16 and $ff]] xor T2[SB[K0 shr 8 and $ff]] xor T3[SB[K0 and $ff]]; end; end; end; end; {---------------------------------------------------------------------------} procedure crypt(const BI: TANUBlock; var BO: TANUBlock; const roundKey: TANURndKey; RR: integer); {-core crypting routine, enc/dec differ only for roundKey} var r: integer; state, inter: TWA4; begin {map plaintext block to cipher state and add initial round key} state[0] := RB(TWA4(BI)[0]) xor roundKey[0][0]; state[1] := RB(TWA4(BI)[1]) xor roundKey[0][1]; state[2] := RB(TWA4(BI)[2]) xor roundKey[0][2]; state[3] := RB(TWA4(BI)[3]) xor roundKey[0][3]; {RR-1 full rounds} for r:=1 to RR-1 do begin inter[0] := T0[state[0] shr 24 ] xor T1[state[1] shr 24 ] xor T2[state[2] shr 24 ] xor T3[state[3] shr 24 ] xor roundKey[r][0]; inter[1] := T0[state[0] shr 16 and $ff] xor T1[state[1] shr 16 and $ff] xor T2[state[2] shr 16 and $ff] xor T3[state[3] shr 16 and $ff] xor roundKey[r][1]; inter[2] := T0[state[0] shr 8 and $ff] xor T1[state[1] shr 8 and $ff] xor T2[state[2] shr 8 and $ff] xor T3[state[3] shr 8 and $ff] xor roundKey[r][2]; inter[3] := T0[state[0] and $ff] xor T1[state[1] and $ff] xor T2[state[2] and $ff] xor T3[state[3] and $ff] xor roundKey[r][3]; state[0] := inter[0]; state[1] := inter[1]; state[2] := inter[2]; state[3] := inter[3]; end; {last round} inter[0] := (T0[state[0] shr 24 ] and Xff000000) xor (T1[state[1] shr 24 ] and X00ff0000) xor (T2[state[2] shr 24 ] and X0000ff00) xor (T3[state[3] shr 24 ] and X000000ff) xor roundKey[RR][0]; inter[1] := (T0[state[0] shr 16 and $ff] and Xff000000) xor (T1[state[1] shr 16 and $ff] and X00ff0000) xor (T2[state[2] shr 16 and $ff] and X0000ff00) xor (T3[state[3] shr 16 and $ff] and X000000ff) xor roundKey[RR][1]; inter[2] := (T0[state[0] shr 8 and $ff] and Xff000000) xor (T1[state[1] shr 8 and $ff] and X00ff0000) xor (T2[state[2] shr 8 and $ff] and X0000ff00) xor (T3[state[3] shr 8 and $ff] and X000000ff) xor roundKey[RR][2]; inter[3] := (T0[state[0] and $ff] and Xff000000) xor (T1[state[1] and $ff] and X00ff0000) xor (T2[state[2] and $ff] and X0000ff00) xor (T3[state[3] and $ff] and X000000ff) xor roundKey[RR][3]; {map cipher state to ciphertext block} TWA4(BO)[0] := RB(inter[0]); TWA4(BO)[1] := RB(inter[1]); TWA4(BO)[2] := RB(inter[2]); TWA4(BO)[3] := RB(inter[3]); end; {$else} {---------------------------------------------------------------------------} function ANU_Init2({$ifdef CONST} const {$else} var {$endif} Key; KeyBits: word; var ctx: TANUContext; decr: byte): integer; {-Anubis context/round key initialization, decrypt if decr<>0} type TBA4 = array[0..3] of byte; var i,j,N,N1,N14,r: integer; K0,K1,K2,K3: longint; RKEnc: TANURndKey; kappa,inter: array[0..9] of longint; kv: array[0..39] of byte absolute kappa; begin if (KeyBits and $1F <> 0) or (KeyBits<128) or (KeyBits>320) then begin ANU_Init2 := ANU_Err_Invalid_Key_Size; exit; end; ANU_Init2 := 0; if FastInit then with ctx do begin {Clear only the necessary context data at init. IV and buf} {remain uninitialized, other fields are initialized below.} bLen :=0; Flag :=0; {$ifdef CONST} IncProc := nil; {$else} {TP5-6 do not like IncProc := nil;} fillchar(IncProc, sizeof(IncProc), 0); {$endif} end else fillchar(ctx, sizeof(ctx), 0); N := KeyBits shr 5; N1 := pred(N); N14 := 4*N1; ctx.Rounds := 8 + N; ctx.Keybits := KeyBits; ctx.Decrypt := decr; {map cipher key to initial key state} for i:=0 to N1 do kappa[i] := RB(TXSBox(Key)[i]); {generate Rounds + 1 round keys} for r:=0 to ctx.Rounds do begin j := N14; K0 := T4[kv[j+3]]; K1 := T4[kv[j+2]]; K2 := T4[kv[j+1]]; K3 := T4[kv[j ]]; for i:=N-2 downto 0 do begin dec(j,4); K0 := T4[kv[j+3]] xor (T5[TBA4(K0)[3]] and Xff000000) xor (T5[TBA4(K0)[2]] and X00ff0000) xor (T5[TBA4(K0)[1]] and X0000ff00) xor (T5[TBA4(K0)[0]] and X000000ff); K1 := T4[kv[j+2]] xor (T5[TBA4(K1)[3]] and Xff000000) xor (T5[TBA4(K1)[2]] and X00ff0000) xor (T5[TBA4(K1)[1]] and X0000ff00) xor (T5[TBA4(K1)[0]] and X000000ff); K2 := T4[kv[j+1]] xor (T5[TBA4(K2)[3]] and Xff000000) xor (T5[TBA4(K2)[2]] and X00ff0000) xor (T5[TBA4(K2)[1]] and X0000ff00) xor (T5[TBA4(K2)[0]] and X000000ff); K3 := T4[kv[j ]] xor (T5[TBA4(K3)[3]] and Xff000000) xor (T5[TBA4(K3)[2]] and X00ff0000) xor (T5[TBA4(K3)[1]] and X0000ff00) xor (T5[TBA4(K3)[0]] and X000000ff); end; {for i} ctx.RK[r][0] := K0; ctx.RK[r][1] := K1; ctx.RK[r][2] := K2; ctx.RK[r][3] := K3; if r<ctx.Rounds then begin for i:=0 to N1 do begin j := 4*i; inter[i] := T0[kv[j+3]]; if j=0 then j:=N14 else dec(j,4); inter[i] := inter[i] xor T1[kv[j+2]]; if j=0 then j:=N14 else dec(j,4); inter[i] := inter[i] xor T2[kv[j+1]]; if j=0 then j:=N14 else dec(j,4); inter[i] := inter[i] xor T3[kv[j ]]; end; kappa[0] := inter[0] xor RC[r]; for i:=1 to N1 do kappa[i] := inter[i]; end; end; {generate inverse key schedule} if decr<>0 then with ctx do begin RKEnc := RK; j := Rounds; for i:=0 to 3 do begin RK[0][i] := RKEnc[j][i]; RK[j][i] := RKEnc[0][i]; end; for r:=1 to pred(j) do begin for i:=0 to 3 do begin K0 := RKEnc[j-r][i]; RK[r][i] := T0[SB[TBA4(K0)[3]]] xor T1[SB[TBA4(K0)[2]]] xor T2[SB[TBA4(K0)[1]]] xor T3[SB[TBA4(K0)[0]]]; end; end; end; end; {---------------------------------------------------------------------------} {$ifdef BASM16} {$ifdef CONST} procedure crypt(const BI: TANUBlock; var BO: TANUBlock; const roundKey: TANURndKey; RR: integer); {-core crypting routine, enc/dec differ only for roundKey} {$else} procedure crypt(var BI: TANUBlock; var BO: TANUBlock; var roundKey: TANURndKey; RR: integer); {-core crypting routine, enc/dec differ only for roundKey} {$endif} var state, inter: TWA4; sv: TANUBlock absolute state; iv: TANUBlock absolute inter; const X000000ff: longint = $000000ff; X0000ff00: longint = $0000ff00; X00ff0000: longint = $00ff0000; Xff000000: longint = $ff000000; begin asm {map plaintext block to cipher state and add initial round key} push ds lds si,[bi] les di,[roundkey] {state[0] := RB(TWA4(BI)[0]) xor roundKey[0][0]} db $66; mov ax,[si] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; xor ax,es:[di] db $66; mov word ptr state[0], ax {state[1] := RB(TWA4(BI)[1]) xor roundKey[0][1]} db $66; mov ax,[si+4] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; xor ax,es:[di+4] db $66; mov word ptr state[4], ax {state[2] := RB(TWA4(BI)[2]) xor roundKey[0][2]} db $66; mov ax,[si+8] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; xor ax,es:[di+8] db $66; mov word ptr state[8], ax {state[3] := RB(TWA4(BI)[3]) xor roundKey[0][3]} db $66; mov ax,[si+12] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; xor ax,es:[di+12] db $66; mov word ptr state[12], ax add di,16 pop ds {load cx with RR-1, skip if RR<2} mov cx,[RR] sub cx,1 jle @@2 { *Note* in the following round loop } { op eax, mem[4*bx] is calculated as } { lea esi, [ebx + 2*ebx] } { op eax, mem[ebx+esi] } { lea esi,[ebx+2*ebx] = db $66,$67,$8D,$34,$5B; } db $66; sub bx,bx {clear ebx} {RR-1 full rounds} @@1: {inter[0] := T0[sv[ 3]] xor T1[sv[ 7]] xor T2[sv[11]] xor T3[sv[15]] xor roundKey[r][0]} mov bl,byte ptr sv[3] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] mov bl,byte ptr sv[7] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T1[bx+si] mov bl,byte ptr sv[11] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T2[bx+si] mov bl,byte ptr sv[15] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T3[bx+si] db $66; xor ax,es:[di] db $66; mov word ptr inter[0],ax {inter[1] := T0[sv[ 2]] xor T1[sv[ 6]] xor T2[sv[10]] xor T3[sv[14]] xor roundKey[r][1]} mov bl,byte ptr sv[2] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] mov bl,byte ptr sv[6] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T1[bx+si] mov bl,byte ptr sv[10] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T2[bx+si] mov bl,byte ptr sv[14] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T3[bx+si] db $66; xor ax,es:[di+4] db $66; mov word ptr inter[4],ax {inter[2] := T0[sv[ 1]] xor T1[sv[ 5]] xor T2[sv[ 9]] xor T3[sv[13]] xor roundKey[r][2]} mov bl,byte ptr sv[1] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] mov bl,byte ptr sv[5] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T1[bx+si] mov bl,byte ptr sv[9] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T2[bx+si] mov bl,byte ptr sv[13] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T3[bx+si] db $66; xor ax,es:[di+8] db $66; mov word ptr inter[8],ax {inter[3] := T0[sv[ 0]] xor T1[sv[ 4]] xor T2[sv[ 8]] xor T3[sv[12]] xor roundKey[r][3]} mov bl,byte ptr sv[0] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] mov bl,byte ptr sv[4] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T1[bx+si] mov bl,byte ptr sv[8] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T2[bx+si] mov bl,byte ptr sv[12] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T3[bx+si] db $66; xor ax,es:[di+12] db $66; mov word ptr inter[12],ax {state[0] := inter[0]} {state[1] := inter[1]} {state[2] := inter[2]} {state[3] := inter[3]} db $66; mov ax,word ptr inter[0] db $66; mov word ptr state[0],ax db $66; mov ax,word ptr inter[4] db $66; mov word ptr state[4],ax db $66; mov ax,word ptr inter[8] db $66; mov word ptr state[8],ax db $66; mov ax,word ptr inter[12] db $66; mov word ptr state[12],ax add di,16 dec cx jnz @@1 @@2: {inter[0] := (T0[sv[ 3]] and Xff000000) xor (T1[sv[ 7]] and X00ff0000) xor (T2[sv[11]] and X0000ff00) xor (T3[sv[15]] and X000000ff) xor roundKey[RR][0];} db $66; mov cx,es:[di] mov bl,byte ptr sv[3] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] db $66; and ax,word ptr Xff000000 db $66; xor cx,ax mov bl,byte ptr sv[7] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T1[bx+si] db $66; and ax,word ptr X00ff0000 db $66; xor cx,ax mov bl,byte ptr sv[11] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T2[bx+si] db $66; and ax,word ptr X0000ff00 db $66; xor cx,ax mov bl,byte ptr sv[15] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T3[bx+si] db $66; and ax,word ptr X000000ff db $66; xor ax,cx db $66; mov word ptr inter[0],ax {inter[1] := (T0[sv[ 2]] and Xff000000) xor (T1[sv[ 6]] and X00ff0000) xor (T2[sv[10]] and X0000ff00) xor (T3[sv[14]] and X000000ff) xor roundKey[RR][1];} db $66; mov cx,es:[di+4] mov bl,byte ptr sv[2] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] db $66; and ax,word ptr Xff000000 db $66; xor cx,ax mov bl,byte ptr sv[6] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T1[bx+si] db $66; and ax,word ptr X00ff0000 db $66; xor cx,ax mov bl,byte ptr sv[10] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T2[bx+si] db $66; and ax,word ptr X0000ff00 db $66; xor cx,ax mov bl,byte ptr sv[14] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T3[bx+si] db $66; and ax,word ptr X000000ff db $66; xor ax,cx db $66; mov word ptr inter[4],ax {inter[2] := (T0[sv[ 1]] and Xff000000) xor (T1[sv[ 5]] and X00ff0000) xor (T2[sv[ 9]] and X0000ff00) xor (T3[sv[13]] and X000000ff) xor roundKey[RR][2];} db $66; mov cx,es:[di+8] mov bl,byte ptr sv[1] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] db $66; and ax,word ptr Xff000000 db $66; xor cx,ax mov bl,byte ptr sv[5] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T1[bx+si] db $66; and ax,word ptr X00ff0000 db $66; xor cx,ax mov bl,byte ptr sv[9] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T2[bx+si] db $66; and ax,word ptr X0000ff00 db $66; xor cx,ax mov bl,byte ptr sv[13] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T3[bx+si] db $66; and ax,word ptr X000000ff db $66; xor ax,cx db $66; mov word ptr inter[8],ax {inter[3] := (T0[sv[ 0]] and Xff000000) xor (T1[sv[ 4]] and X00ff0000) xor (T2[sv[ 8]] and X0000ff00) xor (T3[sv[12]] and X000000ff) xor roundKey[RR][3];} db $66; mov cx,es:[di+12] mov bl,byte ptr sv[0] db $66,$67,$8D,$34,$5B; db $66; mov ax,word ptr T0[bx+si] db $66; and ax,word ptr Xff000000 db $66; xor cx,ax mov bl,byte ptr sv[4] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T1[bx+si] db $66; and ax,word ptr X00ff0000 db $66; xor cx,ax mov bl,byte ptr sv[8] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T2[bx+si] db $66; and ax,word ptr X0000ff00 db $66; xor cx,ax mov bl,byte ptr sv[12] db $66,$67,$8D,$34,$5B; db $66; xor ax,word ptr T3[bx+si] db $66; and ax,word ptr X000000ff db $66; xor ax,cx db $66; mov word ptr inter[12],ax {map cipher state to ciphertext block} les di,[BO] {TWA4(BO)[0] := RB(inter[0])} db $66; mov ax,word ptr inter[0] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; mov es:[di],ax {TWA4(BO)[1] := RB(inter[1])} db $66; mov ax,word ptr inter[4] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; mov es:[di+4],ax {TWA4(BO)[2] := RB(inter[2])} db $66; mov ax,word ptr inter[8] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; mov es:[di+8],ax {TWA4(BO)[3] := RB(inter[3])} db $66; mov ax,word ptr inter[12] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; mov es:[di+12],ax end; end; {$else} {---------------------------------------------------------------------------} {$ifdef CONST} procedure crypt(const BI: TANUBlock; var BO: TANUBlock; const roundKey: TANURndKey; RR: integer); {-core crypting routine, enc/dec differ only for roundKey} {$else} procedure crypt(var BI: TANUBlock; var BO: TANUBlock; var roundKey: TANURndKey; RR: integer); {-core crypting routine, enc/dec differ only for roundKey} {$endif} var r: integer; state, inter: TWA4; sv: TANUBlock absolute state; iv: TANUBlock absolute inter; begin {map plaintext block to cipher state and add initial round key} state[0] := RB(TWA4(BI)[0]) xor roundKey[0][0]; state[1] := RB(TWA4(BI)[1]) xor roundKey[0][1]; state[2] := RB(TWA4(BI)[2]) xor roundKey[0][2]; state[3] := RB(TWA4(BI)[3]) xor roundKey[0][3]; {RR-1 full rounds} for r:=1 to RR-1 do begin inter[0] := T0[sv[ 3]] xor T1[sv[ 7]] xor T2[sv[11]] xor T3[sv[15]] xor roundKey[r][0]; inter[1] := T0[sv[ 2]] xor T1[sv[ 6]] xor T2[sv[10]] xor T3[sv[14]] xor roundKey[r][1]; inter[2] := T0[sv[ 1]] xor T1[sv[ 5]] xor T2[sv[ 9]] xor T3[sv[13]] xor roundKey[r][2]; inter[3] := T0[sv[ 0]] xor T1[sv[ 4]] xor T2[sv[ 8]] xor T3[sv[12]] xor roundKey[r][3]; state[0] := inter[0]; state[1] := inter[1]; state[2] := inter[2]; state[3] := inter[3]; end; {last round} inter[0] := (T0[sv[ 3]] and Xff000000) xor (T1[sv[ 7]] and X00ff0000) xor (T2[sv[11]] and X0000ff00) xor (T3[sv[15]] and X000000ff) xor roundKey[RR][0]; inter[1] := (T0[sv[ 2]] and Xff000000) xor (T1[sv[ 6]] and X00ff0000) xor (T2[sv[10]] and X0000ff00) xor (T3[sv[14]] and X000000ff) xor roundKey[RR][1]; inter[2] := (T0[sv[ 1]] and Xff000000) xor (T1[sv[ 5]] and X00ff0000) xor (T2[sv[ 9]] and X0000ff00) xor (T3[sv[13]] and X000000ff) xor roundKey[RR][2]; inter[3] := (T0[sv[ 0]] and Xff000000) xor (T1[sv[ 4]] and X00ff0000) xor (T2[sv[ 8]] and X0000ff00) xor (T3[sv[12]] and X000000ff) xor roundKey[RR][3]; {map cipher state to ciphertext block} TWA4(BO)[0] := RB(inter[0]); TWA4(BO)[1] := RB(inter[1]); TWA4(BO)[2] := RB(inter[2]); TWA4(BO)[3] := RB(inter[3]); end; {$endif} {$endif} {---------------------------------------------------------------------------} function ANU_Init_Encr({$ifdef CONST} const {$else} var {$endif} Key; KeyBits: word; var ctx: TANUContext): integer; {-Anubis context/round key initialization} begin ANU_Init_Encr := ANU_Init2(Key, KeyBits, ctx, 0); end; {---------------------------------------------------------------------------} function ANU_Init_Decr({$ifdef CONST} const {$else} var {$endif} Key; KeyBits: word; var ctx: TANUContext): integer; {-Anubis context/round key initialization} begin ANU_Init_Decr := ANU_Init2(Key, KeyBits, ctx, 1); end; {---------------------------------------------------------------------------} procedure ANU_Encrypt(var ctx: TANUContext; {$ifdef CONST} const {$else} var {$endif} BI: TANUBlock; var BO: TANUBlock); {-encrypt one block (in ECB mode)} begin {$ifndef DLL} {$ifdef debug} {Check correct key setup} if ctx.Decrypt<>0 then RunError(210); {$endif} {$endif} {$ifdef BASM16} {Make x in inter/state dword aligned for optimized 32 bit access} if (sptr and 3)=0 then asm push ax end; {$endif} crypt(BI,BO,ctx.RK,ctx.rounds); end; {---------------------------------------------------------------------------} procedure ANU_Decrypt(var ctx: TANUContext; {$ifdef CONST} const {$else} var {$endif} BI: TANUBlock; var BO: TANUBlock); {-decrypt one block (in ECB mode)} begin {$ifndef DLL} {$ifdef debug} {Check correct key setup} if ctx.Decrypt=0 then RunError(210); {$endif} {$endif} {$ifdef BASM16} {Make x in inter/state dword aligned for optimized 32 bit access} if (sptr and 3)=0 then asm push ax end; {$endif} crypt(BI,BO,ctx.RK,ctx.rounds); end; {---------------------------------------------------------------------------} function ANU_T0Ofs: byte; {-Return offset of Table T0 mod 15, used to optimize BASM16 32 bit access} begin ANU_T0Ofs := __P2I(@T0) and 15; end; end.
unit browserapp; {$mode objfpc} interface uses Classes, SysUtils, Types, JS, web, CustApp; type { TBrowserApplication } TBrowserApplication = class(TCustomApplication) protected function GetHTMLElement(aID : String) : TJSHTMLElement; function CreateHTMLElement(aTag : String; aID : String = '') : TJSHTMLElement; procedure DoRun; override; function GetConsoleApplication: boolean; override; Function LogGetElementErrors : Boolean; function GetLocation: String; override; public procedure GetEnvironmentList(List: TStrings; NamesOnly: Boolean); override; procedure ShowException(E: Exception); override; procedure HandleException(Sender: TObject); override; end; procedure ReloadEnvironmentStrings; implementation uses Rtl.BrowserLoadHelper; var EnvNames: TJSObject; Params : TStringDynArray; procedure ReloadEnvironmentStrings; var I : Integer; S,N : String; A,P : TStringDynArray; begin if Assigned(EnvNames) then FreeAndNil(EnvNames); EnvNames:=TJSObject.new; S:=Window.Location.search; S:=Copy(S,2,Length(S)-1); A:=TJSString(S).split('&'); for I:=0 to Length(A)-1 do begin P:=TJSString(A[i]).split('='); N:=LowerCase(decodeURIComponent(P[0])); if Length(P)=2 then EnvNames[N]:=decodeURIComponent(P[1]) else if Length(P)=1 then EnvNames[N]:='' end; end; procedure ReloadParamStrings; begin SetLength(Params,1); Params[0]:=Window.location.pathname; end; function GetParamCount: longint; begin Result:=Length(Params)-1; end; function GetParamStr(Index: longint): String; begin Result:=Params[Index] end; function MyGetEnvironmentVariable(Const EnvVar: String): String; Var aName : String; begin aName:=Lowercase(EnvVar); if EnvNames.hasOwnProperty(aName) then Result:=String(EnvNames[aName]) else Result:=''; end; function MyGetEnvironmentVariableCount: Integer; begin Result:=length(TJSOBject.getOwnPropertyNames(envNames)); end; function MyGetEnvironmentString(Index: Integer): String; begin Result:=String(EnvNames[TJSOBject.getOwnPropertyNames(envNames)[Index]]); end; { TBrowserApplication } function TBrowserApplication.GetHTMLElement(aID: String): TJSHTMLElement; begin Result:=TJSHTMLElement(Document.getElementById(aID)); if (Result=Nil) and LogGetElementErrors then Writeln('Could not find element with ID ',aID); end; function TBrowserApplication.CreateHTMLElement(aTag: String; aID: String): TJSHTMLElement; begin Result:=TJSHTMLElement(Document.createElement(aTag)); if aID<>'' then Result.ID:=aID; end; procedure TBrowserApplication.DoRun; begin // Override in descendent classes. end; function TBrowserApplication.GetConsoleApplication: boolean; begin Result:=true; end; function TBrowserApplication.LogGetElementErrors: Boolean; begin Result:=True; end; function TBrowserApplication.GetLocation: String; begin Result:=''; // ToDo ExtractFilePath(GetExeName); end; procedure TBrowserApplication.GetEnvironmentList(List: TStrings; NamesOnly: Boolean); var Names: TStringDynArray; i: Integer; begin Names:=TJSObject.getOwnPropertyNames(EnvNames); for i:=0 to length(Names)-1 do begin if NamesOnly then List.Add(Names[i]) else List.Add(Names[i]+'='+String(EnvNames[Names[i]])); end; end; procedure TBrowserApplication.ShowException(E: Exception); Var S : String; begin if (E<>nil) then S:=E.ClassName+': '+E.Message else if ExceptObjectJS then s:=TJSObject(ExceptObjectJS).toString; window.alert('Unhandled exception caught:'+S); end; procedure TBrowserApplication.HandleException(Sender: TObject); begin if ExceptObject is Exception then ShowException(ExceptObject); inherited HandleException(Sender); end; initialization IsConsole:=true; OnParamCount:=@GetParamCount; OnParamStr:=@GetParamStr; ReloadEnvironmentStrings; ReloadParamStrings; OnGetEnvironmentVariable:=@MyGetEnvironmentVariable; OnGetEnvironmentVariableCount:=@MyGetEnvironmentVariableCount; OnGetEnvironmentString:=@MyGetEnvironmentString; end.
unit IM.Procs; {$mode Delphi} interface uses Classes, SysUtils, JPL.IniFile, JPL.TStr, JPL.Console, JPL.Conversion, IM.Types; function ParamExists(ParamStrValue: string): Boolean; function IsFileMask(const FileName: string): Boolean; procedure DisplayIniValue(const IniFileName, Section, Key: string; Encoding: TEncoding); procedure DisplayIniSectionKeys(const IniFileName, Section: string; Encoding: TEncoding); procedure DisplayIniSection(const IniFileName, Section: string; Encoding: TEncoding); procedure WriteIniValue(const IniFileName, Section, Key, Value: string; Encoding: TEncoding); procedure WriteIniFileComment(const IniFileName: string; Comment: string; Encoding: TEncoding; PaddingSpaces: integer = 0); procedure RemoveIniFileComment(const IniFileName: string; Encoding: TEncoding); procedure WriteIniSectionComment(const IniFileName, Section: string; Comment: string; Encoding: TEncoding; PaddingSpaces: integer = 0); procedure RemoveIniSectionComment(const IniFileName, Section: string; Encoding: TEncoding); procedure RenameIniKey(const IniFileName, Section, OldKeyName, NewKeyName: string; Encoding: TEncoding); procedure RemoveIniKey(const IniFileName, Section, Key: string; Encoding: TEncoding); procedure RemoveIniSection(const IniFileName, Section: string; Encoding: TEncoding); procedure RemoveIniAllSections(const IniFileName: string; Encoding: TEncoding); procedure ListIniSections(const IniFileName: string; Encoding: TEncoding); implementation function ParamExists(ParamStrValue: string): Boolean; var i: integer; begin Result := False; ParamStrValue := UpperCase(ParamStrValue); for i := 1 to ParamCount do if UpperCase(ParamStr(i)) = ParamStrValue then begin Result := True; Break; end; end; function IsFileMask(const FileName: string): Boolean; begin Result := TStr.Contains(FileName, '*') or TStr.Contains(FileName, '?'); end; {$region ' DisplayIniValue '} procedure DisplayIniValue(const IniFileName, Section, Key: string; Encoding: TEncoding); var s: string; Ini: TJPIniFile; IniSection: TJPIniSection; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := False; IniSection := Ini.GetSection(Section, False); if not Assigned(IniSection) then Exit; if not IniSection.KeyExists(Key) then begin Writeln('Key "' + Key + '" does not exists!'); Exit; end; s := IniSection.ReadString(Key, ''); if s <> '' then TConsole.WriteTaggedTextLine('<color=' + AppColors.Value + '>' + s + '</color>'); finally Ini.Free; end; end; {$endregion DisplayIniValue} {$region ' DisplayIniSectionKeys '} procedure DisplayIniSectionKeys(const IniFileName, Section: string; Encoding: TEncoding); var s: string; i: integer; Ini: TJPIniFile; sl: TStringList; begin Ini := TJPIniFile.Create(IniFileName, Encoding); sl := TStringList.Create; try Ini.UpdateFileOnExit := False; if not Ini.SectionExists(Section) then begin if not AppParams.Silent then Writeln('Section "' + Section + '" does not exists!'); Exit; end; Ini.ReadSection(Section, sl); for i := 0 to sl.Count - 1 do begin s := sl[i]; if s <> '' then TConsole.WriteTaggedTextLine('<color=' + AppColors.Key + '>' + s + '</color>'); end; finally sl.Free; Ini.Free; end; end; {$endregion DisplayIniSectionKeys} {$region ' DisplayIniSection '} procedure DisplayIniSection(const IniFileName, Section: string; Encoding: TEncoding); var Key, Value: string; i: integer; Ini: TJPIniFile; sl: TStringList; begin Ini := TJPIniFile.Create(IniFileName, Encoding); sl := TStringList.Create; try Ini.UpdateFileOnExit := False; Ini.ReadSection(Section, sl); for i := 0 to sl.Count - 1 do begin Key := sl[i]; Value := Ini.ReadString(Section, Key, ''); TConsole.WriteTaggedTextLine( '<color=' + AppColors.Key + '>' + Key + '</color><color=' + AppColors.Symbol + '>=</color><color=' + AppColors.Value + '>' + Value + '</color>' ); end; finally sl.Free; Ini.Free; end; end; {$endregion DisplayIniSection} {$region ' WriteIniValue '} procedure WriteIniValue(const IniFileName, Section, Key, Value: string; Encoding: TEncoding); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := True; Ini.WriteString(Section, Key, Value); finally Ini.Free; end; end; {$endregion WriteIniValue} {$region ' WriteIniFileComment '} procedure WriteIniFileComment(const IniFileName: string; Comment: string; Encoding: TEncoding; PaddingSpaces: integer = 0); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := True; if PaddingSpaces > 0 then Comment := StringOfChar(' ', PaddingSpaces) + Comment; Ini.Sections[0].WriteComment(Comment, True); finally Ini.Free; end; end; {$endregion WriteIniFileComment} {$region ' RemoveIniFileComment '} procedure RemoveIniFileComment(const IniFileName: string; Encoding: TEncoding); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := True; Ini.ClearIniComment; finally Ini.Free; end; end; {$endregion RemoveIniFileComment} {$region ' WriteIniSectionComment '} procedure WriteIniSectionComment(const IniFileName, Section: string; Comment: string; Encoding: TEncoding; PaddingSpaces: integer = 0); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := True; if PaddingSpaces > 0 then Comment := StringOfChar(' ', PaddingSpaces) + Comment; Ini.WriteComment(Section, Comment, True); finally Ini.Free; end; end; {$endregion WriteIniSectionComment} {$region ' RemoveIniSectionComment '} procedure RemoveIniSectionComment(const IniFileName, Section: string; Encoding: TEncoding); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := False; if Ini.RemoveSectionComment(Section, True) then Ini.UpdateFile; finally Ini.Free; end; end; {$endregion RemoveIniSectionComment} {$region ' RenameIniKey '} procedure RenameIniKey(const IniFileName, Section, OldKeyName, NewKeyName: string; Encoding: TEncoding); var Ini: TJPIniFile; IniSection: TJPIniSection; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := False; if not Ini.SectionExists(Section) then Exit; IniSection := Ini.GetSection(Section, False); if not IniSection.KeyExists(OldKeyName) then begin if not AppParams.Silent then Writeln('Cannot rename: Key "' + OldKeyName + '" does not exists!'); Exit; end; if IniSection.KeyExists(NewKeyName) then begin if not AppParams.Silent then Writeln('Cannot rename: Key "' + NewKeyName + '" already exists!'); Exit; end; if IniSection.RenameKey(OldKeyName, NewKeyName) then Ini.UpdateFile; finally Ini.Free; end; end; {$endregion RenameIniKey} {$region ' RemoveIniKey '} procedure RemoveIniKey(const IniFileName, Section, Key: string; Encoding: TEncoding); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := False; if not Ini.KeyExists(Section, Key) then begin if not AppParams.Silent then Writeln('Cannot remove: Key "' + Key + '" does not exists!'); Exit; end; if Ini.DeleteKey(Section, Key) then Ini.UpdateFile; finally Ini.Free; end; end; {$endregion RemoveIniKey} {$region ' RemoveIniSection '} procedure RemoveIniSection(const IniFileName, Section: string; Encoding: TEncoding); var Ini: TJPIniFile; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := False; if not Ini.SectionExists(Section) then begin if not AppParams.Silent then Writeln('Cannot remove: Section "' + Section + '" does not exists!'); Exit; end; Ini.EraseSection(Section); Ini.UpdateFile; finally Ini.Free; end; end; {$endregion RemoveIniSection} {$region ' RemoveIniAllSections '} procedure RemoveIniAllSections(const IniFileName: string; Encoding: TEncoding); var Ini: TJPIniFile; SectionName, FileComment, s: string; Items: TJPIniSectionItems; i: integer; sl: TStringList; begin FileComment := ''; Ini := TJPIniFile.Create(IniFileName, Encoding); try if Ini.Sections.Count > 0 then begin SectionName := Ini.Sections[0].Name; Items := Ini.GetSectionItems(SectionName); for i := 0 to Items.Count - 1 do begin if Items[i].ItemType = iitComment then begin s := Items[i].Value; if not TStr.StartsWith(';', s) then s := ';' + s; FileComment := FileComment + s + ENDL; end else Break; end; end; Ini.Sections.Clear; Ini.UpdateFile; finally Ini.Free; end; if FileComment <> '' then begin sl := TStringList.Create; try sl.Text := FileComment; sl.WriteBOM := True; sl.SaveToFile(IniFileName, Encoding); finally sl.Free; end; end; end; {$endregion RemoveIniAllSections} {$region ' ListIniSections '} procedure ListIniSections(const IniFileName: string; Encoding: TEncoding); var Ini: TJPIniFile; IniSections: TJPIniSections; i, x: integer; begin Ini := TJPIniFile.Create(IniFileName, Encoding); try Ini.UpdateFileOnExit := False; IniSections := Ini.Sections; x := IniSections.Count - 1; if x <= 0 then begin if not AppParams.Silent then Writeln('The file does not contain any sections.'); Exit; end; if not AppParams.Silent then TConsole.WriteTaggedTextLine('Section list (' + itos(x) + '):'); for i := 1 to IniSections.Count - 1 do begin TConsole.WriteTaggedTextLine('<color=' + AppColors.Section + '>' + IniSections[i].Name + '</color>'); end; finally Ini.Free; end; end; {$endregion ListIniSections} end.
unit uFastStringConverter; {$I ..\Include\IntXLib.inc} interface uses SysUtils, {$IFDEF DELPHI} Generics.Collections, {$ENDIF DELPHI} {$IFDEF FPC} gstack, {$ENDIF FPC} uEnums, uDigitHelper, uStringConverterBase, uIMultiplier, uIDivider, uMultiplyManager, uDivideManager, uIStringConverter, uConstants, uXBits, uIntX, uIntXLibTypes; type /// <summary> /// Fast ToString converting algorithm using divide-by-two. /// </summary> TFastStringConverter = class sealed(TStringConverterBase) private /// <summary> /// Classic Converter Instance. /// </summary> F_classicStringConverter: IIStringConverter; public /// <summary> /// Creates new <see cref="FastStringConverter" /> instance. /// </summary> /// <param name="pow2StringConverter">Converter for pow2 case.</param> /// <param name="mclassicStringConverter">Classic converter.</param> constructor Create(pow2StringConverter: IIStringConverter; mclassicStringConverter: IIStringConverter); /// <summary> /// Destructor. /// </summary> destructor Destroy(); override; /// <summary> /// Converts digits from internal representation into given base. /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="mlength">Big integer length.</param> /// <param name="numberBase">Base to use for output.</param> /// <param name="outputLength">Calculated output length (will be corrected inside).</param> /// <returns>Conversion result (later will be transformed to string).</returns> function ToString(digits: TIntXLibUInt32Array; mlength: UInt32; numberBase: UInt32; var outputLength: UInt32) : TIntXLibUInt32Array; override; end; implementation constructor TFastStringConverter.Create(pow2StringConverter: IIStringConverter; mclassicStringConverter: IIStringConverter); begin inherited Create(pow2StringConverter); F_classicStringConverter := mclassicStringConverter; end; destructor TFastStringConverter.Destroy(); begin F_classicStringConverter := Nil; inherited Destroy; end; function TFastStringConverter.ToString(digits: TIntXLibUInt32Array; mlength: UInt32; numberBase: UInt32; var outputLength: UInt32) : TIntXLibUInt32Array; var outputArray, resultArray, resultArray2, tempBuffer, tempArray: TIntXLibUInt32Array; resultLengthLog2, i: Integer; resultLength, loLength, innerStep, outerStep, j: UInt32; multiplier: IIMultiplier; divider: IIDivider; baseIntStack: TStack<TIntX>; baseInt: TIntX; resultPtr1Const, resultPtr2Const, tempBufferPtr, resultPtr1, resultPtr2, tempPtr, ptr1, ptr2, ptr1end, baseIntPtr, outputPtr: PCardinal; begin outputArray := Inherited ToString(digits, mlength, numberBase, outputLength); // Maybe base method already converted this number if (outputArray <> Nil) then begin result := outputArray; Exit; end; // Check length - maybe use classic converter instead if (mlength < TConstants.FastConvertLengthLowerBound) then begin result := F_classicStringConverter.ToString(digits, mlength, numberBase, outputLength); Exit; end; resultLengthLog2 := TBits.CeilLog2(outputLength); resultLength := UInt32(1) shl resultLengthLog2; // Create and initially fill array for transformed numbers storing SetLength(resultArray, resultLength); Move(digits[0], resultArray[0], mlength * SizeOf(UInt32)); // Create and initially fill array with lengths SetLength(resultArray2, resultLength); resultArray2[0] := mlength; multiplier := TMultiplyManager.GetCurrentMultiplier(); divider := TDivideManager.GetCurrentDivider(); // Generate all needed pows of numberBase in stack baseIntStack := TStack<TIntX>.Create; try baseInt := Default (TIntX); i := 0; while i < (resultLengthLog2) do begin if TIntX.CompareRecords(baseInt, Default (TIntX)) then begin baseInt := numberBase; end else begin baseInt := multiplier.Multiply(baseInt, baseInt); end; baseIntStack.Push(baseInt); Inc(i); end; // Create temporary buffer for second digits when doing div operation SetLength(tempBuffer, baseInt._length); // We will use unsafe code here resultPtr1Const := @resultArray[0]; resultPtr2Const := @resultArray2[0]; tempBufferPtr := @tempBuffer[0]; // Results pointers which will be modified (on swap) resultPtr1 := resultPtr1Const; resultPtr2 := resultPtr2Const; // Outer cycle instead of recursion innerStep := resultLength shr 1; outerStep := resultLength; while (innerStep) > 0 do begin ptr1 := resultPtr1; ptr2 := resultPtr2; ptr1end := resultPtr1 + resultLength; // Get baseInt from stack and fix it too {$IFDEF DELPHI} baseInt := TIntX(baseIntStack.Pop()); {$ENDIF DELPHI} {$IFDEF FPC} baseInt := TIntX(baseIntStack.Top()); baseIntStack.Pop(); {$ENDIF FPC} baseIntPtr := @baseInt._digits[0]; // Cycle through all digits and their lengths while ptr1 < (ptr1end) do begin // Divide ptr1 (with length in *ptr2) by baseIntPtr here. // Results are stored in ptr2 & (ptr2 + innerStep), lengths - in *ptr1 and (*ptr1 + innerStep) loLength := ptr2^; (ptr1 + innerStep)^ := divider.DivMod(ptr1, ptr2, loLength, baseIntPtr, tempBufferPtr, baseInt._length, ptr2 + innerStep, TDivModResultFlags(Ord(TDivModResultFlags.dmrfDiv) or Ord(TDivModResultFlags.dmrfMod)), -2); ptr1^ := loLength; ptr1 := ptr1 + outerStep; ptr2 := ptr2 + outerStep; end; // After inner cycle resultArray will contain lengths and resultArray2 will contain actual values // so we need to swap them here tempArray := resultArray; resultArray := resultArray2; resultArray2 := tempArray; tempPtr := resultPtr1; resultPtr1 := resultPtr2; resultPtr2 := tempPtr; innerStep := innerStep shr 1; outerStep := outerStep shr 1; end; // Retrieve real output length outputLength := TDigitHelper.GetRealDigitsLength(resultArray2, outputLength); // Create output array SetLength(outputArray, outputLength); // Copy each digit but only if length is not null outputPtr := @outputArray[0]; j := 0; while j < (outputLength) do begin if (resultPtr2[j] <> 0) then begin outputPtr[j] := resultPtr1[j]; end; Inc(j); end; {$IFDEF DELPHI} baseIntStack.Clear; {$ENDIF DELPHI} finally baseIntStack.Free; end; result := outputArray; end; end.
unit Ths.Erp.Helper.CustomFileDialog; interface {$I ThsERP.inc} uses Winapi.Windows, Vcl.Forms, System.Classes, Dialogs; type TCustomFileDialogHelper = class helper for TCustomFileDialog public function ExecuteCenter : Boolean; end; implementation { TCustomFileDialogHelper } function TCustomFileDialogHelper.ExecuteCenter: Boolean; var ADialog : TCustomFileDialog; begin ADialog := Self; TThread.CreateAnonymousThread( procedure begin while not IsWindowVisible(ADialog.Handle) do ; TThread.Queue( nil, procedure var ALeft, ATop : Integer; ARect : TRect; AHandle : NativeUInt; begin AHandle := BeginDeferWindowPos(1); try GetWindowRect(ADialog.Handle, ARect); ALeft := (Screen.Width div 2) - (ARect.Width div 2); ATop := (Screen.Height div 2) - (ARect.Height div 2); DeferWindowPos( AHandle, ADialog.Handle, 0, ALeft, ATop, ARect.Width, ARect.Height, SWP_NOZORDER ); finally EndDeferWindowPos(AHandle); end; end ); end ).Start; Result := Self.Execute; end; end.
{*******************************************************} { } { Midas RemoteDataModule Pooler Demo } { } {*******************************************************} unit untEasyRDMPooler; interface uses ComObj, ActiveX, EasyPlateServer_TLB, Classes, SyncObjs, Windows, Variants, DB, Provider, Messages, Forms; type { This is the pooler class. It is responsible for managing the pooled RDMs. It implements the same interface as the RDM does, and each call will get an unused RDM and use it for the call. } TPooler = class(TAutoObject, IRDMEasyPlateServer) private function LockRDM: IRDMEasyPlateServer; procedure UnlockRDM(Value: IRDMEasyPlateServer); // 手工加入 function InnerGetData(strSQL: String): OleVariant; function InnerPostData(Delta: OleVariant; out ErrorCode: Integer): OleVariant; protected { IAppServer } function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall; function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant): OleVariant; safecall; function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; function AS_GetProviderNames: OleVariant; safecall; function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall; function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall; procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant); safecall; function EasyGetRDMData(const ASQL: WideString): OleVariant; safecall; function EasySaveRDMData(const ATableName: WideString; ADelta: OleVariant; const AKeyField: WideString; out AErrorCode: SYSINT): OleVariant; safecall; function EasySaveRDMDatas(ATableNameOLE, ADeltaOLE, AKeyFieldOLE, ACodeErrorOLE: OleVariant): OleVariant; safecall; function EasyGetRDMDatas(ASQLOLE: OleVariant): OleVariant; safecall; end; { The pool manager is responsible for keeping a list of RDMs that are being pooled and for giving out unused RDMs. } TPoolManager = class(TObject) private FRDMList: TList; FMaxCount: Integer; FTimeout: Integer; FCriticalSection: TCriticalSection; FSemaphore: THandle; function GetLock(Index: Integer): Boolean; procedure ReleaseLock(Index: Integer; var Value: IRDMEasyPlateServer); function CreateNewInstance: IRDMEasyPlateServer; public constructor Create; destructor Destroy; override; function LockRDM: IRDMEasyPlateServer; procedure UnlockRDM(var Value: IRDMEasyPlateServer); property Timeout: Integer read FTimeout; property MaxCount: Integer read FMaxCount; end; PRDM = ^TRDM; TRDM = record Intf: IRDMEasyPlateServer; InUse: Boolean; end; var PoolManager: TPoolManager; implementation uses ComServ, untRDMEasyPlateServer, SysUtils, untEasyPlateServerMain; constructor TPoolManager.Create; begin FRDMList := TList.Create; FCriticalSection := TCriticalSection.Create; FTimeout := 5000; FMaxCount := 5; FSemaphore := CreateSemaphore(nil, FMaxCount, FMaxCount, nil); // PostMessage(Application.MainForm.Handle, WM_USER + 101, 0, 0); end; destructor TPoolManager.Destroy; var i: Integer; begin FCriticalSection.Free; for i := 0 to FRDMList.Count - 1 do begin PRDM(FRDMList[i]).Intf := nil; FreeMem(PRDM(FRDMList[i])); end; FRDMList.Free; CloseHandle(FSemaphore); inherited Destroy; end; function TPoolManager.GetLock(Index: Integer): Boolean; begin FCriticalSection.Enter; try Result := not PRDM(FRDMList[Index]).InUse; if Result then PRDM(FRDMList[Index]).InUse := True; finally FCriticalSection.Leave; end; end; procedure TPoolManager.ReleaseLock(Index: Integer; var Value: IRDMEasyPlateServer); begin FCriticalSection.Enter; try PRDM(FRDMList[Index]).InUse := False; Value := nil; ReleaseSemaphore(FSemaphore, 1, nil); finally FCriticalSection.Leave; end; end; function TPoolManager.CreateNewInstance: IRDMEasyPlateServer; var p: PRDM; begin FCriticalSection.Enter; try New(p); p.Intf := RDMFactory.CreateComObject(nil) as IRDMEasyPlateServer; p.InUse := True; FRDMList.Add(p); Result := p.Intf; PostMessage(Application.MainForm.Handle, WM_USER + 101, 0, 0); finally FCriticalSection.Leave; end; end; function TPoolManager.LockRDM: IRDMEasyPlateServer; var i: Integer; begin Result := nil; if WaitForSingleObject(FSemaphore, Timeout) = WAIT_FAILED then raise Exception.Create('服务器繁忙!');//Server too busy for i := 0 to FRDMList.Count - 1 do begin if GetLock(i) then begin Result := PRDM(FRDMList[i]).Intf; Exit; end; end; if FRDMList.Count < MaxCount then Result := CreateNewInstance; if Result = nil then { This shouldn't happen because of the sempahore locks } raise Exception.Create('无法锁定远程数据服务模块!'); //Unable to lock RDM end; procedure TPoolManager.UnlockRDM(var Value: IRDMEasyPlateServer); var i: Integer; begin for i := 0 to FRDMList.Count - 1 do begin if Value = PRDM(FRDMList[i]).Intf then begin ReleaseLock(i, Value); break; end; end; end; { Each call for the server is wrapped in a call to retrieve the RDM, and then when it is finished it releases the RDM. } function TPooler.LockRDM: IRDMEasyPlateServer; begin Result := PoolManager.LockRDM; end; procedure TPooler.UnlockRDM(Value: IRDMEasyPlateServer); begin PoolManager.UnlockRDM(Value); end; function TPooler.AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try Result := RDM.AS_ApplyUpdates(ProviderName, Delta, MaxErrors, ErrorCount, OwnerData); finally UnlockRDM(RDM); end; end; function TPooler.AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try Result := RDM.AS_DataRequest(ProviderName, Data); finally UnlockRDM(RDM); end; end; procedure TPooler.AS_Execute(const ProviderName, CommandText: WideString; var Params, OwnerData: OleVariant); var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try RDM.AS_Execute(ProviderName, CommandText, Params, OwnerData); finally UnlockRDM(RDM); end; end; function TPooler.AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try Result := RDM.AS_GetParams(ProviderName, OwnerData); finally UnlockRDM(RDM); end; end; function TPooler.AS_GetProviderNames: OleVariant; var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try Result := RDM.AS_GetProviderNames; finally UnlockRDM(RDM); end; end; function TPooler.AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant): OleVariant; var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try Result := RDM.AS_GetRecords(ProviderName, Count, RecsOut, Options, CommandText, Params, OwnerData); finally UnlockRDM(RDM); end; end; function TPooler.AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; var RDM: IRDMEasyPlateServer; begin RDM := LockRDM; try Result := RDM.AS_RowRequest(ProviderName, Row, RequestType, OwnerData); finally UnlockRDM(RDM); end; end; function TPooler.EasyGetRDMData(const ASQL: WideString): OleVariant; begin Result := Self.InnerGetData(ASQL); end; function TPooler.EasyGetRDMDatas(ASQLOLE: OleVariant): OleVariant; var ACount, I: Integer; begin ACount := VarArrayHighBound(ASQLOLE, 1); Result := VarArrayCreate([0, ACount], varVariant); for I := VarArrayLowBound(ASQLOLE, 1) to VarArrayHighBound(ASQLOLE, 1) do Result[I] := EasyGetRDMData(ASQLOLE[I]); end; function TPooler.EasySaveRDMData(const ATableName: WideString; ADelta: OleVariant; const AKeyField: WideString; out AErrorCode: SYSINT): OleVariant; var KeyField: TField; begin //执行之前检查要更新的字段是否存在 with RDMEasyPlateServer do begin EasyRDMCds.Data := ADelta; if EasyRDMCds.IsEmpty then Exit; KeyField := EasyRDMCds.FindField(AKeyField); if KeyField=nil then begin frmEasyPlateServerMain.mmErrorLog.Lines.Add('主键字段:' + AKeyField + '未提供'); Exit; end; EasyRDMQry.SQL.Text := 'SELECT * FROM ' + ATableName + ' WHERE 1 > 2'; EasyRDMQry.Open; with EasyRDMQry.FieldByName(AKeyField) do ProviderFlags := ProviderFlags + [pfInKey]; EasyRDMDsp.UpdateMode := upWhereKeyOnly; Result := InnerPostData(ADelta, AErrorCode); end; end; function TPooler.EasySaveRDMDatas(ATableNameOLE, ADeltaOLE, AKeyFieldOLE, ACodeErrorOLE: OleVariant): OleVariant; var I, ErrorCode: Integer; CanCommit: Boolean; begin CanCommit := True; with RDMEasyPlateServer do begin if EasyRDMADOConn.InTransaction then EasyRDMADOConn.RollbackTrans; if VarArrayHighBound(ATableNameOLE, 1) <> VarArrayHighBound(AKeyFieldOLE, 1) then begin AddExecLog('表数量<>主健数量', 1); Exit; end; if VarArrayHighBound(ATableNameOLE, 1) <> VarArrayHighBound(ADeltaOLE, 1) then begin AddExecLog('表数量<>提交数据集数量', 1); Exit; end; if VarArrayHighBound(ATableNameOLE, 1) <> VarArrayHighBound(ACodeErrorOLE, 1) then begin AddExecLog('表数量<>错误返回数量', 1); Exit; end; EasyRDMADOConn.BeginTrans; AddExecLog('BeginTrans'); try for I := VarArrayLowBound(ATableNameOLE, 1) to VarArrayHighBound(ATableNameOLE, 1) do begin Result := EasySaveRDMData(ATableNameOLE[I], ADeltaOLE[I], AKeyFieldOLE[I], ErrorCode); ACodeErrorOLE[I] := ErrorCode; end; for I := VarArrayLowBound(ACodeErrorOLE, 1) to VarArrayHighBound(ACodeErrorOLE, 1) do begin if ACodeErrorOLE[I] <> 0 then CanCommit := False; end; if CanCommit then begin EasyRDMADOConn.CommitTrans; AddExecLog('CommitTrans'); end else begin EasyRDMADOConn.RollbackTrans; AddExecLog('RollbackTrans'); end; except on e:Exception do begin EasyRDMADOConn.RollbackTrans; AddExecLog('RollbackTrans:' + e.Message); end; end; end; end; function TPooler.InnerGetData(strSQL: String): OleVariant; var I: Integer; begin // 必须是CLOSE状态, 否则报错. with RDMEasyPlateServer do begin if EasyRDMQry.Active then EasyRDMQry.Active := False; Result := Self.AS_GetRecords('EasyRDMDsp', -1, I, ResetOption+MetaDataOption, strSQL, Params, OwnerData); end; end; function TPooler.InnerPostData(Delta: OleVariant; out ErrorCode: Integer): OleVariant; begin with RDMEasyPlateServer do begin Result := Self.AS_ApplyUpdates('EasyRDMDsp', Delta, 0, ErrorCode, OwnerData); end; end; {ciInternal --对象不受外部影响 ciSingleInstance --单实例,每启动一个COM新实例就是一个新进程 ciMultiInstance --多实例, 启动多个COM实例也只启动一个进程 tmSingle --单线程, 自动化对象的执行线程是主线程 tmApartment --公寓线程, 自动化对象的执行线程也是主线程 tmFree --自由线程,自动化对象的执行线程是新的工作线程 tmBoth --没研究,效果同上 tmNeutral --没研究,效果同上} {initialization PoolManager := TPoolManager.Create; //自由线程,自动化对象的执行线程是新的工作线程 TAutoObjectFactory.Create(ComServer, TPooler, CLASS_RDMEasyPlatePoolerServer, ciMultiInstance, tmFree); //tmFree finalization PoolManager.Free; } end.
unit MarkDownHtmlU; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LazFileUtils, SynEdit, SynHighlighterHTML, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Clipbrd, MarkdownProcessor, MarkdownUtils, LCLIntf, ComCtrls, Buttons, StrUtils, HtmlView, HtmlGlobals, HTMLUn2; type { TMainForm } TMainForm = class(TForm) B_Save: TBitBtn; B_Copy: TButton; B_Paste: TButton; B_ViewBrowser: TButton; B_OpenFile: TButton; B_Convert: TButton; HtmlViewer: THtmlViewer; OpenDialog1: TOpenDialog; PageControl1: TPageControl; Panel1: TPanel; SaveDialog1: TSaveDialog; SE_MarkDown: TSynEdit; SE_HTML: TSynEdit; Splitter1: TSplitter; SynHTMLSyn1: TSynHTMLSyn; TS_MarkDown: TTabSheet; TS_HTML: TTabSheet; procedure B_CopyClick(Sender: TObject); procedure B_PasteClick(Sender: TObject); procedure B_ViewBrowserClick(Sender: TObject); procedure B_OpenFileClick(Sender: TObject); procedure B_ConvertClick(Sender: TObject); procedure B_SaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HtmlViewerHotSpotClick(Sender: TObject; const SRC: ThtString; var Handled: Boolean); procedure HtmlViewerHotSpotTargetClick(Sender: TObject; const Target, URL: ThtString; var Handled: boolean); procedure HtmlViewerImageRequest(Sender: TObject; const SRC: ThtString; var Stream: TStream); procedure SE_HTMLChange(Sender: TObject); private procedure OpenInBrowser; procedure SetPreview; public end; var MainForm: TMainForm; implementation {$R *.lfm} var RootPath,f:string; md:TMarkdownProcessor=nil; MStream: TMemoryStream = nil; const CSSDecoration = '<style type="text/css">'+ 'code{'+ ' color: #A00;'+ '}'+ 'pre{'+ ' background: #f4f4f4;'+ ' border: 1px solid #ddd;'+ ' border-left: 3px solid #f36d33;'+ ' color: #555;'+ ' overflow: auto;'+ ' padding: 1em 1.5em;'+ ' display: block;'+ '}'+ 'pre code{'+ ' color: inherit;'+ '}'+ '</style>'; (* More decoration: <style type="text/css"> pre { background-color: #eee; border: 1px solid #999; display: block; padding: 10px; } Blockquote{ border-left: 3px solid #d0d0d0; padding-left: 0.5em; margin-left:1em; } Blockquote p{ margin: 0; } </style> *) { TMainForm } procedure TMainForm.SetPreview; begin if SE_HTML.Modified then begin HtmlViewer.LoadFromString(CSSDecoration+SE_HTML.Text); SE_HTML.Modified:=false; end; end; procedure TMainForm.B_ConvertClick(Sender: TObject); begin SE_HTML.Text:=md.process(SE_MarkDown.Text); SE_HTML.Modified:=true; SetPreview; end; procedure TMainForm.B_SaveClick(Sender: TObject); begin PageControl1.ActivePageIndex:=0; if savedialog1.Execute then begin SE_MarkDown.Lines.SaveToFile(savedialog1.FileName); end; end; procedure TMainForm.FormCreate(Sender: TObject); var i:integer; begin md := TMarkdownProcessor.createDialect(mdCommonMark); md.UnSafe := false; RootPath:=GetTempDir; I:=0; Repeat f:=Format('%s%.3d.html',['markdown',I]); Inc(I); Until not FileExists(RootPath+f); PageControl1.ActivePageIndex:=0; HtmlViewer.DefBackground:=clWhite; HtmlViewer.DefFontColor:=clBlack; HtmlViewer.DefFontName:='Helvetica'; HtmlViewer.DefFontSize:=10; // HtmlViewer.DefPreFontName:='Lucida Console'; HtmlViewer.DefPreFontName:='Courier'; HtmlViewer.ServerRoot:=RootPath; // HtmlViewer.OnHotSpotTargetClick:=@HtmlViewerHotSpotTargetClick; HtmlViewer.OnHotSpotClick:=@HtmlViewerHotSpotClick; HtmlViewer.OnImageRequest:=@HtmlViewerImageRequest; MStream := TMemoryStream.Create; B_ConvertClick(Self); end; procedure TMainForm.FormDestroy(Sender: TObject); begin if FileExists(RootPath+f) then DeleteFile(RootPath+f); if Assigned(MStream) then freeandnil(MStream); if assigned(md) then md.Free; end; procedure TMainForm.HtmlViewerHotSpotClick(Sender: TObject; const SRC: ThtString; var Handled: Boolean); begin Handled:=OpenUrl(SRC); end; procedure TMainForm.HtmlViewerHotSpotTargetClick(Sender: TObject; const Target, URL: ThtString; var Handled: boolean); begin Handled:=OpenUrl(URL); end; procedure TMainForm.HtmlViewerImageRequest(Sender: TObject; const SRC: ThtString; var Stream: TStream); var Filename: string; begin Stream:=nil; FileName:=IfThen(FileExists(SRC),SRC,RootPath+SRC); if FileExists(FileName) then begin MStream.LoadFromFile(FileName); Stream := MStream; end; end; procedure TMainForm.SE_HTMLChange(Sender: TObject); begin SetPreview; end; procedure TMainForm.B_CopyClick(Sender: TObject); begin Clipboard.AsText:=SE_MarkDown.text; end; procedure TMainForm.B_PasteClick(Sender: TObject); begin SE_MarkDown.Clear; SE_MarkDown.PasteFromClipboard; PageControl1.ActivePageIndex:=0; end; procedure TMainForm.B_ViewBrowserClick(Sender: TObject); begin OpenInBrowser; end; procedure TMainForm.B_OpenFileClick(Sender: TObject); var NewPath:string; begin if OpenDialog1.Execute then begin SE_MarkDown.Lines.LoadFromFile(OpenDialog1.FileName); NewPath:=ExtractFilePath(OpenDialog1.FileName); if NewPath<>RootPath then begin SE_HTML.Clear; HtmlViewer.Clear; if FileExists(RootPath+f) then DeleteFile(RootPath+f); HtmlViewer.ServerRoot:=NewPath; RootPath:=NewPath; end; SaveDialog1.FileName:=OpenDialog1.FileName; PageControl1.ActivePageIndex:=0; end; end; procedure TMainForm.OpenInBrowser; var p:string; begin p:=IfThen(DirectoryIsWritable(RootPath),RootPath+f,GetTempDir+f); try SE_HTML.Lines.SaveToFile(p); OpenURL('file://'+p); except ShowMessage('Can not create and open the temp file'); end; end; end.
{******************************************} { TeeChart. Draw Example } { Copyright (c) 1995-2001 by David Berneda } { All Rights Reserved } {******************************************} unit udraw; interface { THIS EXAMPLE SHOWS HOW TO DRAW ADDITIONAL CUSTOMIZED THINGS TO A CHART COMPONENT } uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Chart, Series, ExtCtrls, Teengine, StdCtrls, Buttons, TeeProcs; type TDrawForm = class(TForm) Chart1: TChart; LineSeries1: TLineSeries; Panel1: TPanel; BitBtn3: TBitBtn; CheckBox1: TCheckBox; Timer1: TTimer; BitBtn1: TBitBtn; CheckBox2: TCheckBox; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure LineSeries1BeforeDrawValues(Sender: TObject); procedure LineSeries1AfterDrawValues(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); private { Private declarations } public { Public declarations } Percent:Double; DeltaPercent:Integer; end; implementation {$R *.dfm} procedure TDrawForm.FormCreate(Sender: TObject); begin Percent:=50; { <-- used for this demo only } LineSeries1.FillSampleValues(20); end; procedure TDrawForm.LineSeries1BeforeDrawValues(Sender: TObject); Const MyColors:array[1..5] of TColor= ( clNavy, clGreen, clYellow, clRed, $00000080 { very red } ); var t,partial:Longint; tmpRect:TRect; YPosition:Longint; tmpYCenterValue:Double; begin With Chart1 do Begin { we will divide the total chart width by 5 } tmpRect:=ChartRect; tmpRect.Right:=tmpRect.Left; partial:=ChartWidth div 5; { change the brush style } Canvas.Brush.Style:=bsDiagCross; Canvas.Pen.Style:=psClear; { for each section, fill with a specific color } for t:=1 to 5 do Begin { adjust the rectangle dimension } tmpRect.Right :=tmpRect.Right+partial+1 ; { set the brush color } Canvas.Brush.Color:=MyColors[t]; { paint !!! } With tmpRect do Canvas.Rectangle( Left+Width3D,Top-Height3D,Right+Width3D,Bottom-Height3D ); { adjust rectangle } tmpRect.Left:=tmpRect.Right; end; { first calculate the middle vertical value (based on LineSeries points) } With LineSeries1.YValues do tmpYCenterValue:=MinValue+Percent*(MaxValue-MinValue)/100.0; { then calculate the Screen Pixel coordinate of the above value } YPosition:=LeftAxis.CalcYPosValue(tmpYCenterValue); With Canvas do begin { change pen and draw the line } Pen.Width:=3; Pen.Style:=psSolid; Pen.Color:=clRed; MoveTo(ChartRect.Left,YPosition); LineTo(ChartRect.Left+Width3D,YPosition-Height3D); LineTo(ChartRect.Right+Width3D,YPosition-Height3D); end; end; end; procedure TDrawForm.LineSeries1AfterDrawValues(Sender: TObject); Var YPosition:Longint; tmpYCenterValue:Double; begin With Chart1,Canvas do Begin { first calculate the middle vertical value (based on LineSeries points) } With LineSeries1.YValues do tmpYCenterValue:=MinValue+Percent*(MaxValue-MinValue)/100.0; { then calculate the Screen Pixel coordinate of the above value } YPosition:=LeftAxis.CalcYPosValue(tmpYCenterValue); { change pen and draw the line } Pen.Width:=3; Pen.Style:=psSolid; Pen.Color:=clRed; MoveTo(ChartRect.Left,YPosition); LineTo(ChartRect.Right,YPosition); LineTo(ChartRect.Right+Width3D,YPosition-Height3D); { change font and draw some text above the line } Font.Name:='Arial'; { VERY IMPORTANT !!!!!! } { THIS IS NECESSARY IF YOU'RE GOING TO PRINT !!!! } { IT MAKES FONT SIZES TO WORK FINE BOTH AT SCREEN AND PRINTER. } Font.Height:=-24; { <-- express font size in "Height", NOT "Size" } Font.Color:=clYellow; Font.Style:=[fsBold]; { Set transparent background... } Brush.Style:=bsClear; { Output some text... } TextOut( ChartRect.Left+20, YPosition-24 , 'This is '+FloatToStr(tmpYCenterValue)); end; end; procedure TDrawForm.Timer1Timer(Sender: TObject); begin if Percent+DeltaPercent>100 then begin Percent:=100; DeltaPercent:=-5; end else if Percent+DeltaPercent<0 then begin Percent:=0; DeltaPercent:=5; end else Percent:=Percent+DeltaPercent; Chart1.Repaint; end; procedure TDrawForm.CheckBox1Click(Sender: TObject); begin Timer1.Enabled:=CheckBox1.Checked; DeltaPercent:=5; end; procedure TDrawForm.BitBtn1Click(Sender: TObject); begin { try with and without this ---> Chart1.PrintResolution := -100; } Chart1.PrintLandscape; end; procedure TDrawForm.CheckBox2Click(Sender: TObject); begin Chart1.View3D:=CheckBox2.Checked; end; end.
unit QueryGroupUnit2; interface uses System.Classes, System.Contnrs, BaseEventsQuery, System.Generics.Collections, FireDAC.Comp.Client; type TQueryGroup2 = class(TComponent) private FEventList: TObjectList; FQList: TList<TQueryBaseEvents>; function GetActive: Boolean; function GetChangeCount: Integer; function GetConnection: TFDCustomConnection; protected function GetHaveAnyChanges: Boolean; virtual; property EventList: TObjectList read FEventList; property QList: TList<TQueryBaseEvents> read FQList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddClient; virtual; function ApplyUpdates: Boolean; virtual; procedure CancelUpdates; virtual; procedure Commit; virtual; procedure DisableControls; procedure EnableControls; procedure RefreshData; virtual; procedure RemoveClient; virtual; procedure ReOpen; virtual; procedure Rollback; virtual; procedure SaveBookmark; procedure RestoreBookmark; procedure TryOpen; procedure TryPost; virtual; property Active: Boolean read GetActive; property ChangeCount: Integer read GetChangeCount; property Connection: TFDCustomConnection read GetConnection; property HaveAnyChanges: Boolean read GetHaveAnyChanges; end; implementation uses System.SysUtils; constructor TQueryGroup2.Create(AOwner: TComponent); begin inherited; FEventList := TObjectList.Create; FQList := TList<TQueryBaseEvents>.Create; end; destructor TQueryGroup2.Destroy; begin // Отписываемся от всех событий! FreeAndNil(FEventList); FreeAndNil(FQList); inherited; end; procedure TQueryGroup2.AddClient; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].AddClient; end; function TQueryGroup2.ApplyUpdates: Boolean; var Q: TQueryBaseEvents; begin Result := False; Assert(FQList.Count > 0); for Q in QList do begin Q.ApplyUpdates; // Если сохранение не удалось if Q.HaveAnyChanges then Exit; end; Result := True; end; procedure TQueryGroup2.CancelUpdates; var I: Integer; begin Assert(QList.Count > 0); // отменяем все сделанные изменения на стороне клиента for I := QList.Count - 1 downto 0 do begin if QList[I].FDQuery.CachedUpdates then QList[I].CancelUpdates; end; end; procedure TQueryGroup2.Commit; begin ApplyUpdates; if Connection.InTransaction then Connection.Commit; end; procedure TQueryGroup2.DisableControls; var I: Integer; begin for I := QList.Count - 1 downto 0 do QList[I].FDQuery.DisableControls; end; procedure TQueryGroup2.EnableControls; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].FDQuery.EnableControls; end; function TQueryGroup2.GetActive: Boolean; var I: Integer; begin Result := False; for I := 0 to QList.Count - 1 do begin if not QList[I].FDQuery.Active then Exit; end; Result := True; end; function TQueryGroup2.GetChangeCount: Integer; var Q: TQueryBaseEvents; begin Result := 0; for Q in QList do begin Inc(Result, Q.FDQuery.ChangeCount); end; end; function TQueryGroup2.GetConnection: TFDCustomConnection; begin Assert(QList.Count > 0); Result := QList[0].FDQuery.Connection; end; function TQueryGroup2.GetHaveAnyChanges: Boolean; var Q: TQueryBaseEvents; begin Result := False; for Q in QList do begin Result := Q.HaveAnyChanges; if Result then Exit; end; end; procedure TQueryGroup2.RefreshData; var I: Integer; begin // DisableControls; // try for I := QList.Count - 1 downto 0 do QList[I].Wrap.SaveBookmark; ReOpen; for I := 0 to QList.Count - 1 do QList[I].Wrap.RestoreBookmark; // finally // !! FDQuery.EnableControls вызывает ошибку в cxGrid у дочернего представления // EnableControls; // end; end; procedure TQueryGroup2.RemoveClient; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].RemoveClient; end; procedure TQueryGroup2.ReOpen; var I: Integer; begin for I := QList.Count - 1 downto 0 do QList[I].FDQuery.Close; for I := 0 to QList.Count - 1 do QList[I].FDQuery.Open; end; procedure TQueryGroup2.Rollback; begin CancelUpdates; Assert(Connection.InTransaction); Connection.Rollback; RefreshData; end; procedure TQueryGroup2.SaveBookmark; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].Wrap.SaveBookmark; end; procedure TQueryGroup2.RestoreBookmark; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].Wrap.RestoreBookmark; end; procedure TQueryGroup2.TryOpen; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].Wrap.TryOpen; end; procedure TQueryGroup2.TryPost; var I: Integer; begin for I := 0 to QList.Count - 1 do QList[I].Wrap.TryPost; end; end.
unit NsUtils; interface uses Windows, WinSock; const I_SIO_GET_INTERFACE_LIST = $4004747F; I_IFF_UP = $00000001; I_IFF_BROADCAST = $00000002; I_IFF_LOOPBACK = $00000004; I_IFF_POINTTOPOINT = $00000008; I_IFF_MULTICAST = $00000010; function WSAIOCtl(S: TSocket; Cmd: Dword; lpInBuffer: PChar; dwInBufferLen: Dword; lpOutBuffer: PChar; dwOutBufferLen: Dword; lpdwOutBytesReturned: lpDword; lpOverLapped: Pointer; lpOverLappedRoutine: Pointer): Integer; stdcall; external 'WS2_32.DLL'; type SockAddrGen = packed record AddressIn: SockAddr_In; Filler: packed array[0..7] of Char; end; type TInterfaceInfo = packed record iiFlags: u_long; iiAddress: SockAddrGen; iiBroadcastAddress: SockAddrGen; iiNetmask: SockAddrGen; end; TInterface = packed record IPAddress: string; Mask: string; Broadcast: string; IsUp: Boolean; IsBroadcastSupported: Boolean; IsLoopback: Boolean; end; TInterfaces = array of TInterface; type TUserFormat = (ufNameUnknown, ufNameFullyQualifiedDN, ufNameSamCompatible, ufNameDisplay, ufNA4, ufNA5, ufNameUniqueId, ufNameCanonical, ufNameUserPrincipal, ufNameCanonicalEx, ufNameServicePrincipal, ufNA11, ufNameDnsDomain); type TOSVersion = record MajorVersion: Dword; MinorVersion: Dword; BuildNumber: Dword; CSDVersion: string; PlatformName: string; end; type TProcArray = array of string; type TWaitAppType = (watNone, watInput, watClose); type TCharArray = array[0..255] of Char; TCharDynArray = array of Char; // CMD utils function HasCmdParam(const ParamName: string; SkipParamCount: Integer = 0): Boolean; procedure RunApp(const CmdLine: string; const DefaultDir: string = ''; WaitType: TWaitAppType = watNone); procedure RunElevateApp(const CmdLine: string; const DefaultDir: string = ''); procedure gsShellExecute(const hWindow: HWND; const Operation, FileName: string; const Parameters: string = ''; const Directory: string = ''; const ShowCmd: Integer = SW_SHOWNORMAL); function GetAppPath: AnsiString; procedure ShowMsg(Msg: AnsiString); // SysInfo utils function GetCPUInfo: string; function GetCPULevel: string; function GetCPUSpeed: Double; function GetPhysicalMemory: Int64; function GetDriveType_Ns(Drive: Char): string; function GetDiskFreeSpaceInfo(Drive: Char; out TotalSize, FreeSize: Int64): Boolean; function GetVideoCard: string; function GetLANIPAddress: string; //function GetInterfaces(var sInt: String): Boolean; function GetInterfaces(var Interfaces: TInterfaces): Boolean; function GetKeyboardLanguage: string; function GetComputerName_Ns: string; function GetOSRegInfo(var RegOwner: string; var RegOrg: string): Integer; function GetWindowsUserName: string; function GetLoggedOnUserName(UserFormat: TUserFormat): string; function GetPlatformName: string; function GetWindowsVersion: string; function GetOSVersionInfo(var OSVersion: TOSVersion): string; function GetProcessesWin95(var Processes: TProcArray): Integer; function GetProcessesWinNT(var Processes: TProcArray): Integer; function GetWindowsDir: string; function GetSystemDir: string; function GetCurrentDir: string; // File utils function GetFileInfo(const AFileName: string; out FileSize: Integer; out FileTime: Int64): Boolean; function GetFileVersion(const FileName: string; out MajorVersion, MinorVersion: Integer): Boolean; function GetFullFileVersion(const FileName: string): string; function GetFullPathOfFile(const FileName: string): string; // CRC function CRCMakerPas(InputByte, CRCByte: Byte): Byte; function CRCMakerAsm(InputByte, CRCByte: Byte): Byte; // String Utils function DeleteLineBreaks(const S: String): String; // Convert function StringToArray(Str: string): TCharArray; function StringToDynArray(Str: string): TCharDynArray; function DefCurrency(Value: Variant): Currency; function DefInteger(Value: Variant): Integer; function BoolToInt(Value: Boolean): Integer; function StrToBoolean(S: String): Boolean; function ExtendLeft(Str: String; NewLen: Integer; AddStr: String): String; const VK_O = 79; VK_LEFT = 37; VK_UP = 38; VK_RIGHT = 39; VK_DOWN = 40; VK_0 = 48; VK_1 = 49; VK_2 = 50; VK_3 = 51; VK_4 = 52; VK_5 = 53; VK_6 = 54; VK_7 = 55; VK_8 = 56; VK_9 = 57; implementation uses SysUtils, Registry, ActiveX, ShellAPI, TlHelp32, PSAPI, Forms; //--------------------------------------------------------------------------- { CMD Utils} function HasCmdParam(const ParamName: string; SkipParamCount: Integer = 0): Boolean; var I: Integer; begin Result := False; for I := 1 + SkipParamCount to ParamCount do if SameText(ParamStr(I), ParamName) then begin Result := True; Break; end; end; //--------------------------------------------------------------------------- procedure RunApp(const CmdLine: string; const DefaultDir: string = ''; WaitType: TWaitAppType = watNone); var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_SHOW; FillChar(ProcessInfo, SizeOf(ProcessInfo), 0); if not CreateProcess(nil, PChar(CmdLine), nil, nil, False, 0, nil, Pointer(DefaultDir), StartupInfo, ProcessInfo) then RaiseLastOSError; case WaitType of watInput: WaitForInputIdle(ProcessInfo.hProcess, INFINITE); watClose: WaitForSingleObject(ProcessInfo.hProcess, INFINITE); end; CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; //--------------------------------------------------------------------------- procedure RunElevateApp(const CmdLine: string; const DefaultDir: string = ''); var ShellExecuteInfo: TShellExecuteInfo; begin ShellExecuteInfo.cbSize := SizeOf(TShellExecuteInfo); ShellExecuteInfo.fMask := 0; ShellExecuteInfo.Wnd := 0; ShellExecuteInfo.lpVerb := 'runas'; ShellExecuteInfo.lpFile := PAnsiChar(CmdLine); ShellExecuteInfo.lpParameters := nil; ShellExecuteInfo.lpDirectory := PAnsiChar(DefaultDir); ShellExecuteInfo.nShow := SW_SHOWNORMAL; ShellExecuteEx(@ShellExecuteInfo); WaitForSingleObject(ShellExecuteInfo.hProcess, INFINITE); end; //--------------------------------------------------------------------------- procedure gsShellExecute(const hWindow: HWND; const Operation, FileName: string; const Parameters: string = ''; const Directory: string = ''; const ShowCmd: Integer = SW_SHOWNORMAL); var ExecInfo: TShellExecuteInfo; NeedUninitialize: Boolean; begin Assert(FileName <> ''); NeedUninitialize := Succeeded(CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE)); try FillChar(ExecInfo, SizeOf(ExecInfo), 0); ExecInfo.cbSize := SizeOf(ExecInfo); ExecInfo.Wnd := hWindow; ExecInfo.lpVerb := Pointer(Operation); ExecInfo.lpFile := PChar(FileName); ExecInfo.lpParameters := Pointer(Parameters); ExecInfo.lpDirectory := Pointer(Directory); ExecInfo.nShow := ShowCmd; ExecInfo.fMask := //SEE_MASK_NOASYNC { = SEE_MASK_FLAG_DDEWAIT для старых версий Delphi } //or SEE_MASK_FLAG_NO_UI; {$IFDEF UNICODE} // Не обязательно, см. http://www.transl-gunsmoker.ru/2015/01/what-does-SEEMASKUNICODE-flag-in-ShellExecuteEx-actually-do.html ExecInfo.fMask := ExecInfo.fMask or SEE_MASK_UNICODE; {$ENDIF} {$WARN SYMBOL_PLATFORM OFF} Win32Check(ShellExecuteEx(@ExecInfo)); {$WARN SYMBOL_PLATFORM ON} finally if NeedUninitialize then CoUninitialize; end; end; //--------------------------------------------------------------------------- function GetAppPath: AnsiString; begin Result := ExtractFilePath(Application.ExeName); end; //--------------------------------------------------------------------------- procedure ShowMsg(Msg: AnsiString); begin MessageBox(Application.Handle, PChar(Msg), PChar(''), 0); end; //--------------------------------------------------------------------------- { SysInfo Utils } function GetCPUInfo: string; const KEY_NAME = 'Hardware\Description\System\CentralProcessor\0'; VALUE_NAME = 'ProcessorNameString'; begin Result := ''; with TRegistry.Create do try begin Access := KEY_READ; RootKey := HKEY_LOCAL_MACHINE; if OpenKey(KEY_NAME, False) then begin if ValueExists(VALUE_NAME) then Result := Trim(ReadString(VALUE_NAME)); CloseKey; end; end; finally Free; end; end; //--------------------------------------------------------------------------- function GetCPULevel: string; var SysInfo: TSystemInfo; begin GetSystemInfo(SysInfo); case SysInfo.wProcessorLevel of 3: Result := '80386'; 4: Result := '80486'; 5: Result := 'Pentium'; 6: Result := 'Pentium Pro'; else Result := IntToStr(SysInfo.wProcessorLevel); end; end; //--------------------------------------------------------------------------- function GetCPUSpeed: Double; const DelayTime = 500; var TimerHi: Dword; TimerLo: Dword; PriorityClass: Integer; Priority: Integer; begin PriorityClass := GetPriorityClass(GetCurrentProcess); Priority := GetThreadPriority(GetCurrentThread); SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL); Sleep(10); asm DW 310Fh // rdtsc MOV TimerLo, EAX MOV TimerHi, EDX end; Sleep(DelayTime); asm DW 310Fh // rdtsc SUB EAX, TimerLo SBB EDX, TimerHi MOV TimerLo, EAX MOV TimerHi, EDX end; SetThreadPriority(GetCurrentThread, Priority); SetPriorityClass(GetCurrentProcess, PriorityClass); Result := TimerLo / (1000.0 * DelayTime); end; //--------------------------------------------------------------------------- function GetPhysicalMemory: Int64; var MemStatus: TMemoryStatus; begin GlobalMemoryStatus(MemStatus); Result := MemStatus.dwTotalPhys; end; //--------------------------------------------------------------------------- function GetDriveType_Ns(Drive: Char): string; var DriveType: Dword; begin DriveType := GetDriveType(@Drive); case DriveType of 0: Result := '?'; 1: Result := 'Path does not exists'; Drive_Removable: Result := 'Removable'; Drive_Fixed: Result := 'Fixed'; Drive_Remote: Result := 'Remote'; Drive_CDROM: Result := 'CD-ROM'; Drive_RamDisk: Result := 'RAMDisk' else Result := 'Unknown'; end; end; //--------------------------------------------------------------------------- function GetDiskFreeSpaceInfo(Drive: Char; out TotalSize, FreeSize: Int64): Boolean; var FDummy: Int64; S: string; begin S := Drive + ':'; Result := GetDiskFreeSpaceEx(PChar(S), FDummy, TotalSize, @FreeSize); end; //--------------------------------------------------------------------------- function GetVideoCard: string; var DisplayDevice: TDisplayDevice; DeviceNum: Dword; dwFlags: Dword; begin DisplayDevice.cb := SizeOf(DisplayDevice); DeviceNum := 0; dwFlags := 0; while EnumDisplayDevices(nil, DeviceNum, DisplayDevice, dwFlags) do begin Inc(DeviceNum); Result := DisplayDevice.DeviceName; end; end; //--------------------------------------------------------------------------- function GetLANIPAddress: string; var WSAData: TWSAData; HostEntry: PHostEnt; HostName: array[0..255] of AnsiChar; rc: Integer; begin Result := ''; rc := WSAStartup($0101, WSAData); if rc <> 0 then Exit; GetHostName(HostName, 256); HostEntry := GetHostByName(HostName); Result := inet_ntoa(PInAddr(HostEntry.h_addr_list^)^); WSACleanup; end; //--------------------------------------------------------------------------- // http://www.sources.ru/delphi/delphi_get_ip_for_all_interfaces.shtml function GetInterfaces(var Interfaces: TInterfaces): Boolean; var Soc: TSocket; WSAData: TWSAData; NumInterfaces: Integer; BytesReturned, SetFlags: u_long; pAddrInet: SockAddr_In; pAddrString: PChar; PtrA: Pointer; Buffer: array[0..20] of TInterfaceInfo; I, rc: Integer; begin Result := False; Soc := INVALID_SOCKET; rc := WSAStartup($0101, WSAData); if rc <> 0 then Exit; try begin Soc := Socket(AF_INET, SOCK_STREAM, 0); if (Soc = INVALID_SOCKET) then Exit; try PtrA := @BytesReturned; if (WSAIoCtl(Soc, I_SIO_GET_INTERFACE_LIST, nil, 0, @Buffer, 1024, PtrA, nil, nil) <> SOCKET_ERROR) then begin NumInterfaces := BytesReturned div SizeOf(InterfaceInfo); SetLength(Interfaces, NumInterfaces * SizeOf(TInterface)); for i := 0 to NumInterfaces - 1 do begin pAddrInet := Buffer[i].iiAddress.addressIn; pAddrString := inet_ntoa(pAddrInet.sin_addr); Interfaces[NumInterfaces].IPAddress := pAddrString; pAddrInet := Buffer[i].iiNetMask.addressIn; pAddrString := inet_ntoa(pAddrInet.sin_addr); Interfaces[NumInterfaces].Mask := pAddrString; pAddrInet := Buffer[i].iiBroadCastAddress.addressIn; pAddrString := inet_ntoa(pAddrInet.sin_addr); Interfaces[NumInterfaces].Broadcast := pAddrString; SetFlags := Buffer[i].iiFlags; Interfaces[NumInterfaces].IsUp := (SetFlags and I_IFF_UP) = I_IFF_UP; Interfaces[NumInterfaces].IsBroadcastSupported := (SetFlags and I_IFF_BROADCAST) = I_IFF_BROADCAST; Interfaces[NumInterfaces].IsLoopback := (SetFlags and I_IFF_LOOPBACK) = I_IFF_LOOPBACK; end; end; except begin // end; end; end; finally begin CloseSocket(Soc); WSACleanUp; end; end; Result := True; end; //--------------------------------------------------------------------------- function GetKeyboardLanguage: string; var LanguageID: LangID; Language: array[0..100] of Char; begin LanguageID := GetSystemDefaultLangID; VerLanguageName(LanguageID, Language, 100); Result := string(Language); end; //--------------------------------------------------------------------------- function GetComputerName_Ns: string; var Buffer: array[0..MAX_COMPUTERNAME_LENGTH] of Char; NameSize: Cardinal; begin NameSize := MAX_COMPUTERNAME_LENGTH + 1; if not GetComputerName(Buffer, NameSize) then RaiseLastOSError; Result := Buffer; end; //--------------------------------------------------------------------------- function GetOSRegInfo(var RegOwner: string; var RegOrg: string): Integer; const WIN95_KEY = '\SOFTWARE\Microsoft\Windows\CurrentVersion'; WINNT_KEY = '\SOFTWARE\Microsoft\Windows NT\CurrentVersion'; var VersionKey: PChar; begin Result := 0; if GetPlatformName = 'Win95' then VersionKey := WIN95_KEY else if GetPlatformName = 'WinNT' then VersionKey := WINNT_KEY else begin Result := -1; Exit; end; with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; if OpenKey(VersionKey, False) then begin RegOwner := ReadString('RegisteredOwner'); RegOrg := ReadString('RegisteredOrganization'); end; finally Free; end; end; //--------------------------------------------------------------------------- function GetWindowsUserName: string; var UserName: string; UserNameLen: Dword; begin UserNameLen := 255; SetLength(userName, UserNameLen); if GetUserName(PChar(UserName), UserNameLen) then Result := Copy(UserName, 1, UserNameLen - 1) else Result := 'Unknown'; end; //--------------------------------------------------------------------------- procedure GetUserNameEx(NameFormat: Dword; lpNameBuffer: lpStr; nSize: puLong); stdcall; external 'secur32.dll' Name 'GetUserNameExA'; function GetLoggedOnUserName(UserFormat: TUserFormat): string; var UserName: array[0..250] of Char; NameSize: Dword; begin NameSize := 250; GetUserNameEx(Cardinal(UserFormat), @UserName, @NameSize); Result := UserName; end; //--------------------------------------------------------------------------- function GetPlatformName: string; var VersionInfo: TOSVersionInfo; begin VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo); GetVersionEx(VersionInfo); case VersionInfo.dwPlatformId of Ver_Platform_Win32s: Result := 'Win32s'; Ver_Platform_Win32_Windows: Result := 'Win95'; Ver_Platform_Win32_NT: Result := 'WinNT' else Result := 'Unknown Platform'; end; end; //--------------------------------------------------------------------------- function GetWindowsVersion: string; type TWinVersion = (wvUnknown, wv95, wv98, wvME, wvNT3, wvNT4, wvW2K, wvXP, wv2003, wvVista); const FWinVersionStr: array[TWinVersion] of string = ('', 'WIN_95', 'WIN_98', 'WIN_ME', 'WIN_NT3', 'WIN_NT4', 'WIN_2000', 'WIN_XP', 'WIN_2003', 'WIN_VISTA'); var WinVersion: TWinVersion; VersionInfo: TOSVersionInfo; ServicePack: string; begin WinVersion := wvUnknown; ServicePack := ''; VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo); if GetVersionEx(VersionInfo) then begin case VersionInfo.DwMajorVersion of 3: WinVersion := wvNT3; 4: case VersionInfo.DwMinorVersion of 0: if VersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT then WinVersion := wvNT4 else WinVersion := wv95; 10: WinVersion := wv98; 90: WinVersion := wvME; end; 5: case VersionInfo.DwMinorVersion of 0: WinVersion := wvW2K; 1: WinVersion := wvXP; 2: WinVersion := wv2003; end; 6: case VersionInfo.DwMinorVersion of 0: WinVersion := wvVista; end; end; ServicePack := Trim(VersionInfo.szCSDVersion); end; if WinVersion <> wvUnknown then Result := FWinVersionStr[WinVersion] + ' ' + ServicePack else Result := Format('%d_%d', [VersionInfo.DwMajorVersion, VersionInfo.DwMinorVersion]); end; //--------------------------------------------------------------------------- function GetOSVersionInfo(var OSVersion: TOSVersion): string; var VersionInfo: TOSVersionInfo; begin VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo); GetVersionEx(VersionInfo); OSVersion.MajorVersion := VersionInfo.dwMajorVersion; OSVersion.MinorVersion := VersionInfo.dwMinorVersion; OSVersion.BuildNumber := LoWord(VersionInfo.dwBuildNumber); OSVersion.CSDVersion := VersionInfo.szCSDVersion; case VersionInfo.dwPlatformId of Ver_Platform_Win32s: OSVersion.PlatformName := 'Win32s'; Ver_Platform_Win32_Windows: OSVersion.PlatformName := 'Win95'; Ver_Platform_Win32_NT: OSVersion.PlatformName := 'WinNT' else OSVersion.PlatformName := 'Unknown Platform'; end; Result := Format('%s version %d.%d build %d %s', [OSVersion.PlatformName, OSVersion.MajorVersion, OSVersion.MinorVersion, OSVersion.BuildNumber, OSVersion.CSDVersion]); end; //--------------------------------------------------------------------------- function GetProcessesWin95(var Processes: TProcArray): Integer; var FSnap: THandle; ProcEntry: TProcessEntry32; PProcEntry: PProcessEntry32; I: Integer; begin if FSnap > 0 then CloseHandle(FSnap); FSnap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); ProcEntry.dwSize := SizeOf(ProcEntry); I := 0; SetLength(Processes, $3FFF - 1); if Process32First(FSnap, ProcEntry) then repeat New(PProcEntry); PProcEntry^ := ProcEntry; Processes[I] := PProcEntry.szExeFile; I := I + 1; until not Process32Next(FSnap, ProcEntry); Result := I; if FSnap > 0 then CloseHandle(FSnap); end; //--------------------------------------------------------------------------- function GetProcessesWinNT(var Processes: TProcArray): Integer; var Num: Integer; PIDs: array[0..$3FFF - 1] of Dword; BufferSize: Dword; BufferRealSize: Dword; ProcHandle: THandle; ModuleHandle: HModule; ModuleName: array[0..MAX_PATH] of Char; I: Integer; begin ProcHandle := 0; ModuleHandle := 0; BufferSize := 0; EnumProcesses(@PIDs, BufferSize, BufferRealSize); Num := BufferRealSize div SizeOf(Dword); SetLength(Processes, Num); for I := 0 to Num - 1 do begin ProcHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PIDs[I]); if GetModuleFileNameEx(ProcHandle, ModuleHandle, ModuleName, SizeOf(ModuleName)) > 0 then Processes[I] := ModuleName else Processes[I] := 'Unknown'; end; if ProcHandle > 0 then CloseHandle(ProcHandle); Result := Num; end; //--------------------------------------------------------------------------- function GetWindowsDir: string; var S: array[0..MAX_PATH] of Char; begin GetWindowsDirectory(S, SizeOf(S)); Result := S; end; //--------------------------------------------------------------------------- function GetSystemDir: string; var S: array[0..MAX_PATH] of Char; begin GetSystemDirectory(S, SizeOf(S)); Result := S; end; //--------------------------------------------------------------------------- function GetCurrentDir: string; var S: array[0..MAX_PATH] of Char; begin GetCurrentDirectory(SizeOf(S), S); Result := S; end; //--------------------------------------------------------------------------- { File Utils } function GetFileInfo(const AFileName: string; out FileSize: Integer; out FileTime: Int64): Boolean; var F: TSearchRec; begin Result := FindFirst(AFileName, 0, F) = 0; if Result then try FileSize := F.Size; Int64Rec(FileTime).Lo := F.FindData.ftLastWriteTime.dwLowDateTime; Int64Rec(FileTime).Hi := F.FindData.ftLastWriteTime.dwHighDateTime; finally SysUtils.FindClose(F); end; end; //--------------------------------------------------------------------------- function GetFileVersion(const FileName: string; out MajorVersion, MinorVersion: Integer): Boolean; var Info: Pointer; InfoSize: Cardinal; Dummy: Cardinal; FileInfo: PVSFixedFileInfo; FileInfoSize: Cardinal; begin Result := False; InfoSize := GetFileVersionInfoSize(PChar(FileName), Dummy); if InfoSize > 0 then begin GetMem(Info, InfoSize); try if not GetFileVersionInfo(PChar(FileName), 0, InfoSize, Info) then RaiseLastOSError; if VerQueryValue(Info, '\', Pointer(FileInfo), FileInfoSize) then begin MajorVersion := FileInfo.dwFileVersionMS shr 16; MinorVersion := FileInfo.dwFileVersionMS and $FFFF; Result := True; end; finally FreeMem(Info); end; end; end; //-------------------------------------------------------------------------- function GetFullFileVersion(const FileName: string): string; var InfoSize, puLen: Dword; Info, InfoPtr: Pointer; FileInfo: TVSFixedFileInfo; begin InfoSize := GetFileVersionInfoSize(PChar(FileName), puLen); if InfoSize > 0 then begin GetMem(Info, InfoSize); try if not GetFileVersionInfo(PChar(FileName), 0, InfoSize, Info) then RaiseLastOSError; FillChar(FileInfo, SizeOf(TVSFixedFileInfo), 0); VerQueryValue(Info, '\', InfoPtr, puLen); Move(InfoPtr^, FileInfo, SizeOf(TVSFixedFileInfo)); finally FreeMem(Info); end; Result := Format('%u.%u.%u.%u', [HiWord(FileInfo.dwProductVersionMS), LoWord(FileInfo.dwProductVersionMS), HiWord(FileInfo.dwProductVersionLS), LoWord(FileInfo.dwProductVersionLS)]); end else Result := ''; end; //--------------------------------------------------------------------------- function GetFullPathOfFile(const FileName: string): string; const KB = 1024; var Buffer: array[0..KB] of Char; FilePart: PChar; begin if GetFullPathName(PChar(FileName), KB, Buffer, FilePart) = 0 then RaiseLastOSError; SetString(Result, Buffer, FilePart - Buffer); end; //--------------------------------------------------------------------------- { CRC } function CRCMakerPas(InputByte, CRCByte: Byte): Byte; var C: Byte; W: Word; I: Integer; begin W := InputByte + CRCByte shl 8; for I := 0 to 7 do begin C := W and $8000; W := W shl 1; if C <> 0 then W := W xor $6900; end; Result := W shr 8; end; //--------------------------------------------------------------------------- function CRCMakerAsm(InputByte, CRCByte: Byte): Byte; begin Result := 0; { asm mov al,InputByte mov ah,CRCByte mov cx,8 mod1: rol al,1 rcl ah,1 jnc mod2 xor ah,69h mod2: dec cx jnz mod1 mov al,ah end; } end; //--------------------------------------------------------------------------- { String Utils } // Взято отсюда и изменено: // http://www.delphifaq.ru/rabota-s-tekstom-i-strokami/kak-udalit-perenosy-iz-stroki.html function DeleteLineBreaks(const S: String): String; var Source, SourceEnd: PAnsiChar; begin Result := ''; Source := Pointer(S); SourceEnd := Source + Length(S); while Source < SourceEnd do begin case Source^ of #10, #13, #32:; else Result := Result + Source^; end; Inc(Source); end; end; //--------------------------------------------------------------------------- // Взято отсюда и изменено: // http://www.delphifaq.ru/rabota-s-tekstom-i-strokami/algoritm-poiska-podstroki-v-stroke.html { **** UBPFD *********** by delphibase.endimus.com **** >> алгоритм поиска подстроки в строке Зависимости: SysUtils Автор: ALex2) Copyright: 2) Дата: 1 февраля 2003 г. ***************************************************** } function BMSearch(const S, Pattern: String; StartPos: Integer = 1): Integer; type TBMTable = array[0..255] of Integer; var Position, LenPattern, I: Integer; BMT: TBMTable; begin Result := 0; LenPattern := Length(Pattern); Position := StartPos + LenPattern - 1; for I := 0 to 255 do BMT[I] := LenPattern; for I := LenPattern downto 1 do if BMT[Byte(Pattern[I])] = LenPattern then BMT[Byte(Pattern[I])] := LenPattern - I; while Position <= Length(S) do begin if Pattern[LenPattern] <> S[Position] then Position := Position + BMT[Byte(S[Position])] else begin if LenPattern = 1 then begin Result := Position; Exit; end else begin for I := LenPattern - 1 downto 1 do if Pattern[I] <> S[Position - LenPattern + I] then begin Inc(Position); Break; end else begin if I = 1 then begin Result := Position - LenPattern + 1; Exit; end; end; end; end; end; end; //--------------------------------------------------------------------------- { Convert } function StringToArray(Str: string): TCharArray; begin FillChar(Result, High(Byte), #0); Move(Str[1], Result, Length(Str)); end; //--------------------------------------------------------------------------- function StringToDynArray(Str: string): TCharDynArray; begin SetLength(Result, Length(Str)); Move(Str[1], Result[0], Length(Str)); end; //--------------------------------------------------------------------------- function DefCurrency(Value: Variant): Currency; const S_DOT: AnsiString = '.'; S_COMMA: AnsiString = ','; S_SPACE: AnsiString = ' '; S_NOTHING: AnsiString = ''; NUMBERS = [#48..#58]; // Numbers from 0 to 9 var I: Integer; DSExists: Boolean; StrValue: AnsiString; begin try Result := StrToFloat(Value); except try StrValue := Value; // Replace separators { if AnsiPos(S_DOT, StrValue) <> 0 then Value := StringReplace(StrValue, S_DOT, DecimalSeparator, [rfReplaceAll]); } if AnsiPos(S_COMMA, StrValue) <> 0 then Value := StringReplace(StrValue, S_COMMA, '.', [rfReplaceAll]); if AnsiPos(S_SPACE, StrValue) <> 0 then Value := StringReplace(StrValue, S_SPACE, S_NOTHING, [rfReplaceAll]); // Check for non-numeric symbols and separators count DSExists := False; for I := 1 to Length(StrValue) do begin // Non-numeric symbols if not(StrValue[I] in NUMBERS) and (StrValue[I] <> DecimalSeparator) then Break; // Separators count if StrValue[I] = DecimalSeparator then if not DSExists then DSExists := True else Break; end; Result := StrToFloat(StrValue); except Result := 0; end; end; end; //--------------------------------------------------------------------------- function DefInteger(Value: Variant): Integer; begin try Result := StrToInt(Value) except Result := 0; end; end; //--------------------------------------------------------------------------- function BoolToInt(Value: Boolean): Integer; begin Result := 0; if Value then Result := 1; end; //--------------------------------------------------------------------------- function StrToBoolean(S: String): Boolean; begin Result := False; if UpperCase(S) = 'ДА' then Result := True; if UpperCase(S) = 'НЕТ' then Result := False; end; function ExtendLeft(Str: String; NewLen: Integer; AddStr: String): String; begin while Length(Str) < NewLen do Str := AddStr + Str; Result := Str; end; end.
unit UnContasAPagar; {Verificado -.edit; -.post; } interface uses Db, DBTables, classes, sysUtils, painelGradiente, UnDadosProduto, UnDados, UnDadosCR, UnCaixa, UnClientes, SQLExpr,Tabela; // calculos type TCalculosContasAPagar = class private calcula : TSQLQuery; public constructor criar( aowner : TComponent; VpaBaseDados : TSQLConnection ); virtual; destructor destroy; override; function SomaTotalParcelas(VpaCodFilial,VpaLanPagar : Integer ) : Double;overload; function somaTotalParcelas(VpaDContasAPagar : TRBDContasaPagar) : Double;overload; end; // localizacao Type TLocalizaContasAPagar = class(TCalculosContasAPagar) public procedure LocalizaParcela(VpaTabela : TDataSet; VpaCodFilial, VpaLancamento, VpaNumParcela : integer); procedure LocalizaContaCP(VpaTabela : TDataSet; VpaCodFilial, VpaLanPagar : Integer); procedure LocalizaParcelasSemParciais(tabela : TSQLQUERY; lancamento : Integer); procedure LocalizaParcelasComParciais(VpaTabela : TDataSet; VpaCodFilial, VpaLancamento : Integer); procedure LocalizaJoinContaParcelas(tabela : TSQLQUERY; lancamento : Integer; CampoOrderBy : string); procedure LocalizaMov(tabela : TDataSet); procedure LocalizaCad(tabela : TSQLQUERY); procedure LocalizaParcelasAbertas(VpaTabela : TSQLQUERY; VpaLanPagar : Integer; VpaCampoOrderBy : string); procedure LocalizaParcelaAberta(VpaTabela : TSQLQUERY; VpaLanPagar, VpaNumParcela : Integer ); procedure LocalizaFormaPagamento(VpaTabela : TSQLQUERY; VpaCodFormaPagto : integer ); end; // funcoes type TFuncoesContasAPagar = class(TLocalizaContasAPagar) private Aux, Tabela : TSQLQuery; Cadastro, Cadastro2 : TSQL; VprBaseDados : TSQlConnection; function EstornaParcelaParcial(VpaCodFilial, VpaLanPagar, VpaNumParcelaFilha : integer) : string; function RParcelaAGerarParcial(VpaDBaixa : TRBDBaixaCP): TRBDParcelaCP; function GeraParcelaParcial( VpaDBaixa : TRBDBaixaCP) : string; function GravaParcelaParcial(VpaDParcelaOriginal : TRBDParcelaCP;VpaValParcial : Double;VpaDatVencimento : TDateTime):string; function BaixaParcelaPagar(VpaDBaixa : TRBDBaixaCP;VpaDParcela : TRBDParcelaCP):string; function BaixaContasaPagarAutomatico(VpaDContasaPagar : TRBDContasaPagar) : string; procedure LocalizaChequesCP(VpaTabela : TSQLQUERY;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); procedure CarDChequesCP(VpaListaCheques : TList;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); procedure CarParcelasCheque(VpaParcelas : TList;VpaSeqCheque, VpaCodFilialOriginal, VpaLanPagarOriginal, VpaNumParcelaOriginal : Integer); function GravaDContasaPagar(VpaDContasAPagar : TRBDContasaPagar) : String; function GravaDParcelaPagar(VpaDContasAPagar : TRBDContasaPagar) : String; function RNumParcelas(VpaDBaixaCP : TRBDBaixaCP) : string; function FornecedorPossuiDebito(VpaCreditos : TList;VpaTipo : TRBDTipoCreditoDebito) : Boolean; function BaixaParcelacomDebitoFornecedor(VpaDContasaPagar : TRBDContasaPagar; VpaCredito : TList):string; public constructor criar( aowner : TComponent; VpaBaseDados : TSQLConnection ); override; destructor Destroy; override; procedure CarDContasaPagar(VpaDContasaPagar : TRBDContasaPagar;VpaCodFilial,VpaLanPagar : Integer;VpaCarregarParcelas : Boolean); procedure CarDContasaPagarParcela(VpaDContasaPagar : TRBDContasaPagar;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); function GravaDParcelaCP(VpaDParcelaCP : TRBDParcelaCP) : String; function GravaDChequeCP(VpaParcelas, VpaCheques : TList):string; // gera parcela function CriaContaPagar(VpaDContasaPagar : TRBDContasaPagar;VpaDCliente : TRBDCliente) : string; procedure CriaParcelas( VpaDContasaPagar : TRBDContasaPagar ); procedure AtualizaValorTotal(VpaCodfilial, VpaLanPagar : integer ); function VerificaAtualizaValoresParcelas(ValorInicialParcelas : double; lancamento : Integer ) : boolean; procedure AjustaValorUltimaParcela(VpaDContasAPagar : TRBDContasaPagar;VpaValorInicial : Double); // baixa parcela function BaixaContasAPagar(VpaDBaixa : TRBDBaixaCP) : string; function GeraNroProximoParcela(VpaCodFilial,VpaLancamento : Integer) : Integer; procedure CalculaValorTotalBaixa(VpaDBaixa : TRBDBaixaCP); function VerificaSeValorPagoQuitaTodasDuplicatas(VpaDBaixa : TRBDBaixaCP;VpaValAReceber : Double) : String; function VerificaSeGeraParcial(VpaDBaixa : TRBDBaixaCP;VpaValAReceber : Double;VpaIndSolicitarData : Boolean) : String; function RValTotalCheques(VpaDBaixaCP : TRBDBaixaCP) : Double; function RValTotalParcelasBaixa(VpaDBaixaCP : TRBDBaixaCP) : Double; procedure DistribuiValAcrescimoDescontoNasParcelas(VpaDBaixa : TRBDBaixaCP); procedure CarDParcelaBaixa(VpaDParcela : TRBDParcelaCP;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); function ValidaParcelaPagamento(VpaCodFilial, VpaLanPagar, VpaNumParcela : integer) : boolean; function PossuiChequeDigitado(VpaDBaixa : TRBDBaixaCP):Boolean; // estorno e exclusa de conta e titulos function TemParcelasPagas(VpaCodFilial,VpaLanPagar : Integer ): Boolean; function ExcluiConta(VpaCodFilial, VpaLanPagar : integer; VpaVerificarNotaFiscal : Boolean ) : string; function TemParcelas(VpaCodFilial,VpaLanPagamento: Integer): Boolean; function ExcluiTitulo(VpaCodFilial, VpaLanPagar, VpaNumParcela : Integer ) : string; function VerificacoesExclusaoCheque(VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer;VpaCheques : TList):string; function ExcluiChequesCP(VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer;VpaCheques : TList):string; function ValidaChequesCP(VpaCodFilial,VpaLanPagar,VpaNumparcela : Integer;Var VpaExisteCheques : Boolean):string; function EstornoParcela(VpaCodFilial, VpaLanPagar,VpaNumParcela, VpaNumParcelaFilha, VpaCodCliente : integer;VpaVerificarCheques : Boolean) : String; function EstornaParcela(VpaLancamentoCP, VpaLancamentoBancario, VpaNroParcela,VpaNroParcelaFilha : integer; VpaDataParcela : TDateTime; VpaFlagParcial : string ) : Boolean; function ValidaEstornoParcela( VpaLancamentoCP : integer; VpaDatPagamento : TDateTime; VpaFlagParcial : string ) : boolean; function EstornaCPChequeDevolvido(VpaCheques : TList) : string; function EstornaValorCPChequeDevolvido(VpaValCheque : Double; VpaParcelas : TList) : string; // adicionais function RetiraAdicionalConta(Lancamento, Parcela : Integer; ValorRetirar: Double) : Boolean; function VerificaContaReceberVinculada(VpaNroOrdem, VpaParcela: Integer): Boolean; procedure AlteraValorRecebidoCAB(VpaOrdem: Integer; VpaValor:Double); //retornos function GeraCPTarifasRetorno(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDRetornoItem : TRBDRetornoItem;VpaValor : Double;VpaDescricao,VpaPlanoContas : String) : String; // diversos procedure BaixaConta( Valor, valorDesconto, ValorAcrescimo : double; Data : TDateTime; lancamento, NroParcela : integer ); procedure ConfiguraFormaPagto( FormaInicio, FormaFim, lancamento, Nroparcela : Integer; NroConta : string ); function ExcluiContaNotaFiscal( SeqNota : integer ) : Boolean; procedure AtualizaFormaPagamento(LancamentoCP, ParcelaCP, CodigoFormaPagamento: string); function NotaPossuiParcelaPaga(VpaCodFilial, VpaSeqNota : Integer) : Boolean; function FlagBaixarContaFormaPagamento(VpaCodFormapagamento : Integer):Boolean; function ExisteCheque(VpaNumCheque : Integer;var VpaExisteVariosCheques : Boolean;VpaDCheque : TRBDCheque): Boolean; procedure CarParcelasCPCheque(VpaSeqCheque : Integer;VpaParcelas : TList); procedure InterpretaCodigoBarras(VpaDContasAPagar : TRBDContasaPagar;VpaCodBarras : String); function ValorProjetosMaiorQueContasaPagar(VpaDContasaPagar : TRBDContasaPagar;VpaValContasAPagar : Double):string; function RPercentualProjetoFaltante(VpaDContasAPagar : TRBDContasaPagar) : Double; function ProjetoDuplicado(VpaDContasAPagar : TRBDContasaPagar) : boolean; procedure ExcluiPlanoContas(VpaPlanoOrigem, VpaPlanoDestino : String); procedure CarDProjetoContasaPagar(VpaDContasAPagar : TRBDContasaPagar); function GravaDDespesaProjeto(VpaDContasAPagar : TRBDContasaPagar) : String; function MarcaProrrogado(VpaCodFilial,VpaLanPagar, VpaNumParcela : Integer;VpaMarcarProrrogado : boolean):string; function RValPrevistoPlanoContas(VpaCodEmpresa, VpaCodCentroCusto : Integer;VpaCodPlanoContas : String;VpaDatInicio, VpaDatFim : TDateTime) : double; end; var FunContasAPagar : TFuncoesContasAPagar; implementation uses constMsg, constantes, funSql, funstring, fundata, FunNumeros,AMostraParPagarOO, AChequesCP, UnContasAReceber, FunObjeto,ABaixaContasaPagarOO, UnSistema; {############################################################################# TCalculo Contas a Pagar ############################################################################# } { ****************** Na criação da classe ******************************** } constructor TCalculosContasAPagar.criar( aowner : TComponent; VpaBaseDados : TSQLConnection ); begin inherited; calcula := TSQLQuery.Create(aowner); calcula.SQLConnection := VpaBaseDados; end; { ******************* Quando destroy a classe ****************************** } destructor TCalculosContasAPagar.destroy; begin Calcula.close; calcula.Destroy; inherited; end; { *************************************************************************** } function TCalculosContasAPagar.SomaTotalParcelas(VpaDContasAPagar: TRBDContasaPagar): Double; var VpfLaco : Integer; begin result := 0; for VpfLaco := 0 to VpaDContasAPagar.Parcelas.Count - 1 do begin result := result + TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[VpfLaco]).ValParcela; end; VpaDContasAPagar.ValTotal := result; end; { ******************* Soma Total das parcelas ****************************** } function TCalculosContasAPagar.SomaTotalParcelas(VpaCodFilial,VpaLanPagar : Integer ) : Double; begin AdicionaSQLAbreTabela(calcula, ' select sum(N_VLR_DUP) as valorDup from MovContasaPagar ' + ' where I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial) ); // <> canceladas Result := calcula.fieldByName('valorDup').AsCurrency; FechaTabela(calcula); end; {############################################################################# TLocaliza Contas a Pagar ############################################################################# } { ******************** localiza uma parcela ********************************* } procedure TLocalizaContasAPagar.LocalizaParcela(VpaTabela : TDataSet; VpaCodFilial, VpaLancamento, VpaNumParcela : integer); begin AdicionaSQLAbreTabela( VpaTabela,' select * from MOVCONTASAPAGAR ' + ' Where I_EMP_FIL = ' + IntToStr(VpaCodfilial)+ ' and I_NRO_PAR = ' + IntToStr(VpaNumParcela)+ ' and I_LAN_APG = ' + IntToStr(VpaLancamento)); end; { ****************** localiza uma conta ************************************ } procedure TLocalizaContasAPagar.LocalizaContaCP(VpaTabela : TDataset; VpaCodFilial, VpaLanPagar : Integer); begin AdicionaSQLAbreTabela(VpaTabela,' select * from CadContasaPagar ' + ' Where I_EMP_FIL = ' + IntToStr(VpaCodFilial)+ ' and I_LAN_APG = ' + IntToStr(VpaLanPagar)); end; {*********************** localiza parcelas sem parciais ********************** } procedure TLocalizaContasAPagar.LocalizaParcelasSemParciais(tabela : TSQLQUERY; lancamento : Integer); begin AdicionaSQLAbreTabela(tabela, ' select * from MovContasaPagar ' + ' where i_lan_apg = ' + IntToStr(Lancamento) + ' and i_emp_fil = ' + Inttostr(varia.CodigoEmpFil) + ' and c_fla_par = ''N''' + // parcelas parciais ' order by i_nro_par' ); end; {*********************** localiza parcelas com parciais ********************** } procedure TLocalizaContasAPagar.LocalizaParcelasComParciais(VpaTabela : TDataSet; VpaCodFilial, VpaLancamento : Integer); begin AdicionaSQLAbreTabela(VpaTabela, ' select * from MovContasaPagar ' + ' where i_lan_apg = ' + IntToStr(VpaLancamento) + ' and i_emp_fil = ' + Inttostr(VpaCodFilial) + ' order by i_nro_par' ); end; procedure TLocalizaContasAPagar.LocalizaJoinContaParcelas(tabela : TSQLQUERY; lancamento : Integer; CampoOrderBy : string); begin AdicionaSQLAbreTabela(tabela, ' select * from MovContasaPagar as MCP, CadContasapagar as CP '+ ' where ' + ' CP.I_LAN_APG = ' + IntToStr(lancamento) + ' and CP.I_EMP_FIL = ' + IntTostr(varia.CodigoEmpFil) + ' and CP.I_EMP_FIL = MCP.I_EMP_FIL ' + ' and CP.I_LAN_APG = MCP.I_LAN_APG ' + ' order by MCP.'+ CampoOrderBy ); end; procedure TLocalizaContasAPagar.LocalizaMov(tabela : TDataSet); begin AdicionaSQLAbreTabela(tabela, 'select * from MovContasaPagar'); end; procedure TLocalizaContasAPagar.LocalizaCad(tabela : TSQLQUERY); begin AdicionaSQLAbreTabela(tabela, 'select * from CadContasapagar'); end; {******************************************************************************} procedure TLocalizaContasAPagar.LocalizaParcelasAbertas(VpaTabela : TSQLQUERY; VpaLanPagar : Integer; VpaCampoOrderBy : string); begin AdicionaSQLAbreTabela(VpaTabela,' select * from MovContasaPagar as MCP '+ ' where I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntTostr(varia.CodigoEmpFil) + ' and D_DAT_PAG is null ' + ' order by ' + VpaCampoOrderBy ); end; {******************************************************************************} procedure TLocalizaContasAPagar.LocalizaParcelaAberta(VpaTabela : TSQLQUERY; VpaLanPagar, VpaNumParcela : Integer ); begin AdicionaSQLAbreTabela(Vpatabela,' select * from MOVCONTASAPAGAR ' + ' where I_EMP_FIL = ' + IntTostr(varia.CodigoEmpFil) + ' and I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and D_DAT_PAG is null ' + ' and I_NRO_PAR = ' + IntToStr(VpaNumParcela)); end; {******************************************************************************} procedure TLocalizaContasAPagar.LocalizaFormaPagamento(VpaTabela : TSQLQUERY; VpaCodFormaPagto : integer ); begin AdicionaSQLAbreTabela( VpaTabela, ' select * from CadFormasPagamento ' + ' where i_cod_frm = ' + InttoStr(VpaCodFormaPagto) ); end; {############################################################################# TFuncoes Contas a Pagar ############################################################################# } { ****************** Na criação da classe ******************************** } constructor TFuncoesContasAPagar.criar( aowner : TComponent; VpaBaseDados : TSQLConnection ); begin inherited; VprBaseDados := VpaBaseDados; Aux := TSQLQuery.Create(nil); Aux.SQLConnection := VpaBaseDados; Tabela := TSQLQuery.Create(aowner); Tabela.SQLConnection := VpaBaseDados; Cadastro := tSQL.create(aowner); Cadastro.ASQLConnection := VpaBaseDados; Cadastro2 := tSQL.create(aowner); Cadastro2.ASQLConnection := VpaBaseDados; end; { ******************* Quando destroy a classe ****************************** } destructor TFuncoesContasAPagar.Destroy; begin FechaTabela(tabela); Tabela.Destroy; Cadastro.free; Cadastro2.free; Aux.free; inherited; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarDContasaPagar(VpaDContasaPagar : TRBDContasaPagar;VpaCodFilial,VpaLanPagar : Integer;VpaCarregarParcelas : Boolean); begin AdicionaSQLAbreTabela(Tabela,'Select * from CADCONTASAPAGAR '+ ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' and I_LAN_APG = ' + IntToStr(VpaLanPagar)); VpaDContasAPagar.CodFilial := Tabela.FieldByName('I_EMP_FIL').AsInteger; VpaDContasAPagar.CodCondicaoPagamento := Tabela.FieldByName('I_COD_PAG').AsInteger; VpaDContasAPagar.CodCentroCusto := Tabela.FieldByName('I_COD_CEN').AsInteger; VpaDContasAPagar.DatEmissao := Tabela.FieldByName('D_DAT_EMI').AsDateTime; VpaDContasAPagar.DesPathFoto := Tabela.FieldByName('C_PAT_FOT').AsString; VpaDContasAPagar.NumNota := Tabela.FieldByName('I_NRO_NOT').AsInteger; VpaDContasAPagar.SeqNota := Tabela.FieldByName('I_SEQ_NOT').AsInteger; VpaDContasAPagar.CodFornecedor := Tabela.FieldByName('I_COD_CLI').AsInteger; VpaDContasAPagar.ValTotal := Tabela.FieldByName('N_VLR_TOT').AsFloat; VpaDContasAPagar.CodPlanoConta := Tabela.FieldByName('C_CLA_PLA').AsString; VpaDContasAPagar.LanPagar := Tabela.FieldByName('I_LAN_APG').AsInteger; Tabela.close; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarDContasaPagarParcela(VpaDContasaPagar : TRBDContasaPagar;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); begin CarDContasaPagar(VpaDContasaPagar,VpaCodFilial,VpaLanPagar,false); CarDParcelaBaixa(VpaDContasaPagar.addParcela,VpaCodFilial,VpaLanPagar,VpaNumParcela); VpaDContasaPagar.ValTotal := TRBDParcelaCP(VpaDContasaPagar.Parcelas.Items[0]).ValParcela; end; {******************************************************************************} function TFuncoesContasAPagar.GravaDParcelaCP(VpaDParcelaCP : TRBDParcelaCP) : String; begin result := ''; if VpaDParcelaCP.ValPago = 0 then result := EstornaParcelaParcial(VpaDParcelaCP.CodFilial,VpaDParcelaCP.LanPagar,VpaDParcelaCP.NumParcelaParcial); AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASAPAGAR '+ ' Where I_EMP_FIL = ' +IntToStr(VpaDParcelaCP.CodFilial)+ ' AND I_LAN_APG = ' + IntToStr(VpaDParcelaCP.LanPagar)+ ' AND I_NRO_PAR = ' +IntToStr(VpaDParcelaCP.NumParcela)); Cadastro.edit; if VpaDParcelaCP.NumContaCorrente <> '' then Cadastro.FieldByname('C_NRO_CON').AsString := VpaDParcelaCP.NumContaCorrente else Cadastro.FieldByname('C_NRO_CON').clear; Cadastro.FieldByname('I_COD_FRM').AsInteger := VpaDParcelaCP.CodFormaPagamento; if VpaDParcelaCP.ValPago <> 0 then Cadastro.FieldByname('N_VLR_PAG').AsFloat := VpaDParcelaCP.ValPago else begin Cadastro.FieldByname('N_VLR_PAG').Clear; Cadastro.FieldByname('D_DAT_PAG').Clear; end; Cadastro.post; result := Cadastro.AMensagemErroGravacao; Cadastro.close; end; {########################## na criacaco das parcelas ######################### } {************************ Cria uma nova conta completa *********************** } function TFuncoesContasAPagar.CriaContaPagar(VpaDContasaPagar : TRBDContasaPagar;VpaDCliente : TRBDCliente) : string; var VpfCreditoCliente : TList; begin result := ''; VpfCreditoCliente := TList.create; CriaParcelas(VpaDContasaPagar); // formas de pagamento if (VpaDContasaPagar.CodCondicaoPagamento = Varia.CondPagtoVista) and ((VpaDContasaPagar.DesTipFormaPagamento = 'D') or (VpaDContasaPagar.DesTipFormaPagamento = 'T') or (VpaDContasaPagar.DesTipFormaPagamento = 'E')) then // caso par 1 e = dinheiro, cartao, cheque eletronico naum chamar detalhes VpaDContasaPagar.IndMostrarParcelas := false; // detalhes do cheque, boleto, etc if VpaDContasaPagar.IndMostrarParcelas then begin FMostraParPagarOO := TFMostraParPagarOO.CriarSDI(nil,'',true); if not FMostraParPagarOO.MostraParcelas(VpaDContasaPagar) then result := 'FINANCEIRO CANCELADO!!!'#13'A operação foi cancelada porque o financeiro foi cancelado.'; FMostraParPagarOO.free; end; if (result = '') then begin result := GravaDContasaPagar(VpaDContasaPagar); if result = '' then begin if VpaDContasaPagar.IndBaixarConta then begin result := BaixaContasaPagarAutomatico(VpaDContasaPagar); end; if result = '' then begin if config.ControlarDebitoeCreditoCliente then begin VpaDContasaPagar.ValUtilizadoCredito := 0; FunClientes.CarCreditoCliente(VpaDContasaPagar.CodFornecedor,VpfCreditoCliente,true,dcDebito); if FornecedorPossuiDebito(VpfCreditoCliente,dcDebito) then begin if confirmacao('FORNECEDOR POSSUI DÉBITO!!!'#13'Esse fornecedor possui um débito de "'+ FormatFloat('R$ #,###,###,##0.00',FunContasAReceber.RValTotalCredito(VpfCreditoCliente,dcDebito))+ '".Deseja utilizar o débito para quitar essa conta? ') then result := BaixaParcelacomDebitoFornecedor(VpaDContasaPagar,VpfCreditoCliente); end; end; end; if result = '' then begin if VpaDCliente <> nil then begin result := FunClientes.AtualizaCliente(VpaDCliente,VpaDContasAPagar); end; end; end; end; FreeTObjectsList(VpfCreditoCliente); VpfCreditoCliente.free; end; {********* criacao das parcelas **********************************************} procedure TFuncoesContasAPagar.CriaParcelas(VpaDContasaPagar : TRBDContasaPagar); var VpfParcela, VpfDiaAtual : integer; VpfDParcela : TRBDParcelaCP; VpfDatVencimento : TDatetime; begin FreeTObjectsList(VpaDContasaPagar.Parcelas); VpfDatVencimento := VpaDContasaPagar.DatEmissao; VpfParcela := 1; VpfDiaAtual := dia(VpfDatVencimento); // usado para modificar data fixa, nos dia (29,30,e 31 ) com vencimento sempre na data da compra AdicionaSQLAbreTabela(Tabela,'Select CAD.N_IND_REA, CAD.N_PER_DES, CAD.I_DIA_CAR, CAD.I_QTD_PAR, '+ ' MOV.N_PER_PAG, MOV.N_PER_CON,'+ ' MOV.C_CRE_DEB,MOV.D_DAT_FIX, MOV.I_DIA_FIX, MOV.I_NUM_DIA'+ ' from CADCONDICOESPAGTO CAD, MOVCONDICAOPAGTO MOV '+ ' Where CAD.I_COD_PAG = MOV.I_COD_PAG '+ ' AND CAD.I_COD_PAG = '+ IntToStr(VpaDContasaPagar.CodCondicaoPagamento)+ ' ORDER BY I_NRO_PAR'); while not Tabela.Eof do begin VpfDParcela := VpaDContasaPagar.addParcela; VpfDParcela.CodFilial := VpaDContasaPagar.CodFilial; VpfDParcela.LanPagar := VpaDContasaPagar.LanPagar; VpfDParcela.NumParcela := VpfParcela; VpfDParcela.NumParcelaParcial := 0; VpfDParcela.CodCliente := VpaDContasaPagar.CodFornecedor; VpfDParcela.NomCliente := VpaDContasaPagar.NomFornecedor; VpfDParcela.CodFormaPagamento := VpaDContasaPagar.CodFormaPagamento; VpfDParcela.NumContaCorrente := VpaDContasaPagar.NumContaCaixa; VpfDParcela.NumNotaFiscal := VpaDContasaPagar.NumNota; VpfDParcela.NumDuplicata := IntToStr(VpaDContasaPagar.NumNota)+'/'+IntToStr(VpfParcela); VpfDParcela.DatEmissao := VpaDContasaPagar.DatEmissao; VpfDatVencimento := FunContasAReceber.CalculaVencimento(VpfDatVencimento,Tabela.FieldByName('I_NUM_DIA').AsInteger, Tabela.FieldByName('I_DIA_FIX').AsInteger,Tabela.FieldByName('D_DAT_FIX').AsDateTime, VpfDiaAtual); if VpfParcela = 1 then begin if VpaDContasaPagar.CodBarras <> '' then begin VpfDParcela.DatVencimento := IncDia(MontaData(7,10,1997),VpaDContasaPagar.FatorVencimento); VpfDParcela.CodBarras := VpaDContasaPagar.CodBarras; end else VpfDParcela.DatVencimento := VpfDatVencimento; end else VpfDParcela.DatVencimento := VpfDatVencimento; VpfDatVencimento := VpfDParcela.DatVencimento; VpfDParcela.DatPagamento := montadata(1,1,1900); VpfDParcela.ValParcela := VpaDContasaPagar.ValParcela; VpfDParcela.PerMora := Varia.Mora; VpfDParcela.PerJuros := Varia.Juro; VpfDParcela.PerMulta := Varia.Multa; VpfDParcela.IndContaOculta := VpaDContasaPagar.IndEsconderConta; inc(VpfParcela); Tabela.next; end; Tabela.close; AjustaValorUltimaParcela(VpaDContasaPagar,VpaDContasaPagar.ValTotal); end; {*************** atualiza o valor total do cadcontasapagar ***************** } procedure TFuncoesContasAPagar.AtualizaValorTotal(VpaCodfilial, VpaLanPagar : integer ); begin LocalizaContaCP(Cadastro2,VpaCodFilial,VpaLanPagar); if not Cadastro2.eof then begin //atualiza a data de alteracao para poder exportar Cadastro2.edit; Cadastro2.FieldByname('D_ULT_ALT').AsDateTime := Date; Cadastro2.FieldByName('N_VLR_TOT').AsFloat := SomaTotalParcelas(VpaCodfilial,VpaLanPagar); Cadastro2.post; end; Cadastro2.close; end; { ****** verifica se as parcelas possuem o mesmo valor do total da conta ****** } function TFuncoesContasAPagar.VerificaAtualizaValoresParcelas(ValorInicialParcelas : double; lancamento : Integer ) : boolean; var Total : double; begin Total := SomaTotalParcelas(varia.CodigoEmpFil,Lancamento); Result := false; if Total <> ValorInicialParcelas then begin if not Confirmacao(CT_ValorDiferente + ' Nota = ' + FormatFloat(Varia.MascaraMoeda,ValorInicialParcelas) + ' -> parcelas = ' + FormatFloat(varia.MascaraMoeda,Total) + '. Você deseja corrigir ?' ) then begin Result := True; AtualizaValorTotal(varia.CodigoEmpFil,lancamento); end; end else Result := True; end; {########################### baixa Parcela ##################################} {******************************************************************************} function TFuncoesContasAPagar.BaixaContasAPagar(VpaDBaixa : TRBDBaixaCP) : string; var VpfLaco : Integer; VpfDParcela : TRBDParcelaCP; VpfValTotalParcelas : Double; begin result := GeraParcelaParcial(VpaDBaixa); if result = '' then begin for vpflaco :=0 to VpaDBaixa.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); result := BaixaParcelaPagar(VpaDBaixa,VpfDParcela); end; if result = '' then begin result := FunContasAReceber.GravaDCheques(VpaDBaixa.Cheques); end; if result = '' then begin Result := GravaDChequeCP(VpaDBaixa.Parcelas,VpaDBaixa.Cheques); if result = '' then begin if config.ControlarDebitoeCreditoCliente then begin VpfValTotalParcelas := RValTotalParcelasBaixa(VpaDBaixa); if VpaDBaixa.ValorPago > VpfValTotalParcelas then begin if confirmacao('VALOR PAGO A MAIOR!!!'#13'Está sendo pago um valor de "'+FormatFloat('R$ #,###,###,###,##0.00',VpaDBaixa.ValorPago - RValTotalParcelasBaixa(VpaDBaixa))+ '" a mais do que o valor da(s) parcela(s). Deseja gerar esse valor de debito com o fornecedor?') then begin result := FunClientes.AdicionaCredito(VpfDParcela.CodCliente,VpaDBaixa.ValorPago - VpfValTotalParcelas,'D','Referente valor pago a maior das parcelas "'+RNumParcelas(VpaDBaixa)+'"'); VpaDBaixa.ValParaGerardeDebito := VpaDBaixa.ValorPago - VpfValTotalParcelas; end; end; end; if ConfigModulos.Caixa then begin result := FunCaixa.AdicionaBaixaCPCaixa(VpaDBaixa); end; end; end; end; end; {********* gera numero proxima parcela ************************************** } function TFuncoesContasAPagar.GeraNroProximoParcela(VpaCodFilial,VpaLancamento : Integer) : Integer; begin AdicionaSQLAbreTabela(Calcula,' select max(i_nro_par) I_NRO_PAR from MOVCONTASAPAGAR ' + ' Where I_EMP_FIL = ' + IntTostr(Varia.CodigoEmpFil)+ ' and I_LAN_APG = ' + IntToStr(VpaLancamento)); Result := Calcula.fieldByname('I_NRO_PAR').AsInteger + 1; FechaTabela(calcula); end; {******************************************************************************} procedure TFuncoesContasAPagar.CalculaValorTotalBaixa(VpaDBaixa : TRBDBaixaCP); var VpfLaco : Integer; VpfDParcela : TRBDParcelaCP; begin VpaDBaixa.ValorPago := 0; VpaDBaixa.ValorAcrescimo := 0; VpaDBaixa.ValorDesconto := 0; for VpfLaco := 0 to VpaDBaixa.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); VpaDBaixa.ValorAcrescimo := VpaDBaixa.ValorAcrescimo + VpfDParcela.ValAcrescimo; VpaDBaixa.ValorDesconto := VpaDBaixa.ValorDesconto + VpfDParcela.ValDesconto; VpaDBaixa.ValorPago := VpaDBaixa.ValorPago + VpfDParcela.ValParcela; end; VpaDBaixa.ValorPago := VpaDBaixa.ValorPago + VpaDBaixa.ValorAcrescimo-VpaDBaixa.ValorDesconto; end; {******************************************************************************} function TFuncoesContasAPagar.VerificaSeValorPagoQuitaTodasDuplicatas(VpaDBaixa : TRBDBaixaCP;VpaValAReceber : Double) : String; var VpfLaco : Integer; VpfDParcela : TRBDParcelaCP; begin result := ''; if VpaDBaixa.Parcelas.Count > 0 then begin for VpfLaco := 0 to VpaDBaixa.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); if VpaValAReceber <= 0 then begin result := 'O valor pago não é suficiente para quitar todas as duplicatas. '+ ' É necessário eliminar da baixa as duplicatas que estão em vermelho.'; VpfDParcela.IndValorQuitaEssaParcela := false; end else VpfDParcela.IndValorQuitaEssaParcela := true; VpaValAReceber := VpaValAReceber - (VpfDParcela.ValParcela - VpfDParcela.ValDesconto+VpfDParcela.ValAcrescimo); end; end; end; {******************************************************************************} function TFuncoesContasAPagar.VerificaSeGeraParcial(VpaDBaixa : TRBDBaixaCP;VpaValAReceber : Double;VpaIndSolicitarData : Boolean) : String; var VpfLaco : Integer; VpfDParcela : TRBDParcelaCP; begin result := ''; VpaDBaixa.IndPagamentoParcial := false; VpaDBaixa.ValParcialFaltante := 0; if VpaDBaixa.Parcelas.Count > 0 then begin for VpfLaco := 0 to VpaDBaixa.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); VpfDParcela.IndGeraParcial := false; VpaValAReceber := VpaValAReceber - (VpfDParcela.ValParcela - VpfDParcela.ValDesconto+VpfDParcela.ValAcrescimo); if ArredondaDecimais(VpaValAReceber,2) < 0 then begin VpaDBaixa.ValParcialFaltante := VpaValAReceber * - 1; VpfDParcela.IndGeraParcial := true; VpaDBaixa.IndPagamentoParcial := true; VpaDBaixa.DatVencimentoParcial := VpfDParcela.DatVencimento; end; end; end; if VpaDBaixa.IndPagamentoParcial then begin if VpaDBaixa.DatVencimentoParcial < date then VpaDBaixa.DatVencimentoParcial := date; if VpaIndSolicitarData then if not EntraData('Pagamento Parcial','Valor Parcial = '+FormatFloat(Varia.MascaraValor,VpaDBaixa.ValParcialFaltante),VpaDBaixa.DatVencimentoParcial) Then result :='PARGAMENTO PARCIAL CANCELADO!!!'#13'Não foi gerado o pagamento parcial.'; end; end; {******************************************************************************} function TFuncoesContasAPagar.RValPrevistoPlanoContas(VpaCodEmpresa, VpaCodCentroCusto: Integer;VpaCodPlanoContas: String; VpaDatInicio, VpaDatFim: TDateTime): double; var VpfMesAtual : TDatetime; VpfAnoAtual : Integer; begin result := 0; VpfMesAtual := VpaDatInicio; VpfAnoAtual := -999; while VpfMesAtual < VpaDatFim do begin if VpfAnoAtual <> ano(VpfMesAtual) then begin AdicionaSQLAbreTabela(Tabela,'Select * from PLANOCONTAORCADO ' + ' WHERE CODEMPRESA = ' +IntToStr(VpaCodEmpresa)+ ' AND CODPLANOCONTA = '''+VpaCodPlanoContas+''''+ ' AND ANOORCADO = '+ IntToStr(Ano(VpfMesAtual))+ ' AND CODCENTROCUSTO = '+IntToStr(VpaCodCentroCusto)); VpfAnoAtual := Ano(VpfMesAtual); end; case Mes(VpfMesAtual) of 1 : result := result + Tabela.FieldByName('VALJANEIRO').AsFloat; 2 : result := result + Tabela.FieldByName('VALFEVEREIRO').AsFloat; 3 : result := result + Tabela.FieldByName('VALMARCO').AsFloat; 4 : result := result + Tabela.FieldByName('VALABRIL').AsFloat; 5 : result := result + Tabela.FieldByName('VALMAIO').AsFloat; 6 : result := result + Tabela.FieldByName('VALJUNHO').AsFloat; 7 : result := result + Tabela.FieldByName('VALJULHO').AsFloat; 8 : result := result + Tabela.FieldByName('VALAGOSTO').AsFloat; 9 : result := result + Tabela.FieldByName('VALSETEMBRO').AsFloat; 10 : result := result + Tabela.FieldByName('VALOUTUBRO').AsFloat; 11 : result := result + Tabela.FieldByName('VALNOVEMBRO').AsFloat; 12 : result := result + Tabela.FieldByName('VALDEZEMBRO').AsFloat; end; VpfMesAtual := incmes(VpfMesAtual,1); end; Tabela.Close; end; {******************************************************************************} function TFuncoesContasAPagar.RValTotalCheques(VpaDBaixaCP : TRBDBaixaCP) : Double; var VpfLaco : Integer; begin result := 0; for VpfLaco := 0 to VpaDBaixaCP.Cheques.Count - 1 do result := Result + TRBDCheque(VpaDBaixaCP.Cheques.Items[VpfLaco]).ValCheque; end; {******************************************************************************} function TFuncoesContasAPagar.RValTotalParcelasBaixa(VpaDBaixaCP : TRBDBaixaCP) : Double; var VpfLaco : Integer; VpfDParcela : TRBDParcelaCP; begin result := 0; for VpfLaco := 0 to VpaDBaixaCP.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixaCP.Parcelas.Items[VpfLaco]); result := result + VpfDParcela.ValParcela + VpfDParcela.ValAcrescimo - VpfDParcela.ValDesconto; end; end; {******************************************************************************} procedure TFuncoesContasAPagar.DistribuiValAcrescimoDescontoNasParcelas(VpaDBaixa : TRBDBaixaCP); Var VpfLaco : Integer; VpfValTotal,VpfPerSobreTotal : Double; VpfDParcela : TRBDParcelaCP; begin VpfValTotal := 0; for VpfLaco := 0 to VpaDBaixa.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); VpfValTotal := VpfValTotal + VpfDParcela.ValParcela; end; for VpfLaco := 0 to VpaDBaixa.Parcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); VpfPerSobreTotal := (VpfDParcela.ValParcela * 100)/VpfValTotal; if VpaDBaixa.ValorAcrescimo = 0 then VpfDParcela.ValAcrescimo := 0 else VpfDParcela.ValAcrescimo := (VpaDBaixa.ValorAcrescimo * VpfPerSobreTotal)/100; if VpaDBaixa.ValorDesconto = 0 then VpfDParcela.ValDesconto := 0 else VpfDParcela.ValDesconto := (VpaDBaixa.ValorDesconto * VpfPerSobreTotal)/100; end; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarDParcelaBaixa(VpaDParcela : TRBDParcelaCP;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); begin AdicionaSQLAbreTabela(Tabela,'Select CAD.I_COD_CLI, CAD.I_NRO_NOT, CAD.D_DAT_EMI, CAD.C_IND_CAD, '+ ' CAD.I_QTD_PAR, '+ ' MOV.I_COD_FRM, MOV.C_NRO_DUP, MOV.C_NRO_CON, MOV.L_OBS_APG ,'+ ' MOV.D_DAT_VEN, MOV.N_VLR_DUP, MOV.N_PER_MOR, MOV.N_PER_JUR, '+ ' MOV.N_PER_MUL, I_PAR_FIL, MOV.N_VLR_PAG, '+ ' CLI.C_NOM_CLI, '+ ' FRM.C_NOM_FRM '+ ' from CADCONTASAPAGAR CAD, MOVCONTASAPAGAR MOV, CADCLIENTES CLI, '+ ' CADFORMASPAGAMENTO FRM '+ ' Where CAD.I_EMP_FIL = MOV.I_EMP_FIL '+ ' and CAD.I_LAN_APG = MOV.I_LAN_APG '+ ' and CAD.I_COD_CLI = CLI.I_COD_CLI '+ ' and MOV.I_COD_FRM = FRM.I_COD_FRM '+ ' AND MOV.I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND MOV.I_LAN_APG = '+IntToStr(VpaLanPagar)+ ' AND MOV.I_NRO_PAR = '+IntToStr(VpaNumParcela)); VpaDParcela.CodFilial := VpaCodFilial; VpaDParcela.LanPagar := VpaLanPagar; VpaDParcela.NumParcela := VpaNumParcela; VpaDParcela.NumParcelaParcial := Tabela.FieldByname('I_PAR_FIL').AsInteger; VpaDParcela.NomCliente := Tabela.FieldByname('C_NOM_CLI').AsString; VpaDParcela.NomFormaPagamento := Tabela.FieldByname('C_NOM_FRM').AsString; VpaDParcela.DesObservacoes := Tabela.FieldByname('L_OBS_APG').AsString; VpaDParcela.CodCliente := Tabela.FieldByname('I_COD_CLI').AsInteger; VpaDParcela.CodFormaPagamento := Tabela.FieldByname('I_COD_FRM').AsInteger; VpaDParcela.QtdParcelas := Tabela.FieldByname('I_QTD_PAR').AsInteger; VpaDParcela.NumNotaFiscal := Tabela.FieldByname('I_NRO_NOT').AsInteger; VpaDParcela.NumDuplicata := Tabela.FieldByname('C_NRO_DUP').AsString; VpaDParcela.NumContaCorrente := Tabela.FieldByname('C_NRO_CON').AsString; VpaDParcela.DatEmissao := Tabela.FieldByname('D_DAT_EMI').AsDateTime; VpaDParcela.DatVencimento := Tabela.FieldByname('D_DAT_VEN').AsDateTime; VpaDParcela.ValParcela := Tabela.FieldByname('N_VLR_DUP').AsFloat; VpaDParcela.ValPago := Tabela.FieldByname('N_VLR_PAG').AsFloat; VpaDParcela.IndContaOculta := (Tabela.FieldByname('C_IND_CAD').AsString = 'S'); VpaDParcela.PerMora := Tabela.FieldByname('N_PER_MOR').AsFloat; VpaDParcela.PerJuros := Tabela.FieldByname('N_PER_JUR').AsFloat; VpaDParcela.PerMulta := Tabela.FieldByname('N_PER_MUL').AsFloat; if Tabela.FieldByname('D_DAT_VEN').AsDateTime < date then VpaDParcela.NumDiasAtraso := DiasPorPeriodo(Tabela.FieldByname('D_DAT_VEN').AsDateTime,date) else VpaDParcela.NumDiasAtraso := 0; Tabela.Close; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarDProjetoContasaPagar(VpaDContasAPagar: TRBDContasaPagar); Var VpfDDespesaProjeto : TRBDContasaPagarProjeto; begin FreeTObjectsList(VpaDContasAPagar.DespesaProjeto); AdicionaSQLAbreTabela(Tabela,'Select PRO.CODPROJETO, PRO.NOMPROJETO, '+ ' CPP.VALDESPESA, CPP.PERDESPESA ' + ' From PROJETO PRO, CONTAAPAGARPROJETO CPP ' + ' WHERE PRO.CODPROJETO = CPP.CODPROJETO ' + ' AND CPP.CODFILIAL = '+IntToStr( VpaDContasAPagar.CodFilial)+ ' AND CPP.LANPAGAR = '+IntToStr(VpaDContasAPagar.LanPagar)+ ' ORDER BY SEQDESPESA '); while not Tabela.Eof do begin VpfDDespesaProjeto := VpaDContasAPagar.addDespesaProjeto; VpfDDespesaProjeto.CodProjeto := Tabela.FieldByName('CODPROJETO').AsInteger; VpfDDespesaProjeto.NomProjeto := Tabela.FieldByName('NOMPROJETO').AsString; VpfDDespesaProjeto.PerDespesa := Tabela.FieldByName('PERDESPESA').AsFloat; VpfDDespesaProjeto.ValDespesa := Tabela.FieldByName('VALDESPESA').AsFloat; Tabela.Next; end; Tabela.Close; end; {******************************************************************************} function TFuncoesContasAPagar.ValidaParcelaPagamento(VpaCodFilial, VpaLanPagar, VpaNumParcela : integer) : boolean; begin result := true; if config.BaixaParcelaAntVazia then begin AdicionaSQLAbreTabela(Tabela,' select * from MOVCONTASAPAGAR '+ ' where i_emp_fil = '+ IntToStr(VpaCodFilial) + ' and I_LAN_APG = ' + IntTostr(VpaLanPagar) + ' and I_NRO_PAR < '+ IntToStr(VpaNumParcela)+ ' and d_dat_pag is null '); if not tabela.Eof then begin aviso(CT_ParcelaAntVAzia); result := false; end; tabela.close; end; end; {******************************************************************************} function TFuncoesContasAPagar.ValorProjetosMaiorQueContasaPagar(VpaDContasaPagar: TRBDContasaPagar;VpaValContasAPagar : Double): string; var VpfValProjetos : Double; VpfLaco : Integer; begin result := ''; VpfValProjetos := 0; for VpfLaco := 0 to VpaDContasaPagar.DespesaProjeto.Count - 1 do begin VpfValProjetos := VpfValProjetos + TRBDContasaPagarProjeto(VpaDContasaPagar.DespesaProjeto.Items[VpfLaco]).ValDespesa; end; if ArredondaDecimais(VpfValProjetos,2) > ArredondaDecimais(VpaValContasAPagar,2) then begin result := 'VALOR PROJETOS MAIOR QUE O VALOR DO CONTAS A PAGAR!!!'#13'O valor das depesas do projeto soma "'+FormatFloat('R$ #,###,###,##0.00',VpfValProjetos)+'" e o valor do contas a pagar é "'+FormatFloat('R$ #,###,###,##0.00',VpaValContasAPagar)+'"'; end else if ArredondaDecimais(VpfValProjetos,2) < ArredondaDecimais(VpaValContasAPagar,2) then result := 'VALOR PROJETOS MENOR QUE O VALOR DO CONTAS A PAGAR!!!'#13'O valor das depesas do projeto soma "'+FormatFloat('R$ #,###,###,##0.00',VpfValProjetos)+'" e o valor do contas a pagar é "'+FormatFloat('R$ #,###,###,##0.00',VpaValContasAPagar)+'"'; end; {******************************************************************************} function TFuncoesContasAPagar.EstornaParcelaParcial(VpaCodFilial, VpaLanPagar, VpaNumParcelaFilha : integer) : string; begin result := ''; if VpaNumParcelaFilha <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'select * from MOVCONTASAPAGAR '+ ' Where I_EMP_FIL = ' + IntToStr(VpaCodFilial) + ' and I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_NRO_PAR = ' + IntToStr(VpaNumParcelaFilha)); if not Cadastro.eof then begin if Cadastro.FieldByName('I_PAR_FIL').AsInteger <> 0 then result := CT_EstonoPacialInvalida else Cadastro.Delete; end; Cadastro.close; end; end; {******************************************************************************} function TFuncoesContasAPagar.RParcelaAGerarParcial(VpaDBaixa : TRBDBaixaCP): TRBDParcelaCP; var VpfLaco : Integer; begin result := nil; for VpfLaco := 0 to VpaDBaixa.Parcelas.Count - 1 do begin if TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]).IndGeraParcial then result := TRBDParcelaCP(VpaDBaixa.Parcelas.Items[VpfLaco]); end; end; {******************************************************************************} function TFuncoesContasAPagar.RPercentualProjetoFaltante(VpaDContasAPagar: TRBDContasaPagar): Double; var VpfPerProjetos : Double; VpfLaco : Integer; begin result := 0; VpfPerProjetos := 0; for VpfLaco := 0 to VpaDContasaPagar.DespesaProjeto.Count - 1 do VpfPerProjetos := VpfPerProjetos + TRBDContasaPagarProjeto(VpaDContasaPagar.DespesaProjeto.Items[VpfLaco]).PerDespesa; if VpfPerProjetos < 100 then result := 100 - VpfPerProjetos; end; {******************************************************************************} function TFuncoesContasAPagar.GeraParcelaParcial( VpaDBaixa : TRBDBaixaCP) : string; var VpfDParcelaOriginal : TRBDParcelaCP; begin result := ''; if VpaDBaixa.IndPagamentoParcial then begin VpfDParcelaOriginal := RParcelaAGerarParcial(VpaDBaixa); result := GravaParcelaParcial(VpfDParcelaOriginal,VpaDBaixa.ValParcialFaltante,VpaDBaixa.DatVencimentoParcial); end; end; {******************************************************************************} function TFuncoesContasAPagar.GravaParcelaParcial(VpaDParcelaOriginal : TRBDParcelaCP;VpaValParcial : Double;VpaDatVencimento : TDateTime):string; begin result := ''; VpaDParcelaOriginal.NumParcelaParcial := GeraNroProximoParcela(VpaDParcelaOriginal.CodFilial,VpaDParcelaOriginal.LanPagar ); //atualiza o numero da parcial na parcela mae LocalizaParcela(Cadastro2,VpaDParcelaOriginal.CodFilial, VpaDParcelaOriginal.LanPagar,VpaDParcelaOriginal.NumParcela); Cadastro2.edit; Cadastro2.FieldByName('I_PAR_FIL').AsInteger := VpaDParcelaOriginal.NumParcelaParcial; Cadastro2.post; LocalizaMov(Cadastro); Cadastro.insert; Cadastro.FieldByName('I_EMP_FIL').AsInteger := VpaDParcelaOriginal.CodFilial; Cadastro.FieldByName('I_LAN_APG').AsInteger := VpaDParcelaOriginal.LanPagar; Cadastro.FieldByName('I_NRO_PAR').AsInteger := VpaDParcelaOriginal.NumParcelaParcial; Cadastro.FieldByName('D_DAT_VEN').AsDateTime := MontaData(dia(VpaDatVencimento),mes(VpaDatVencimento),ano(VpaDatVencimento)); Cadastro.FieldByName('L_OBS_APG').AsString := Cadastro2.FieldByName('L_OBS_APG').AsString + ' - Lançamento originado da parcela ' + IntToStr(VpaDParcelaOriginal.NumParcela); Cadastro.FieldByName('N_VLR_DUP').AsFloat := VpaValParcial; Cadastro.FieldByName('I_COD_MOE').AsInteger := Cadastro2.FieldByName('I_COD_MOE').AsInteger; Cadastro.FieldByName('N_PER_MUL').AsFloat := Cadastro2.fieldByName('N_PER_MUL').AsCurrency; Cadastro.FieldByName('N_PER_MOR').AsFloat := Cadastro2.fieldByName('N_PER_MOR').AsCurrency; Cadastro.FieldByName('N_PER_JUR').AsFloat := Cadastro2.fieldByName('N_PER_JUR').AsCurrency; Cadastro.FieldByName('N_VLR_JUR').AsFloat := Cadastro2.fieldByName('N_VLR_JUR').AsFloat; Cadastro.FieldByName('N_VLR_MOR').AsFloat := Cadastro2.fieldByName('N_VLR_MOR').AsFloat; Cadastro.FieldByName('N_VLR_MUL').AsFloat := Cadastro2.fieldByName('N_VLR_MUL').AsFloat; if Cadastro2.FieldByName('C_NRO_CON').AsString <> '' then Cadastro.FieldByName('C_NRO_CON').AsString := Cadastro2.FieldByName('C_NRO_CON').AsString; Cadastro.FieldByName('C_FLA_PAR').AsString := 'S'; Cadastro.FieldByName('I_COD_USU').AsInteger := Varia.CodigoUsuario; Cadastro.FieldByName('C_FLA_CHE').AsString := 'N'; Cadastro.FieldByName('C_IMP_CHE').AsString := 'N'; Cadastro.FieldByName('C_DES_PRR').AsString := 'N'; Cadastro.FieldByName('I_COD_FRM').Asinteger := Cadastro2.fieldByName('I_COD_FRM').Asinteger; //atualiza a data de alteracao para poder exportar Cadastro.FieldByName('D_ULT_ALT').AsDateTime := Date; if Cadastro2.fieldByName('C_NRO_DUP').AsString <> '' then begin Cadastro.FieldByName('C_NRO_DUP').AsString := Cadastro2.fieldByName('C_NRO_DUP').AsString + '/' + IntTostr(VpaDParcelaOriginal.NumParcelaParcial); Cadastro.FieldByName('C_NRO_DOC').AsString := Cadastro2.fieldByName('C_NRO_DOC').AsString + '/' + IntTostr(VpaDParcelaOriginal.NumParcelaParcial); end; Cadastro.post; result := Cadastro.AMensagemErroGravacao; Cadastro.close; Cadastro2.close; end; {******************************************************************************} function TFuncoesContasAPagar.GravaDChequeCP(VpaParcelas, VpaCheques : TList ):string; var VpfLacoCheque, VpfLacoParcelas : Integer; VpfDCheque : TRBDCheque; VpfDParcela : TRBDParcelaCP; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from CHEQUECP'+ ' Where SEQCHEQUE = 0 AND CODFILIALPAGAR = 0 '+ ' AND LANPAGAR = 0 AND NUMPARCELA = 0 '); for VpfLacoCheque := 0 to VpaCheques.Count - 1 do begin VpfDCheque := TRBDCheque(VpaCheques.Items[VpfLacoCheque]); if (VpfDCheque.TipFormaPagamento = fpChequeTerceiros) then //cheque de terceiros. result := FunContasAReceber.CompensaCheque(VpfDCheque,'D',false); if result = '' then begin for VpfLacoParcelas := 0 to VpaParcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpaParcelas.Items[VpfLacoParcelas]); Cadastro.insert; Cadastro.FieldByname('SEQCHEQUE').AsInteger := VpfDCheque.SeqCheque; Cadastro.FieldByname('CODFILIALPAGAR').AsInteger := VpfDParcela.CodFilial; Cadastro.FieldByname('LANPAGAR').AsInteger := VpfDParcela.LanPagar; Cadastro.FieldByname('NUMPARCELA').AsInteger := VpfDParcela.NumParcela; Cadastro.post; result := Cadastro.AMensagemErroGravacao; if Cadastro.AErronaGravacao then break; end; end; end; Cadastro.close; end; {******************************************************************************} procedure TFuncoesContasAPagar.LocalizaChequesCP(VpaTabela : TSQLQUERY;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); begin AdicionaSQLAbreTabela(VpaTabela,'select CHE.SEQCHEQUE, CHE.CODBANCO, CHE.CODFORMAPAGAMENTO,'+ ' CHP.CODFILIALPAGAR, CHP.LANPAGAR, '+ ' CHP.NUMPARCELA, CHE.NOMEMITENTE, CHE.NUMCHEQUE, CHE.DATCADASTRO, ' + ' CHE.DATVENCIMENTO, CHE.DATCOMPENSACAO, CHE.VALCHEQUE, CHE.DATDEVOLUCAO, '+ ' CHE.DATALTERACAO, CHE.CODUSUARIO,CHE.NUMCONTACAIXA, CHE.TIPCHEQUE, '+ ' FRM.C_NOM_FRM, FRM.C_FLA_TIP, '+ ' CON.C_NOM_CRR, CON.C_TIP_CON ' + ' from CHEQUE CHE, CHEQUECP CHP, CADFORMASPAGAMENTO FRM, CADCONTAS CON ' + ' Where CHE.CODFORMAPAGAMENTO = FRM.I_COD_FRM ' + ' AND CHE.NUMCONTACAIXA = CON.C_NRO_CON ' + ' AND CHE.SEQCHEQUE = CHP.SEQCHEQUE '+ ' AND CHP.CODFILIALPAGAR = ' + IntToStr(VpaCodFilial)+ ' AND CHP.LANPAGAR = ' + IntToStr(VpaLanPagar)+ ' AND CHP.NUMPARCELA = ' + IntToStr(VpaNumParcela)); end; {******************************************************************************} function TFuncoesContasAPagar.MarcaProrrogado(VpaCodFilial, VpaLanPagar, VpaNumParcela: Integer; VpaMarcarProrrogado: boolean): string; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASAPAGAR ' + ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND I_LAN_APG = '+IntToStr(VpaLanPagar)+ ' AND I_NRO_PAR = '+IntToStr(VpaNumParcela)); Cadastro.Edit; if VpaMarcarProrrogado then Cadastro.FieldByName('C_DES_PRR').AsString := 'S' else Cadastro.FieldByName('C_DES_PRR').AsString := 'N'; Cadastro.Post; result := Cadastro.AMensagemErroGravacao; Cadastro.Close; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarDChequesCP(VpaListaCheques : TList;VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer); var VpfDCheque : TRBDCheque; begin FreeTObjectsList(VpaListaCheques); LocalizaChequesCP(Tabela,VpaCodFilial,VpaLanPagar,VpaNumParcela); While not Tabela.Eof do begin VpfDCheque := TRBDCheque.cria; VpaListaCheques.Add(VpfDCheque); VpfDCheque.SeqCheque := Tabela.FieldByname('SEQCHEQUE').AsInteger; VpfDCheque.CodBanco := Tabela.FieldByname('CODBANCO').AsInteger; VpfDCheque.CodFormaPagamento := Tabela.FieldByname('CODFORMAPAGAMENTO').AsInteger; VpfDCheque.NumCheque := Tabela.FieldByname('NUMCHEQUE').AsInteger; VpfDCheque.CodUsuario := Tabela.FieldByname('CODUSUARIO').AsInteger; VpfDCheque.NumContaCaixa := Tabela.FieldByname('NUMCONTACAIXA').AsString ; VpfDCheque.NomContaCaixa := Tabela.FieldByname('C_NOM_CRR').AsString ; VpfDCheque.NomEmitente := Tabela.FieldByname('NOMEMITENTE').AsString ; VpfDCheque.NomFormaPagamento := Tabela.FieldByname('C_NOM_FRM').AsString ; VpfDCheque.TipFormaPagamento := FunContasAReceber.RTipoFormapagamento(Tabela.FieldByname('C_FLA_TIP').AsString); VpfDCheque.TipCheque := Tabela.FieldByName('TIPCHEQUE').AsString; VpfDCheque.TipContaCaixa := Tabela.FieldByName('C_TIP_CON').AsString; VpfDCheque.ValCheque := Tabela.FieldByname('VALCHEQUE').AsFloat ; VpfDCheque.DatCadastro := Tabela.FieldByname('DATCADASTRO').AsDateTime ; VpfDCheque.DatVencimento := Tabela.FieldByname('DATVENCIMENTO').AsDateTime ; VpfDCheque.DatCompensacao := Tabela.FieldByname('DATCOMPENSACAO').AsDateTime ; VpfDCheque.DatDevolucao := Tabela.FieldByname('DATDEVOLUCAO').AsDateTime ; Tabela.Next; end; Tabela.Close; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarParcelasCheque(VpaParcelas : TList;VpaSeqCheque, VpaCodFilialOriginal, VpaLanPagarOriginal, VpaNumParcelaOriginal : Integer); var VpfDParcela : TRBDParcelaCP; begin FreeTObjectsList(VpaParcelas); AdicionaSQLAbreTabela(calcula,'Select CODFILIALPAGAR, LANPAGAR, NUMPARCELA '+ ' from CHEQUECP '+ ' Where SEQCHEQUE = '+IntToStr(VpaSeqCheque)); While not Calcula.eof do begin if not((Calcula.FieldByname('CODFILIALPAGAR').AsInteger = VpaCodFilialOriginal) and (Calcula.FieldByname('LANPAGAR').AsInteger = VpaLanPagarOriginal) and (Calcula.FieldByname('NUMPARCELA').AsInteger = VpaNumParcelaOriginal)) then begin VpfDParcela := TRBDParcelaCP.Cria; CarDParcelaBaixa(VpfDParcela,Calcula.FieldByname('CODFILIALPAGAR').AsInteger,Calcula.FieldByname('LANPAGAR').AsInteger, Calcula.FieldByname('NUMPARCELA').AsInteger); VpaParcelas.Add(VpfDParcela); end; Calcula.next; end; Calcula.close; end; {******************************************************************************} function TFuncoesContasAPagar.GravaDContasaPagar(VpaDContasAPagar : TRBDContasaPagar) : String; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from CADCONTASAPAGAR '+ ' Where I_EMP_FIL = '+IntToStr(VpaDContasAPagar.CodFilial)+ ' and I_LAN_APG = ' + IntToStr(VpaDContasAPagar.LanPagar)); if Cadastro.Eof then Cadastro.Insert else Cadastro.edit; Cadastro.FieldByName('I_COD_EMP').AsInteger := Varia.CodigoEmpresa; Cadastro.FieldByName('I_EMP_FIL').AsInteger := VpaDContasAPagar.CodFilial; Cadastro.FieldByName('I_COD_PAG').AsInteger := VpaDContasAPagar.CodCondicaoPagamento; if VpaDContasAPagar.IndDespesaPrevista then Cadastro.FieldByName('I_QTD_PAR').AsInteger := 1 else Cadastro.FieldByName('I_QTD_PAR').AsInteger := Sistema.RQtdParcelasCondicaoPagamento(VpaDContasAPagar.CodCondicaoPagamento); if VpaDContasAPagar.CodCentroCusto <> 0 then Cadastro.FieldByName('I_COD_CEN').AsInteger := VpaDContasAPagar.CodCentroCusto else Cadastro.FieldByName('I_COD_CEN').clear; if (VpaDContasAPagar.IndDespesaPrevista) then VpaDContasAPagar.DatEmissao := TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[0]).DatVencimento; Cadastro.FieldByName('D_DAT_MOV').AsDateTime := date; Cadastro.FieldByName('D_DAT_EMI').AsDateTime := VpaDContasAPagar.DatEmissao; Cadastro.FieldByName('I_COD_USU').AsInteger := Varia.CodigoUsuario; // adiciona o usuario que esta cadastrando if DeletaEspacoDE(VpaDContasAPagar.DesPathFoto) <> '' then Cadastro.FieldByName('C_PAT_FOT').AsString := VpaDContasAPagar.DesPathFoto; // Parâmetros. if VpaDContasAPagar.NumNota <> 0 then Cadastro.FieldByName('I_NRO_NOT').AsInteger := VpaDContasAPagar.NumNota; if VpaDContasAPagar.SeqNota <> 0 then Cadastro.FieldByName('I_SEQ_NOT').AsInteger := VpaDContasAPagar.SeqNota; Cadastro.FieldByName('I_COD_CLI').AsInteger := VpaDContasAPagar.CodFornecedor; Cadastro.FieldByName('N_VLR_TOT').AsFloat := VpaDContasAPagar.ValTotal; Cadastro.FieldByName('C_CLA_PLA').AsString := VpaDContasAPagar.CodPlanoConta; if VpaDContasAPagar.IndEsconderConta then Cadastro.FieldByName('C_IND_CAD').AsString := 'S'; if VpaDContasAPagar.IndDespesaPrevista then Cadastro.FieldByName('C_IND_PRE').AsString := 'S' else Cadastro.FieldByName('C_IND_PRE').AsString := 'N'; VpaDContasAPagar.LanPagar := GeraProximoCodigo('i_lan_apg','CADCONTASAPAGAR','I_EMP_FIL', varia.CodigoEmpFil, false,VprBaseDados); Cadastro.FieldByName('I_LAN_APG').AsInteger := VpaDContasAPagar.LanPagar; //atualiza a data de alteracao para poder exportar Cadastro.FieldByName('D_ULT_ALT').AsDateTime := Date; Cadastro.post; if Cadastro.AErronaGravacao then begin // caso erro na Cadastro de codigos sequencial a o proximo do movCadastro Cadastro.FieldByName('I_LAN_APG').AsInteger := GeraProximoCodigo('i_lan_apg','cadContasAPagar','i_emp_fil', varia.CodigoEmpFil, true,VprBaseDados); Cadastro.POST; result := Cadastro.AMensagemErroGravacao; end; Cadastro.close; if result = '' then begin Result := GravaDParcelaPagar(VpaDContasAPagar); if result = '' then result := GravaDDespesaProjeto(VpaDContasAPagar); end; if (VpaDContasAPagar.IndDespesaPrevista) then begin VpaDContasAPagar.Parcelas.Delete(0); if (VpaDContasAPagar.Parcelas.Count > 0) then begin VpaDContasAPagar.LanPagar := 0; TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[0]).DatEmissao := TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[0]).DatVencimento; GravaDContasaPagar(VpaDContasAPagar); end; end; end; {******************************************************************************} function TFuncoesContasAPagar.GravaDDespesaProjeto(VpaDContasAPagar: TRBDContasaPagar): String; var VpfDDespesa :TRBDContasaPagarProjeto; VpfLaco : Integer; begin result := ''; ExecutaComandoSql(Aux,'Delete from CONTAAPAGARPROJETO '+ ' Where CODFILIAL = '+IntToStr(VpaDContasAPagar.CodFilial)+ ' and LANPAGAR = ' + IntToStr(VpaDContasAPagar.LanPagar)); AdicionaSQLAbreTabela(Cadastro,'Select * from CONTAAPAGARPROJETO '+ ' Where CODFILIAL = 0 AND LANPAGAR = 0 '); for VpfLaco := 0 to VpaDContasAPagar.DespesaProjeto.Count - 1 do begin VpfDDespesa := TRBDContasaPagarProjeto(VpaDContasAPagar.DespesaProjeto.Items[VpfLaco]); Cadastro.insert; Cadastro.FieldByName('CODFILIAL').AsInteger := VpaDContasAPagar.CodFilial; Cadastro.FieldByName('LANPAGAR').AsInteger := VpaDContasAPagar.LanPagar; Cadastro.FieldByName('SEQDESPESA').AsInteger := VpfLaco + 1; Cadastro.FieldByName('CODPROJETO').AsInteger := VpfDDespesa.CodProjeto; Cadastro.FieldByName('PERDESPESA').AsFloat := VpfDDespesa.PerDespesa; Cadastro.FieldByName('VALDESPESA').AsFloat := VpfDDespesa.ValDespesa; Cadastro.Post; result := Cadastro.AMensagemErroGravacao; if Cadastro.AErronaGravacao then break; end; Cadastro.Close; end; {******************************************************************************} function TFuncoesContasAPagar.GravaDParcelaPagar(VpaDContasAPagar : TRBDContasaPagar) : String; Var VpfLaco : Integer; VpfDParcelaCP : TRBDParcelaCP; begin result := ''; ExecutaComandoSql(Aux,'Delete from MOVCONTASAPAGAR '+ ' Where I_EMP_FIL = '+IntToStr(VpaDContasAPagar.CodFilial)+ ' and I_LAN_APG = ' + IntToStr(VpaDContasAPagar.LanPagar)); AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASAPAGAR '+ ' Where I_EMP_FIL = '+IntToStr(VpaDContasAPagar.CodFilial)+ ' and I_LAN_APG = ' + IntToStr(VpaDContasAPagar.LanPagar)); for VpfLaco := 0 to VpaDContasAPagar.Parcelas.Count - 1 do begin VpfDParcelaCP := TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[VpfLaco]); VpfDParcelaCP.CodFilial := VpaDContasAPagar.CodFilial; VpfDParcelaCP.LanPagar := VpaDContasAPagar.LanPagar; Cadastro.Insert; Cadastro.FieldByname('I_EMP_FIL').AsInteger := VpaDContasAPagar.CodFilial; Cadastro.FieldByname('I_LAN_APG').AsInteger := VpaDContasAPagar.LanPagar; Cadastro.FieldByname('I_NRO_PAR').AsInteger := VpfDParcelaCP.NumParcela; if VpfDParcelaCP.NumContaCorrente <> '' then Cadastro.FieldByname('C_NRO_CON').AsString := VpfDParcelaCP.NumContaCorrente; Cadastro.FieldByname('C_NRO_DUP').AsString := VpfDParcelaCP.NumDuplicata; Cadastro.FieldByname('C_COD_BAR').AsString := VpfDParcelaCP.CodBarras; Cadastro.FieldByname('D_DAT_VEN').AsDateTime := VpfDParcelaCP.DatVencimento; Cadastro.FieldByname('N_VLR_DUP').AsFloat := VpfDParcelaCP.ValParcela; Cadastro.FieldByname('N_PER_JUR').AsFloat := VpfDParcelaCP.PerJuros; Cadastro.FieldByname('N_PER_MOR').AsFloat := VpfDParcelaCP.PerMora; Cadastro.FieldByname('N_PER_MUL').AsFloat := VpfDParcelaCP.PerMulta; Cadastro.FieldByname('I_COD_USU').AsInteger := varia.CodigoUsuario; Cadastro.FieldByname('C_NRO_DOC').AsString := VpfDParcelaCP.NumDuplicata; Cadastro.FieldByname('I_COD_FRM').AsInteger := VpfDParcelaCP.CodFormaPagamento; Cadastro.FieldByname('C_FLA_PAR').AsString := 'N'; Cadastro.FieldByname('C_IMP_CHE').AsString := 'N'; Cadastro.FieldByname('C_BOL_REC').AsString := 'N'; Cadastro.FieldByname('C_DES_PRR').AsString := 'N'; Cadastro.FieldByname('L_OBS_APG').AsString := VpfDParcelaCP.DesObservacoes; Cadastro.FieldByname('I_COD_MOE').AsInteger := VpaDContasAPagar.CodMoeda; Cadastro.FieldByname('D_ULT_ALT').AsDateTime := now; Cadastro.post; result := Cadastro.AMensagemErroGravacao; if Cadastro.AErronaGravacao then break; if VpaDContasAPagar.IndDespesaPrevista then break; end; Cadastro.close; end; {******************************************************************************} function TFuncoesContasAPagar.BaixaParcelacomDebitoFornecedor(VpaDContasaPagar: TRBDContasaPagar; VpaCredito: TList): string; var VpfDBaixa : TRBDBaixaCP; VpfLaco : Integer; VpfDParcelaBaixa : TRBDParcelaCP; VpfValCredito : Double; begin { O que falta: -No credito quem que informar qual a conta caixa que gerou esse credito, para quando excluir o credito no cadastro de clientes tem que adicionar esse valor no caixa novamente;} result := ''; if varia.FormaPagamentoCreditoCliente = 0 then result := 'FORMA DE PAGAMENTO CREDITO CLIENTE NÃO PREENCHIDA!!!'#13'É necessário preencher nas configurações financeiras a forma de pagamento de credito do cliente.'; if result = '' then begin VpfDBaixa := TRBDBaixaCP.Cria; VpfDBaixa.CodFormaPagamento := Varia.FormaPagamentoCreditoCliente; VpfDBaixa.NumContaCaixa := varia.CaixaPadrao; VpfDBaixa.DatPagamento := date; VpfValCredito := FunContasAReceber.RValTotalCredito(VpaCredito,dcDebito); //carrega as parcelas que serao pagas for VpfLaco := 0 to VpaDContasaPagar.Parcelas.Count - 1 do begin VpfDParcelaBaixa := VpfDBaixa.AddParcela; CarDParcelaBaixa(VpfDParcelaBaixa,VpaDContasaPagar.CodFilial,VpaDContasaPagar.LanPagar,TRBDParcelaCP(VpaDContasaPagar.Parcelas.Items[VpfLaco]).NumParcela); VpfValCredito := VpfValCredito - VpfDParcelaBaixa.ValParcela; if VpfValCredito <= 0 then break; end; if VpfValCredito >= 0 then begin VpfDBaixa.ValorPago := VpaDContasaPagar.ValTotal; VpaDContasaPagar.ValSaldoDebitoFornecedor := VpfValCredito; end else begin VpfDBaixa.ValorPago := FunContasAReceber.RValTotalCredito(VpaCredito,dcDebito); VpaDContasaPagar.ValSaldoDebitoFornecedor := 0; end; VpaDContasaPagar.ValUtilizadoCredito := VpfDBaixa.ValorPago; //baixa o contas a receber; result := VerificaSeGeraParcial(VpfDBaixa,VpfDBaixa.ValorPago,false); if result = '' then begin VpfDBaixa.IndBaixaUtilizandoODebitoFornecedor := true; result := BaixaContasAPagar(VpfDBaixa); end; //exclui o valor do credito do cliente; if result = '' then begin result := FunClientes.DiminuiCredito(VpfDParcelaBaixa.CodCliente,VpfDBaixa.ValorPago,dcDebito); end; end; end; {******************************************************************************} function TFuncoesContasAPagar.BaixaParcelaPagar(VpaDBaixa : TRBDBaixaCP;VpaDParcela : TRBDParcelaCP):string; begin result := ''; Localizaparcela(Cadastro,VpaDParcela.CodFilial,VpaDParcela.LanPagar, VpaDParcela.NumParcela); Cadastro.edit; Cadastro.FieldByName('D_DAT_PAG').AsDateTime := VpaDBaixa.DatPagamento; Cadastro.FieldByName('N_VLR_DES').AsCurrency := VpaDBaixa.ValorDesconto; Cadastro.FieldByName('N_VLR_ACR').AsCurrency := VpaDBaixa.ValorAcrescimo; if VpaDParcela.IndGeraParcial then Cadastro.FieldByName('N_VLR_PAG').AsCurrency := VpaDParcela.ValParcela-VpaDBaixa.ValParcialFaltante else Cadastro.FieldByName('N_VLR_PAG').AsCurrency := VpaDParcela.ValParcela+VpaDParcela.ValAcrescimo-VpaDParcela.ValDesconto; Cadastro.FieldByName('L_OBS_APG').AsString := VpaDParcela.DesObservacoes; Cadastro.FieldByName('I_COD_USU').AsInteger := Varia.CodigoUsuario; Cadastro.FieldByName('N_PER_MUL').AsCurrency := VpaDParcela.PerMulta; Cadastro.FieldByName('N_PER_JUR').AsCurrency := VpaDParcela.PerJuros; Cadastro.FieldByName('N_PER_MOR').AsCurrency := VpaDParcela.PerMora; Cadastro.FieldByName('C_NRO_CON').AsString := VpaDBaixa.NumContaCaixa; Cadastro.FieldByName('I_COD_FRM').AsInteger := VpaDBaixa.CodFormaPAgamento; // caso naum mude a frm aqui so no cadastro, ou baixa //atualiza a data de alteracao para poder exportar Cadastro.FieldByName('D_ULT_ALT').AsDateTime := Date; Cadastro.post; result := Cadastro.AMensagemErroGravacao; Cadastro.close; end; {******************************************************************************} function TFuncoesContasAPagar.BaixaContasaPagarAutomatico(VpaDContasaPagar : TRBDContasaPagar) : string; var VpfDBaixa : TRBDBaixaCP; VpfDParcelaCadastro, VpfDParcelaBaixa : TRBDParcelaCP; VpfLaco : Integer; begin result := ''; VpfDBaixa := TRBDBaixaCP.Cria; VpfDBaixa.CodFormaPagamento := VpaDContasaPagar.CodFormaPagamento; VpfDBaixa.TipFormaPagamento := VpaDContasaPagar.DesTipFormaPagamento; VpfDBaixa.NumContaCaixa := VpaDContasaPagar.NumContaCaixa; VpfDBaixa.ValorPago := VpaDContasaPagar.ValTotal; VpfDBaixa.DatPagamento := VpaDContasaPagar.DatEmissao; for VpfLaco := 0 to VpaDContasaPagar.Parcelas.Count - 1 do begin VpfDParcelaCadastro := TRBDParcelaCP(VpaDContasaPagar.Parcelas.Items[VpfLaco]); VpfDParcelaBaixa := VpfDBaixa.AddParcela; with VpfDParcelaBaixa do begin CodFilial := VpfDParcelaCadastro.CodFilial; LanPagar := VpfDParcelaCadastro.LanPagar; NumParcela := VpfDParcelaCadastro.NumParcela; NumParcelaParcial := VpfDParcelaCadastro.NumParcelaParcial; CodCliente := VpfDParcelaCadastro.CodCliente; CodFormaPagamento := VpfDParcelaCadastro.CodFormaPagamento; NumNotaFiscal := VpfDParcelaCadastro.NumNotaFiscal; NumDiasAtraso := VpfDParcelaCadastro.NumDiasAtraso; QtdParcelas := VpfDParcelaCadastro.QtdParcelas; NumContaCorrente := VpaDContasaPagar.NumContaCaixa; NomCliente := VpfDParcelaCadastro.NomCliente; NomFormaPagamento := VpfDParcelaCadastro.NomFormaPagamento; NumDuplicata := VpfDParcelaCadastro.NumDuplicata; DesObservacoes := VpfDParcelaCadastro.DesObservacoes; DatEmissao := VpfDParcelaCadastro.DatEmissao; DatVencimento := VpfDParcelaCadastro.DatVencimento; DatPagamento := VpfDParcelaCadastro.DatPagamento; ValParcela := VpfDParcelaCadastro.ValParcela; ValAcrescimo := VpfDParcelaCadastro.ValAcrescimo; ValDesconto := VpfDParcelaCadastro.ValDesconto; PerMora := VpfDParcelaCadastro.PerMora; PerJuros := VpfDParcelaCadastro.PerJuros; PerMulta := VpfDParcelaCadastro.PerMulta; IndValorQuitaEssaParcela := true; IndGeraParcial := false; IndContaOculta := false; end; end; result := BaixaContasAPagar(VpfDBaixa); VpfDBaixa.Free; end; {##################### estorno e exclusa de conta e titulos ################## } {****************** verifica se tem parcelas pagas ************************** } function TFuncoesContasAPagar.TemParcelasPagas(VpaCodFilial,VpaLanPagar: Integer): Boolean; begin AdicionaSQLAbreTabela(Tabela,' select D_DAT_PAG from MovContasAPagar ' + ' where I_EMP_FIL = ' + IntToStr(VpaCodFilial) + ' and I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and not D_DAT_PAG is null '); Result := (not Tabela.EOF); Tabela.close; end; {*************** exclui uma conta do contas a pagar ********************** } function TFuncoesContasAPagar.ExcluiConta(VpaCodFilial, VpaLanPagar : integer; VpaVerificarNotaFiscal : Boolean ) : string; begin result := ''; if TemParcelasPagas(VpaCodFilial,VpaLanPagar) then result := CT_ParcelaPaga; if result = '' then begin LocalizaContaCP(Tabela,VpaCodFilial,VpaLanPagar); if VpaVerificarNotaFiscal then if Tabela.FieldByname('I_SEQ_NOT').AsInteger <> 0 THEN result := CT_ExclusaoNota; if result = '' then begin sistema.GravaLogExclusao('MOVCONTASAPAGAR','select * from MOVCONTASAPAGAR WHERE ' + ' I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial)); ExecutaComandoSql(Aux,'DELETE CONTAAPAGARPROJETO ' + ' Where LANPAGAR = ' + IntToStr(VpaLanPagar) + ' and CODFILIAL = ' + IntToStr(VpaCodFilial)); ExecutaComandoSql(Aux,'DELETE MOVCONTASAPAGAR WHERE ' + ' I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial)); sistema.GravaLogExclusao('CADCONTASAPAGAR','select * from CADCONTASAPAGAR WHERE ' + ' I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial)); ExecutaComandoSql(Aux,'DELETE CADCONTASAPAGAR WHERE ' + ' I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial)); end; end; Tabela.close; end; { *** verifica se o título tem parcelas *** } function TFuncoesContasAPagar.TemParcelas(VpaCodFilial,VpaLanPagamento : Integer): Boolean; begin AdicionaSQLAbreTabela(Tabela, ' select * from MovContasaPagar ' + ' where I_LAN_APG = ' + IntToStr(VpaLanPagamento) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial)); Result :=(not Tabela.EOF); Tabela.close; end; {******************* exclui um titulo a pagar ****************************** } function TFuncoesContasAPagar.ExcluiTitulo(VpaCodFilial, VpaLanPagar, VpaNumParcela : Integer ) : string; begin result := ''; if result = '' then begin LocalizaContaCP(Tabela,VpaCodFilial,VpaLanPagar); if Tabela.FieldByname('I_SEQ_NOT').AsInteger <> 0 THEN result := CT_ExclusaoNota; if result = '' then begin LocalizaParcela(Tabela,VpaCodFilial,VpaLanPagar,VpaNumParcela); if Tabela.fieldByName('N_VLR_PAG').AsCurrency <> 0 then result := CT_ParcelaPaga; if result = '' then begin ExecutaComandoSql(Aux,'DELETE MOVCONTASAPAGAR WHERE ' + ' I_LAN_APG = ' + IntToStr(VpaLanPagar) + ' and I_EMP_FIL = ' + IntToStr(VpaCodFilial)+ ' and I_NRO_PAR = '+IntTostr(VpaNumParcela) ); end; end; end; Tabela.close; if not TemParcelas(VpaCodFilial,VpaLanPagar) then begin result := ExcluiConta(VpaCodFilial,VpaLanPagar,false); end else AtualizaValorTotal(VpaCodFilial,VpaLanPagar); end; {******************************************************************************} function TFuncoesContasAPagar.ValidaChequesCP(VpaCodFilial,VpaLanPagar,VpaNumparcela : Integer;Var VpaExisteCheques : Boolean):string; Var VpfCheques : TList; begin result := ''; VpaExisteCheques := false; VpfCheques := TList.Create; CarDChequesCP(VpfCheques,VpaCodFilial,VpaLanPagar,VpaNumparcela); if VpfCheques.Count > 0 then begin VpaExisteCheques := true; FChequesCP := TFChequesCP.CriarSDI(nil,'',true); FChequesCP.ConsultaCheques(VpfCheques); if confirmacao('Os cheques que foram recebidos nesta parcela serão excluídos. Tem certeza que deseja continuar?') then result := ExcluiChequesCP(VpaCodFilial,VpaLanPagar,VpaNumparcela,VpfCheques) else result := 'EXCLUSÃO DO CHEQUE CANCELADO!!!'#13'Não é possível cancelar o contas a pagar porque a exclusão dos cheques foi cancelado.'; FChequesCP.free; end; FreeTObjectsList(VpfCheques); VpfCheques.free; end; {******************************************************************************} function TFuncoesContasAPagar.VerificacoesExclusaoCheque(VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer;VpaCheques : TList):string; var VpfDCheque : TRBDCheque; VpfDParcela : TRBDParcelaCP; VpfParcelas : TList; VpfLaco : Integer; begin result := ''; VpfParcelas := TList.Create; if VpaCheques.Count > 0 then begin VpfDCheque := TRBDCheque(VpaCheques.Items[0]); CarParcelasCheque(VpfParcelas,VpfDCheque.SeqCheque,VpaCodFilial,VpaLanPagar,VpaNumParcela); if VpfParcelas.Count > 0 then begin FBaixaContasaPagarOO := TFBaixaContasaPagarOO.CriarSDI(nil,'',true); FBaixaContasaPagarOO.ConsultaParcelasBaixa(VpfParcelas); if not confirmacao('Os cheques estão associados a outras parcelas, a exclusão dos cheques irá resultar no estorno dessas parcelas do contas a receber. Deseja continuar? ') then result := 'Cancelado estorno das parcelas adicionais do cheque'; FBaixaContasaPagarOO.free; if result = '' then begin for VpfLaco := 0 to VpfParcelas.Count - 1 do begin VpfDParcela := TRBDParcelaCP(VpfParcelas.Items[VpfLaco]); result := EstornoParcela(VpfDParcela.CodFilial,VpfDParcela.LanPagar,VpfDParcela.NumParcela,VpfDParcela.NumParcelaParcial,VpfDParcela.CodCliente,false); if result <> '' then break; end; end; end; end; FreeTObjectsList(VpfParcelas); VpfParcelas.free; end; {******************************************************************************} function TFuncoesContasAPagar.ExcluiChequesCP(VpaCodFilial,VpaLanPagar,VpaNumParcela : Integer;VpaCheques : TList):string; var VpfDCheque : TRBDCheque; VpfLaco : Integer; begin result := ''; if VpaCheques.Count > 0 then begin result := VerificacoesExclusaoCheque(VpaCodFilial,VpaLanPagar,VpaNumParcela,VpaCheques); if result = '' then begin for vpfLaco := 0 to VpaCheques.count - 1 do begin VpfDCheque := TRBDCheque(VpaCheques.Items[VpfLaco]); FunContasAReceber.EstornaCheque(VpfDCheque,oeContasaPagar); ExecutaComandoSql(Aux,'Delete from CHEQUECP '+ ' Where SEQCHEQUE = ' +IntToStr(VpfDCheque.SeqCheque)); if VpfDCheque.TipCheque = 'D' then //somente exclui os cheques que foram emitidos, os cheque do tipo 'C'-Credito não pode excluir pois foram recebidos de terceiros, pode somente estornar a compensacao; ExecutaComandoSql(Aux,'Delete from CHEQUE '+ ' Where SEQCHEQUE = ' +IntToStr(VpfDCheque.SeqCheque)); end; end; end; end; {******************************************************************************} function TFuncoesContasAPagar.EstornoParcela(VpaCodFilial, VpaLanPagar,VpaNumParcela, VpaNumParcelaFilha, VpaCodCliente : integer;VpaVerificarCheques : Boolean) : String; var VpfPossuiCheques : Boolean; begin result := ''; if VpaVerificarCheques then result := ValidaChequesCP(VpaCodFilial,VpaLanPagar,VpaNumParcela,VpfPossuiCheques); if result = '' then begin if not VpfPossuiCheques then result := FunCaixa.ExtornaParcelaCPCaixa(VpaCodFilial,VpaLanPagar,VpaNumParcela); if result = '' then begin // Verificar se tem mais de uma parcela parcial. result := EstornaParcelaParcial(VpaCodFilial,VpaLanPagar,VpaNumParcelaFilha); if result = '' then begin LocalizaParcela(Cadastro,VpaCodFilial,VpaLanPagar, VpaNumParcela); if Cadastro.FieldByName('I_COD_FRM').AsInteger = varia.FormaPagamentoCreditoCliente then begin result := FunClientes.AdicionaCredito(VpaCodCliente,Cadastro.FieldByName('N_VLR_PAG').AsFloat,'D','Extorno do C P da duplicata "'+Cadastro.FieldByName('C_NRO_DUP').AsString+'"'); if result = '' then aviso('ADICIONADO "'+FormatFloat('R$ #,###,###,##0.00',Cadastro.FieldByName('N_VLR_PAG').AsFloat) +'" DE DÉBITO PARA O FORNECEDOR!!!'#13'O estorno desse contas a pagar gerou um débito para o fornecedor.'); end; if result = '' then begin Cadastro.edit; // Retira os valoes de pagamento. Cadastro.FieldByName('D_DAT_PAG').Clear; Cadastro.FieldByName('N_VLR_DES').Clear; Cadastro.FieldByName('N_VLR_ACR').Clear; Cadastro.FieldByName('N_VLR_PAG').Clear; Cadastro.FieldByName('N_VLR_CHE').Clear; // Estornar a Impressão de Cheque; Cadastro.FieldByName('C_FLA_CHE').AsString := 'N'; Cadastro.FieldByName('C_IMP_CHE').AsString := 'N'; Cadastro.FieldByName('I_PAR_FIL').AsInteger := 0; //atualiza a data de alteracao para poder exportar Cadastro.FieldByName('D_ULT_ALT').AsDateTime := Date; Cadastro.post; result := Cadastro.AMensagemErroGravacao; Cadastro.close; end; end; end; end; end; { ****** Estorna a Parcela ****** } function TFuncoesContasAPagar.EstornaParcela( VpaLancamentoCP, VpaLancamentoBancario, VpaNroParcela,VpaNroParcelaFilha : integer; VpaDataParcela : TDateTime; VpaFlagParcial : string ) : Boolean; begin Result := false; if ValidaEstornoParcela(VpaLancamentoCP, VpaDataParcela, VpaFlagparcial) then begin // if EstornaParcelaParcial(VpaLancamentoCP, VpaNroParcelaFilha) then begin LocalizaParcela(Cadastro,varia.CodigoEmpfil,VpaLancamentoCP, VpaNroParcela); Cadastro.edit; // Retira os valoes de pagamento. Cadastro.FieldByName('D_DAT_PAG').Clear; Cadastro.FieldByName('N_VLR_DES').Clear; Cadastro.FieldByName('N_VLR_ACR').Clear; Cadastro.FieldByName('N_VLR_PAG').Clear; Cadastro.FieldByName('N_VLR_CHE').Clear; // Estornar a Impressão de Cheque; Cadastro.FieldByName('C_FLA_CHE').AsString := 'N'; Cadastro.FieldByName('C_IMP_CHE').AsString := 'N'; Cadastro.FieldByName('C_NRO_CON').Clear; Cadastro.FieldByName('I_PAR_FIL').AsInteger := 0; //atualiza a data de alteracao para poder exportar Cadastro.FieldByName('D_ULT_ALT').AsDateTime := Date; Cadastro.post; Result := true; end // else // Aviso(CT_EstonoPacialInvalida); end; Cadastro.close; end; {******** valida a parcela, parcela anterior aberta, ************************* } function TFuncoesContasAPagar.ValidaEstornoParcela( VpaLancamentoCP : integer; VpaDatPagamento : TDateTime; VpaFlagParcial : string ) : boolean; begin Result := True; if VpaFlagParcial <> 'S' then begin AdicionaSQLAbreTabela(Tabela,' select * from MOVCONTASAPAGAR '+ ' where i_emp_fil = '+ IntToStr(varia.CodigoEmpFil) + ' and i_lan_apg = ' + IntTostr(VpaLancamentoCP) + ' and d_dat_ven > ''' + DataToStrFormato(AAAAMMDD,VpaDatPagamento,'/') + '''' + ' and not d_dat_pag is null ' + // Já foi paga. ' order by D_DAT_VEN '); if not Tabela.Eof then begin Aviso(CT_ParcelaPosPaga); Result := false; end; Tabela.Close; end; end; {******************************************************************************} function TFuncoesContasAPagar.EstornaCPChequeDevolvido(VpaCheques : TList) : string; var VpfLacoCheque : Integer; VpfDCheque : TRBDCheque; VpfValCheque : Double; VpfParcelas : TList; begin result := ''; VpfParcelas := TList.Create; for VpfLacoCheque := 0 to VpaCheques.Count - 1 do begin VpfDCheque := TRBDCheque(VpaCheques.Items[VpfLacoCheque]); VpfValCheque := VpfDCheque.ValCheque; CarParcelasCPCheque(VpfDCheque.SeqCheque,VpfParcelas); result := EstornaValorCPChequeDevolvido(VpfValCheque,VpfParcelas); if result <> '' then break; //se valor do cheque for maior que zero tem adicionar esse valor como credito com o fornecedor, foi pago a mais end; FreeTObjectsList(VpfParcelas); VpfParcelas.Free; end; {******************************************************************************} function TFuncoesContasAPagar.EstornaValorCPChequeDevolvido(VpaValCheque : Double; VpaParcelas : TList) : string; Var VpfLacoParcelas : Integer; VpfDParcela : TRBDParcelaCP; begin for VpfLacoParcelas := VpaParcelas.Count - 1 downto 0 do begin VpfDParcela := TRBDParcelaCP(VpaParcelas.Items[VpfLacoParcelas]); if VpfDParcela.ValPago > 0 then begin if VpaValCheque >= VpfDParcela.ValPago then begin VpaValCheque := VpaValCheque - VpfDParcela.ValPago; VpfDParcela.ValPago := 0; Result:= GravaDParcelaCP(VpfDParcela); end else begin result := GravaParcelaParcial(VpfDParcela,VpaValCheque,VpfDParcela.DatVencimento); if result = ''then begin VpfDParcela.ValPago := VpfDParcela.ValPago - VpaValCheque; Result:= GravaDParcelaCP(VpfDParcela); VpaValCheque := 0; end; end; if (result <> '') or (VpaValCheque <= 0) then break; end; end; end; {################################## adicionais #############################} {******************* retira adicionais ************************************** } function TFuncoesContasAPagar.RetiraAdicionalConta(Lancamento, Parcela : Integer; ValorRetirar: Double) : Boolean; begin Result:=True; LimpaSQLTabela(Calcula); AdicionaSQLTabela(Calcula, ' UPDATE MOVCONTASARECEBER' + ' set N_VLR_ADI = (ISNULL(N_VLR_ADI, 0) - ' + SubstituiStr(FloatToStr(ValorRetirar),',','.') + ') ' + ' , D_ULT_ALT = '+ SQLTextoDataAAAAMMMDD(DATE) + ' where I_EMP_FIL = ' + IntTostr(Varia.CodigoEmpFil) + ' and I_LAN_REC = ' + IntToStr(Lancamento) + ' and I_NRO_PAR = ' + IntToStr(Parcela) + ' and D_DAT_PAG IS NULL '); Calcula.ExecSQL; end; {******************************************************************************} function TFuncoesContasAPagar.RNumParcelas(VpaDBaixaCP: TRBDBaixaCP): string; var VpfLaco : Integer; begin result := ''; for VpfLaco := 0 to VpaDBaixaCP.Parcelas.Count - 1 do result := result +TRBDParcelaCP(VpaDBaixaCP.Parcelas.Items[VpfLaco]).NumDuplicata+', '; if VpaDBaixaCP.Parcelas.Count > 0 then result := copy(result,1,length(result)-2); end; {*************** verifica conta adicional vinculada ************************ } function TFuncoesContasAPagar.VerificaContaReceberVinculada(VpaNroOrdem, VpaParcela: Integer): Boolean; begin AdicionaSQLAbreTabela(Calcula, ' SELECT * FROM MOVCONTASARECEBER' + ' where I_EMP_FIL = ' + IntTostr(Varia.CodigoEmpFil) + ' and I_LAN_REC = ' + IntToStr(VpaNroOrdem) + ' and I_NRO_PAR = ' + IntToStr(VpaParcela) + ' and NOT D_DAT_PAG IS NULL '); // Paga; Result := Calcula.EOF; if (not Result) then Aviso(CT_Titulo_Pago); calcula.close; end; {***************** configura o valor recebido de um adicional **************** } procedure TFuncoesContasAPagar.AjustaValorUltimaParcela(VpaDContasAPagar: TRBDContasaPagar;VpaValorInicial : Double); begin SomaTotalParcelas(VpaDContasAPagar); if VpaDContasAPagar.ValTotal <> VpaValorInicial then TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[VpaDContasAPagar.Parcelas.Count-1]).ValParcela := TRBDParcelaCP(VpaDContasAPagar.Parcelas.Items[VpaDContasAPagar.Parcelas.Count-1]).ValParcela - (VpaDContasAPagar.ValTotal - VpaValorInicial); end; {***************** configura o valor recebido de um adicional **************** } procedure TFuncoesContasAPagar.AlteraValorRecebidoCAB( VpaOrdem: Integer; VpaValor:Double); begin LimpaSQLTabela(Calcula); AdicionaSQLTabela(Calcula, ' UPDATE CADCONTASAPAGAR' + ' set N_VLR_REC = ' + SubstituiStr(FloatToStr(VpaValor),',','.') + ' , D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(DATE) + ' where I_EMP_FIL = ' + IntTostr(Varia.CodigoEmpFil) + ' and ISNULL(I_LAN_REC, 0) > 0 ' + // Altera somente se é um adiciona de uma conta a receber. ' and ISNULL(I_PAR_REC, 0) > 0 ' + ' and I_LAN_APG = ' + IntToStr(VpaOrdem)); Calcula.ExecSQL; end; {##################### retornos bancários #####################################} {******************************************************************************} function TFuncoesContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDRetornoItem : TRBDRetornoItem;VpaValor : Double;VpaDescricao, VpaPlanoContas : String) : String; Var VpfDContasPagar : TRBDContasaPagar; VpfDBaixa : TDadosBaixaCP; VpfValor : Double; VpfFormaPagamento : Integer; begin result := ''; exit; if VpaDRetornoCorpo.CodFornecedorBancario = 0 then result := 'FORNECEDOR BANCÁRIO NÃO PREENCHIDO!!!'#13'É necessário preencher no cadastro da conta corrento o fornecedor bancario para gerar o contas a pagar'; if Varia.PlanoContasBancario = '' then result := 'PLANO DE CONTAS NÃO PREENCHIDO!!!'#13'É necessário preencher o plano de contas bancário nas configurações da empresa.'; if varia.FormaPagamentoDinheiro = 0 then result := 'FORMA DE PAGAMENTO EM DINHEIRO NÃO PREENCHIDA!!!'#13'É necessário preencher a forma de pagamento em dinheiro nas configurações do financeiras.'; if result = '' then begin if VpaPlanoContas = '' then VpaPlanoContas := varia.PlanoContasBancario; VpfDContasPagar := TRBDContasaPagar.cria; VpfDContasPagar.CodFilial := VpaDRetornoCorpo.CodFilial; VpfDContasPagar.CodFornecedor := VpaDRetornoCorpo.CodFornecedorBancario; VpfDContasPagar.CodFormaPagamento := varia.FormaPagamentoDinheiro; VpfDContasPagar.CodMoeda := varia.MoedaBase; VpfDContasPagar.CodUsuario := varia.CodigoUsuario; VpfDContasPagar.DatEmissao := VpaDRetornoItem.DatOcorrencia; VpfDContasPagar.CodPlanoConta := VpaPlanoContas; VpfDContasPagar.CodCondicaoPagamento := VARIA.CondPagtoVista; VpfDContasPagar.ValParcela := VpaValor; VpfDContasPagar.IndBaixarConta := true; VpfDContasPagar.IndMostrarParcelas := false; VpfDContasPagar.IndEsconderConta := false; VpfDContasPagar.DesTipFormaPagamento := 'D'; VpfDContasPagar.DesObservacao := VpaDescricao; CriaContaPagar(VpfDContasPagar,nil); end; end; {######################## diversos ########################################### } {******************** baixa uma conta da parcela ******************************} procedure TFuncoesContasAPagar.BaixaConta( Valor, valorDesconto, ValorAcrescimo : double; Data : TDateTime; lancamento, NroParcela : integer ); begin LimpaSQLTabela(tabela); AdicionaSQLTabela(Tabela, ' Update movcontasapagar ' + ' set n_vlr_pag = ' + SubstituiStr(FloatToStr(valor),',','.') + ', ' + ' d_dat_pag = ''' + DataToStrFormato(AAAAMMDD,Data,'/') + ''',' + ' n_vlr_acr = ' + SubstituiStr(FloatToStr(ValorAcrescimo),',','.') + ', ' + ' n_vlr_des = ' + SubstituiStr(FloatToStr(valorDesconto),',','.') + ' , D_ULT_ALT = '+ SQLTextoDataAAAAMMMDD(DATE)+ ' where i_lan_apg = ' + IntToStr(lancamento) + ' and i_nro_par = ' + IntToStr(NroParcela) + ' and i_emp_fil = ' + IntToStr(varia.CodigoEmpFil)); Tabela.ExecSQL; end; {******************** altera a forma de pagamento **************************** } procedure TFuncoesContasAPagar.ConfiguraFormaPagto( FormaInicio, FormaFim, lancamento, Nroparcela : Integer; NroConta : string ); var Aux1, Aux2 : TSQLQUERY; LancamentoBancario : string; TipoInicio, TipoFim : string; begin Aux1 := TSQLQUERY.Create(nil); Aux1.SQLConnection := VprBaseDados; Aux2 := TSQLQUERY.Create(nil); Aux2.SQLConnection := VprBaseDados; LocalizaFormaPagamento(aux1, FormaInicio); LocalizaFormaPagamento(aux2, FormaFim); TipoInicio := aux1.FieldByName('C_FLA_TIP').AsString; TipoFim := aux2.FieldByName('C_FLA_TIP').AsString; if TipoInicio <> TipoFim then begin FechaTabela(Aux1); LocalizaParcela(Aux1,Varia.Codigoempfil, lancamento, Nroparcela); end; FechaTabela(aux1); FechaTabela(aux2); Aux1.free; Aux2.free; end; {************ exclui uma conta atraves do estorno da nota fiscal de entrada ** } function TFuncoesContasAPagar.ExcluiContaNotaFiscal( SeqNota : integer ) : Boolean; var Lancamento : integer; VpfResultado : string; begin AdicionaSQLAbreTabela(tabela,' select I_LAN_APG from CADCONTASAPAGAR ' + ' where I_SEQ_NOT = ' + IntToStr(SeqNota ) + ' and I_EMP_FIL = ' + IntTostr(varia.CodigoEmpFil) ); lancamento := Tabela.fieldByName('I_LAN_APG').AsInteger; tabela.close; vpfResultado := ExcluiConta(varia.codigoEmpfil, lancamento, false ); if VpfResultado <> '' then begin result := false; aviso(VpfResultado); end else result := true; end; {******************************************************************************} procedure TFuncoesContasAPagar.ExcluiPlanoContas(VpaPlanoOrigem, VpaPlanoDestino: String); begin ExecutaComandoSql(Aux,'Update CADCLIENTES SET C_CLA_PLA = '''+ VpaPlanoDestino+''''+ ' Where C_CLA_PLA = '''+VpaPlanoOrigem+''''); ExecutaComandoSql(Aux,'Update MOVNATUREZA SET C_CLA_PLA = '''+ VpaPlanoDestino+''''+ ' Where C_CLA_PLA = '''+VpaPlanoOrigem+''''); ExecutaComandoSql(Aux,'UPDATE CADCONTASAPAGAR '+ ' SET C_CLA_PLA = '''+VpaPlanoDestino+''''+ ' Where C_CLA_PLA = '''+VpaPlanoOrigem+''''+ ' and I_COD_EMP = '+IntToStr(Varia.CodigoEmpresa)); ExecutaComandoSql(Aux,'DELETE FROM PLANOCONTAORCADO '+ ' Where CODPLANOCONTA = '''+VpaPlanoOrigem+''''+ ' and CODEMPRESA = '+IntToStr(Varia.CodigoEmpresa)); ExecutaComandoSql(Aux,'DELETE FROM CAD_PLANO_CONTA '+ ' Where C_CLA_PLA = '''+VpaPlanoOrigem+''''+ ' and I_COD_EMP = '+IntToStr(Varia.CodigoEmpresa)); end; {******************** atualiza a forma de pagamento ************************** } procedure TFuncoesContasAPagar.AtualizaFormaPagamento(LancamentoCP, ParcelaCP, CodigoFormaPagamento: string); begin LimpaSQLTabela(Tabela); AdicionaSQLTabela(Tabela, ' UPDATE MOVCONTASAPAGAR SET I_COD_FRM = ' + CodigoFormaPagamento + ' , D_ULT_ALT = '+ SQLTextoDataAAAAMMMDD(DATE)+ ' WHERE I_EMP_FIL = ' + IntToStr(Varia.CodigoEmpFil) + ' AND I_LAN_APG = ' + LancamentoCP + ' AND I_NRO_PAR = ' + ParcelaCP ); Tabela.ExecSQL; end; {******************************************************************************} function TFuncoesContasAPagar.NotaPossuiParcelaPaga(VpaCodFilial, VpaSeqNota : Integer) : Boolean; begin AdicionaSQLAbreTabela(tabela,' select i_lan_apg from CadContasaPagar ' + ' where i_seq_not = ' + IntToStr(VpaSeqNota ) + ' and i_emp_fil = ' + IntTostr(VpaCodFilial) ); result := TemParcelasPagas(VpaCodFilial, Tabela.fieldByName('i_lan_apg').AsInteger); tabela.close; end; {******************************************************************************} function TFuncoesContasAPagar.PossuiChequeDigitado(VpaDBaixa: TRBDBaixaCP): Boolean; var VpfLaco : Integer; VpfDCheque : TRBDCheque; begin result := false; for VpfLaco := 0 to VpaDBaixa.Cheques.Count - 1 do begin VpfDCheque := TRBDCheque(VpaDBaixa.Cheques.Items[VpfLaco]); if VpfDCheque.TipFormaPagamento = fpCheque then begin result := true; break; end; end; end; {******************************************************************************} function TFuncoesContasAPagar.ProjetoDuplicado(VpaDContasAPagar: TRBDContasaPagar): boolean; var VpfLacoInterno, VpfLacoExterno : Integer; VpfDProjetoInterno, VpfDProjetoExterno : TRBDContasaPagarProjeto; begin result := false; for VpfLacoExterno := 0 to VpaDContasAPagar.DespesaProjeto.Count - 2 do begin VpfDProjetoExterno := TRBDContasaPagarProjeto(VpaDContasAPagar.DespesaProjeto.Items[VpfLacoExterno]); for VpfLacoInterno := VpfLacoExterno + 1 to VpaDContasAPagar.DespesaProjeto.Count - 1 do begin VpfDProjetoInterno := TRBDContasaPagarProjeto(VpaDContasAPagar.DespesaProjeto.Items[VpfLacoInterno]); if VpfDProjetoInterno.CodProjeto = VpfDProjetoExterno.CodProjeto then begin result := true; break; end; end; end; end; {******************************************************************************} function TFuncoesContasAPagar.FlagBaixarContaFormaPagamento(VpaCodFormapagamento : Integer):Boolean; begin AdicionaSQLAbreTabela(Tabela,'Select C_BAI_CON from CADFORMASPAGAMENTO '+ ' Where I_COD_FRM = ' +IntToStr(VpaCodFormapagamento)); result := Tabela.FieldByname('C_BAI_CON').AsString = 'S'; Tabela.close; end; {******************************************************************************} function TFuncoesContasAPagar.FornecedorPossuiDebito(VpaCreditos: TList;VpaTipo : TRBDTipoCreditoDebito): Boolean; var VpfLaco : Integer; begin result := false; for VpfLaco := 0 to VpaCreditos.count - 1 do begin if (TRBDCreditoCliente(VpaCreditos.Items[VpfLaco]).ValCredito <> 0) and (TRBDCreditoCliente(VpaCreditos.Items[VpfLaco]).TipCredito = VpaTipo) and not (TRBDCreditoCliente(VpaCreditos.Items[VpfLaco]).IndFinalizado) then begin result := true; break; end; end; end; {******************************************************************************} function TFuncoesContasAPagar.ExisteCheque(VpaNumCheque: Integer; var VpaExisteVariosCheques: Boolean;VpaDCheque : TRBDCheque): Boolean; begin result := false; AdicionaSQLAbreTabela(Tabela,'Select COUNT(CHE.SEQCHEQUE) QTD '+ ' from CHEQUE CHE ' + ' Where CHE.NUMCHEQUE = ' +IntToStr(VpaNumCheque)+ ' AND CHE.DATCOMPENSACAO IS NULL'); if Tabela.FieldbyName('QTD').AsInteger > 1 then VpaExisteVariosCheques := true else if Tabela.FieldbyName('QTD').AsInteger = 1 then begin AdicionaSQLAbreTabela(Tabela,'Select CHE.SEQCHEQUE, CHE.CODBANCO, CHE.NOMEMITENTE, '+ ' CHE.DATVENCIMENTO, CHE.DATCOMPENSACAO, CHE.VALCHEQUE, CHE.NUMCONTACAIXA, '+ ' CHE.NUMCHEQUE, CON.C_TIP_CON '+ ' from CHEQUE CHE, CADCONTAS CON ' + ' Where CHE.NUMCHEQUE = ' +IntToStr(VpaNumCheque)+ ' AND CHE.DATCOMPENSACAO IS NULL'+ ' AND CHE.NUMCONTACAIXA = CON.C_NRO_CON' + ' AND (CHE.CODFORNECEDORRESERVA IS NULL OR ' + ' CHE.CODFORNECEDORRESERVA = ' + IntToStr(VpaDCheque.CodCliente)+ ')'); if tabela.Eof then result := false else begin result := true; VpaDCheque.SeqCheque := Tabela.FieldByname('SEQCHEQUE').AsInteger; VpaDCheque.CodBanco := Tabela.FieldByname('CODBANCO').AsInteger; VpaDCheque.NumCheque := Tabela.FieldByname('NUMCHEQUE').AsInteger; VpaDCheque.ValCheque := Tabela.FieldByname('VALCHEQUE').AsFloat; VpaDCheque.NomEmitente := Tabela.FieldByname('NOMEMITENTE').AsString; VpaDCheque.NumContaCaixa := Tabela.FieldByname('NUMCONTACAIXA').AsString; VpaDCheque.TipCheque := 'C'; VpaDCheque.TipContaCaixa := Tabela.FieldByname('C_TIP_CON').AsString; end; end; Tabela.close; end; {******************************************************************************} procedure TFuncoesContasAPagar.CarParcelasCPCheque(VpaSeqCheque : Integer;VpaParcelas : TList); var VpfDParcelasCP : TRBDParcelaCP; begin AdicionaSQLAbreTabela(Aux,'Select * from CHEQUECP '+ ' Where SEQCHEQUE = '+IntToStr(VpaSeqCheque)+ ' order by CODFILIALPAGAR, LANPAGAR, NUMPARCELA'); while not Aux.eof do begin VpfDParcelasCP := TRBDParcelaCP.Cria; VpaParcelas.Add(VpfDParcelasCP); FunContasAPagar.CarDParcelaBaixa(VpfDParcelasCP,Aux.FieldByname('CODFILIALPAGAR').AsInteger,Aux.FieldByname('LANPAGAR').AsInteger, Aux.FieldByname('NUMPARCELA').AsInteger); Aux.next; end; Aux.close; end; {******************************************************************************} procedure TFuncoesContasAPagar.InterpretaCodigoBarras(VpaDContasAPagar : TRBDContasaPagar;VpaCodBarras : String); begin if length(VpaCodBarras)>=20 then begin VpaDContasAPagar.ValBoleto := StrToFloat(copy(VpaCodBarras,10,10))/100; VpaDContasAPagar.CodFormaPagamento := varia.FormaPagamentoBoleto; VpaDContasAPagar.FatorVencimento := StrToInt(copy(VpaCodBarras,6,4)); VpaDContasAPagar.CodBancoBoleto := StrToInt(copy(VpaCodBarras,1,3)); if (VpaDContasAPagar.CodBancoBoleto = 748) then begin VpaDContasAPagar.DesIdentificacaoBancarioFornecedor := copy(VpaCodBarras,31,11) end; VpaDContasAPagar.CodFornecedor := FunClientes.RCodClientePelaIdentificaoBancaria(VpaDContasAPagar.DesIdentificacaoBancarioFornecedor); end; end; end.
unit FormHlavneOkno; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, StdCtrls, CheckLst; type TZastavka = record Nazov : string; Sur : TPoint; end; THlavneOkno = class(TForm) ScrollBox: TScrollBox; Image: TImage; CheckListBox: TCheckListBox; LabelY: TLabel; LabelX: TLabel; MainMenu1: TMainMenu; Sbor1: TMenuItem; Otvori1: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CheckListBoxClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } procedure InitListBox; procedure UpdateZastavky; procedure ZapisSurDoSuboru; public { Public declarations } ZASTAVKY_FILE : string; Zastavky : TList; end; var HlavneOkno: THlavneOkno; implementation uses SKonstanty; {$R *.DFM} //============================================================================== //============================================================================== // // Constructor // //============================================================================== //============================================================================== procedure THlavneOkno.InitListBox; var I : integer; begin for I := 0 to Zastavky.Count-1 do begin CheckListBox.Items.Add( TZastavka( Zastavky[I]^ ).Nazov ); if (TZastavka( Zastavky[I]^ ).Sur.X = 0) and (TZastavka( Zastavky[I]^ ).Sur.Y = 0) then CheckListBox.State[I] := cbUnchecked else CheckListBox.State[I] := cbChecked; end; end; procedure THlavneOkno.FormCreate(Sender: TObject); begin ZASTAVKY_FILE := ''; Zastavky := TList.Create; Image.Picture.Bitmap.LoadFromFile( MAP_FILE ); Image.Width := Image.Picture.Width; Image.Height := Image.Picture.Height; ScrollBox.VertScrollBar.Range := Image.Height; ScrollBox.HorzScrollBar.Range := Image.Width; InitListBox; UpdateZastavky; end; //============================================================================== //============================================================================== // // Destructor // //============================================================================== //============================================================================== procedure THlavneOkno.ZapisSurDoSuboru; var I : integer; begin if (ZASTAVKY_FILE = '') then exit; AssignFile( Output , ZASTAVKY_FILE ); {$I-} Rewrite( Output ); {$I+} if IOResult <> 0 then raise Exception.Create( 'Nedá sa vytvoriť súbor '+ZASTAVKY_FILE ); for I := 0 to Zastavky.Count-1 do begin Writeln( TZastavka( Zastavky[I]^ ).Nazov ); Writeln( TZastavka( Zastavky[I]^ ).Sur.X ); Writeln( TZastavka( Zastavky[I]^ ).Sur.Y ); end; CloseFile( Output ); end; procedure THlavneOkno.FormClose(Sender: TObject; var Action: TCloseAction); begin ZapisSurDoSuboru; end; //============================================================================== //============================================================================== // // Zobrazenie zastavok // //============================================================================== //============================================================================== procedure THlavneOkno.UpdateZastavky; const r = 5; var I : integer; begin with Image.Canvas do begin Pen.Color := clBlue; Brush.Color := clBlue; end; for I := 0 to Zastavky.Count-1 do begin if (TZastavka( Zastavky[I]^ ).Sur.X = 0) and (TZastavka( Zastavky[I]^ ).Sur.Y = 0) then continue; Image.Canvas.Ellipse( TZastavka( Zastavky[I]^ ).Sur.X - r , TZastavka( Zastavky[I]^ ).Sur.Y - r , TZastavka( Zastavky[I]^ ).Sur.X + r , TZastavka( Zastavky[I]^ ).Sur.Y + r ); end; end; //============================================================================== //============================================================================== // // Komponenty // //============================================================================== //============================================================================== procedure THlavneOkno.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin LabelX.Caption := 'X : '+IntToStr( X ); LabelY.Caption := 'Y : '+IntToStr( Y ); end; procedure THlavneOkno.ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if CheckListBox.ItemIndex < 0 then exit; TZastavka( Zastavky[ CheckListBox.ItemIndex ]^ ).Sur.X := X; TZastavka( Zastavky[ CheckListBox.ItemIndex ]^ ).Sur.Y := Y; CheckListBox.State[ CheckListBox.ItemIndex ] := cbChecked; UpdateZastavky; end; procedure THlavneOkno.CheckListBoxClick(Sender: TObject); begin if (CheckListBox.ItemIndex < 0) or ((TZastavka( Zastavky[CheckListBox.ItemIndex]^ ).Sur.X = 0) and (TZastavka( Zastavky[CheckListBox.ItemIndex]^ ).Sur.Y = 0)) then exit; ScrollBox.VertScrollBar.Position := TZastavka( Zastavky[ CheckListBox.ItemIndex ]^ ).Sur.Y - ScrollBox.Height div 2; ScrollBox.HorzScrollBar.Position := TZastavka( Zastavky[ CheckListBox.ItemIndex ]^ ).Sur.X - ScrollBox.Width div 2; end; procedure THlavneOkno.FormDestroy(Sender: TObject); begin Zastavky.Free; end; end.
unit DTMF; interface // translated from // http://www.answers.com/topic/goertzel-algorithm?cat=technology const Tones: Array[0..3, 0..3] of Char = ( ('1', '4', '7', '*'), ('2', '5', '8', '0'), ('3', '6', '9', '#'), ('A', 'B', 'C', 'D')); type PSmallIntArray = ^TSmallIntArray; TSmallIntArray = array[0..16383] of SmallInt; TDTMF=class(TObject) private FSampleRate:Integer; FSampleCount:Integer; q1,q2,r,coefs:array of Double; Last1,Last2:char; function Test:char;inline;register; public function AddSample(S:Smallint):char;inline;register; constructor Create(SampleRate:Integer); end; implementation const MAX_BINS = 8; GOERTZEL_N = 92; FREQS : array [0..7] of Double = (697, 770, 852, 941, 1209, 1336, 1477, 1633); { TDTMF } function TDTMF.AddSample(S: Smallint):char; var I: Integer; q0:Double; begin Inc(FSampleCount); for I := 0 to MAX_BINS - 1 do begin q0:=coefs[I]*q1[I]-q2[I]+S; q2[I]:=q1[I]; q1[I]:=q0; end; if FSampleCount=GOERTZEL_N then begin for I := 0 to MAX_BINS - 1 do begin r[I]:=q1[I]*q1[I]+q2[I]*q2[I]-coefs[I]*q1[I]*q2[I]; q1[I]:=0; q2[I]:=0; end; Result:=Test; FSampleCount:=0; end else Result:=#0; end; constructor TDTMF.Create(SampleRate: Integer); var I:Integer; begin FSampleRate:=SampleRate; SetLength(q1,MAX_BINS); SetLength(q2,MAX_BINS); SetLength(r,MAX_BINS); SetLength(coefs,MAX_BINS); for I := 0 to MAX_BINS - 1 do coefs[I]:=2*cos(2*PI*FREQS[I]/FSampleRate); end; function TDTMF.Test; var row, col,peak_count, max_index, i :Integer; maxval, t:double; begin row:=0; maxval:=0; for I := 0 to 3 do if r[I]>maxval then begin maxval:=r[I]; row:=I; end; col:=4; maxval:=0; for I := 4 to 7 do if r[I]>maxval then begin maxval:=r[I]; col:=I; end; Result:=#0; if r[row]<4e5 then else if r[col]<4e5 then else begin result:=#1; if r[col]>r[row] then begin max_index:=col; if r[row]<r[col]*0.399 then result:=#0; end else begin max_index:=row; if r[col]<r[row]*0.158 then result:=#0; end; if r[max_index] > 1e9 then t:=r[max_index] * 0.158 else t:=r[max_index] * 0.010; peak_count := 0; for I := 0 to 7 do begin if r[I]>t then inc(peak_count); end; if peak_count>2 then result:=#0; if result=#1 then result:=Tones[col-4][row]; end; if Result<>Last1 then begin if (Result=Last2) and (Result<>#0) then begin Last1:=Result; end else begin if (Last1<>Last2) then Last1:=#0; Last2:=Result; Result:=#0; end; end else begin Last2:=Result; Result:=#0; end; end; end.
// ************************************************************************************************** // Delphi Aio Library. // Unit Gevent // https://github.com/Purik/AIO // The contents of this file are subject to the Apache License 2.0 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // // The Original Code is Gevent.pas. // // Contributor(s): // Pavel Minenkov // Purik // https://github.com/Purik // // The Initial Developer of the Original Code is Pavel Minenkov [Purik]. // All Rights Reserved. // // ************************************************************************************************** unit Gevent; interface uses SysUtils, Classes, SyncObjs, {$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF}; type {* TGevent - allows you to build a state machine around events imperative event-driven programming *} IGevent = interface ['{9F8D9F83-E1DE-478C-86A2-AF641EEF50B7}'] procedure SetEvent(const Sync: Boolean = False); procedure ResetEvent; function WaitFor(aTimeOut: LongWord = INFINITE): TWaitResult; end; TGevent = class(TInterfacedObject, IGevent) type EOperationError = class(Exception); private type TWaitList = TList; TIndexes = array of Integer; IAssociateRef = interface procedure ClearIndexes; function GetIndexes: TIndexes; procedure Lock; procedure Unlock; function Emit(const aResult: TWaitResult; const IsDestroyed: Boolean; Index: Integer): Boolean; procedure SetOwner(Value: TGevent); function GetOwner: TGevent; end; var FAssociateRef: IAssociateRef; FHandle: THandle; FWaiters: tWaitList; FLock: SyncObjs.TCriticalSection; FSignal: Boolean; FManualReset: Boolean; function GreenWaitEvent(aTimeOut: LongWord = INFINITE): TWaitResult; function ThreadWaitEvent(aTimeOut: LongWord = INFINITE): TWaitResult; class procedure SwitchTimeout(Id: THandle; Data: Pointer); static; private procedure Emit(const aResult: TWaitResult; const IsDestroyed: Boolean; const Sync: Boolean = False); protected function WaitersCount: Integer; procedure Lock; inline; procedure Unlock; inline; function TryLock: Boolean; inline; class procedure TimeoutCb(Id: THandle; Data: Pointer); static; property AssociateRef: IAssociateRef read FAssociateRef; class procedure SignalTimeout(Id: THandle; Data: Pointer; const Aborted: Boolean); static; procedure ClearEmptyDescr; public constructor Create(const ManualReset: Boolean=False; const InitialState: Boolean = False); overload; constructor Create(Handle: THandle); overload; destructor Destroy; override; procedure SetEvent(const Sync: Boolean = False); procedure ResetEvent; procedure Associate(Emitter: TGevent; Index: Integer); function WaitFor(aTimeOut: LongWord = INFINITE): TWaitResult; class function WaitMultiple(const Events: array of TGevent; out Index: Integer; const Timeout: LongWord=INFINITE): TWaitResult; end; implementation uses GInterfaces, GreenletsImpl, Greenlets, PasMP, Hub; type TAssociateRef = class(TInterfacedObject, TGevent.IAssociateRef) strict private FOwner: TGevent; FLock: SyncObjs.TCriticalSection; FIndexes: TGevent.TIndexes; function FindIndex(Value: Integer): Boolean; public procedure ClearIndexes; function GetIndexes: TGevent.TIndexes; procedure Lock; procedure Unlock; procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure SetOwner(Value: TGevent); function GetOwner: TGevent; function Emit(const aResult: TWaitResult; const IsDestroyed: Boolean; Index: Integer): Boolean; end; TMultiContextVar = class(TInterfacedObject) strict private FActive: Boolean; FLock: TPasMPSpinLock; function GetActive: Boolean; procedure SetActive(const Active: Boolean); public constructor Create; destructor Destroy; override; property Active: Boolean read GetActive write SetActive; end; PWaitResult = ^TWaitResult; TWaitDescr = class(TInterfacedObject) strict private FProxy: IGreenletProxy; FHub: TCustomHub; FTimeStop: TTime; FResult: TWaitResult; FEvDestroyed: TMultiContextVar; FAssociate: TGevent.IAssociateRef; FTag: Integer; FContext: Pointer; FGevent: TGevent; public constructor Create(Hub: TCustomHub; const Result: TWaitResult; EvDestroyedRef: TMultiContextVar); overload; constructor Create(Associate: TGevent.IAssociateRef; Tag: Integer); overload; destructor Destroy; override; // props property Context: Pointer read FContext write FContext; property Proxy: IGreenletProxy read FProxy write FProxy; property Hub: TCustomHub read FHub; property TimeStop: TTime read FTimeStop write FTimeStop; property Associate: TGevent.IAssociateRef read FAssociate; property Tag: Integer read FTag; property Result: TWaitResult read FResult write FResult; property EvDestroyed: TMultiContextVar read FEvDestroyed; property Gevent: TGevent read FGevent write FGevent; end; TGreenletPimpl = class(TRawGreenletImpl); { TGevent.TAssociateRef } procedure TAssociateRef.AfterConstruction; begin inherited; FLock := SyncObjs.TCriticalSection.Create; end; procedure TAssociateRef.BeforeDestruction; begin inherited; FreeAndNil(FLock); end; procedure TAssociateRef.ClearIndexes; begin Lock; SetLength(FIndexes, 0); Unlock; end; function TAssociateRef.Emit(const aResult: TWaitResult; const IsDestroyed: Boolean; Index: Integer): Boolean; begin Lock; try Result := FOwner <> nil; if Result then begin if not FindIndex(Index) then begin SetLength(FIndexes, Length(FIndexes)+1); FIndexes[High(FIndexes)] := Index; end; FOwner.Emit(aResult, IsDestroyed); Result := FOwner <> nil; end; finally Unlock; end; end; function TAssociateRef.FindIndex(Value: Integer): Boolean; var I: Integer; begin Result := False; for I := 0 to High(FIndexes) do if FIndexes[I] = Value then Exit(True) end; function TAssociateRef.GetIndexes: TGevent.TIndexes; begin Lock; try Result := FIndexes finally UnLock end; end; function TAssociateRef.GetOwner: TGevent; begin Lock; try Result := FOwner; finally Unlock; end; end; procedure TAssociateRef.Lock; begin {$IFDEF DCC} TMonitor.Enter(FLock); {$ELSE} FLock.Acquire; {$ENDIF} end; procedure TAssociateRef.SetOwner(Value: TGevent); begin Lock; try FOwner := Value; finally Unlock; end; end; procedure TAssociateRef.Unlock; begin {$IFDEF DCC} TMonitor.Exit(FLock); {$ELSE} FLock.Release; {$ENDIF} end; { TGevent } procedure TGevent.Associate(Emitter: TGevent; Index: Integer); var Descr: TWaitDescr; begin Lock; try Emitter.Lock; try Emitter.ClearEmptyDescr; Descr := TWaitDescr.Create(FAssociateRef, Index); Descr._AddRef; Emitter.FWaiters.Add(Descr); finally Emitter.Unlock; end; finally Unlock; end; end; constructor TGevent.Create(const ManualReset, InitialState: Boolean); begin FLock := SyncObjs.TCriticalSection.Create; {$IFDEF DCC} TMonitor.SetSpinCount(FLock, 4000); {$ENDIF} FWaiters := tWaitList.Create; FSignal := InitialState; FManualReset := ManualReset; FAssociateRef := TAssociateRef.Create; FAssociateRef.SetOwner(Self); {$IFDEF DEBUG} AtomicIncrement(GeventCounter) {$ENDIF} end; procedure TGevent.ClearEmptyDescr; var Ind: Integer; Descr: TWaitDescr; begin Lock; try Ind := 0; while Ind < FWaiters.Count do begin Descr := TWaitDescr(FWaiters[Ind]); if Assigned(Descr.Associate) and (Descr.Associate.GetOwner = nil) then begin Descr._Release; FWaiters.Delete(Ind) end else Inc(Ind) end; finally Unlock; end; end; constructor TGevent.Create(Handle: THandle); begin Create(False, False); if FHandle <> 0 then raise EOperationError.CreateFmt('Gevent already associated with %d handle', [FHandle]); FHandle := Handle; end; destructor TGevent.Destroy; begin FAssociateRef.SetOwner(nil); Emit(wrAbandoned, True); FAssociateRef := nil; FWaiters.Free; FLock.Free; {$IFDEF DEBUG} AtomicDecrement(GeventCounter); {$ENDIF} inherited; end; procedure TGevent.Emit(const aResult: TWaitResult; const IsDestroyed: Boolean; const Sync: Boolean); var L: array of TWaitDescr; Syncs: array of TWaitDescr; I, SyncsNum: Integer; begin Lock; try FSignal := aResult = wrSignaled; SetLength(L, FWaiters.Count); for I := 0 to FWaiters.Count-1 do begin L[I] := FWaiters[I]; end; FWaiters.Clear; SyncsNum := 0; finally Unlock; end; if Sync then begin SetLength(Syncs, Length(L)); SyncsNum := 0; end; for I := 0 to High(L) do begin if Assigned(L[I].Proxy) and (not (L[I].Proxy.GetState in [gsExecute, gsSuspended])) then begin L[I]._Release; Continue; end; if Assigned(L[I].Associate) then begin if L[I].Associate.Emit(aResult, IsDestroyed, L[I].Tag) then begin if IsDestroyed then L[I]._Release else begin Lock; FWaiters.Add(L[I]); if (aResult = wrSignaled) and FSignal and (not FManualReset) then FSignal := False; Unlock; end; end else begin L[I]._Release end; end else begin L[I].Result := aResult; L[I].EvDestroyed.Active := IsDestroyed; if Assigned(L[I].Proxy) then begin if Sync and (L[I].Hub = GetCurrentHub) then begin Syncs[SyncsNum] := L[I]; Inc(SyncsNum); end else begin L[I].Proxy.Resume; L[I]._Release; end; end else begin L[I].Hub.Pulse; L[I]._Release; end; end end; if Sync then for I := 0 to SyncsNum-1 do begin TRawGreenletImpl(Syncs[I].Context).Resume; Syncs[I]._Release; end; end; function TGevent.GreenWaitEvent(aTimeOut: LongWord): TWaitResult; var Descr: TWaitDescr; Ellapsed: TTime; EvDestroyed: TMultiContextVar; Timeout: THandle; procedure ForceFinalize; var I: Integer; begin if EvDestroyed.Active then Exit; Lock; try for I := 0 to FWaiters.Count-1 do if TWaitDescr(FWaiters[I]).Proxy = Descr.Proxy then begin TWaitDescr(FWaiters[I])._Release; FWaiters.Delete(I); Break; end; finally Unlock; end; end; begin if TRawGreenletImpl(GetCurrent).GetProxy.GetState = gsKilling then Exit(wrAbandoned); Result := wrError; Lock; try if FSignal then begin Exit(wrSignaled) end else if aTimeOut = 0 then begin Exit(wrTimeout); end; EvDestroyed := TMultiContextVar.Create; EvDestroyed._AddRef; Descr := TWaitDescr.Create(GetCurrentHub, wrError, EvDestroyed); Descr._AddRef; if aTimeOut = INFINITE then Descr.TimeStop := 0 else begin Descr.TimeStop := Now + TimeOut2Time(aTimeOut); end; Descr.Proxy := TRawGreenletImpl(GetCurrent).GetProxy; Descr.Context := GetCurrent; Descr.Gevent := Self; Descr._AddRef; FWaiters.Add(Descr); finally Unlock; end; Timeout := 0; try if FHandle <> 0 then begin Descr.Hub.AddEvent(FHandle, SignalTimeout, Self); end; if Descr.TimeStop = 0 then begin while not ((Descr.Result in [wrAbandoned, wrSignaled]) or FSignal) do begin TRawGreenletImpl(GetCurrent).Suspend; Greenlets.Yield; end; if FSignal and (Descr.Result = wrError) then Result := wrSignaled else Result := Descr.Result; end else begin Descr._AddRef; Timeout := Descr.Hub.CreateTimeout(SwitchTimeout, Descr, aTimeOut+1); Ellapsed := Now; Ellapsed := Now - Ellapsed; Descr.TimeStop := Descr.TimeStop - Ellapsed; Descr.Result := wrTimeout; TRawGreenletImpl(GetCurrent).Suspend; while Descr.TimeStop >= Now do begin if (Descr.Result <> wrTimeout) or FSignal then Break else begin TRawGreenletImpl(GetCurrent).Suspend; Greenlets.Yield; end end; if FSignal and (Descr.Result = wrError) then Result := wrSignaled else Result := Descr.Result; end; finally if Result in [wrAbandoned, wrError] then FSignal := False; if FHandle <> 0 then Descr.Hub.RemEvent(FHandle); if Timeout <> 0 then begin Descr.Hub.DestroyTimeout(Timeout); Descr._Release; end; ForceFinalize; EvDestroyed._Release; Descr._Release; end; end; procedure TGevent.Lock; begin {$IFDEF DCC} TMonitor.Enter(FLock); {$ELSE} FLock.Acquire; {$ENDIF} end; procedure TGevent.ResetEvent; begin if not FManualReset then Exit; Lock; try FSignal := False; FAssociateRef.ClearIndexes; finally Unlock; end; end; procedure TGevent.SetEvent(const Sync: Boolean); begin Emit(wrSignaled, False, Sync); end; class procedure TGevent.SignalTimeout(Id: THandle; Data: Pointer; const Aborted: Boolean); begin if Aborted then TGevent(Data).Emit(wrAbandoned, False, True) else TGevent(Data).Emit(wrSignaled, False, True); end; class procedure TGevent.SwitchTimeout(Id: THandle; Data: Pointer); var Descr: TWaitDescr; begin Descr := TWaitDescr(Data); if not Descr.EvDestroyed.Active then TRawGreenletImpl(Descr.Context).Resume; end; class procedure TGevent.TimeoutCb(Id: THandle; Data: Pointer); var Descr: TWaitDescr; begin Descr := TWaitDescr(Data); if not Descr.EvDestroyed.Active then Descr.Gevent.Emit(wrTimeout, False, True); end; function TGevent.TryLock: Boolean; begin {$IFDEF DCC} Result := TMonitor.TryEnter(FLock); {$ELSE} Result := FLock.TryEnter {$ENDIF} end; function TGevent.ThreadWaitEvent(aTimeOut: LongWord): TWaitResult; var Descr: TWaitDescr; EvDestroyed: TMultiContextVar; Timeout: THandle; procedure ForceFinalize; var I: Integer; begin if EvDestroyed.Active then Exit; Lock; try for I := 0 to FWaiters.Count-1 do if (TWaitDescr(FWaiters[I]).Hub = Descr.Hub) and (Descr.Proxy = nil) then begin TWaitDescr(FWaiters[I])._Release; FWaiters.Delete(I); Break; end; finally Unlock; end; end; begin Result := wrError; Lock; try if FSignal then begin Exit(wrSignaled) end else if aTimeOut = 0 then begin Exit(wrTimeout); end; EvDestroyed := TMultiContextVar.Create; EvDestroyed._AddRef; Descr := TWaitDescr.Create(GetCurrentHub, wrError, EvDestroyed); Descr._AddRef; if aTimeOut = INFINITE then Descr.TimeStop := 0 else begin Descr.TimeStop := Now + TimeOut2Time(aTimeOut); end; Descr.Gevent := Self; Descr._AddRef; FWaiters.Add(Descr); finally Unlock; end; Timeout := 0; try if FHandle <> 0 then begin Descr.Hub.AddEvent(FHandle, SignalTimeout, Self); end; Descr.Hub.IsSuspended := True; if Descr.TimeStop = 0 then begin while not ((Descr.Result in [wrAbandoned, wrSignaled]) or FSignal) do Descr.Hub.Serve(INFINITE); if FSignal and (Descr.Result = wrError) then Result := wrSignaled else Result := Descr.Result; end else begin Descr.Result := wrTimeout; Descr._AddRef; Timeout := Descr.Hub.CreateTimeout(TimeoutCb, Descr, aTimeOut+1); while Descr.TimeStop >= Now do begin if (Descr.Result <> wrTimeout) or FSignal then Break else Descr.Hub.Serve(Time2TimeOut(Descr.TimeStop - Now)) end; if FSignal and (Descr.Result = wrError) then Result := wrSignaled else Result := Descr.Result; end; finally Descr.Hub.IsSuspended := False; if Result in [wrAbandoned, wrError] then FSignal := False; if Timeout <> 0 then begin Descr.Hub.DestroyTimeout(Timeout); Descr._Release; end; if FHandle <> 0 then Descr.Hub.RemEvent(FHandle); ForceFinalize; EvDestroyed._Release; Descr._Release; end; end; procedure TGevent.Unlock; begin {$IFDEF DCC} TMonitor.Exit(FLock); {$ELSE} FLock.Release; {$ENDIF} end; function TGevent.WaitersCount: Integer; begin Result := FWaiters.Count end; function TGevent.WaitFor(aTimeOut: LongWord): TWaitResult; begin if TGreenletPimpl.GetCurrent = nil then Result := ThreadWaitEvent(aTimeOut) else Result := GreenWaitEvent(aTimeOut); if not FManualReset then begin Lock; try // ABA-problem if FSignal then Result := wrSignaled; if Result = wrSignaled then begin if (not FManualReset) and FSignal then FSignal := False end; finally Unlock end; end; end; class function TGevent.WaitMultiple(const Events: array of TGevent; out Index: Integer; const Timeout: LongWord): TWaitResult; var Ev, Assoc: TGevent; I: Integer; begin if Length(Events) = 0 then begin Index := -1; Exit(wrError); end; Ev := TGEvent.Create; try for I := 0 to High(Events) do begin Assoc := Events[I]; if Assigned(Assoc) then begin Assoc.Lock; try if Assoc.FSignal then begin Index := I; if not Assoc.FManualReset then Assoc.FSignal := False; Exit(wrSignaled); end; Ev.Associate(Assoc, I); finally Assoc.UnLock; end; end; end; Result := Ev.WaitFor(Timeout); Ev.AssociateRef.Lock;; try if Length(Ev.AssociateRef.GetIndexes) > 0 then Index := Ev.AssociateRef.GetIndexes[0] else Index := -1; finally Ev.AssociateRef.Unlock; end; finally Ev.Free; end; end; { TWaitDescr } constructor TWaitDescr.Create(Associate: TGevent.IAssociateRef; Tag: Integer); begin FAssociate := Associate; FTag := Tag; end; constructor TWaitDescr.Create(Hub: TCustomHub; const Result: TWaitResult; EvDestroyedRef: TMultiContextVar); begin FHub := Hub; FResult := Result; FEvDestroyed := EvDestroyedRef; FEvDestroyed._AddRef; end; destructor TWaitDescr.Destroy; begin FAssociate := nil; Proxy := nil; if Assigned(FEvDestroyed) then FEvDestroyed._Release; inherited; end; { TMultiContextVar } constructor TMultiContextVar.Create; begin FLock := TPasMPSpinLock.Create end; destructor TMultiContextVar.Destroy; begin FLock.Free; inherited; end; function TMultiContextVar.GetActive: Boolean; begin FLock.Acquire; Result := FActive; FLock.Release; end; procedure TMultiContextVar.SetActive(const Active: Boolean); begin FLock.Acquire; FActive := Active; FLock.Release; end; end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Rtti, Pessoa, uTabela, Attributes; type TfrmPrincipal = class(TForm) btnGetMethod: TButton; mmRtti: TMemo; btnGetField: TButton; btnGetProperty: TButton; btnGetPropertiesTypes: TButton; btnSetValue: TButton; btnTRttiMethodTypes: TButton; btnInvoke: TButton; btnRttiValidar: TButton; btnNomeTabela: TButton; btnCampo: TButton; procedure btnGetMethodClick(Sender: TObject); procedure btnGetFieldClick(Sender: TObject); procedure btnGetPropertyClick(Sender: TObject); procedure btnGetPropertiesTypesClick(Sender: TObject); procedure btnSetValueClick(Sender: TObject); procedure btnTRttiMethodTypesClick(Sender: TObject); procedure btnInvokeClick(Sender: TObject); procedure btnNomeTabelaClick(Sender: TObject); procedure btnRttiValidarClick(Sender: TObject); procedure btnCampoClick(Sender: TObject); private procedure PropertyTypeValue(AObj: TPessoa); procedure PropertySetValeu(AObj: TObject); procedure Invoke(AObj: TObject); procedure EscreverCampo(AObj: TObject); function Valida(AObj: TObject): boolean; end; var frmPrincipal: TfrmPrincipal; implementation {$R *.dfm} procedure TfrmPrincipal.btnCampoClick(Sender: TObject); var VPessoa: TPessoa; begin mmRtti.Clear; VPessoa := TPessoa.Create; try VPessoa.Codigo := 100; VPessoa.Nome := 'Jorge'; Self.EscreverCampo(VPessoa); finally VPessoa.Free; end; end; procedure TfrmPrincipal.btnGetFieldClick(Sender: TObject); var VCtx : TRttiContext; VType : TRttiType; VField: TRttiField; begin mmRtti.Clear; VCtx := TRttiContext.Create; try VType := VCtx.GetType(TPessoa); for VField in VType.GetFields do mmRtti.Lines.Add(VField.Name); finally VCtx.Free end; end; procedure TfrmPrincipal.btnGetMethodClick(Sender: TObject); var VCtx : TRttiContext; VType: TRttiType; VMet : TRttiMethod; begin mmRtti.Clear; VCtx := TRttiContext.Create; try VType := VCtx.GetType(TPessoa); for VMet in VType.GetMethods do begin if VMet.Parent.Name = 'TPessoa' then mmRtti.Lines.Add(VMet.Name); end; finally VCtx.Free; end; end; procedure TfrmPrincipal.btnGetPropertiesTypesClick(Sender: TObject); var VPessoa: TPessoa; begin mmRtti.Clear; VPessoa := TPessoa.Create; try VPessoa.Codigo := 1; VPessoa.Nome := 'Márcio'; Self.PropertyTypeValue(VPessoa); finally VPessoa.Free; end; end; procedure TfrmPrincipal.btnGetPropertyClick(Sender: TObject); var VCtx : TRttiContext; VType: TRttiType; VProp: TRttiProperty; begin mmRtti.Clear; VCtx := TRttiContext.Create; try VType := VCtx.GetType(TPessoa); for VProp in VType.GetProperties do mmRtti.Lines.Add(VProp.Name); finally VCtx.Free end; end; procedure TfrmPrincipal.btnInvokeClick(Sender: TObject); var VPessoa: TPessoa; begin mmRtti.Clear; VPessoa := TPessoa.Create; try VPessoa.Codigo := 15; VPessoa.Nome := 'Gabriel'; Self.Invoke(VPessoa); finally VPessoa.Free; end; end; procedure TfrmPrincipal.btnNomeTabelaClick(Sender: TObject); var VCtx : TRttiContext; VType: TRttiType; VAtt : TCustomAttribute; begin mmRtti.Clear; VCtx := TRttiContext.Create(); VType := VCtx.GetType(TPessoa.ClassInfo); for VAtt in VType.GetAttributes() do begin if VAtt is TDataTableAttribute then mmRtti.Lines.Add(TDataTableAttribute(VAtt).Tabela); end; end; procedure TfrmPrincipal.btnRttiValidarClick(Sender: TObject); var VPessoa: TPessoa; begin mmRtti.Clear; VPessoa := TPessoa.Create; try VPessoa.Codigo := 100; VPessoa.Nome := 'Gustavo'; Self.Valida(VPessoa); finally VPessoa.Free; end; end; procedure TfrmPrincipal.btnSetValueClick(Sender: TObject); var VPessoa: TPessoa; begin mmRtti.Clear; VPessoa := TPessoa.Create; try VPessoa.Codigo := 10; VPessoa.Nome := 'Vazio'; mmRtti.Lines.Add(VPessoa.Nome); Self.PropertySetValeu(VPessoa); mmRtti.Lines.Add(VPessoa.Nome); finally FreeAndNil(VPessoa); end; end; procedure TfrmPrincipal.btnTRttiMethodTypesClick(Sender: TObject); var VCtx : TRttiContext; VType: TRttiType; VMet : TRttiMethod; VPar : TRttiParameter; begin mmRtti.Clear; VCtx := TRttiContext.Create; try VType := VCtx.GetType(TPessoa); for VMet in VType.GetMethods do begin //Ignora métodos que não foram implementados diretamente em TPessoa if VMet.Parent.Name <> 'TPessoa' then Continue; mmRtti.Lines.Add('Método ' + VMet.Name); if VMet.ReturnType <> nil then mmRtti.Lines.Add(' Retorno ' + VMet.ReturnType.ToString) else mmRtti.Lines.Add(' Retorno ' + 'Não tem.'); mmRtti.Lines.Add(' Parâmetros'); for VPar in VMet.GetParameters do mmRtti.Lines.Add(' ' + VPar.Name + ': ' + VPar.ParamType.ToString) ; mmRtti.Lines.Add(''); end; finally VCtx.Free; end; end; procedure TfrmPrincipal.EscreverCampo(AObj: TObject); var vCtx : TRttiContext; vType : TRttiType; vProp : TRttiProperty; vAtrib: TCustomAttribute; begin vCtx := TRttiContext.Create; try vType := VCtx.GetType(AObj.ClassInfo); for vProp in VType.GetProperties do begin for vAtrib in vProp.GetAttributes do mmRtti.Lines.Add(TDataFieldAttribute(VAtrib).Campo) end; finally vCtx.Free; end; end; procedure TfrmPrincipal.Invoke(AObj: TObject); var vCtx : TRttiContext; vType: TRttiType; vMet : TRttiMethod; vPar : Array of TValue; begin vCtx := TRttiContext.Create; try vType := VCtx.GetType(AObj.ClassType); vMet := VType.GetMethod('Insert'); SetLength(VPar, 1); vPar[0] := 1; vMet.Invoke(AObj, VPar); finally VCtx.Free; end; end; procedure TfrmPrincipal.PropertySetValeu(AObj: TObject); var vCtx : TRttiContext; vType: TRttiType; vProp: TRttiProperty; begin vCtx := TRttiContext.Create; try vType := vCtx.GetType(AObj.ClassType); vProp := vType.GetProperty('Nome'); vProp.SetValue(AObj, 'Octávio Augusto'); finally VCtx.Free; end; end; procedure TfrmPrincipal.PropertyTypeValue(AObj: TPessoa); var vCtx : TRttiContext; vType: TRttiType; vProp: TRttiProperty; begin vCtx := TRttiContext.Create; try vType := vCtx.GetType(AObj.ClassType); for vProp in vType.GetProperties do mmRtti.Lines.Add(vProp.Name + ': ' + vProp.PropertyType.ToString + '= ' + vProp.GetValue(AObj).ToString); finally vCtx.Free end; end; function TfrmPrincipal.Valida(AObj: TObject): Boolean; var vCtx : TRttiContext; vType : TRttiType; vProp : TRttiProperty; vAtrib: TCustomAttribute; begin Result := True; vCtx := TRttiContext.Create; try vType := VCtx.GetType(AObj.ClassInfo); for vProp in VType.GetProperties do begin for vAtrib in VProp.GetAttributes do begin if vAtrib is TDataFieldAttribute then begin (vAtrib as TDataFieldAttribute).Validar(VProp.GetValue(AObj)); if TDataFieldAttribute(VAtrib).CampoObrigatorio then raise Exception.Create(TDataFieldAttribute(vAtrib).Mensagem); end; end; end; finally vCtx.Free; end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TForm1 = class(TForm) procedure FormPaint(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); private { Private declarations } FGameOver : Boolean; public { Public declarations } backgroundImage : TImage; spriteImage : TImage; paddle : TImage; backgroundCanvas : TCanvas; workCanvas : TCanvas; backgroundRect, spriteRect, changeRect, paddleRect, changePaddleRect :TRect; x, y, xDir, yDir, paddleX, paddleY, paddleCenter, Angle : integer; procedure IdleLoop( Sender: TObject; var Done: Boolean ); procedure WMSetCursor(var Message: TWMSetCursor); message WM_SETCURSOR; end; var Form1: TForm1; implementation {$R *.dfm} uses MMSystem; procedure TForm1.FormPaint(Sender: TObject); begin RealizePalette(backgroundCanvas.Handle); RealizePalette(workCanvas.Handle); Canvas.CopyRect(backgroundRect, workCanvas, backgroundRect); end; procedure TForm1.FormActivate(Sender: TObject); var backgrounddc, workdc : HDC; bkbmp, bmp : HBITMAP; begin backgroundImage := TImage.Create( Self ); spriteImage := TImage.Create( Self ); paddle := TImage.Create( Self ); workCanvas := TCanvas.Create; backgroundCanvas := TCanvas.Create; Angle := 1; spriteImage.Picture.LoadFromFile('Earth.ico'); backgroundImage.Picture.LoadFromFile('androm.bmp'); paddle.Picture.LoadFromFile('paddle.ico'); WindowState := wsMaximized; backgroundRect.Top := 0; backgroundRect.Left := 0; backgroundRect.Right := ClientWidth; backgroundRect.Bottom := ClientHeight; spriteRect.Top := 0; spriteRect.Left := 0; spriteRect.Right := spriteImage.Picture.Width; spriteRect.Bottom := spriteImage.Picture.Height; //Set up backgroundCanvas backgrounddc := CreateCompatibleDC(Canvas.Handle); bkbmp := CreateCompatibleBitmap(Canvas.Handle, ClientWidth, ClientHeight); SelectObject(backgrounddc, bkbmp); SelectPalette(backgrounddc, backgroundImage.Picture.Bitmap.Palette, false); backgroundCanvas.Handle := backgrounddc; backgroundCanvas.StretchDraw( backgroundRect, backgroundImage.Picture.Bitmap); //Set up workCanvas workdc := CreateCompatibleDC(Canvas.Handle); bmp := CreateCompatibleBitmap(Canvas.Handle, ClientWidth, ClientHeight); SelectObject(workdc, bmp); SelectPalette(workdc, backgroundImage.Picture.Bitmap.Palette, false); workCanvas.Handle := workdc; workCanvas.CopyRect(backgroundRect, backgroundCanvas, backgroundRect); workCanvas.Draw( 0, 0, spriteImage.Picture.Icon); paddleX := ClientWidth div 2; paddleY := ClientHeight - 50; workCanvas.Draw( paddleX, paddleY, paddle.Picture.Icon); paddleRect.Left := paddleX - paddle.Width; paddleRect.Right := paddleX + paddle.Width; paddleRect.Top := paddleY; paddleRect.Bottom := paddleY + paddle.Height; RealizePalette(backgroundCanvas.Handle); RealizePalette(workCanvas.Handle); Canvas.CopyRect(backgroundRect, workCanvas, backgroundRect); end; procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin //Animates and moves paddle paddleCenter := X; if(paddleCenter < paddle.Picture.Width div 2) then paddleCenter := paddle.Picture.Width div 2; if(paddleCenter > ClientWidth - (paddle.Picture.Width div 2)) then paddleCenter := ClientWidth - (paddle.Picture.Width div 2); end; procedure TForm1.FormCreate(Sender: TObject); begin //Assign idle time function Application.OnIdle := IdleLoop; if(Application.MessageBox('Would you like to play with Earth?', 'Hello Earthling', MB_OKCANCEL) = IDOK) then begin //load sound effect sndPlaySound('Utopia Default.wav', SND_ASYNC or SND_FILENAME); x := 0; y := 0; FGameOver := false; ShowCursor(false); end else Application.Terminate; end; procedure TForm1.IdleLoop(Sender: TObject; var Done: Boolean); var choice, SideDef, TopDef, PaddleDifference: integer; begin //keeps loop going done := false; //slows down action Sleep(1); changeRect := spriteRect; spriteRect.Left := x; spriteRect.Top := y; spriteRect.Right := x + spriteImage.Picture.Width; spriteRect.Bottom := y + spriteImage.Picture.Height; workCanvas.CopyRect(paddleRect, backgroundCanvas, paddleRect); changePaddleRect := paddleRect; paddleRect.Left := paddleCenter - ((paddle.Picture.Width) div 2); paddleX := paddleRect.Left; paddleRect.Top := paddleY; paddleRect.Right := paddleX + paddle.Picture.Width; paddleRect.Bottom := paddleY + paddle.Picture.Height; SideDef := changeRect.Left - spriteRect.Left; // If SideDiff < 0 the paddle is to the right if(SideDef < 0) then begin changeRect.Right := spriteRect.Right; end else begin changeRect.Left := spriteRect.Left; end; TopDef := changeRect.Top - spriteRect.Top; // If SideDiff < 0 the paddle is to the Down if(TopDef < 0) then begin changeRect.Bottom := spriteRect.Bottom; end else begin changeRect.Top := spriteRect.Top; end; workCanvas.CopyRect(spriteRect, backgroundCanvas, spriteRect); //ChangeRectCalcs if (y <= 0) then begin yDir := 5; end; if (y >= ClientHeight - 16) then begin FGameOver := true; SetCursor(HCURSOR( IDC_ARROW )); ShowCursor(true); choice := MessageBox(Handle, 'You lost Earth', 'Try Again?', MB_RETRYCANCEL); if(choice = IDRETRY) then begin x := 0; y := 0; ShowCursor(false); end else Form1.Close; end; if ( (spriteRect.Bottom - 16) >= (paddleRect.Top) ) and ( (spriteRect.Bottom - 16) <= (paddleRect.Top + 5) ) and ( (spriteRect.Right) >= (paddleRect.Left) ) and ( (spriteRect.Left) <= (paddleRect.Right) ) then begin yDir := -5; sndPlaySound('Utopia Default.wav', SND_ASYNC or SND_FILENAME); end; if (x <= 0) then begin xDir := 5; end; if(x >= ClientWidth - 16) then begin xDir := -5; end; inc ( x , xDir ); inc ( y , yDir ); PaddleDifference := changePaddleRect.Left - paddleRect.Left; // If PaddleDiff < 0 the paddle is to the right if(PaddleDifference < 0) then begin changePaddleRect.Right := paddleRect.Right; end else begin changePaddleRect.Left := paddleRect.Left; end; //Perform dirty rectangle animation on memory and Form canvas workCanvas.Draw(x, y, spriteImage.Picture.Icon); workCanvas.Draw(paddleX, paddleY, paddle.Picture.Icon); RealizePalette(backgroundCanvas.Handle); RealizePalette(workCanvas.Handle); Canvas.CopyRect(changeRect, workCanvas, changeRect); Canvas.CopyRect(changePaddleRect, workCanvas, changePaddleRect); end; procedure TForm1.WMSetCursor(var Message: TWMSetCursor); begin //Hides Cursor if not(FGameOver) then begin SetCursor( HCURSOR( nil ) ); end; end; end.
unit u_DM; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqlite3conn, sqldb, FileUtil; type { TDMFrm } TDMFrm = class(TDataModule) SQLite3Connection1: TSQLite3Connection; SQLQuery1: TSQLQuery; SQLTransaction1: TSQLTransaction; procedure DataModuleCreate(Sender: TObject); private FLastErr: string; public function ReConn(): boolean; procedure AddLoginLog(const UID, State: integer); property LastErr: string read FLastErr; end; var DMFrm: TDMFrm; implementation {$R *.lfm} { TDMFrm } procedure TDMFrm.DataModuleCreate(Sender: TObject); begin //SQLite3Connection1.CharSet:='UTF-8'; SQLite3Connection1.KeepConnection := True; SQLite3Connection1.DatabaseName := UTF8Encode(ExtractFilePath(ParamStr(0)) + 'ctllog.db'); SQLite3Connection1.Transaction := SQLTransaction1; SQLQuery1.DataBase := SQLite3Connection1; end; function TDMFrm.ReConn(): boolean; begin Result:=False; try SQLite3Connection1.Close; SQLite3Connection1.Open; Result:=SQLite3Connection1.Connected; except On Ex: Exception do FLastErr := Ex.Message; end; end; procedure TDMFrm.AddLoginLog(const UID, State: integer); begin try try if not SQLTransaction1.Active then SQLTransaction1.StartTransaction; SQLQuery1.Close; SQLQuery1.SQL.Text := 'insert into LoginLog (UID,LoginTime,State) values (:1,:2,:3)'; SQLQuery1.Params[0].AsInteger := UID; SQLQuery1.Params[1].Value :=FormatDateTime('YYYY-MM-DD hh:nn:ss',Now); SQLQuery1.Params[2].AsInteger := State; //1 Login 2 LogOut SQLQuery1.ExecSQL; finally SQLTransaction1.Commit; end; except On Ex: Exception do FLastErr := Ex.Message; end; end; end.
{*********************************************} { TeeGrid Software Library } { Base abstract Grid class } { Copyright (c) 2016 by Steema Software } { All Rights Reserved } {*********************************************} unit Tee.Grid; {$I Tee.inc} interface { Top high-level agnostic grid class: TCustomTeeGrid Its an abstract class. Cannot be created directly. Other units implement a derived TeeGrid class: VCLTee.Grid -> TTeeGrid for VCL FMXTee.Grid -> TTeeGrid for Firemonkey } uses {System.}Classes, {$IFNDEF FPC} {System.}Types, {$ENDIF} {System.}SysUtils, {$IFNDEF NOUITYPES} System.UITypes, {$ENDIF} Tee.Painter, Tee.Format, Tee.Renders, Tee.Control, Tee.Grid.Columns, Tee.Grid.Header, Tee.Grid.Bands, Tee.Grid.Rows, Tee.Grid.Selection, Tee.Grid.Data, Tee.Grid.RowGroup; type TGridEditing=class(TPersistentChange) private FActive: Boolean; FAlwaysVisible : Boolean; FClass : TClass; FDoubleClick : Boolean; public Constructor Create(const AChanged:TNotifyEvent); override; procedure Assign(Source:TPersistent); override; function ClassOf(const AColumn:TColumn):TClass; property Active:Boolean read FActive write FActive default False; property EditorClass:TClass read FClass write FClass; published property AlwaysVisible:Boolean read FAlwaysVisible write FAlwaysVisible default True; property DoubleClick:Boolean read FDoubleClick write FDoubleClick default True; end; TSelectEvent=procedure(const Sender:TRowGroup) of object; TScroll=TPointF; TCustomTeeGrid=class(TCustomTeeControl) private FData : TVirtualData; FEditing : TGridEditing; FMargins : TMargins; FOnAfterDraw: TNotifyEvent; FOnSelect: TSelectEvent; FRoot: TRowGroup; function AvailableHeight:Single; procedure ChangedRow(const Sender:TObject; const ARow:Integer); procedure CheckHorizScroll(const AColumn:TColumn); procedure CheckVertScroll(const ARow:Integer); procedure DataRefresh(Sender:TObject); function GetCells: TTextRender; function GetFooter: TGridBands; function GetHeader:TColumnHeaderBand; function GetRows:TRows; procedure CheckScroll(const ASelected:TGridSelection); function IsColumnsStored: Boolean; procedure SelectedChanged(Sender:TObject); procedure SetCells(const Value: TTextRender); procedure SetColumns(const Value: TColumns); procedure SetData(const Value:TVirtualData); procedure SetFooter(const Value: TGridBands); procedure SetHeader(const Value: TColumnHeaderBand); procedure SetIndicator(const Value: TIndicator); procedure SetMargins(const Value: TMargins); procedure SetReadOnly(const Value: Boolean); procedure SetRows(const Value: TRows); procedure SetSelected(const Value: TGridSelection); procedure SetEditing(const Value: TGridEditing); function GetReadOnly: Boolean; function GetColumns: TColumns; function GetIndicator: TIndicator; function GetSelected: TGridSelection; function GetCurrent: TRowGroup; inline; procedure SetCurrent(const Value: TRowGroup); inline; protected procedure ChangeHorizScroll(const Value:Single); procedure ChangeVertScroll(const Value:Single); procedure CopySelected; virtual; abstract; procedure DataChanged; virtual; procedure Key(const AState:TKeyState); function HorizScrollBarHeight:Single; virtual; abstract; procedure HorizScrollChanged; virtual; abstract; procedure Mouse(var AState:TMouseState); property Root:TRowGroup read FRoot; procedure StartEditor(const AColumn:TColumn; const ARow:Integer); overload; virtual; abstract; procedure StartEditor; overload; procedure StopEditor; virtual; procedure TryStartEditor; function VertScrollBarWidth:Single; virtual; abstract; procedure VertScrollChanged; virtual; abstract; public Constructor Create(AOwner:TComponent); override; {$IFNDEF AUTOREFCOUNT} Destructor Destroy; override; {$ENDIF} procedure Assign(Source:TPersistent); override; function ClientHeight:Single; override; function ClientWidth:Single; override; function CanExpand(const Sender:TRender; const ARow:Integer):Boolean; procedure Paint; override; procedure RefreshData; property Current:TRowGroup read GetCurrent write SetCurrent; property Data:TVirtualData read FData write SetData; property Rows:TRows read GetRows write SetRows; published property Cells:TTextRender read GetCells write SetCells; property Columns:TColumns read GetColumns write SetColumns stored IsColumnsStored; property Editing:TGridEditing read FEditing write SetEditing; property Footer:TGridBands read GetFooter write SetFooter; property Header:TColumnHeaderBand read GetHeader write SetHeader; property Indicator:TIndicator read GetIndicator write SetIndicator; property Margins:TMargins read FMargins write SetMargins; property ReadOnly:Boolean read GetReadOnly write SetReadOnly default False; property Selected:TGridSelection read GetSelected write SetSelected; property OnAfterDraw:TNotifyEvent read FOnAfterDraw write FOnAfterDraw; property OnSelect:TSelectEvent read FOnSelect write FOnSelect; end; implementation
unit UI.ParserCommand; interface uses System.Classes, System.TypInfo, System.SysUtils, System.Generics.Collections, App.Types, UI.CommandLineParser, UI.Types; type TCommandsParser = class private FDelegate: TProc<strings>; Commands: TObjectDictionary<TCommandsNames, TCommandLinePattern>; public function TryParse(const args: strings): TCommandData; constructor Create; destructor Destroy; override; end; implementation {$REGION 'TCommandsParser'} constructor TCommandsParser.Create; begin Commands := TObjectDictionary<TCommandsNames, TCommandLinePattern>.Create; Commands.Add(TCommandsNames(0), TCommand.WithName('help').HasParameter('commandname', '')); Commands.Add(TCommandsNames(1), TCommand.WithName('node').HasParameter('commandname', '')); Commands.Add(TCommandsNames(2), TCommand.WithName('check').HasParameter('commandname', '')); Commands.Add(TCommandsNames(3), TCommand.WithName('update').HasParameter('commandname', '')); Commands.Add(TCommandsNames(4), TCommand.WithName('quit').HasParameter('commandname', '')); Commands.Add(TCommandsNames(5), TCommand.WithName('createwallet').HasParameter('password', '')); Commands.Add(TCommandsNames(6), TCommand.WithName('openwallet').HasParameter('commandname', '')); Commands.Add(TCommandsNames(7), TCommand.WithName('getwalletlist').HasParameter('commandname', '')); end; destructor TCommandsParser.Destroy; begin Commands.Free; inherited; end; function TCommandsParser.TryParse(const args: strings): TCommandData; var PatternCommand: TCommandLinePattern; begin case TCommandsNames.AsCommand(LowerCase(args[0])) of TCommandsNames.help: begin if Commands.TryGetValue(TCommandsNames.help, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.node: begin if Commands.TryGetValue(TCommandsNames.node, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.check: begin if Commands.TryGetValue(TCommandsNames.check, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.update: begin if Commands.TryGetValue(TCommandsNames.update, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.quit: begin if Commands.TryGetValue(TCommandsNames.quit, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.createwallet: begin if Commands.TryGetValue(TCommandsNames.createwallet, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.openwallet: begin if Commands.TryGetValue(TCommandsNames.openwallet, PatternCommand) then Result := PatternCommand.Parse(args); end; TCommandsNames.getwalletlist: begin if Commands.TryGetValue(TCommandsNames.getwalletlist, PatternCommand) then Result := PatternCommand.Parse(args); end; else TThread.Queue(nil, procedure begin raise Exception.Create('Error syntax command! No command with name: ' + quotedstr(args[0])) end); end; end; {$ENDREGION} end.
(* *************************************************************************** * * * 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. * * * *************************************************************************** *) unit fImportProgress; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls,lcltype, synachar, ExtCtrls, httpsend, blcksock, iniFiles, FileUtil; type { TfrmImportProgress } TfrmImportProgress = class(TForm) lblCount: TLabel; lblErrors: TLabel; lblComment: TLabel; pBarProg: TProgressBar; tmrImport: TTimer; procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure tmrImportTimer(Sender: TObject); private running : Boolean; FileSize : Int64; procedure ImportDXCCTables; procedure DownloadDXCCData; procedure SockCallBack (Sender: TObject; Reason: THookSocketReason; const Value: string); public ImportType : Integer; FileName : String; Directory : String; CloseAfImport : Boolean; end; var frmImportProgress: TfrmImportProgress; implementation { TfrmImportProgress } uses dData, dUtils, dDXCC, uCfgStorage; procedure TfrmImportProgress.FormActivate(Sender: TObject); begin tmrImport.Enabled := False; if not running then begin running := True; case ImportType of 1 : ImportDXCCTables; 3 : DownloadDXCCData; end // case end end; procedure TfrmImportProgress.FormCreate(Sender: TObject); begin CloseAfImport := False; FileSize := 0 end; procedure TfrmImportProgress.FormDestroy(Sender: TObject); begin end; procedure TfrmImportProgress.FormShow(Sender: TObject); begin running := False; tmrImport.Enabled := True end; procedure TfrmImportProgress.tmrImportTimer(Sender: TObject); begin FormActivate(nil) end; procedure TfrmImportProgress.ImportDXCCTables; var f : TStringList; i,z,y,c : Integer; Result : TExplodeArray; Prefixes : TExplodeArray; ADIF : Integer; List : TStringList; tmp : String; begin SetLength(Prefixes,0); SetLength(Result,0); f := TStringList.Create; List := TStringList.Create; List.Clear; dmDXCC.Q.Close; dmDXCC.trQ.StartTransaction; dmDXCC.Q.SQL.Text := 'DELETE FROM cqrtest_common.dxcc_ref'; dmDXCC.Q.ExecSQL; dmDXCC.trQ.Commit; c := 0; try /////////////////////////////////////////////////////////////////////////// country.tab dmDXCC.trQ.StartTransaction; f.Clear; lblComment.Caption := 'Importing file country.tab ...'; Application.ProcessMessages; f.LoadFromFile(Directory+'Country.tab'); for z:=0 to f.Count-1 do begin inc(c); Result := dmUtils.Explode('|',f.Strings[z]); Prefixes := dmUtils.Explode(' ',Result[0]); ADIF := StrToInt(Result[8]); if ADIF > 0 then begin dmDXCC.Q.SQL.Text := 'INSERT INTO cqrtest_common.dxcc_ref (pref,name,cont,utc,lat,'+ 'longit,itu,waz,adif,deleted) VALUES ('+ QuotedStr(Prefixes[0])+','+ QuotedStr(Result[1])+','+ QuotedStr(Result[2])+','+QuotedStr(Result[3])+','+ QuotedStr(Result[4])+','+QuotedStr(Result[5])+','+ QuotedStr(Result[6])+','+QuotedStr(Result[7])+','+ IntToStr(ADIF)+',0)'; dmUtils.DebugMsg(dmDXCC.Q.SQL.Text); dmDXCC.Q.ExecSQL end end; List.AddStrings(f); dmDXCC.trQ.Commit; ////////////////////////////////////////////////////////////// countrydel.tab dmDXCC.trQ.StartTransaction; f.Clear; lblComment.Caption := 'Importing file countrydel.tab ...'; Application.ProcessMessages; f.LoadFromFile(Directory+'CountryDel.tab'); for z:=0 to f.Count-1 do begin Result := dmUtils.Explode('|',f.Strings[z]); Prefixes := dmUtils.Explode(' ',Result[0]); ADIF := StrToInt(Result[8]); if ADIF > 0 then begin dmDXCC.Q.SQL.Text := 'INSERT INTO cqrtest_common.dxcc_ref (pref,name,cont,utc,lat,'+ 'longit,itu,waz,adif,deleted) VALUES ('+ QuotedStr(Prefixes[0]+'*')+','+ QuotedStr(Result[1])+','+ QuotedStr(Result[2])+','+QuotedStr(Result[3])+','+ QuotedStr(Result[4])+','+QuotedStr(Result[5])+','+ QuotedStr(Result[6])+','+QuotedStr(Result[7])+','+ IntToStr(ADIF)+','+'1'+')'; dmUtils.DebugMsg(dmDXCC.Q.SQL.Text); dmDXCC.Q.ExecSQL end; end; dmDXCC.trQ.Commit; f.SaveToFile(dmData.AppHomeDir+'dxcc_data'+PathDelim+'country_del.tab'); /////////////////////////////////////////////////////////////////// exceptions.tbl CopyFile(Directory+'Exceptions.tab',dmData.AppHomeDir+'dxcc_data'+PathDelim+'exceptions.tab'); ////////////////////////////////////////////////////////////////// callresolution.tbl f.Clear; lblComment.Caption := 'Importing file Callresolution.tbl ...'; Application.ProcessMessages; f.LoadFromFile(Directory+'CallResolution.tbl'); List.AddStrings(f); ////////////////////////////////////////////////////////////////// AreaOK1RR.tab f.Clear; f.LoadFromFile(Directory+'AreaOK1RR.tbl'); List.AddStrings(f); for y:=0 to List.Count-1 do begin if List.Strings[y][1] = '%' then begin for i:=65 to 90 do list.Add(chr(i)+copy(list.Strings[y],2,Length(list.Strings[y])-1)); end; end; List.SaveToFile(dmData.AppHomeDir+'dxcc_data'+PathDelim+'country.tab'); //////////////////////////////////////////////////////////// ambigous.tbl; CopyFile(Directory+'Ambiguous.tbl',dmData.AppHomeDir+'dxcc_data'+PathDelim+'ambiguous.tab'); lblComment.Caption := 'Importing LoTW and eQSL users ...'; Application.ProcessMessages; if FileExistsUTF8(Directory+'lotw1.txt') then begin DeleteFileUTF8(dmData.AppHomeDir+'lotw1.txt'); CopyFile(Directory+'lotw1.txt',dmData.AppHomeDir+'lotw1.txt'); //dmData.LoadLoTWCalls end; if FileExistsUTF8(Directory+'eqsl.txt') then begin DeleteFileUTF8(dmData.AppHomeDir+'eqsl.txt'); CopyFile(Directory+'eqsl.txt',dmData.AppHomeDir+'eqsl.txt'); //dmData.LoadeQSLCalls end; if FileExistsUTF8(Directory+'MASTER.SCP') then begin DeleteFileUTF8(dmData.AppHomeDir+'MASTER.SCP'); CopyFile(Directory+'MASTER.SCP',dmData.AppHomeDir+'MASTER.SCP'); end; lblComment.Caption := 'Importing IOTA table ...'; Application.ProcessMessages; dmData.Q.Close(); dmData.Q.SQL.Text := 'DELETE FROM cqrtest_common.iota_list'; dmData.trQ.StartTransaction; dmData.Q.ExecSQL; dmData.trQ.Commit; f.Clear; f.LoadFromFile(Directory + 'iota.tbl'); dmData.trQ.StartTransaction; for i:= 0 to f.Count-1 do begin Result := dmUtils.Explode('|',f.Strings[i]); if Length(Result) = 3 then dmData.Q.SQL.Text := 'INSERT INTO cqrtest_common.iota_list (iota_nr,island_name,dxcc_ref)'+ ' VALUES ('+QuotedStr(Result[0]) + ',' + QuotedStr(Result[1]) + ',' + QuotedStr(Result[2]) + ')' else begin tmp := Result[3]; if pos('/',tmp) > 0 then tmp := Copy(tmp,1,pos('/',tmp)-1)+ '.*' + Copy(tmp,pos('/',tmp),Length(tmp)-pos('/',tmp)+1); dmData.Q.SQL.Text := 'INSERT INTO cqrtest_common.iota_list (iota_nr,island_name,dxcc_ref,pref)'+ ' VALUES ('+QuotedStr(Result[0]) + ',' + QuotedStr(Result[1]) + ',' + QuotedStr(Result[2]) + ',' + QuotedStr(tmp) + ')' end; dmUtils.DebugMsg(dmData.Q.SQL.Text); if length(Result[1]) > 250 then ShowMessage(Result[0]); if length(Result[2]) > 15 then ShowMessage(Result[0]); if length(Result) > 3 then if length(Result[3]) > 15 then ShowMessage(Result[0]); dmData.Q.ExecSQL; end; dmData.trQ.Commit; finally //dmDXCC.trDXCCRef.StartTransaction; dmDXCC.qDXCCRef.SQL.Text := 'SELECT * FROM cqrtest_common.dxcc_ref ORDER BY adif'; dmDXCC.qDXCCRef.Open; f.Free; List.Free; Close end end; procedure TfrmImportProgress.DownloadDXCCData; var HTTP : THTTPSend; m : TFileStream; begin FileName := dmData.AppHomeDir+'ctyfiles/cqrlog-cty.tar.gz'; if FileExists(FileName) then DeleteFile(FileName); http := THTTPSend.Create; m := TFileStream.Create(FileName,fmCreate); try HTTP.Sock.OnStatus := @SockCallBack; HTTP.ProxyHost := iniLocal.ReadString('Program','Proxy',''); HTTP.ProxyPort := iniLocal.ReadString('Program','Port',''); HTTP.UserName := iniLocal.ReadString('Program','User',''); HTTP.Password := iniLocal.ReadString('Program','Passwd',''); if HTTP.HTTPMethod('GET', 'http://www.ok2cqr.com/linux/cqrlog/ctyfiles/cqrlog-cty.tar.gz') then begin http.Document.Seek(0,soBeginning); m.CopyFrom(http.Document,HTTP.Document.Size); if dmUtils.UnTarFiles(FileName,ExtractFilePath(FileName)) then begin Directory := ExtractFilePath(FileName); ImportDXCCTables end; end; finally http.Free; m.Free; end end; procedure TfrmImportProgress.SockCallBack (Sender: TObject; Reason: THookSocketReason; const Value: string); begin if Reason = HR_ReadCount then begin FileSize := FileSize + StrToInt(Value); lblCount.Caption := IntToStr(FileSize); Repaint; Application.ProcessMessages end end; initialization {$I fImportProgress.lrs} end.
unit Ths.Erp.Database.Table.SysApplicationSettingsOther; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TSysApplicationSettingsOther = class(TTable) private FIsEdefterAktif: TFieldDB; FVarsayilanSatisCariKod: TFieldDB; FVarsayilanAlisCariKod: TFieldDB; FIsBolumAmbardaUretimYap: TFieldDB; FIsUretimMuhasebeKaydiOlustursun: TFieldDB; FIsStokSatimdaNegatifeDusebilir: TFieldDB; FIsMalSatisSayilariniGoster: TFieldDB; FIsPcbUretim: TFieldDB; FIsProformaNoGoster: TFieldDB; FIsSatisTakip: TFieldDB; FIsHammaddeGiriseGoreSirala: TFieldDB; FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle: TFieldDB; FIsTahsilatListesiVirmanli: TFieldDB; FIsOrtalamaVadeSifirsaSevkiyataIzinVerme: TFieldDB; FIsSiparisteTeslimTarihiYazdir: TFieldDB; FIsTeklifAyrintilariniGoster: TFieldDB; FIsFaturaIrsaliyeNoSifirlaBaslasin: TFieldDB; FIsExcelEkliIrsaliyeYazdirma: TFieldDB; FIsAmbarTransferNumarasiOtomatikGelsin: TFieldDB; FIsAmbarTransferOnayliCalissin: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property IsEdefterAktif: TFieldDB read FIsEdefterAktif write FIsEdefterAktif; Property VarsayilanSatisCariKod: TFieldDB read FVarsayilanSatisCariKod write FVarsayilanSatisCariKod; Property VarsayilanAlisCariKod: TFieldDB read FVarsayilanAlisCariKod write FVarsayilanAlisCariKod; Property IsBolumAmbardaUretimYap: TFieldDB read FIsBolumAmbardaUretimYap write FIsBolumAmbardaUretimYap; Property IsUretimMuhasebeKaydiOlustursun: TFieldDB read FIsUretimMuhasebeKaydiOlustursun write FIsUretimMuhasebeKaydiOlustursun; Property IsStokSatimdaNegatifeDusebilir: TFieldDB read FIsStokSatimdaNegatifeDusebilir write FIsStokSatimdaNegatifeDusebilir; Property IsMalSatisSayilariniGoster: TFieldDB read FIsMalSatisSayilariniGoster write FIsMalSatisSayilariniGoster; Property IsPcbUretim: TFieldDB read FIsPcbUretim write FIsPcbUretim; Property IsProformaNoGoster: TFieldDB read FIsProformaNoGoster write FIsProformaNoGoster; Property IsSatisTakip: TFieldDB read FIsSatisTakip write FIsSatisTakip; Property IsHammaddeGiriseGoreSirala: TFieldDB read FIsHammaddeGiriseGoreSirala write FIsHammaddeGiriseGoreSirala; Property IsUretimEntegrasyonHammaddeKullanimHesabiIscilikle: TFieldDB read FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle write FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle; Property IsTahsilatListesiVirmanli: TFieldDB read FIsTahsilatListesiVirmanli write FIsTahsilatListesiVirmanli; Property IsOrtalamaVadeSifirsaSevkiyataIzinVerme: TFieldDB read FIsOrtalamaVadeSifirsaSevkiyataIzinVerme write FIsOrtalamaVadeSifirsaSevkiyataIzinVerme; Property IsSiparisteTeslimTarihiYazdir: TFieldDB read FIsSiparisteTeslimTarihiYazdir write FIsSiparisteTeslimTarihiYazdir; Property IsTeklifAyrintilariniGoster: TFieldDB read FIsTeklifAyrintilariniGoster write FIsTeklifAyrintilariniGoster; Property IsFaturaIrsaliyeNoSifirlaBaslasin: TFieldDB read FIsFaturaIrsaliyeNoSifirlaBaslasin write FIsFaturaIrsaliyeNoSifirlaBaslasin; Property IsExcelEkliIrsaliyeYazdirma: TFieldDB read FIsExcelEkliIrsaliyeYazdirma write FIsExcelEkliIrsaliyeYazdirma; Property IsAmbarTransferNumarasiOtomatikGelsin: TFieldDB read FIsAmbarTransferNumarasiOtomatikGelsin write FIsAmbarTransferNumarasiOtomatikGelsin; Property IsAmbarTransferOnayliCalissin: TFieldDB read FIsAmbarTransferOnayliCalissin write FIsAmbarTransferOnayliCalissin; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TSysApplicationSettingsOther.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'sys_application_settings_other'; SourceCode := '1000'; FIsEdefterAktif := TFieldDB.Create('is_edefter_aktif', ftBoolean, False); FVarsayilanSatisCariKod := TFieldDB.Create('varsayilan_satis_cari_kod', ftString, ''); FVarsayilanAlisCariKod := TFieldDB.Create('varsayilan_alis_cari_kod', ftString, ''); FIsBolumAmbardaUretimYap := TFieldDB.Create('is_bolum_ambarda_uretim_yap', ftBoolean, False); FIsUretimMuhasebeKaydiOlustursun := TFieldDB.Create('is_uretim_muhasebe_kaydi_olustursun', ftBoolean, False); FIsStokSatimdaNegatifeDusebilir := TFieldDB.Create('is_stok_satimda_negatife_dusebilir', ftBoolean, False); FIsMalSatisSayilariniGoster := TFieldDB.Create('is_mal_satis_sayilarini_goster', ftBoolean, False); FIsPcbUretim := TFieldDB.Create('is_pcb_uretim', ftBoolean, False); FIsProformaNoGoster := TFieldDB.Create('is_proforma_no_goster', ftBoolean, False); FIsSatisTakip := TFieldDB.Create('is_satis_takip', ftBoolean, False); FIsHammaddeGiriseGoreSirala := TFieldDB.Create('is_hammadde_girise_gore_sirala', ftString, ''); FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle := TFieldDB.Create('is_uretim_entegrasyon_hammadde_kullanim_hesabi_iscilikle', ftBoolean, False); FIsTahsilatListesiVirmanli := TFieldDB.Create('is_tahsilat_listesi_virmanli', ftBoolean, False); FIsOrtalamaVadeSifirsaSevkiyataIzinVerme := TFieldDB.Create('is_ortalama_vade_0_ise_sevkiyata_izin_verme', ftBoolean, False); FIsSiparisteTeslimTarihiYazdir := TFieldDB.Create('is_sipariste_teslim_tarihi_yazdir', ftBoolean, False); FIsTeklifAyrintilariniGoster := TFieldDB.Create('is_teklif_ayrintilarini_goster', ftBoolean, False); FIsFaturaIrsaliyeNoSifirlaBaslasin := TFieldDB.Create('is_fatura_irsaliye_no_0_ile_baslasin', ftBoolean, False); FIsExcelEkliIrsaliyeYazdirma := TFieldDB.Create('is_excel_ekli_irsaliye_yazdirma', ftBoolean, False); FIsAmbarTransferNumarasiOtomatikGelsin := TFieldDB.Create('is_ambar_transfer_numara_otomatik_gelsin', ftBoolean, False); FIsAmbarTransferOnayliCalissin := TFieldDB.Create('is_ambar_transfer_onayli_calissin', ftBoolean, False); end; procedure TSysApplicationSettingsOther.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FIsEdefterAktif.FieldName, TableName + '.' + FVarsayilanSatisCariKod.FieldName, TableName + '.' + FVarsayilanAlisCariKod.FieldName, TableName + '.' + FIsBolumAmbardaUretimYap.FieldName, TableName + '.' + FIsUretimMuhasebeKaydiOlustursun.FieldName, TableName + '.' + FIsStokSatimdaNegatifeDusebilir.FieldName, TableName + '.' + FIsMalSatisSayilariniGoster.FieldName, TableName + '.' + FIsPcbUretim.FieldName, TableName + '.' + FIsProformaNoGoster.FieldName, TableName + '.' + FIsSatisTakip.FieldName, TableName + '.' + FIsHammaddeGiriseGoreSirala.FieldName, TableName + '.' + FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName, TableName + '.' + FIsTahsilatListesiVirmanli.FieldName, TableName + '.' + FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName, TableName + '.' + FIsSiparisteTeslimTarihiYazdir.FieldName, TableName + '.' + FIsTeklifAyrintilariniGoster.FieldName, TableName + '.' + FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName, TableName + '.' + FIsExcelEkliIrsaliyeYazdirma.FieldName, TableName + '.' + FIsAmbarTransferNumarasiOtomatikGelsin.FieldName, TableName + '.' + FIsAmbarTransferOnayliCalissin.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FIsEdefterAktif.FieldName).DisplayLabel := 'E-Defter Aktif?'; Self.DataSource.DataSet.FindField(FVarsayilanSatisCariKod.FieldName).DisplayLabel := 'Varsayılan Satış Cari Kod'; Self.DataSource.DataSet.FindField(FVarsayilanAlisCariKod.FieldName).DisplayLabel := 'Varsayılan Alış Cari Kod'; Self.DataSource.DataSet.FindField(FIsBolumAmbardaUretimYap.FieldName).DisplayLabel := 'Bölüm Ambarda Üretim Yap'; Self.DataSource.DataSet.FindField(FIsUretimMuhasebeKaydiOlustursun.FieldName).DisplayLabel := 'Üretim Muhasebe Kaydı Oluştursun?'; Self.DataSource.DataSet.FindField(FIsStokSatimdaNegatifeDusebilir.FieldName).DisplayLabel := 'Stok Satımda Negatife Düşebilir?'; Self.DataSource.DataSet.FindField(FIsMalSatisSayilariniGoster.FieldName).DisplayLabel := 'Mal Satış Sayılarını Göster'; Self.DataSource.DataSet.FindField(FIsPcbUretim.FieldName).DisplayLabel := 'PCB Üretim'; Self.DataSource.DataSet.FindField(FIsProformaNoGoster.FieldName).DisplayLabel := 'Proforma Numarası Göster'; Self.DataSource.DataSet.FindField(FIsSatisTakip.FieldName).DisplayLabel := 'Satış Takip'; Self.DataSource.DataSet.FindField(FIsHammaddeGiriseGoreSirala.FieldName).DisplayLabel := 'Hammadde Girişe Göre Sırala'; Self.DataSource.DataSet.FindField(FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName).DisplayLabel := 'Üretim Entegrasyon Hamadde Kullanım Hesabı İşçilikle'; Self.DataSource.DataSet.FindField(FIsTahsilatListesiVirmanli.FieldName).DisplayLabel := 'Tahsilat Listesi Virmanlı'; Self.DataSource.DataSet.FindField(FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName).DisplayLabel := 'Ortalama Vade Sıfır ise Sevkiyata İzin Verme'; Self.DataSource.DataSet.FindField(FIsSiparisteTeslimTarihiYazdir.FieldName).DisplayLabel := 'Siparişte Teslim Tarihi Yazdır'; Self.DataSource.DataSet.FindField(FIsTeklifAyrintilariniGoster.FieldName).DisplayLabel := 'Teklif Ayrıntılarını Göster'; Self.DataSource.DataSet.FindField(FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName).DisplayLabel := 'Fatura-İrsaliye No Sıfırla Başlasın'; Self.DataSource.DataSet.FindField(FIsExcelEkliIrsaliyeYazdirma.FieldName).DisplayLabel := 'Excel Ekli İrsaliye Yazdırma'; Self.DataSource.DataSet.FindField(FIsAmbarTransferNumarasiOtomatikGelsin.FieldName).DisplayLabel := 'Ambar Transfer Numarası Otomatik Gelsin'; Self.DataSource.DataSet.FindField(FIsAmbarTransferOnayliCalissin.FieldName).DisplayLabel := 'Ambar Transfer Onaylı Çalışsın'; end; end; end; procedure TSysApplicationSettingsOther.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FIsEdefterAktif.FieldName, TableName + '.' + FVarsayilanSatisCariKod.FieldName, TableName + '.' + FVarsayilanAlisCariKod.FieldName, TableName + '.' + FIsBolumAmbardaUretimYap.FieldName, TableName + '.' + FIsUretimMuhasebeKaydiOlustursun.FieldName, TableName + '.' + FIsStokSatimdaNegatifeDusebilir.FieldName, TableName + '.' + FIsMalSatisSayilariniGoster.FieldName, TableName + '.' + FIsPcbUretim.FieldName, TableName + '.' + FIsProformaNoGoster.FieldName, TableName + '.' + FIsSatisTakip.FieldName, TableName + '.' + FIsHammaddeGiriseGoreSirala.FieldName, TableName + '.' + FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName, TableName + '.' + FIsTahsilatListesiVirmanli.FieldName, TableName + '.' + FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName, TableName + '.' + FIsSiparisteTeslimTarihiYazdir.FieldName, TableName + '.' + FIsTeklifAyrintilariniGoster.FieldName, TableName + '.' + FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName, TableName + '.' + FIsExcelEkliIrsaliyeYazdirma.FieldName, TableName + '.' + FIsAmbarTransferNumarasiOtomatikGelsin.FieldName, TableName + '.' + FIsAmbarTransferOnayliCalissin.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FIsEdefterAktif.Value := FormatedVariantVal(FieldByName(FIsEdefterAktif.FieldName).DataType, FieldByName(FIsEdefterAktif.FieldName).Value); FVarsayilanSatisCariKod.Value := FormatedVariantVal(FieldByName(FVarsayilanSatisCariKod.FieldName).DataType, FieldByName(FVarsayilanSatisCariKod.FieldName).Value); FVarsayilanAlisCariKod.Value := FormatedVariantVal(FieldByName(FVarsayilanAlisCariKod.FieldName).DataType, FieldByName(FVarsayilanAlisCariKod.FieldName).Value); FIsBolumAmbardaUretimYap.Value := FormatedVariantVal(FieldByName(FIsBolumAmbardaUretimYap.FieldName).DataType, FieldByName(FIsBolumAmbardaUretimYap.FieldName).Value); FIsUretimMuhasebeKaydiOlustursun.Value := FormatedVariantVal(FieldByName(FIsUretimMuhasebeKaydiOlustursun.FieldName).DataType, FieldByName(FIsUretimMuhasebeKaydiOlustursun.FieldName).Value); FIsStokSatimdaNegatifeDusebilir.Value := FormatedVariantVal(FieldByName(FIsStokSatimdaNegatifeDusebilir.FieldName).DataType, FieldByName(FIsStokSatimdaNegatifeDusebilir.FieldName).Value); FIsMalSatisSayilariniGoster.Value := FormatedVariantVal(FieldByName(FIsMalSatisSayilariniGoster.FieldName).DataType, FieldByName(FIsMalSatisSayilariniGoster.FieldName).Value); FIsPcbUretim.Value := FormatedVariantVal(FieldByName(FIsPcbUretim.FieldName).DataType, FieldByName(FIsPcbUretim.FieldName).Value); FIsProformaNoGoster.Value := FormatedVariantVal(FieldByName(FIsProformaNoGoster.FieldName).DataType, FieldByName(FIsProformaNoGoster.FieldName).Value); FIsSatisTakip.Value := FormatedVariantVal(FieldByName(FIsSatisTakip.FieldName).DataType, FieldByName(FIsSatisTakip.FieldName).Value); FIsHammaddeGiriseGoreSirala.Value := FormatedVariantVal(FieldByName(FIsHammaddeGiriseGoreSirala.FieldName).DataType, FieldByName(FIsHammaddeGiriseGoreSirala.FieldName).Value); FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.Value := FormatedVariantVal(FieldByName(FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName).DataType, FieldByName(FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName).Value); FIsTahsilatListesiVirmanli.Value := FormatedVariantVal(FieldByName(FIsTahsilatListesiVirmanli.FieldName).DataType, FieldByName(FIsTahsilatListesiVirmanli.FieldName).Value); FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.Value := FormatedVariantVal(FieldByName(FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName).DataType, FieldByName(FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName).Value); FIsSiparisteTeslimTarihiYazdir.Value := FormatedVariantVal(FieldByName(FIsSiparisteTeslimTarihiYazdir.FieldName).DataType, FieldByName(FIsSiparisteTeslimTarihiYazdir.FieldName).Value); FIsTeklifAyrintilariniGoster.Value := FormatedVariantVal(FieldByName(FIsTeklifAyrintilariniGoster.FieldName).DataType, FieldByName(FIsTeklifAyrintilariniGoster.FieldName).Value); FIsFaturaIrsaliyeNoSifirlaBaslasin.Value := FormatedVariantVal(FieldByName(FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName).DataType, FieldByName(FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName).Value); FIsExcelEkliIrsaliyeYazdirma.Value := FormatedVariantVal(FieldByName(FIsExcelEkliIrsaliyeYazdirma.FieldName).DataType, FieldByName(FIsExcelEkliIrsaliyeYazdirma.FieldName).Value); FIsAmbarTransferNumarasiOtomatikGelsin.Value := FormatedVariantVal(FieldByName(FIsAmbarTransferNumarasiOtomatikGelsin.FieldName).DataType, FieldByName(FIsAmbarTransferNumarasiOtomatikGelsin.FieldName).Value); FIsAmbarTransferOnayliCalissin.Value := FormatedVariantVal(FieldByName(FIsAmbarTransferOnayliCalissin.FieldName).DataType, FieldByName(FIsAmbarTransferOnayliCalissin.FieldName).Value); List.Add(Self.Clone()); Next; end; Close; end; end; end; procedure TSysApplicationSettingsOther.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FIsEdefterAktif.FieldName, FVarsayilanSatisCariKod.FieldName, FVarsayilanAlisCariKod.FieldName, FIsBolumAmbardaUretimYap.FieldName, FIsUretimMuhasebeKaydiOlustursun.FieldName, FIsStokSatimdaNegatifeDusebilir.FieldName, FIsMalSatisSayilariniGoster.FieldName, FIsPcbUretim.FieldName, FIsProformaNoGoster.FieldName, FIsSatisTakip.FieldName, FIsHammaddeGiriseGoreSirala.FieldName, FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName, FIsTahsilatListesiVirmanli.FieldName, FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName, FIsSiparisteTeslimTarihiYazdir.FieldName, FIsTeklifAyrintilariniGoster.FieldName, FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName, FIsExcelEkliIrsaliyeYazdirma.FieldName, FIsAmbarTransferNumarasiOtomatikGelsin.FieldName, FIsAmbarTransferOnayliCalissin.FieldName ]); NewParamForQuery(QueryOfInsert, FIsEdefterAktif); NewParamForQuery(QueryOfInsert, FVarsayilanSatisCariKod); NewParamForQuery(QueryOfInsert, FVarsayilanAlisCariKod); NewParamForQuery(QueryOfInsert, FIsBolumAmbardaUretimYap); NewParamForQuery(QueryOfInsert, FIsUretimMuhasebeKaydiOlustursun); NewParamForQuery(QueryOfInsert, FIsStokSatimdaNegatifeDusebilir); NewParamForQuery(QueryOfInsert, FIsMalSatisSayilariniGoster); NewParamForQuery(QueryOfInsert, FIsPcbUretim); NewParamForQuery(QueryOfInsert, FIsProformaNoGoster); NewParamForQuery(QueryOfInsert, FIsSatisTakip); NewParamForQuery(QueryOfInsert, FIsHammaddeGiriseGoreSirala); NewParamForQuery(QueryOfInsert, FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle); NewParamForQuery(QueryOfInsert, FIsTahsilatListesiVirmanli); NewParamForQuery(QueryOfInsert, FIsOrtalamaVadeSifirsaSevkiyataIzinVerme); NewParamForQuery(QueryOfInsert, FIsSiparisteTeslimTarihiYazdir); NewParamForQuery(QueryOfInsert, FIsTeklifAyrintilariniGoster); NewParamForQuery(QueryOfInsert, FIsFaturaIrsaliyeNoSifirlaBaslasin); NewParamForQuery(QueryOfInsert, FIsExcelEkliIrsaliyeYazdirma); NewParamForQuery(QueryOfInsert, FIsAmbarTransferNumarasiOtomatikGelsin); NewParamForQuery(QueryOfInsert, FIsAmbarTransferOnayliCalissin); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TSysApplicationSettingsOther.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FIsEdefterAktif.FieldName, FVarsayilanSatisCariKod.FieldName, FVarsayilanAlisCariKod.FieldName, FIsBolumAmbardaUretimYap.FieldName, FIsUretimMuhasebeKaydiOlustursun.FieldName, FIsStokSatimdaNegatifeDusebilir.FieldName, FIsMalSatisSayilariniGoster.FieldName, FIsPcbUretim.FieldName, FIsProformaNoGoster.FieldName, FIsSatisTakip.FieldName, FIsHammaddeGiriseGoreSirala.FieldName, FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldName, FIsTahsilatListesiVirmanli.FieldName, FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldName, FIsSiparisteTeslimTarihiYazdir.FieldName, FIsTeklifAyrintilariniGoster.FieldName, FIsFaturaIrsaliyeNoSifirlaBaslasin.FieldName, FIsExcelEkliIrsaliyeYazdirma.FieldName, FIsAmbarTransferNumarasiOtomatikGelsin.FieldName, FIsAmbarTransferOnayliCalissin.FieldName ]); NewParamForQuery(QueryOfUpdate, FIsEdefterAktif); NewParamForQuery(QueryOfUpdate, FVarsayilanSatisCariKod); NewParamForQuery(QueryOfUpdate, FVarsayilanAlisCariKod); NewParamForQuery(QueryOfUpdate, FIsBolumAmbardaUretimYap); NewParamForQuery(QueryOfUpdate, FIsUretimMuhasebeKaydiOlustursun); NewParamForQuery(QueryOfUpdate, FIsStokSatimdaNegatifeDusebilir); NewParamForQuery(QueryOfUpdate, FIsMalSatisSayilariniGoster); NewParamForQuery(QueryOfUpdate, FIsPcbUretim); NewParamForQuery(QueryOfUpdate, FIsProformaNoGoster); NewParamForQuery(QueryOfUpdate, FIsSatisTakip); NewParamForQuery(QueryOfUpdate, FIsHammaddeGiriseGoreSirala); NewParamForQuery(QueryOfUpdate, FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle); NewParamForQuery(QueryOfUpdate, FIsTahsilatListesiVirmanli); NewParamForQuery(QueryOfUpdate, FIsOrtalamaVadeSifirsaSevkiyataIzinVerme); NewParamForQuery(QueryOfUpdate, FIsSiparisteTeslimTarihiYazdir); NewParamForQuery(QueryOfUpdate, FIsTeklifAyrintilariniGoster); NewParamForQuery(QueryOfUpdate, FIsFaturaIrsaliyeNoSifirlaBaslasin); NewParamForQuery(QueryOfUpdate, FIsExcelEkliIrsaliyeYazdirma); NewParamForQuery(QueryOfUpdate, FIsAmbarTransferNumarasiOtomatikGelsin); NewParamForQuery(QueryOfUpdate, FIsAmbarTransferOnayliCalissin); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TSysApplicationSettingsOther.Clone():TTable; begin Result := TSysApplicationSettingsOther.Create(Database); Self.Id.Clone(TSysApplicationSettingsOther(Result).Id); FIsEdefterAktif.Clone(TSysApplicationSettingsOther(Result).FIsEdefterAktif); FVarsayilanSatisCariKod.Clone(TSysApplicationSettingsOther(Result).FVarsayilanSatisCariKod); FVarsayilanAlisCariKod.Clone(TSysApplicationSettingsOther(Result).FVarsayilanAlisCariKod); FIsBolumAmbardaUretimYap.Clone(TSysApplicationSettingsOther(Result).FIsBolumAmbardaUretimYap); FIsUretimMuhasebeKaydiOlustursun.Clone(TSysApplicationSettingsOther(Result).FIsUretimMuhasebeKaydiOlustursun); FIsStokSatimdaNegatifeDusebilir.Clone(TSysApplicationSettingsOther(Result).FIsStokSatimdaNegatifeDusebilir); FIsMalSatisSayilariniGoster.Clone(TSysApplicationSettingsOther(Result).FIsMalSatisSayilariniGoster); FIsPcbUretim.Clone(TSysApplicationSettingsOther(Result).FIsPcbUretim); FIsProformaNoGoster.Clone(TSysApplicationSettingsOther(Result).FIsProformaNoGoster); FIsSatisTakip.Clone(TSysApplicationSettingsOther(Result).FIsSatisTakip); FIsHammaddeGiriseGoreSirala.Clone(TSysApplicationSettingsOther(Result).FIsHammaddeGiriseGoreSirala); FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.Clone(TSysApplicationSettingsOther(Result).FIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle); FIsTahsilatListesiVirmanli.Clone(TSysApplicationSettingsOther(Result).FIsTahsilatListesiVirmanli); FIsOrtalamaVadeSifirsaSevkiyataIzinVerme.Clone(TSysApplicationSettingsOther(Result).FIsOrtalamaVadeSifirsaSevkiyataIzinVerme); FIsSiparisteTeslimTarihiYazdir.Clone(TSysApplicationSettingsOther(Result).FIsSiparisteTeslimTarihiYazdir); FIsTeklifAyrintilariniGoster.Clone(TSysApplicationSettingsOther(Result).FIsTeklifAyrintilariniGoster); FIsFaturaIrsaliyeNoSifirlaBaslasin.Clone(TSysApplicationSettingsOther(Result).FIsFaturaIrsaliyeNoSifirlaBaslasin); FIsExcelEkliIrsaliyeYazdirma.Clone(TSysApplicationSettingsOther(Result).FIsExcelEkliIrsaliyeYazdirma); FIsAmbarTransferNumarasiOtomatikGelsin.Clone(TSysApplicationSettingsOther(Result).FIsAmbarTransferNumarasiOtomatikGelsin); FIsAmbarTransferOnayliCalissin.Clone(TSysApplicationSettingsOther(Result).FIsAmbarTransferOnayliCalissin); end; end.
PROGRAM ZahlenMitBasen; type NumbRange = 'A'..'Z'; FUNCTION ValueOf(digits: string; base: INTEGER): INTEGER; var helpChars: array of NumbRange; var i: integer; var endSum: integer; BEGIN (* ValueOf *) IF ((base < 2) OR (base > 36)) THEN BEGIN Exit(-1); END; (* IF *) IF (base > 10) THEN BEGIN SetLength(helpChars, base - 10); END; (* IF *) endSum := 0; FOR i := 0 TO Length(helpChars) - 1 DO BEGIN helpChars[i] := Chr(i + Ord('A')); END; (* FOR *) FOR i := 1 TO Length(digits) DO BEGIN IF((digits[i] >= '0') AND ((Ord(digits[i]) - Ord('0')) < base)) THEN BEGIN endSum := endSum * base + Ord(digits[i]) - Ord('0'); END ELSE IF (base > 10) THEN BEGIN IF ((digits[i] >= helpChars[0]) AND (digits[i] <= helpChars[Length(helpChars) - 1])) THEN BEGIN endSum := endSum * base + Ord(digits[i]) - Ord('A') + 10; END; (* IF *) END ELSE BEGIN Exit(-1); END; END; (* FOR *) ValueOf:= endSum; END; (* ValueOf *) FUNCTION DigitsOf(value: integer; base: integer): string; var output, newDigitString: string; var newDigitInt: integer; var decreaseInteger: boolean; BEGIN (* DigitsOf *) output := ''; IF ((base < 2) OR (base > 36)) THEN BEGIN Exit('-1'); END; (* IF *) WHILE (value > 0) DO BEGIN decreaseInteger := false; IF (value < base) THEN BEGIN newDigitInt := value; END ELSE BEGIN newDigitInt := value MOD base; END; (* IF *) IF (newDigitInt < 10) THEN BEGIN newDigitString := Chr(newDigitInt + Ord('0')); END ELSE BEGIN newDigitString := Chr(newDigitInt - 10 + Ord('A')); END; (* IF *) output := newDigitString + output; IF (Round(value/base) > value/base) THEN BEGIN decreaseInteger := true; END ELSE BEGIN decreaseInteger := false; END; (* IF *) value := Round(value/base); IF (decreaseInteger) THEN BEGIN Dec(value); END; (* IF *) END; (* WHILE *) DigitsOf := output; END; (* DigitsOf *) FUNCTION Sum(v1: string; b1: integer; v2: string; b2: integer): integer; var v1InDecimal, v2InDecimal: integer; BEGIN (* Sum *) v1InDecimal := ValueOf(v1, b1); v2InDecimal := ValueOf(v2, b2); Sum := v1InDecimal + v2InDecimal; END; (* Sum *) FUNCTION Diff(v1: string; b1: integer; v2: string; b2: integer): integer; var v1InDecimal, v2InDecimal: integer; BEGIN (* Diff *) v1InDecimal := ValueOf(v1, b1); v2InDecimal := ValueOf(v2, b2); IF (v1InDecimal > v2InDecimal) THEN BEGIN Diff := v1InDecimal - v2InDecimal; END ELSE BEGIN Diff := v2InDecimal - v1InDecimal; END; (* IF *) END; (* Diff *) FUNCTION Prod(v1: string; b1: integer; v2: string; b2: integer): integer; var v1InDecimal, v2InDecimal: integer; BEGIN (* Prod *) v1InDecimal := ValueOf(v1, b1); v2InDecimal := ValueOf(v2, b2); Prod := v1InDecimal * v2InDecimal; END; (* Prod *) FUNCTION Quot(v1: string; b1: integer; v2: string; b2: integer): integer; var v1InDecimal, v2InDecimal: integer; BEGIN (* Quot *) v1InDecimal := ValueOf(v1, b1); v2InDecimal := ValueOf(v2, b2); IF (v1InDecimal > v2InDecimal) THEN BEGIN Quot := Round(v1InDecimal / v2InDecimal); END ELSE BEGIN Quot := Round(v2InDecimal / v1InDecimal); END; (* IF *) END; (* Quot *) var number: string; var numberInt: integer; var base: integer; var v1, v2: string; var b1, b2: integer; var input: integer; BEGIN (* ZahlenMitBasen *) WriteLn('Waehlen Sie die gewuenschte Funktion aus:'); WriteLn('0: Beendet das Programm.'); WriteLn('1: Zahl mit beliebiger Basis zwischen 2 und 36 ins Dezimalsystem umrechnen.'); WriteLn('2: Zahl aus dem Dezimalsystem in eine Zahl mit beliebiger Basis zwischen 2 und 36 umrechnen.'); WriteLn('3: Zwei Zahlen mit beliebiger Basis zwischen 2 und 36 addieren.'); WriteLn('4: Zwei Zahlen mit beliebiger Basis zwischen 2 und 36 subtrahieren.'); WriteLn('5: Zwei Zahlen mit beliebiger Basis zwischen 2 und 36 multiplizieren.'); WriteLn('6: Zwei Zahlen mit beliebiger Basis zwischen 2 und 36 dividieren.'); Write('Eingabe: '); ReadLn(input); WHILE (input <> 0) DO BEGIN IF (input = 1) THEN BEGIN Write('Zahl: '); Read(number); Write('Basis: '); Read(base); WriteLn('Zahl im Dezimalsystem: ', ValueOf(number, base)); END ELSE IF (input = 2) THEN BEGIN Write('Zahl: '); Read(numberInt); Write('Basis: '); Read(base); WriteLn('Zahl mit Basis ', base, ': ', DigitsOf(numberInt, base)); END ELSE IF (input = 3) THEN BEGIN Write('Zahl 1: '); Read(v1); Write('Basis 1: '); ReadLn(b1); Write('Zahl 2: '); Read(v2); Write('Basis 2: '); Read(b2); IF (b1 = b2) THEN BEGIN WriteLn('Ergebnis: ', DigitsOf(Sum(v1, b1, v2, b2), b1), ' (Basis: ', b1, ')'); END ELSE BEGIN WriteLn('Ergebnis: ', Sum(v1, b1, v2, b2), ' (Basis: 10)'); END; (* IF *) END ELSE IF (input = 4) THEN BEGIN Write('Zahl 1: '); Read(v1); Write('Basis 1: '); ReadLn(b1); Write('Zahl 2: '); Read(v2); Write('Basis 2: '); Read(b2); IF (b1 = b2) THEN BEGIN WriteLn('Ergebnis: ', DigitsOf(Diff(v1, b1, v2, b2), b1), ' (Basis: ', b1, ')'); END ELSE BEGIN WriteLn('Ergebnis: ', Diff(v1, b1, v2, b2), ' (Basis: 10)'); END; (* IF *) END ELSE IF (input = 5) THEN BEGIN Write('Zahl 1: '); Read(v1); Write('Basis 1: '); ReadLn(b1); Write('Zahl 2: '); Read(v2); Write('Basis 2: '); Read(b2); IF (b1 = b2) THEN BEGIN WriteLn('Ergebnis: ', DigitsOf(Prod(v1, b1, v2, b2), b1), ' (Basis: ', b1, ')'); END ELSE BEGIN WriteLn('Ergebnis: ', Prod(v1, b1, v2, b2), ' (Basis: 10)'); END; (* IF *) END ELSE IF (input = 6) THEN BEGIN Write('Zahl 1: '); Read(v1); Write('Basis 1: '); ReadLn(b1); Write('Zahl 2: '); Read(v2); Write('Basis 2: '); Read(b2); IF (b1 = b2) THEN BEGIN WriteLn('Ergebnis: ', DigitsOf(Quot(v1, b1, v2, b2), b1), ' (Basis: ', b1, ')'); END ELSE BEGIN WriteLn('Ergebnis: ', Quot(v1, b1, v2, b2), ' (Basis: 10)'); END; (* IF *) END ELSE BEGIN WriteLn('Ungueltige Eingabe, Programm wird beendet.'); Exit(); END; (* IF *) Write('Eingabe: '); ReadLn(input); END; (* WHILE *) END. (* ZahlenMitBasen *)
unit caClasses; {$INCLUDE ca.inc} {.$DEFINE LOG_CREATE_DESTROY} {.$DEFINE LOG_REF_COUNT} interface uses // Standard Delphi units  Classes, Sysutils, // ca units  caLog; type {$IFDEF D5} IInterface = IUnknown; {$ENDIF} TcaColRow = packed record Col: Integer; Row: Integer; end; EcaException = class(Exception); TcaInterfacedPersistent = class; TcaProcedure = procedure of object; TcaNotifyEvent = procedure(const Sender: IInterface) of object; //--------------------------------------------------------------------------- // IcaAssignable   //--------------------------------------------------------------------------- IcaAssignable = interface ['{C0C4B0D1-57DA-405D-AD25-7B071D611E15}'] // Public methods  procedure AssignFromInterface(Source: IUnknown); procedure AssignFromObject(Source: TPersistent); end; //--------------------------------------------------------------------------- // IcaCloneable   //--------------------------------------------------------------------------- IcaCloneable = interface ['{478BF36E-F5DD-49A8-B680-EC85FAA7FBBC}'] // Public methods  function CloneAsInterface: IUnknown; function CloneAsObject: TcaInterfacedPersistent; end; //---------------------------------------------------------------------------- // TcaInterfacedPersistent   //    // A base for Persistent Interfaces descendents    //    // Note that in D5 (at least), any persistent properties intended for display  // in the Object Inspector must still be created as object instances, not as   // interfaces. Hopefully this will change in D6/Kylix.    //---------------------------------------------------------------------------- TcaInterfacedPersistent = class(TPersistent, IUnknown, IcaCloneable, IcaAssignable) private {$IFDEF LOG_CREATE_DESTROY} FLogCreateAndDestroy: Boolean; {$ENDIF} {$IFDEF LOG_REF_COUNT} FLogRefCount: Boolean; {$ENDIF} protected // Interface support  FNoRefCount: Boolean; FRefCount: Integer; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; // Owned list object support  procedure ClearListObjects(AList: TList); public constructor CreateNonRefCounted; // Overridden public methods  procedure AfterConstruction; override; procedure BeforeDestruction; override; class function NewInstance: TObject; override; // IcaAssignable  procedure AssignFromInterface(Source: IUnknown); virtual; procedure AssignFromObject(Source: TPersistent); virtual; // IcaCloneable  function CloneAsInterface: IUnknown; virtual; function CloneAsObject: TcaInterfacedPersistent; virtual; // Properties  {$IFDEF LOG_CREATE_DESTROY} property LogCreateAndDestroy: Boolean read FLogCreateAndDestroy write FLogCreateAndDestroy; {$ENDIF} {$IFDEF LOG_REF_COUNT} property LogRefCount: Boolean read FLogRefCount write FLogRefCount; {$ENDIF} property RefCount: Integer read FRefCount; end; TcaInterfacedPersistentClass = class of TcaInterfacedPersistent; //---------------------------------------------------------------------------- // IcaString   //---------------------------------------------------------------------------- IcaString = interface ['{48FDBB25-74B3-4A99-B048-0C36ADC0F1F4}'] // Property methods  function GetS: String; procedure SetS(const Value: String); // Interface methods  function EndsWith(const AValue: string): Boolean; function IsNumChar(N: Integer): Boolean; function Left(N: Integer): String; function Length: Integer; function LowerCase: string; function Mid(N, ForN: Integer): String; function PadLeft(ALength: Integer): String; function PadRight(ALength: Integer): String; function PosFromEnd(const AFindStr: String): Integer; function PosFromStart(const AFindStr: String): Integer; function PreZero(ALength: Integer): String; function Reverse: String; function Right(const S: string; N: Integer): String; function Str2Float(const S: string; Default: Extended): Extended; function Str2Int(const S: string; Default: Integer): Integer; function UpperCase: string; procedure Add(const S: String); procedure CleanIntString(var S: string); procedure CleanNumString(var S: string); procedure DeleteFromEnd(var S: string; N: Integer); procedure DeleteFromStart(var S: string; N: Integer); procedure SplitCamelCaps; procedure StripChar(C: Char); // Properties  property S: String read GetS write SetS; end; //---------------------------------------------------------------------------- // TcaString   //---------------------------------------------------------------------------- TcaString = class(TInterfacedObject, IcaString) private // Property fields  FS: String; // Property methods  function GetS: String; procedure SetS(const Value: String); public // Create/Destroy  constructor Create(AString: String); overload; constructor Create(AInteger: Integer); overload; // Interface methods  function EndsWith(const AValue: string): Boolean; function IsNumChar(N: Integer): Boolean; function Left(N: Integer): String; function Length: Integer; function LowerCase: string; function Mid(N, ForN: Integer): String; function PadLeft(ALength: Integer): String; function PadRight(ALength: Integer): String; function PosFromEnd(const AFindStr: String): Integer; function PosFromStart(const AFindStr: String): Integer; function PreZero(ALength: Integer): String; function Ref: Integer; function Reverse: String; function Right(N: Integer): String; function UpperCase: string; procedure Add(const S: String); procedure DeleteFromEnd(N: Integer); procedure DeleteFromStart(N: Integer); procedure SplitCamelCaps; // Properties  property S: String read GetS write SetS; end; //---------------------------------------------------------------------------- // IcaByteString   //---------------------------------------------------------------------------- IcaByteString = interface ['{9BCD9406-CE4F-420A-A6CD-6383DFDDAE98}'] // Property methods  function GetAsString: string; function GetByte(Index: Integer): Byte; function GetCount: Integer; procedure SetAsString(const Value: string); procedure SetByte(Index: Integer; const Value: Byte); procedure SetCount(const Value: Integer); // Interface methods  procedure Clear; // Properties  property AsString: string read GetAsString write SetAsString; property Bytes[Index: Integer]: Byte read GetByte write SetByte; property Count: Integer read GetCount write SetCount; end; //---------------------------------------------------------------------------- // TcaByteString   //---------------------------------------------------------------------------- TcaByteString = class(TcaString, IcaByteString) private // Property methods  function GetAsString: string; function GetByte(Index: Integer): Byte; function GetCount: Integer; procedure SetAsString(const Value: string); procedure SetByte(Index: Integer; const Value: Byte); procedure SetCount(const Value: Integer); // Private methods  function ByteToStr(AByte: Byte): string; procedure CheckIndex(Index: Integer); procedure GetAsStrings(AStrings: TStrings); procedure SetAsStrings(AStrings: TStrings); public // Create/Destroy  constructor Create(ACount: Integer); overload; // Interface methods  procedure Clear; // Properties  property AsString: string read GetAsString write SetAsString; property Bytes[Index: Integer]: Byte read GetByte write SetByte; property Count: Integer read GetCount write SetCount; end; //---------------------------------------------------------------------------- // IcaStringList   //---------------------------------------------------------------------------- IcaStringList = interface ['{B4DCD412-9B9B-4C52-8AC8-B4F5144750F2}'] // TStrings private  function GetAdapter: IStringsAdapter; function GetCommaText: string; function GetDuplicates: TDuplicates; function GetName(Index: Integer): string; function GetSorted: Boolean; function GetValue(const Name: string): string; procedure SetCommaText(const Value: string); procedure SetDuplicates(const Value: TDuplicates); procedure SetSorted(const Value: Boolean); procedure SetStringsAdapter(const Value: IStringsAdapter); procedure SetValue(const Name, Value: string); // TStrings protected  function Get(Index: Integer): string; function GetCapacity: Integer; function GetCount: Integer; function GetObject(Index: Integer): TObject; function GetTextStr: string; procedure DefineProperties(Filer: TFiler); procedure Put(Index: Integer; const S: string); procedure PutObject(Index: Integer; AObject: TObject); procedure SetCapacity(NewCapacity: Integer); procedure SetTextStr(const Value: string); procedure SetUpdateState(Updating: Boolean); // TStrings public  function Add(const S: string): Integer; overload; function Add(const S: string; const Args: array of const): Integer; overload; function AddObject(const S: string; AObject: TObject): Integer; function Equals(Strings: TStrings): Boolean; function GetText: PChar; function IndexOf(const S: string): Integer; function IndexOfName(const Name: string): Integer; function IndexOfObject(AObject: TObject): Integer; procedure AddStrings(AStrings: TStrings); overload; procedure AddStrings(AStrings: IcaStringList); overload; procedure AddStrings(AStrings: array of string); overload; procedure Append(const S: string); procedure Assign(Source: TPersistent); procedure BeginUpdate; procedure Clear; procedure Delete(Index: Integer); procedure EndUpdate; procedure Exchange(Index1, Index2: Integer); procedure Insert(Index: Integer; const S: string); procedure InsertObject(Index: Integer; const S: string; AObject: TObject); procedure LoadFromFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure Move(CurIndex, NewIndex: Integer); procedure SaveToFile(const FileName: string); procedure SaveToStream(Stream: TStream); procedure SetText(Text: PChar); procedure Sort; // Properties  property Capacity: Integer read GetCapacity write SetCapacity; property CommaText: string read GetCommaText write SetCommaText; property Count: Integer read GetCount; property Duplicates: TDuplicates read GetDuplicates write SetDuplicates; property Names[Index: Integer]: string read GetName; property Objects[Index: Integer]: TObject read GetObject write PutObject; property Sorted: Boolean read GetSorted write SetSorted; property Strings[Index: Integer]: string read Get write Put; default; property StringsAdapter: IStringsAdapter read GetAdapter write SetStringsAdapter; property Text: string read GetTextStr write SetTextStr; property Values[const Name: string]: string read GetValue write SetValue; // New ca methods + properties  function Contains(const AString: String): Boolean; function GetHigh: Integer; function GetLow: Integer; function GetStrings: TStrings; function IsIndexValid(AIndex: Integer): Boolean; function IndexOfWidest: Integer; function WidthOfWidest: Integer; procedure ReadData(Reader: TReader); procedure WriteData(Writer: TWriter); property High: Integer read GetHigh; property Low: Integer read GetLow; end; //--------------------------------------------------------------------------- // IcaStringStack   //--------------------------------------------------------------------------- IcaStringStack = interface ['{B021D469-AE1F-428D-AFA8-8C832128B6E6}'] // Interface methods  function HasItems: Boolean; function IsEmpty: Boolean; function Peek: String; function Pop: String; function Push(const AItem: String): Integer; function Size: Integer; end; //--------------------------------------------------------------------------- // TcaStringList   //--------------------------------------------------------------------------- TcaStringList = class(TcaInterfacedPersistent, IcaStringList, IcaStringStack, IcaLoggable) private FStrings: TStrings; FAdapter: IStringsAdapter; // IcaStringList new methods  procedure ReadData(Reader: TReader); procedure WriteData(Writer: TWriter); protected // Protected interface property methods  function GetAdapter: IStringsAdapter; function GetCommaText: string; function GetDuplicates: TDuplicates; function GetName(Index: Integer): string; function GetSorted: Boolean; function GetValue(const Name: string): string; procedure SetCommaText(const Value: string); procedure SetDuplicates(const Value: TDuplicates); procedure SetSorted(const Value: Boolean); procedure SetStringsAdapter(const Value: IStringsAdapter); procedure SetValue(const Name, Value: string); // IcaStringList new property methods  function GetHigh: Integer; function GetLow: Integer; // Protected virtual methods  function Get(Index: Integer): string; virtual; function GetCapacity: Integer; virtual; function GetCount: Integer; virtual; function GetObject(Index: Integer): TObject; virtual; function GetTextStr: string; virtual; procedure DefineProperties(Filer: TFiler); override; procedure Error(const Msg: string; Data: Integer); overload; procedure Error(Msg: PResStringRec; Data: Integer); overload; procedure Put(Index: Integer; const S: string); virtual; procedure PutObject(Index: Integer; AObject: TObject); virtual; procedure SetCapacity(NewCapacity: Integer); virtual; procedure SetTextStr(const Value: string); virtual; procedure SetUpdateState(Updating: Boolean); virtual; public constructor Create; overload; constructor Create(const AString: string); overload; constructor Create(AStrings: TStrings); overload; constructor Create(AStrings: array of String); overload; destructor Destroy; override; function Add(const S: string): Integer; overload; virtual; function Add(const S: string; const Args: array of const): Integer; overload; virtual; function AddObject(const S: string; AObject: TObject): Integer; virtual; function Equals(Strings: TStrings): Boolean; function GetStrings: TStrings; function GetText: PChar; virtual; function IndexOf(const S: string): Integer; virtual; function IndexOfName(const Name: string): Integer; function IndexOfObject(AObject: TObject): Integer; procedure AddStrings(AStrings: TStrings); overload; virtual; procedure AddStrings(AStrings: IcaStringList); overload; virtual; procedure AddStrings(AStrings: array of string); overload; procedure Append(const S: string); procedure Assign(Source: TPersistent); override; procedure AssignFromInterface(Source: IUnknown); override; procedure AssignFromObject(Source: TPersistent); override; procedure BeginUpdate; procedure Clear; virtual; procedure Delete(Index: Integer); virtual; procedure EndUpdate; procedure Exchange(Index1, Index2: Integer); virtual; procedure Insert(Index: Integer; const S: string); virtual; procedure InsertObject(Index: Integer; const S: string; AObject: TObject); procedure LoadFromFile(const FileName: string); virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure Move(CurIndex, NewIndex: Integer); virtual; procedure SaveToFile(const FileName: string); virtual; procedure SaveToStream(Stream: TStream); virtual; procedure SetText(Text: PChar); virtual; procedure Sort; // Properties  property Capacity: Integer read GetCapacity write SetCapacity; property CommaText: string read GetCommaText write SetCommaText; property Count: Integer read GetCount; property Duplicates: TDuplicates read GetDuplicates write SetDuplicates; property Names[Index: Integer]: string read GetName; property Objects[Index: Integer]: TObject read GetObject write PutObject; property Sorted: Boolean read GetSorted write SetSorted; property Strings[Index: Integer]: string read Get write Put; default; property StringsAdapter: IStringsAdapter read FAdapter write SetStringsAdapter; property Text: string read GetTextStr write SetTextStr; property Values[const Name: string]: string read GetValue write SetValue; // IcaStringList new methods + properties  function Contains(const AString: String): Boolean; function IndexOfWidest: Integer; function IsIndexValid(AIndex: Integer): Boolean; function WidthOfWidest: Integer; property High: Integer read GetHigh; property Low: Integer read GetLow; // IcaStringStack  function HasItems: Boolean; function IsEmpty: Boolean; function Peek: String; function Pop: String; function Push(const AItem: String): Integer; function Size: Integer; // IcaLoggable  procedure SendToLog(const AMsg: String; AClearLog: Boolean = False); end; //--------------------------------------------------------------------------- // IcaComponentState   //--------------------------------------------------------------------------- IcaComponentState = interface ['{2C6F6EBB-9D75-4D76-9452-CC9DE84231CD}'] function GetComponent: TComponent; function GetIsAncestor: Boolean; function GetIsDesigning: Boolean; function GetIsDestroying: Boolean; function GetIsFixups: Boolean; function GetIsFreeNotification: Boolean; function GetIsInline: Boolean; function GetIsLoading: Boolean; function GetIsReading: Boolean; function GetIsRunTime: Boolean; function GetIsUpdating: Boolean; function GetIsWriting: Boolean; procedure SetComponent(const Value: TComponent); property Component: TComponent read GetComponent write SetComponent; property IsAncestor: Boolean read GetIsAncestor; property IsDesigning: Boolean read GetIsDesigning; property IsDestroying: Boolean read GetIsDestroying; property IsFixups: Boolean read GetIsFixups; property IsFreeNotification: Boolean read GetIsFreeNotification; property IsInline: Boolean read GetIsInline; property IsLoading: Boolean read GetIsLoading; property IsReading: Boolean read GetIsReading; property IsRunTime: Boolean read GetIsRunTime; property IsUpdating: Boolean read GetIsUpdating; property IsWriting: Boolean read GetIsWriting; end; //--------------------------------------------------------------------------- // TcaComponentState   //--------------------------------------------------------------------------- TcaComponentState = class(TInterfacedObject, IcaComponentState) private FComponent: TComponent; function GetComponent: TComponent; function GetIsAncestor: Boolean; function GetIsDesigning: Boolean; function GetIsDestroying: Boolean; function GetIsFixups: Boolean; function GetIsFreeNotification: Boolean; function GetIsInline: Boolean; function GetIsLoading: Boolean; function GetIsReading: Boolean; function GetIsRunTime: Boolean; function GetIsUpdating: Boolean; function GetIsWriting: Boolean; procedure SetComponent(const Value: TComponent); public constructor Create(AComponent: TComponent); overload; property Component: TComponent read GetComponent write SetComponent; property IsAncestor: Boolean read GetIsAncestor; property IsDesigning: Boolean read GetIsDesigning; property IsDestroying: Boolean read GetIsDestroying; property IsFixups: Boolean read GetIsFixups; property IsFreeNotification: Boolean read GetIsFreeNotification; property IsInline: Boolean read GetIsInline; property IsLoading: Boolean read GetIsLoading; property IsReading: Boolean read GetIsReading; property IsRunTime: Boolean read GetIsRunTime; property IsUpdating: Boolean read GetIsUpdating; property IsWriting: Boolean read GetIsWriting; end; //--------------------------------------------------------------------------- // IcaList   //--------------------------------------------------------------------------- TcaList = class; IcaList = interface ['{B01C4736-8D07-48B0-9979-7285AE28A9A7}'] // Property methods  function GetCapacity: Integer; function GetCount: Integer; function GetList: TList; procedure SetCapacity(const Value: Integer); procedure SetCount(const Value: Integer); // Public methods  function Expand: TList; procedure Clear; procedure CopyList(AList: TList); procedure CopyTo(SourceList: TcaList); overload; procedure CopyTo(SourceList: IcaList); overload; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); procedure Move(CurIndex, NewIndex: Integer); procedure Pack; procedure Sort(Compare: TListSortCompare); // Properties  property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property List: TList read GetList; end; //--------------------------------------------------------------------------- // TcaList   //--------------------------------------------------------------------------- TcaList = class(TInterfacedObject, IcaList) private FList: TList; function GetCapacity: Integer; function GetCount: Integer; function GetList: TList; procedure SetCapacity(const Value: Integer); procedure SetCount(const Value: Integer); protected // Protected methods  procedure CopyList(AList: TList); public constructor Create; destructor Destroy; override; function Expand: TList; procedure Clear; procedure CopyTo(SourceList: TcaList); overload; procedure CopyTo(SourceList: IcaList); overload; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); procedure Move(CurIndex, NewIndex: Integer); procedure Pack; procedure Sort(Compare: TListSortCompare); property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property List: TList read GetList; end; //--------------------------------------------------------------------------- // IcaPointerList   //--------------------------------------------------------------------------- IcaPointerList = interface ['{3136D62F-00BF-4E07-9DB6-A41CB71CAB0E}'] // Property methods  function GetItem(Index: Integer): Pointer; procedure SetItem(Index: Integer; const AItem: Pointer); // Public methods  function Add(AItem: Pointer; Unique: Boolean = False): Integer; function Extract(AItem: Pointer): Pointer; function First: Pointer; function IndexOf(AItem: Pointer): Integer; function Last: Pointer; function Remove(AItem: Pointer): Integer; procedure Insert(Index: Integer; AItem: Pointer); // Properties  property Items[Index: Integer]: Pointer read GetItem write SetItem; default; end; //--------------------------------------------------------------------------- // IcaPointerStack   //--------------------------------------------------------------------------- IcaPointerStack = interface ['{E1A286D0-F5A6-4758-993E-BF6DCE07D300}'] // Interface methods  function HasItems: Boolean; function IsEmpty: Boolean; function Peek: Pointer; function Pop: Pointer; function Push(AItem: Pointer): Integer; function Size: Integer; end; //--------------------------------------------------------------------------- // TcaPointerList   //--------------------------------------------------------------------------- TcaPointerList = class(TInterfacedObject, IcaList, IcaPointerList, IcaPointerStack) private // Private fields  FListBase: IcaList; // Property methods  function GetItem(Index: Integer): Pointer; procedure SetItem(Index: Integer; const Value: Pointer); public constructor Create; // Public methods  function Add(AItem: Pointer; Unique: Boolean = False): Integer; function Extract(AItem: Pointer): Pointer; function First: Pointer; function IndexOf(AItem: Pointer): Integer; function Last: Pointer; function Remove(AItem: Pointer): Integer; procedure Insert(Index: Integer; AItem: Pointer); // IcaPointerList interface methods  function HasItems: Boolean; function IsEmpty: Boolean; function Peek: Pointer; function Pop: Pointer; function Push(AItem: Pointer): Integer; function Size: Integer; // Properties  property Items[Index: Integer]: Pointer read GetItem write SetItem; default; property ListBase: IcaList read FListBase implements IcaList; end; //--------------------------------------------------------------------------- // IcaObjectList   //--------------------------------------------------------------------------- IcaObjectList = interface ['{63181262-097A-4006-A50C-6556BDF9E8E7}'] // Property methods  function GetItem(Index: Integer): TObject; procedure SetItem(Index: Integer; const AItem: TObject); // Public methods  function Add(AItem: TObject; Unique: Boolean = False): Integer; function Extract(AItem: TObject): TObject; function First: TObject; function IndexOf(AItem: TObject): Integer; function Last: TObject; function Remove(AItem: TObject): Integer; procedure Insert(Index: Integer; AItem: TObject); // Properties  property Items[Index: Integer]: TObject read GetItem write SetItem; default; end; //--------------------------------------------------------------------------- // IcaObjectStack   //--------------------------------------------------------------------------- IcaObjectStack = interface ['{E6DE2996-6601-41ED-8343-0EF115BDEEC7}'] // Interface methods   function HasItems: Boolean; function IsEmpty: Boolean; function Peek: TObject; function Pop: TObject; function Push(AItem: TObject): Integer; function Size: Integer; end; //--------------------------------------------------------------------------- // TcaObjectList   //--------------------------------------------------------------------------- TcaObjectList = class(TInterfacedObject, IcaList, IcaObjectList, IcaObjectStack) private FListBase: IcaList; function GetItem(Index: Integer): TObject; procedure SetItem(Index: Integer; const Value: TObject); public constructor Create; // Public methods  function Add(AItem: TObject; Unique: Boolean = False): Integer; function Extract(AItem: TObject): TObject; function First: TObject; function IndexOf(AItem: TObject): Integer; function Last: TObject; function Remove(AItem: TObject): Integer; procedure Insert(Index: Integer; AItem: TObject); // IcaObjectList interface methods  function HasItems: Boolean; function IsEmpty: Boolean; function Peek: TObject; function Pop: TObject; function Push(AItem: TObject): Integer; function Size: Integer; // Properties  property Items[Index: Integer]: TObject read GetItem write SetItem; default; property ListBase: IcaList read FListBase implements IcaList; end; //--------------------------------------------------------------------------- // IcaSparseMatrix   //--------------------------------------------------------------------------- IcaSparseMatrix = interface ['{49F7CC68-7362-47D3-9D43-CB8C16015E7C}'] // Property methods  function GetColCount: Integer; function GetItem(ACol, ARow: Integer): Pointer; function GetRowCount: Integer; procedure SetColCount(const Value: Integer); procedure SetItem(ACol, ARow: Integer; const Value: Pointer); procedure SetRowCount(const Value: Integer); // Properties  property ColCount: Integer read GetColCount write SetColCount; property Items[ACol, ARow: Integer]: Pointer read GetItem write SetItem; default; property RowCount: Integer read GetRowCount write SetRowCount; // Public methods  procedure ReleaseElement(ACol, ARow: Integer); procedure ReleaseElements; end; //--------------------------------------------------------------------------- // TcaSparseMatrix   //--------------------------------------------------------------------------- TcaSparseMatrix = class(TInterfacedObject, IcaSparseMatrix) private // Private fields  FCols: TList; FRowCount: Integer; // Property methods  function GetColCount: Integer; function GetItem(ACol, ARow: Integer): Pointer; function GetRowCount: Integer; procedure SetColCount(const Value: Integer); procedure SetItem(ACol, ARow: Integer; const Value: Pointer); procedure SetRowCount(const Value: Integer); // Private methods  procedure FreeRows; public constructor Create; destructor Destroy; override; // Public methods  procedure ReleaseElement(ACol, ARow: Integer); procedure ReleaseElements; // Properties  property ColCount: Integer read GetColCount write SetColCount; property Items[ACol, ARow: Integer]: Pointer read GetItem write SetItem; default; property RowCount: Integer read GetRowCount write SetRowCount; end; //--------------------------------------------------------------------------- // IcaStringCase   //--------------------------------------------------------------------------- IcaStringCase = interface ['{B200E7CD-996D-43FE-86C5-964F3EB32458}'] function CaseOf(const AString: String): Integer; procedure AddOption(const AOption: String); end; //--------------------------------------------------------------------------- // TcaStringCase   //--------------------------------------------------------------------------- TcaStringCase = class(TcaInterfacedPersistent, IcaStringCase) private FOptions: TcaStringList; public constructor Create(const AOptions: array of String); destructor Destroy; override; // Public methods  function CaseOf(const AString: String): Integer; procedure AddOption(const AOption: String); end; //--------------------------------------------------------------------------- // IcaArgs   //--------------------------------------------------------------------------- IcaArgs = interface ['{D0C1FFE0-2E69-4DF0-BDCC-15DFD095D9AA}'] // Property methods  function Get(Index: Integer): string; function GetCount: Integer; function GetExecutable: String; function GetValue(const Name: string): string; procedure Put(Index: Integer; const S: string); procedure SetValue(const Name, Value: string); // Public methods  function HasArg(const AArg: String): Boolean; // Properties  property Count: Integer read GetCount; property Executable: String read GetExecutable; property Strings[Index: Integer]: string read Get write Put; default; property Values[const Name: string]: string read GetValue write SetValue; end; //--------------------------------------------------------------------------- // TcaArgs   //--------------------------------------------------------------------------- TcaArgs = class(TcaStringList, IcaArgs) private // Property methods  function GetExecutable: String; // Private methods  procedure UpdateArgs; protected // IcaArgs methods  function HasArg(const AArg: String): Boolean; public // Public overridden methods  procedure AfterConstruction; override; // Properties  property Executable: String read GetExecutable; end; //--------------------------------------------------------------------------- // IcaAutoFree   //--------------------------------------------------------------------------- IcaAutoFree = interface ['{FEC11200-4C4E-49D7-9F9F-C7178A687DA4}'] // Property methods  function GetInstance: Pointer; // Properties  property Instance: Pointer read GetInstance; end; //--------------------------------------------------------------------------- // TcaAutoFree   //--------------------------------------------------------------------------- TcaAutoFree = class(TcaInterfacedPersistent, IcaAutoFree) private // Private fields  FInstance: TObject; // Property methods  function GetInstance: Pointer; public constructor Create(AInstance: TObject); destructor Destroy; override; end; //--------------------------------------------------------------------------- // TcaProperties   //--------------------------------------------------------------------------- TcaProperties = class(TPersistent) protected // Protected virtual methods  procedure Finalize; virtual; procedure Initialize; virtual; public // Create/Destroy  constructor Create; destructor Destroy; override; end; //--------------------------------------------------------------------------- // TcaNotifyProperties   //--------------------------------------------------------------------------- TcaNotifyProperties = class(TcaProperties) private // Private fields  FNotifyMethod: TcaProcedure; protected // Protected static methods  procedure Changed; procedure SetBooleanProperty(var AProperty: Boolean; AValue: Boolean); procedure SetIntegerProperty(var AProperty: Integer; AValue: Integer); // Protected properties  property NotifyMethod: TcaProcedure read FNotifyMethod; public // Create/Destroy  constructor Create(ANotifyMethod: TcaProcedure); virtual; destructor Destroy; override; end; function Auto(AInstance: TObject): IcaAutoFree; var caInterfaceBalance: Int64 = 0; {$IFDEF D5} function Supports(const Instance: IUnknown; const Intf: TGUID): Boolean; overload; {$ENDIF} implementation uses // Standard Delphi units;  Consts, SysConst, // ca units  caConsts, caMath, caUtils; {$IFDEF D5} function Supports(const Instance: IUnknown; const Intf: TGUID): Boolean; var Unk: IUnknown; begin Result := Sysutils.Supports(Instance, Intf, Unk); end; {$ENDIF} //---------------------------------------------------------------------------- // TcaInterfacedPersistent   //---------------------------------------------------------------------------- function InterlockedIncrement(var Addend: Integer): Integer; stdcall; external cKernel name 'InterlockedIncrement'; function InterlockedDecrement(var Addend: Integer): Integer; stdcall; external cKernel name 'InterlockedDecrement'; constructor TcaInterfacedPersistent.CreateNonRefCounted; begin inherited Create; FNoRefCount := True; end; procedure TcaInterfacedPersistent.AfterConstruction; begin InterlockedDecrement(FRefCount); {$IFDEF LOG_REF_COUNT} FLogRefCount := True; {$ENDIF} {$IFDEF LOG_CREATE_DESTROY} FLogCreateAndDestroy := True; Inc(caInterfaceBalance); if FLogCreateAndDestroy then Log.Send(ClassName + ' - Create', caInterfaceBalance); {$ENDIF} end; procedure TcaInterfacedPersistent.BeforeDestruction; begin if RefCount <> 0 then raise Exception.Create(SInvalidPointer + ' in ' + ClassName); {$IFDEF LOG_CREATE_DESTROY} Dec(caInterfaceBalance); if FLogCreateAndDestroy then Log.Send(ClassName + ' - Destroy', caInterfaceBalance); {$ENDIF} end; class function TcaInterfacedPersistent.NewInstance: TObject; begin Result := inherited NewInstance; TcaInterfacedPersistent(Result).FRefCount := 1; end; function TcaInterfacedPersistent._AddRef: Integer; begin if FNoRefCount then Result := -1 else Result := InterlockedIncrement(FRefCount); {$IFDEF LOG_REF_COUNT} if FLogRefCount then Log.Send(ClassName + ' - _AddRef: ', FRefCount); {$ENDIF} end; function TcaInterfacedPersistent._Release: Integer; begin if FNoRefCount then Result := -1 else begin Result := InterlockedDecrement(FRefCount); {$IFDEF LOG_REF_COUNT} if FLogRefCount then Log.Send(ClassName + ' - _Release: ', FRefCount); {$ENDIF} if Result = 0 then Destroy; end; end; function TcaInterfacedPersistent.QueryInterface(const IID: TGUID; out Obj): HResult; const E_NOINTERFACE = HResult($80004002); begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; // Owned list object support  procedure TcaInterfacedPersistent.ClearListObjects(AList: TList); var Index: Integer; begin for Index := 0 to Pred(AList.Count) do TObject(AList[Index]).Free; AList.Clear; end; // IcaAssignable  procedure TcaInterfacedPersistent.AssignFromInterface(Source: IUnknown); var SourceObject: TcaInterfacedPersistent; SourceCloneable: IcaCloneable; begin if Supports(Source, IcaCloneable, SourceCloneable) then begin SourceObject := SourceCloneable.CloneAsObject; try AssignFromObject(SourceObject); finally SourceObject.Free; end; end; end; procedure TcaInterfacedPersistent.AssignFromObject(Source: TPersistent); begin if not Utils.ShallowCopy(Source, Self, True) then inherited Assign(Source); end; // IcaCloneable  function TcaInterfacedPersistent.CloneAsInterface: IUnknown; var Assignable: IcaAssignable; CloneClass: TcaInterfacedPersistentClass; begin CloneClass := TcaInterfacedPersistentClass(ClassType); Result := CloneClass.Create; Assignable := Result as IcaAssignable; Assignable.AssignFromObject(Self); end; function TcaInterfacedPersistent.CloneAsObject: TcaInterfacedPersistent; var CloneClass: TcaInterfacedPersistentClass; begin CloneClass := TcaInterfacedPersistentClass(ClassType); Result := CloneClass.Create; Result.AssignFromObject(Self); end; //---------------------------------------------------------------------------- // TcaString   //---------------------------------------------------------------------------- constructor TcaString.Create(AString: String); begin inherited Create; FS := AString; end; procedure TcaString.Add(const S: String); begin FS := FS + S; end; constructor TcaString.Create(AInteger: Integer); begin inherited Create; FS := IntToStr(AInteger); end; procedure TcaString.DeleteFromStart(N: Integer); begin FS := Right(Length - N); end; procedure TcaString.DeleteFromEnd(N: Integer); begin FS := Left(Length - N); end; function TcaString.GetS: String; begin Result := FS; end; function TcaString.EndsWith(const AV: string): Boolean; var RightSub: string; begin Result := False; if System.Length(S) <= Length then begin RightSub := Right(System.Length(S)); Result := RightSub = S; end; end; function TcaString.IsNumChar(N: Integer): Boolean; var Validator: IcaValidNum; NumStr: String; begin Validator := TcaValidNum.Create(vtFloat); NumStr := Mid(N, 1); Validator.NumString := NumStr; Result := Validator.IsValid; end; function TcaString.Left(N: Integer): String; begin Result := Copy(FS, 1, N); end; function TcaString.Length: Integer; begin Result := System.Length(FS); end; function TcaString.Mid(N, ForN: Integer): String; begin Result := Copy(FS, N, ForN); end; function TcaString.PadRight(ALength: Integer): String; begin Result := Utils.PadRight(FS, ' ', ALength); end; function TcaString.PadLeft(ALength: Integer): String; begin Result := Utils.PadLeft(FS, ' ', ALength); end; function TcaString.PreZero(ALength: Integer): String; begin Result := Utils.PadLeft(FS, '0', ALength); end; function TcaString.PosFromEnd(const AFindStr: String): Integer; var FindStr: IcaString; RevFindStr: String; RevStr: String; PosVal: Integer; begin FindStr := TcaString.Create(AFindStr); RevFindStr := FindStr.Reverse; RevStr := Reverse; PosVal := Utils.PosFromStart(RevFindStr, RevStr); Result := PosVal; if PosVal > 0 then Result := Length - PosVal - FindStr.Length + 2; end; function TcaString.PosFromStart(const AFindStr: String): Integer; begin Result := Utils.PosFromStart(AFindStr, S); end; function TcaString.Ref: Integer; begin Result := RefCount; end; function TcaString.Reverse: String; var Index: Integer; Len: Integer; begin Len := Length; SetLength(Result, Len); for Index := Len downto 1 do Result[Len - Index + 1] := FS[Index]; end; function TcaString.Right(N: Integer): String; begin Result := Copy(FS, Length - N + 1, N); end; procedure TcaString.SetS(const Value: String); begin FS := Value; end; procedure TcaString.LowerCase; begin FS := SysUtils.LowerCase(FS); end; procedure TcaString.SplitCamelCaps; begin Utils.SplitCamelCaps(FS); end; procedure TcaString.UpperCase; begin FS := SysUtils.UpperCase(FS); end; //---------------------------------------------------------------------------- // TcaByteString   //---------------------------------------------------------------------------- // Create/Destroy  constructor TcaByteString.Create(ACount: Integer); begin inherited Create; SetCount(ACount); end; // Interface methods  procedure TcaByteString.Clear; begin S := ''; end; // Private methods  function TcaByteString.ByteToStr(AByte: Byte): string; begin Result := Format('%.2x', [AByte]); end; procedure TcaByteString.CheckIndex(Index: Integer); begin if Index >= GetCount then SetCount(Succ(Index)); end; procedure TcaByteString.GetAsStrings(AStrings: TStrings); var Index: Integer; begin AStrings.Clear; Index := 1; while Index <= Length do begin AStrings.Add(Copy(S, Index, 2)); Inc(Index, 2); end; end; procedure TcaByteString.SetAsStrings(AStrings: TStrings); var Index: Integer; begin Clear; for Index := 0 to Pred(AStrings.Count) do Add(AStrings[Index]); end; // Property methods  function TcaByteString.GetAsString: string; begin Result := S; end; function TcaByteString.GetByte(Index: Integer): Byte; var Offset: Integer; begin CheckIndex(Index); Offset := Succ(Index * 2); Result := StrToInt('$' + Copy(S, Offset, 2)); end; function TcaByteString.GetCount: Integer; begin Result := Length div 2; end; procedure TcaByteString.SetAsString(const Value: string); begin S := Value; end; procedure TcaByteString.SetByte(Index: Integer; const Value: Byte); var Strings: TStrings; begin CheckIndex(Index); Strings := Auto(TStringList.Create).Instance; GetAsStrings(Strings); Strings[Index] := ByteToStr(Value); SetAsStrings(Strings); end; procedure TcaByteString.SetCount(const Value: Integer); begin while GetCount < Value do S := S + '00'; end; //---------------------------------------------------------------------------- // TcaStringList   //---------------------------------------------------------------------------- type TcaStringList_Protected = class(TStringList); constructor TcaStringList.Create; begin inherited; FStrings := TStringList.Create; end; constructor TcaStringList.Create(const AString: string); begin inherited Create; FStrings := TStringList.Create; FStrings.Text := AString; end; constructor TcaStringList.Create(AStrings: TStrings); begin inherited Create; FStrings := TStringList.Create; FStrings.Assign(AStrings); end; constructor TcaStringList.Create(AStrings: array of String); var Index: Integer; begin inherited Create; FStrings := TStringList.Create; for Index := System.Low(AStrings) to System.High(AStrings) do FStrings.Add(AStrings[Index]); end; destructor TcaStringList.Destroy; begin FStrings.Free; inherited; end; function TcaStringList.Add(const S: string): Integer; begin Result := FStrings.Add(S); end; function TcaStringList.Add(const S: string; const Args: array of const): Integer; begin Result := Add(Format(S, Args)); end; function TcaStringList.AddObject(const S: string; AObject: TObject): Integer; begin Result := FStrings.AddObject(S, AObject); end; procedure TcaStringList.AddStrings(AStrings: TStrings); begin FStrings.AddStrings(AStrings); end; procedure TcaStringList.AddStrings(AStrings: IcaStringList); begin FStrings.AddStrings(AStrings.GetStrings); end; procedure TcaStringList.AddStrings(AStrings: array of string); var Index: Integer; begin for Index := System.Low(AStrings) to System.High(AStrings) do Add(AStrings[Index]); end; procedure TcaStringList.Append(const S: string); begin FStrings.Append(S); end; procedure TcaStringList.Assign(Source: TPersistent); begin if (Source is TcaStringList) or (Source is TStrings) then begin BeginUpdate; try Clear; if Source is TcaStringList then AddStrings(TcaStringList(Source).GetStrings) else AddStrings(TStrings(Source)); finally EndUpdate; end; end else inherited Assign(Source); end; procedure TcaStringList.AssignFromInterface(Source: IUnknown); var AStringList: IcaStringList; begin if Supports(Source, IcaStringList, AStringList) then AssignFromObject(AStringList.GetStrings); end; procedure TcaStringList.AssignFromObject(Source: TPersistent); begin Assign(Source); end; procedure TcaStringList.BeginUpdate; begin FStrings.BeginUpdate; end; procedure TcaStringList.Clear; begin FStrings.Clear; end; function TcaStringList.Contains(const AString: String): Boolean; begin Result := FStrings.IndexOf(AString) >= 0; end; procedure TcaStringList.ReadData(Reader: TReader); begin Reader.ReadListBegin; BeginUpdate; try Clear; while not Reader.EndOfList do Add(Reader.ReadString); finally EndUpdate; end; Reader.ReadListEnd; end; procedure TcaStringList.WriteData(Writer: TWriter); var I: Integer; begin Writer.WriteListBegin; for I := 0 to Count - 1 do Writer.WriteString(Get(I)); Writer.WriteListEnd; end; procedure TcaStringList.DefineProperties(Filer: TFiler); function DoWrite: Boolean; begin if Filer.Ancestor <> nil then begin Result := True; if Filer.Ancestor is TStrings then Result := not Equals(TStrings(Filer.Ancestor)) end else Result := Count > 0; end; begin Filer.DefineProperty('Strings', ReadData, WriteData, DoWrite); end; procedure TcaStringList.Delete(Index: Integer); begin FStrings.Delete(Index); end; procedure TcaStringList.EndUpdate; begin FStrings.EndUpdate; end; function TcaStringList.Equals(Strings: TStrings): Boolean; begin Result := FStrings.Equals(Strings); end; procedure TcaStringList.Error(Msg: PResStringRec; Data: Integer); begin Error(LoadResString(Msg), Data); end; procedure TcaStringList.Error(const Msg: string; Data: Integer); function ReturnAddr: Pointer; asm MOV EAX,[EBP+4] end; begin raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddr; end; procedure TcaStringList.Exchange(Index1, Index2: Integer); begin FStrings.Exchange(Index1, Index2); end; function TcaStringList.Get(Index: Integer): string; begin Result := FStrings.Strings[Index]; end; function TcaStringList.GetAdapter: IStringsAdapter; begin Result := FStrings.StringsAdapter; end; function TcaStringList.GetCapacity: Integer; begin Result := FStrings.Count; end; function TcaStringList.GetCommaText: string; begin Result := FStrings.CommaText; end; function TcaStringList.GetCount: Integer; begin Result := FStrings.Count; end; function TcaStringList.GetDuplicates: TDuplicates; begin Result := TStringList(FStrings).Duplicates; end; function TcaStringList.GetName(Index: Integer): string; begin Result := FStrings.Names[Index]; end; function TcaStringList.GetSorted: Boolean; begin Result := TStringList(FStrings).Sorted; end; function TcaStringList.GetObject(Index: Integer): TObject; begin Result := FStrings.Objects[Index]; end; function TcaStringList.GetText: PChar; begin Result := FStrings.GetText; end; function TcaStringList.GetTextStr: string; begin Result := FStrings.Text; end; function TcaStringList.GetValue(const Name: string): string; begin Result := FStrings.Values[Name]; end; function TcaStringList.IndexOf(const S: string): Integer; begin Result := FStrings.IndexOf(S); end; function TcaStringList.IndexOfName(const Name: string): Integer; begin Result := FStrings.IndexOfName(Name); end; function TcaStringList.IndexOfObject(AObject: TObject): Integer; begin Result := FStrings.IndexOfObject(AObject); end; procedure TcaStringList.InsertObject(Index: Integer; const S: string; AObject: TObject); begin FStrings.InsertObject(Index, S, AObject); end; procedure TcaStringList.LoadFromFile(const FileName: string); begin FStrings.LoadFromFile(FileName); end; procedure TcaStringList.LoadFromStream(Stream: TStream); begin FStrings.LoadFromStream(Stream); end; procedure TcaStringList.Move(CurIndex, NewIndex: Integer); begin FStrings.Move(CurIndex, NewIndex); end; procedure TcaStringList.Put(Index: Integer; const S: string); begin FStrings.Strings[Index] := S; end; procedure TcaStringList.PutObject(Index: Integer; AObject: TObject); begin FStrings.Objects[Index] := AObject; end; procedure TcaStringList.SaveToFile(const FileName: string); begin FStrings.SaveToFile(FileName); end; procedure TcaStringList.SaveToStream(Stream: TStream); begin FStrings.SaveToStream(Stream); end; procedure TcaStringList.SetCapacity(NewCapacity: Integer); begin FStrings.Capacity := NewCapacity; end; procedure TcaStringList.SetCommaText(const Value: string); begin FStrings.CommaText := Value; end; procedure TcaStringList.SetDuplicates(const Value: TDuplicates); begin TStringList(FStrings).Duplicates := Value; end; procedure TcaStringList.SetSorted(const Value: Boolean); begin TStringList(FStrings).Sorted := Value; end; procedure TcaStringList.SetStringsAdapter(const Value: IStringsAdapter); begin FStrings.StringsAdapter := Value; end; procedure TcaStringList.SetText(Text: PChar); begin FStrings.Text := String(Text); end; procedure TcaStringList.SetTextStr(const Value: string); begin FStrings.Text := Value; end; procedure TcaStringList.SetUpdateState(Updating: Boolean); begin TcaStringList_Protected(FStrings).SetUpdateState(Updating); end; procedure TcaStringList.SetValue(const Name, Value: string); begin FStrings.Values[Name] := Value; end; //--------------------------------------------------------------------------- // IcaStringList new methods   //--------------------------------------------------------------------------- function TcaStringList.GetHigh: Integer; begin Result := Count - 1; end; function TcaStringList.GetLow: Integer; begin Result := 0; end; function TcaStringList.GetStrings: TStrings; begin Result := FStrings; end; function TcaStringList.IndexOfWidest: Integer; var Index: Integer; Len: Integer; begin Result := -1; for Index := Low to High do begin Len := Length(Strings[Index]); if Len > Result then Result := Index; end; end; procedure TcaStringList.Insert(Index: Integer; const S: string); begin FStrings.Insert(Index, S); end; function TcaStringList.WidthOfWidest: Integer; var Widest: Integer; begin Result := 0; Widest := IndexOfWidest; if Widest >= 0 then Result := Length(Strings[Widest]);; end; // IcaStringStack  function TcaStringList.HasItems: Boolean; begin Result := not IsEmpty; end; function TcaStringList.IsEmpty: Boolean; begin Result := GetCount = 0; end; function TcaStringList.IsIndexValid(AIndex: Integer): Boolean; begin Result := (AIndex >= 0) and (AIndex < GetCount); end; function TcaStringList.Peek: String; begin if GetCount = 0 then Result := '' else Result := Strings[GetHigh]; end; function TcaStringList.Pop: String; begin if GetCount = 0 then Result := '' else begin Result := Peek; Delete(GetHigh); end; end; function TcaStringList.Push(const AItem: String): Integer; begin Result := Add(AItem); end; function TcaStringList.Size: Integer; begin Result := GetCount; end; procedure TcaStringList.Sort; begin TStringList(FStrings).Sort; end; // IcaLoggable  procedure TcaStringList.SendToLog(const AMsg: String; AClearLog: Boolean = False); var Index: Integer; begin if AClearLog then Log.Clear; if AMsg <> '' then Log.Send(AMsg); for Index := 0 to GetCount - 1 do Log.Send(FStrings[Index]); end; //--------------------------------------------------------------------------- // TcaComponentState   //--------------------------------------------------------------------------- constructor TcaComponentState.Create(AComponent: TComponent); begin inherited Create; FComponent := AComponent; end; function TcaComponentState.GetComponent: TComponent; begin Result := FComponent; end; function TcaComponentState.GetIsAncestor: Boolean; begin Result := csAncestor in FComponent.ComponentState; end; function TcaComponentState.GetIsDesigning: Boolean; begin Result := csDesigning in FComponent.ComponentState; end; function TcaComponentState.GetIsDestroying: Boolean; begin Result := csDestroying in FComponent.ComponentState; end; function TcaComponentState.GetIsFixups: Boolean; begin Result := csFixups in FComponent.ComponentState; end; function TcaComponentState.GetIsFreeNotification: Boolean; begin Result := csFreeNotification in FComponent.ComponentState; end; function TcaComponentState.GetIsInline: Boolean; begin Result := csInline in FComponent.ComponentState; end; function TcaComponentState.GetIsLoading: Boolean; begin Result := csLoading in FComponent.ComponentState; end; function TcaComponentState.GetIsReading: Boolean; begin Result := csReading in FComponent.ComponentState; end; function TcaComponentState.GetIsRunTime: Boolean; begin Result := not GetIsDesigning; end; function TcaComponentState.GetIsUpdating: Boolean; begin Result := csUpdating in FComponent.ComponentState; end; function TcaComponentState.GetIsWriting: Boolean; begin Result := csWriting in FComponent.ComponentState; end; procedure TcaComponentState.SetComponent(const Value: TComponent); begin FComponent := Value; end; //--------------------------------------------------------------------------- // TcaList   //--------------------------------------------------------------------------- constructor TcaList.Create; begin inherited; FList := TList.Create; end; destructor TcaList.Destroy; begin FList.Free; inherited; end; procedure TcaList.Clear; begin FList.Clear; end; procedure TcaList.CopyTo(SourceList: TcaList); begin SourceList.CopyList(FList); end; procedure TcaList.CopyTo(SourceList: IcaList); begin SourceList.CopyList(FList); end; procedure TcaList.Delete(Index: Integer); begin FList.Delete(Index); end; procedure TcaList.Exchange(Index1, Index2: Integer); begin FList.Exchange(Index1, Index2); end; function TcaList.Expand: TList; begin Result := FList.Expand; end; function TcaList.GetCapacity: Integer; begin Result := FList.Capacity; end; function TcaList.GetCount: Integer; begin Result := FList.Count; end; function TcaList.GetList: TList; begin Result := FList; end; procedure TcaList.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); end; procedure TcaList.Pack; begin FList.Pack; end; procedure TcaList.SetCapacity(const Value: Integer); begin FList.Capacity := Value; end; procedure TcaList.SetCount(const Value: Integer); begin FList.Count := Value; end; procedure TcaList.Sort(Compare: TListSortCompare); begin FList.Sort(Compare); end; // Protected methods  procedure TcaList.CopyList(AList: TList); var Index: Integer; begin Clear; for Index := 0 to Pred(GetCount) do FList.Add(AList[Index]); end; //--------------------------------------------------------------------------- // TcaPointerList   //--------------------------------------------------------------------------- constructor TcaPointerList.Create; begin inherited; FListBase := TcaList.Create; end; // Public methods  function TcaPointerList.Add(AItem: Pointer; Unique: Boolean = False): Integer; var ShouldAdd: Boolean; begin Result := -1; ShouldAdd := True; if Unique then ShouldAdd := IndexOf(AItem) = -1; if ShouldAdd then Result := FListBase.List.Add(AItem); end; function TcaPointerList.Extract(AItem: Pointer): Pointer; begin Result := FListBase.List.Extract(AItem); end; function TcaPointerList.First: Pointer; begin Result := FListBase.List.First; end; function TcaPointerList.IndexOf(AItem: Pointer): Integer; begin Result := FListBase.List.IndexOf(AItem); end; function TcaPointerList.Last: Pointer; begin Result := FListBase.List.Last; end; function TcaPointerList.Remove(AItem: Pointer): Integer; begin Result := FListBase.List.Remove(AItem); end; procedure TcaPointerList.Insert(Index: Integer; AItem: Pointer); begin FListBase.List.Insert(Index, AItem); end; // IcaPointerList interface methods  function TcaPointerList.HasItems: Boolean; begin Result := FListBase.Count <> 0; end; function TcaPointerList.IsEmpty: Boolean; begin Result := not HasItems; end; function TcaPointerList.Peek: Pointer; begin if FListBase.Count = 0 then Result := nil else Result := Last; end; function TcaPointerList.Pop: Pointer; begin Result := Peek; if Result <> nil then FListBase.Delete(FListBase.Count - 1); end; function TcaPointerList.Push(AItem: Pointer): Integer; begin Result := Add(AItem); end; function TcaPointerList.Size: Integer; begin Result := FListBase.Count; end; // Property methods  function TcaPointerList.GetItem(Index: Integer): Pointer; begin Result := FListBase.List.Items[Index]; end; procedure TcaPointerList.SetItem(Index: Integer; const Value: Pointer); begin FListBase.List.Items[Index] := Value; end; //--------------------------------------------------------------------------- // TcaObjectList   //--------------------------------------------------------------------------- constructor TcaObjectList.Create; begin inherited; FListBase := TcaList.Create; end; // Public methods  function TcaObjectList.Add(AItem: TObject; Unique: Boolean = False): Integer; var ShouldAdd: Boolean; begin Result := -1; ShouldAdd := True; if Unique then ShouldAdd := IndexOf(AItem) = -1; if ShouldAdd then Result := FListBase.List.Add(Pointer(AItem)); end; function TcaObjectList.Extract(AItem: TObject): TObject; begin Result := TObject(FListBase.List.Extract(Pointer(AItem))); end; function TcaObjectList.First: TObject; begin Result := TObject(FListBase.List.First); end; function TcaObjectList.IndexOf(AItem: TObject): Integer; begin Result := FListBase.List.IndexOf(Pointer(AItem)); end; function TcaObjectList.Last: TObject; begin Result := TObject(FListBase.List.Last); end; function TcaObjectList.Remove(AItem: TObject): Integer; begin Result := FListBase.List.Remove(Pointer(AItem)); end; procedure TcaObjectList.Insert(Index: Integer; AItem: TObject); begin FListBase.List.Insert(Index, Pointer(AItem)); end; // IcaObjectList interface methods  function TcaObjectList.HasItems: Boolean; begin Result := FListBase.Count <> 0; end; function TcaObjectList.IsEmpty: Boolean; begin Result := not HasItems; end; function TcaObjectList.Peek: TObject; begin if FListBase.Count = 0 then Result := nil else Result := Last; end; function TcaObjectList.Pop: TObject; begin Result := Peek; if Result <> nil then FListBase.Delete(FListBase.Count - 1); end; function TcaObjectList.Push(AItem: TObject): Integer; begin Result := Add(AItem); end; function TcaObjectList.Size: Integer; begin Result := FListBase.Count; end; // Property methods  function TcaObjectList.GetItem(Index: Integer): TObject; begin Result := TObject(FListBase.List.Items[Index]); end; procedure TcaObjectList.SetItem(Index: Integer; const Value: TObject); begin FListBase.List.Items[Index] := Pointer(Value); end; //--------------------------------------------------------------------------- // TcaSparseMatrix   //--------------------------------------------------------------------------- constructor TcaSparseMatrix.Create; begin inherited; FCols := TList.Create; end; destructor TcaSparseMatrix.Destroy; begin FreeRows; FCols.Free; inherited; end; procedure TcaSparseMatrix.ReleaseElement(ACol, ARow: Integer); var Item: TObject; begin Item := TObject(GetItem(ACol, ARow)); Item.Free; SetItem(ACol, ARow, nil); end; procedure TcaSparseMatrix.ReleaseElements; var ACol: Integer; ARow: Integer; begin for ACol := 0 to ColCount - 1 do for ARow := 0 to RowCount - 1 do ReleaseElement(ACol, ARow); end; // Private methods  procedure TcaSparseMatrix.FreeRows; var Index: Integer; begin for Index := 0 to Pred(FCols.Count) do TObject(FCols[Index]).Free; end; // Property methods  function TcaSparseMatrix.GetColCount: Integer; begin Result := FCols.Count; end; function TcaSparseMatrix.GetItem(ACol, ARow: Integer): Pointer; var Rows: TList; begin Rows := TList(FCols[ACol]); Result := Rows[ARow]; end; function TcaSparseMatrix.GetRowCount: Integer; begin Result := FRowCount; end; procedure TcaSparseMatrix.SetColCount(const Value: Integer); var RowIndex: Integer; Rows: TList; begin if Value <> FCols.Count then begin if Value > FCols.Count then begin while FCols.Count < Value do begin Rows := TList.Create; for RowIndex := 0 to FRowCount - 1 do Rows.Add(nil); FCols.Add(Rows); end; end else while FCols.Count > Value do FCols.Delete(FCols.Count - 1); end; end; procedure TcaSparseMatrix.SetItem(ACol, ARow: Integer; const Value: Pointer); var Rows: TList; begin Rows := TList(FCols[ACol]); Rows[ARow] := Value; end; procedure TcaSparseMatrix.SetRowCount(const Value: Integer); var ACol: Integer; Rows: TList; begin if Value <> FRowCount then begin FRowCount := Value; for ACol := 0 to FCols.Count - 1 do begin Rows := TList(FCols[ACol]); if FRowCount > Rows.Count then while Rows.Count < FRowCount do Rows.Add(nil) else while Rows.Count > FRowCount do Rows.Delete(Rows.Count - 1); end; end; end; //--------------------------------------------------------------------------- // TcaStringCase   //--------------------------------------------------------------------------- constructor TcaStringCase.Create(const AOptions: array of String); begin inherited Create; FOptions := TcaStringList.Create(AOptions); end; destructor TcaStringCase.Destroy; begin FOptions.Free; inherited; end; // Public methods  procedure TcaStringCase.AddOption(const AOption: String); begin FOptions.Add(AOption); end; function TcaStringCase.CaseOf(const AString: String): Integer; begin Result := FOptions.IndexOf(AString); end; //--------------------------------------------------------------------------- // TcaArgs   //--------------------------------------------------------------------------- // Public overridden methods  procedure TcaArgs.AfterConstruction; begin inherited; UpdateArgs; end; // IcaArgs methods  function TcaArgs.HasArg(const AArg: String): Boolean; begin Result := (IndexOfName(AArg) >= 0) or (IndexOf(AArg) >= 0); end; // Private methods  procedure TcaArgs.UpdateArgs; var Index: Integer; Param: String; begin Clear; for Index := 1 to ParamCount do begin Param := ParamStr(Index); Add(Param); end; end; // Property methods  function TcaArgs.GetExecutable: String; begin Result := ParamStr(0); end; //--------------------------------------------------------------------------- // TcaAutoFree   //--------------------------------------------------------------------------- constructor TcaAutoFree.Create(AInstance: TObject); begin inherited Create; FInstance := AInstance; end; destructor TcaAutoFree.Destroy; begin FInstance.Free; inherited; end; // Property methods  function TcaAutoFree.GetInstance: Pointer; begin Result := FInstance; end; function Auto(AInstance: TObject): IcaAutoFree; begin Result := TcaAutoFree.Create(AInstance); end; //--------------------------------------------------------------------------- // TcaProperties   //--------------------------------------------------------------------------- // Create/Destroy  constructor TcaProperties.Create; begin inherited; Initialize; end; destructor TcaProperties.Destroy; begin inherited; end; // Protected virtual methods  procedure TcaProperties.Finalize; begin // Virtual  end; procedure TcaProperties.Initialize; begin // Virtual  end; //--------------------------------------------------------------------------- // TcaNotifyProperties   //--------------------------------------------------------------------------- // Create/Destroy  constructor TcaNotifyProperties.Create(ANotifyMethod: TcaProcedure); begin inherited Create; FNotifyMethod := ANotifyMethod; end; destructor TcaNotifyProperties.Destroy; begin inherited; end; // Protected static methods  procedure TcaNotifyProperties.Changed; begin if Assigned(FNotifyMethod) then FNotifyMethod; end; // Private methods  procedure TcaNotifyProperties.SetBooleanProperty(var AProperty: Boolean; AValue: Boolean); begin if AValue <> AProperty then begin AProperty := AValue; Changed; end; end; procedure TcaNotifyProperties.SetIntegerProperty(var AProperty: Integer; AValue: Integer); begin if AValue <> AProperty then begin AProperty := AValue; Changed; end; end; end.
unit ncSerializeADO; interface uses System.Classes, System.SysUtils, System.Variants, Data.DB, Data.Win.ADODB, System.Win.ComObj, Winapi.ADOInt, Winapi.ActiveX; // SysUtils: Need TBytes // Classes: Need TBytesStream // ADODB: Need TPersistFormat // ADOInt: Need function PersistFormatEnum // ActiveX: Need IStream function ReadString(var aBuffer: TBytes; var aOfs: Integer): string; inline; procedure WriteString(const aValue: string; var aBuffer: TBytes; var aBufLen: Integer); inline; function ReadBytes(var aBuffer: TBytes; var aOfs: Integer): TBytes; inline; procedure WriteBytes(const aValue: TBytes; var aBuffer: TBytes; var aBufLen: Integer); inline; function RecordsetToStream(const aRecordset: _Recordset; aFormat: TPersistFormat): TBytesStream; function RecordsetToBytes(const aRecordset: _Recordset; aFormat: TPersistFormat = pfADTG): TBytes; function StreamToRecordset(const aStream: TBytesStream; aConnection: TADOConnection = nil): _Recordset; function BytesToRecordset(const aBytes: TBytes; aConnection: TADOConnection = nil): _Recordset; function VariantToBytes(aVar: Variant): TBytes; function BytesToVariant(aBytes: TBytes): Variant; function ParametersToBytes(aParameters: TParameters): TBytes; procedure BytesToParameters(aBytes: TBytes; aParameters: TParameters); implementation uses ncSources; function ReadInteger(var aBuffer: TBytes; var aOfs: Integer): Integer; inline; const ResultCount = SizeOf(Result); begin move(aBuffer[aOfs], Result, ResultCount); aOfs := aOfs + ResultCount; end; function ReadInt64(var aBuffer: TBytes; var aOfs: Integer): Int64; inline; const ResultCount = SizeOf(Result); begin move(aBuffer[aOfs], Result, ResultCount); aOfs := aOfs + ResultCount; end; function ReadDouble(var aBuffer: TBytes; var aOfs: Integer): Double; const ResultCount = SizeOf(Result); begin move(aBuffer[aOfs], Result, ResultCount); aOfs := aOfs + ResultCount; end; function ReadSingle(var aBuffer: TBytes; var aOfs: Integer): Single; inline; const ResultCount = SizeOf(Result); begin move(aBuffer[aOfs], Result, ResultCount); aOfs := aOfs + ResultCount; end; function ReadDate(var aBuffer: TBytes; var aOfs: Integer): TDateTime; inline; begin Result := ReadDouble(aBuffer, aOfs); end; function ReadCurrency(var aBuffer: TBytes; var aOfs: Integer): Currency; inline; begin Result := ReadDouble(aBuffer, aOfs); end; function ReadBool(var aBuffer: TBytes; var aOfs: Integer): Boolean; inline; const ResultCount = SizeOf(Result); begin move(aBuffer[aOfs], Result, ResultCount); aOfs := aOfs + ResultCount; end; function ReadByte(var aBuffer: TBytes; var aOfs: Integer): Byte; inline; const ResultCount = SizeOf(Result); begin move(aBuffer[aOfs], Result, ResultCount); aOfs := aOfs + ResultCount; end; function ReadBytes(var aBuffer: TBytes; var aOfs: Integer): TBytes; inline; var ResultCount: Integer; begin ResultCount := ReadInteger(aBuffer, aOfs); SetLength(Result, ResultCount); if ResultCount > 0 then begin move(aBuffer[aOfs], Result[0], ResultCount); aOfs := aOfs + ResultCount; end; end; function ReadString(var aBuffer: TBytes; var aOfs: Integer): string; inline; begin Result := StringOf(ReadBytes(aBuffer, aOfs)); end; procedure WriteInteger(const aValue: Integer; var aBuffer: TBytes; var aBufLen: Integer); inline; const ValByteCount = SizeOf(aValue); begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue, aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; procedure WriteInt64(const aValue: Int64; var aBuffer: TBytes; var aBufLen: Integer); inline; const ValByteCount = SizeOf(aValue); begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue, aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; procedure WriteDouble(const aValue: Double; var aBuffer: TBytes; var aBufLen: Integer); const ValByteCount = SizeOf(aValue); begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue, aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; procedure WriteSingle(const aValue: Single; var aBuffer: TBytes; var aBufLen: Integer); inline; const ValByteCount = SizeOf(aValue); begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue, aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; procedure WriteDate(const aValue: TDateTime; var aBuffer: TBytes; var aBufLen: Integer); inline; begin WriteDouble(aValue, aBuffer, aBufLen); end; procedure WriteCurrency(const aValue: Currency; var aBuffer: TBytes; var aBufLen: Integer); inline; begin WriteDouble(aValue, aBuffer, aBufLen); end; procedure WriteBool(const aValue: Boolean; var aBuffer: TBytes; var aBufLen: Integer); inline; const ValByteCount = SizeOf(aValue); begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue, aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; procedure WriteByte(const aValue: Byte; var aBuffer: TBytes; var aBufLen: Integer); inline; const ValByteCount = SizeOf(aValue); begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue, aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; procedure WriteBytes(const aValue: TBytes; var aBuffer: TBytes; var aBufLen: Integer); inline; var ValByteCount: Integer; begin ValByteCount := Length(aValue); WriteInteger(ValByteCount, aBuffer, aBufLen); if ValByteCount > 0 then begin SetLength(aBuffer, aBufLen + ValByteCount); move(aValue[0], aBuffer[aBufLen], ValByteCount); aBufLen := aBufLen + ValByteCount; end; end; procedure WriteString(const aValue: string; var aBuffer: TBytes; var aBufLen: Integer); inline; begin WriteBytes(BytesOf(aValue), aBuffer, aBufLen); end; function VariantToBytes(aVar: Variant): TBytes; var VariantType: TVarType; BufLen: Integer; begin VariantType := FindVarData(aVar)^.VType; SetLength(Result, SizeOf(VariantType)); move(VariantType, Result[0], SizeOf(VariantType)); BufLen := Length(Result); if not(VariantType in [varEmpty, varNull]) then begin case VariantType of varByte, varSmallint, varShortInt, varInteger, varWord, varLongWord: WriteInteger(aVar, Result, BufLen); varSingle, varDouble: WriteDouble(aVar, Result, BufLen); varCurrency: WriteCurrency(aVar, Result, BufLen); varDate: WriteDate(aVar, Result, BufLen); varBoolean: WriteBool(aVar, Result, BufLen); varInt64, varUInt64: WriteInt64(aVar, Result, BufLen); varOleStr, varStrArg, varString, varUString: WriteString(aVar, Result, BufLen); else raise Exception.Create('Cannot pack specified parameter'); end; end; end; function BytesToVariant(aBytes: TBytes): Variant; var VariantType: TVarType; Ofs: Integer; begin move(aBytes[0], VariantType, SizeOf(VariantType)); Ofs := SizeOf(VariantType); if not(VariantType in [varEmpty, varNull]) then begin case VariantType of varEmpty: Result := System.Variants.Unassigned; varNull: Result := System.Variants.Null; varByte, varSmallint, varShortInt, varInteger, varWord, varLongWord: Result := ReadInteger(aBytes, Ofs); varSingle, varDouble: Result := ReadDouble(aBytes, Ofs); varCurrency: Result := ReadCurrency(aBytes, Ofs); varDate: Result := ReadDate(aBytes, Ofs); varBoolean: Result := ReadBool(aBytes, Ofs); varInt64, varUInt64: Result := ReadInt64(aBytes, Ofs); varOleStr, varStrArg, varString, varUString: Result := ReadString(aBytes, Ofs); else raise Exception.Create('Cannot pack specified parameter'); end; end; end; function ParametersToBytes(aParameters: TParameters): TBytes; var BufLen: Integer; i: Integer; begin BufLen := 0; WriteInteger(aParameters.Count, Result, BufLen); for i := 0 to aParameters.Count - 1 do WriteBytes(VariantToBytes(aParameters.Items[i].Value), Result, BufLen); end; procedure BytesToParameters(aBytes: TBytes; aParameters: TParameters); var ParameterCount: Integer; Ofs: Integer; i: Integer; begin if Length(aBytes) > 0 then begin Ofs := 0; if not Assigned(aParameters) then raise Exception.Create('Parameters object not assigned'); ParameterCount := ReadInteger(aBytes, Ofs); if ParameterCount <> aParameters.Count then raise Exception.Create('Bytes stream parameters differ from SQL Parameters'); for i := 0 to ParameterCount - 1 do aParameters.Items[i].Value := BytesToVariant(ReadBytes(aBytes, Ofs)); end; end; function RecordsetToStream(const aRecordset: _Recordset; aFormat: TPersistFormat): TBytesStream; var ADOStream: IStream; begin // Create a stream to hold the data Result := TBytesStream.Create; try // Since ADO can't write directly to a Delphi stream, we must wrap the Delphi stream ADOStream := TStreamAdapter.Create(Result, soReference) as IStream; try // Save the content of the recordset to the stream aRecordset.Save(ADOStream, PersistFormatEnum(aFormat)); finally ADOStream := nil; end; // The Stream now contains the data // Position the stream at the start Result.Position := 0; except Result.Free; raise; end; end; function RecordsetToBytes(const aRecordset: _Recordset; aFormat: TPersistFormat = pfADTG): TBytes; var tmpSS: TBytesStream; begin tmpSS := RecordsetToStream(aRecordset, aFormat); try Result := tmpSS.Bytes; finally tmpSS.Free; end; end; function StreamToRecordset(const aStream: TBytesStream; aConnection: TADOConnection = nil): _Recordset; var ADOStream: IStream; begin Result := CoRecordset.Create; try // Since ADO can't write directly to a Delphi stream, we must wrap the Delphi stream ADOStream := TStreamAdapter.Create(aStream, soReference) as IStream; try // Save the content of the stream to the recordset Result.Open(ADOStream, EmptyParam, adOpenKeyset, adLockBatchOptimistic, adCmdFile); // You need to Set_ActiveConnection in order to be able to update a recordset. if Assigned(aConnection) then Result.Set_ActiveConnection(aConnection.ConnectionObject); finally ADOStream := nil; end; except Result := nil; raise; end; end; function BytesToRecordset(const aBytes: TBytes; aConnection: TADOConnection = nil): _Recordset; var Stream: TBytesStream; begin Stream := TBytesStream.Create(aBytes); try Stream.Position := 0; Result := StreamToRecordset(Stream, aConnection); finally Stream.Free; end; end; end.
unit uLexer; interface uses uText, IniFiles, SysUtils; const cLexemeTypeEnd = 0; type TLexeme = record LexemeType : Byte; Pos : TPosInText; Data : string; end; ILexer = interface function GetLexeme: TLexeme; end; ILexemeList = interface end; TKeyWordList = class(TObject) strict private FList: THashedStringList; FFirstIndex: Integer; public constructor Create; destructor Destroy; override; function IndexOf(const AStr: string): Integer; property FirstIndex: Integer read FFirstIndex write FFirstIndex; end; TBaseLexer = class(TInterfacedObject, ILexer) strict protected FText: IText; public constructor Create(const AText: IText); reintroduce; function GetLexeme: TLexeme; virtual; abstract; end; TNativeLexer = class(TBaseLexer) protected FKeyWordList: TKeyWordList; public constructor Create(const AText: IText); destructor Destroy; override; end; implementation { TBaseLexer } constructor TBaseLexer.Create(const AText: IText); begin inherited Create; FText := AText; FText.First; end; { TKeyWordList } constructor TKeyWordList.Create; begin FList := THashedStringList.Create; end; destructor TKeyWordList.Destroy; begin FreeAndNil(FList); inherited; end; function TKeyWordList.IndexOf(const AStr: string): Integer; begin Result := FList.IndexOf(AStr); if Result >= 0 then Result := Result + FFirstIndex; end; { TNativeLexer } constructor TNativeLexer.Create(const AText: IText); begin inherited; FKeyWordList := TKeyWordList.Create; end; destructor TNativeLexer.Destroy; begin FreeAndNil(FKeyWordList); inherited; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book September '1999 Problem 36 O(N3) StronglyConnectedComponents Method } program TransitiveReduction; const MaxN = 100; var N, E : Integer; A, B, C : array [0 .. MaxN, 0 .. MaxN] of Integer; M : array [1 .. MaxN] of Boolean; Map, Comp : array [1 .. MaxN] of Integer; I, J, K, D, Time, X, Y : Integer; F : Text; procedure ReadInput; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N, E); for I := 1 to E do begin Readln(F, X, Y); A[X, Y] := 1; end; Close(F); end; procedure Dfs1 (V : Integer); var I : Integer; begin M[V] := True; for I := 1 to N do if (A[V, I] = 1) and not M[I] then Dfs1(I); Inc(Time); Map[N + 1 - Time] := V; end; procedure Dfs2 (V : Integer); var I : Integer; begin Inc(B[B[0, 0], 0]); B[B[0, 0], B[B[0, 0], 0]] := V; M[V] := True; for I := 1 to N do if (A[I, V] = 1) and not M[I] then Dfs2(I); end; procedure StConnected; begin for I := 1 to N do if not M[I] then Dfs1(I); FillChar(M, SizeOf(M), 0); for I := 1 to N do if not M[Map[I]] then begin Inc(B[0, 0]); Dfs2(Map[I]); end; end; procedure MakeDag; begin E := 0; for I := 1 to B[0, 0] do for J := 1 to B[I, 0] do Comp[B[I, J]] := I; for I := 1 to N do for J := 1 to N do if A[I, J] = 1 then C[Comp[I], Comp[J]] := 1; end; procedure ReduceDag; begin for I := 1 to N do C[I, I] := 0; for K := 1 to N do for I := 1 to N do for J := 1 to N do if (C[I, K] > 0) and (C[K, J] > 0) and (C[I, J] < C[I, K] + C[K, J]) then C[I, J] := C[I, K] + C[K, J]; for I := 1 to N do for J := 1 to N do if C[I, J] > 1 then C[I, J] := 0; end; procedure CalcEdges; begin for I := 1 to N do for J := 1 to N do if C[I, J] = 1 then Inc(E); for I := 1 to B[0, 0] do if B[I, 0] > 1 then Inc(E, B[I, 0]); end; procedure Reduce; begin MakeDag; ReduceDag; CalcEdges; end; procedure WriteOutput; begin Assign(F, 'output.txt'); ReWrite(F); Writeln(F, N, ' ', E); for I := 1 to N do for J := 1 to N do if C[I, J] = 1 then Writeln(F, B[I, 1], ' ', B[J, 1]); for I := 1 to B[0, 0] do begin for J := 1 to B[I, 0] - 1 do Writeln(F, B[I, J], ' ', B[I, J + 1]); if B[I, 0] > 1 then Writeln(F, B[I, B[I, 0]], ' ', B[I, 1]); end; Close(F); end; begin ReadInput; StConnected; Reduce; WriteOutput; end.
unit fraDSSQLEdit; interface {$I ..\FIBPlus.inc} uses Windows, Messages, SysUtils, Classes, {$IFDEF D_XE2} Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, {$ENDIF} fraSQLEdit, DB, pFIBInterfaces,uFIBEditorForm; type TOnCanUseFields=procedure(const FieldName:string; Allow:boolean) of object; TFrame=TFIBEditorCustomFrame;// Fake for D5 TfDSSQLEdit = class(TFrame) pgCtrl: TPageControl; shSelect: TTabSheet; SelectSQLEdit: TfSQLEdit; shGenOptions: TTabSheet; Panel2: TPanel; Label3: TLabel; cmbTables: TComboBox; btnGetFields: TButton; btnGenSql: TButton; btnClearSQLs: TButton; GroupBox1: TGroupBox; chFieldOrigin: TCheckBox; GroupBox2: TGroupBox; chByPrimary: TCheckBox; chNonUpdPrKey: TCheckBox; Label2: TLabel; cmbParamSymbol: TComboBox; Panel3: TPanel; Label1: TLabel; LstKeyFields: TListBox; Splitter1: TSplitter; Panel5: TPanel; Label4: TLabel; LstUpdFields: TListBox; shModifySQLs: TTabSheet; grSQLKind: TRadioGroup; ModifySQLEdit: TfSQLEdit; cmbGenerateKind: TComboBox; procedure pgCtrlChange(Sender: TObject); procedure btnGetFieldsClick(Sender: TObject); procedure grSQLKindClick(Sender: TObject); procedure btnGenSqlClick(Sender: TObject); procedure cmbTablesChange(Sender: TObject); procedure SelectSQLEditSpeedButton1Click(Sender: TObject); procedure btnClearSQLsClick(Sender: TObject); procedure SelectSQLEditbtnGenSQLClick(Sender: TObject); procedure Panel2MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private function GetDialect: integer; procedure viewSQLOnExit(Sender: TObject); private FDatabase:TComponent; FOnCanUseFields:TOnCanUseFields; FAllFields :TStrings; FUpdTableSynonym:string; FPreparedSelect:string; procedure FillCmbTables; procedure ShowModifySQL; procedure GenerateInsertSQL; procedure GenerateUpdateSQL; procedure GenerateDeleteSQL; procedure GenerateRefreshSQL; function WhereClause(withSyn:boolean):string; property Dialect :integer read GetDialect; public vDataSet:TDataSet; vShablonDS:TDataSet; FInsertSQL,FUpdateSQL, FDeleteSQL,FRefreshSQL:string; procedure ReadOptions; procedure SaveOptions; procedure SetProposal; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure PrepareFrame(Database:TComponent; const aSelectSQLText,aInsertSQL,aUpdateSQL, aDeleteSQL,aRefreshSQL:string); property OnCanUseFields:TOnCanUseFields read FOnCanUseFields write FOnCanUseFields; end; const RegFIBSQLEdOptions='SQLEditor'; implementation uses RegistryUtils,TypInfo {$IFDEF D6+ }, Variants {$ENDIF} , RegFIBPlusEditors, pFIBEditorsConsts, RTTIRoutines, IBSQLSyn; {$R *.dfm} { TfDSSQLEdit } constructor TfDSSQLEdit.Create(AOwner: TComponent); begin inherited; FAllFields :=TStringList.Create; cmbGenerateKind.ItemIndex:=0; vShablonDS:= TDataSet(expDatasetClass.Create(Self)) end; destructor TfDSSQLEdit.Destroy; begin // SaveOptions; FAllFields.Free; inherited; end; procedure TfDSSQLEdit.FillCmbTables; {var i:integer;} begin with cmbTables do begin SelectSQLEdit.FStringer.AllTables(SelectSQLEdit.SQLText,Items,False,True); { for i:=0 to Pred(Items.Count) do begin if Pos('"',Items[i])>0 then begin Items[i]:=Copy(Items[i],2,MaxInt); Items[i]:=Copy(Items[i],1,Pos('"',Items[i])-1); end else Items[i]:=FastUpperCase(ExtractWord(1, Items[i],[' '])); end;} if Items.Count>0 then begin ItemIndex:=0; cmbTablesChange(cmbTables) end; FPreparedSelect:=SelectSQLEdit.SQLText; end; end; procedure TfDSSQLEdit.pgCtrlChange(Sender: TObject); begin if (pgCtrl.ActivePage=shGenOptions) and ((cmbTables.Items.Count=0)or (FPreparedSelect<>SelectSQLEdit.SQLText))then FillCmbTables end; procedure TfDSSQLEdit.btnGetFieldsClick(Sender: TObject); var i,j:integer; tfd:TFieldDef; NeedField:boolean; PrimaryKey:string; tn:string; ids: IFIBDataSet; begin if ObjSupports(vShablonDS,IFIBDataSet,ids) then with vShablonDS,ids,SelectSQLEdit.FStringer do begin SetObjectProp(vShablonDS,'Database',FDatabase); SetObjectProp(vShablonDS,'Transaction',SelectSQLEdit.trTransaction); SetPropValue(vShablonDS,'PrepareOptions','[]'); SetPropValue(vShablonDS,'Options','[poNoForceIsNull]'); AssignStringsToProp(vShablonDS,'SelectSQL',SelectSQLEdit.SQLText); ids.Prepare; FAllFields.Clear; for j:=0 to FieldDefs.Count-1 do begin tfd:=FieldDefs[j]; NeedField:=True; if Assigned(FOnCanUseFields) then FOnCanUseFields(tfd.Name,NeedField); if NeedField then if FUpdTableSynonym<>'' then begin tn:= TableAliasForField(tfd.Name); NeedField:=(FUpdTableSynonym=tn) or (FUpdTableSynonym='"'+tn+'"') end else NeedField:=(cmbTables.Text=GetRelationTableName(tfd)); if NeedField then begin FAllFields.AddObject(tfd.Name,tfd); end; end; tn:=ExtractWord(1,cmbTables.Text,[' ']); LstKeyFields.Items.BeginUpdate; LstUpdFields.Items.BeginUpdate; try LstKeyFields.Items.Assign(FAllFields); LstUpdFields.Items.Assign(FAllFields); if chByPrimary.Checked then PrimaryKey:= ';'+SelectSQLEdit.FMetaExtractor.DBPrimaryKeys( tn,SelectSQLEdit.trTransaction)+';' else PrimaryKey:=''; with LstKeyFields,LstKeyFields.Items do begin i:=0; while i<Count do begin tfd:=TFieldDef(Objects[i]); if (tfd.DataType=ftBlob) or (tfd.DataType=ftMemo) or (tfd.DataType=ftBytes) then begin Delete(i); Continue; end; Selected[i]:=not chByPrimary.Checked or (Pos(';'+Items[i]+';',PrimaryKey)>0); Inc(i) end; end; for i:=0 to Pred(LstUpdFields.Items.Count) do if not SelectSQLEdit.FMetaExtractor.IsCalculatedField( tn,LstUpdFields.Items[i],SelectSQLEdit.trTransaction) then LstUpdFields.Selected[i]:=True; finally LstKeyFields.Items.EndUpdate; LstUpdFields.Items.EndUpdate; end; end end; type THackWinControl=class(TWinControl); procedure TfDSSQLEdit.PrepareFrame(Database: TComponent; const aSelectSQLText, aInsertSQL,aUpdateSQL, aDeleteSQL,aRefreshSQL:string ); begin FDatabase:=Database; with SelectSQLEdit do begin FDatabase:=Database; vEditedQuery:= vDataSet.FindComponent('SelectQuery'); PrepareFrame(Database); SQLText:=aSelectSQLText; cmbKindSQL.Enabled:=False; end; with ModifySQLEdit do begin PrepareFrame(Database); THackWinControl(ModifySQLEdit.viewSQL).OnExit:=viewSQLOnExit; end; FInsertSQL:=aInsertSQL; FUpdateSQL:=aUpdateSQL; FDeleteSQL:=aDeleteSQL; FRefreshSQL:=aRefreshSQL; ModifySQLEdit.btnGenSQL.Visible:=False; ModifySQLEdit.SpeedButton1.Visible:=False; ModifySQLEdit.Panel6.Visible:=False; ModifySQLEdit.Splitter2.Visible:=False; shGenOptions.TabVisible:= SelectSQLEdit.CanConnect; ShowModifySQL end; procedure TfDSSQLEdit.ShowModifySQL; begin with ModifySQLEdit do case grSQLKind.ItemIndex of -1,0: begin vEditedQuery:=vDataSet.FindComponent('InsertQuery'); SQLText:=FInsertSQL; end; 1: begin vEditedQuery:=vDataSet.FindComponent('UpdateQuery'); SQLText:=FUpdateSQL; end; 2: begin vEditedQuery:=vDataSet.FindComponent('DeleteQuery'); SQLText:=FDeleteSQL; end; 3: begin vEditedQuery:=vDataSet.FindComponent('RefreshQuery'); SQLText:=FRefreshSQL; end; end; ModifySQLEdit.ShowEditorStatus end; procedure TfDSSQLEdit.grSQLKindClick(Sender: TObject); begin ShowModifySQL end; procedure TfDSSQLEdit.GenerateInsertSQL; var j:integer; pn,rfn,tmpStr,tmpStr1:string; // vpFIBTableInfo:TpFIBTableInfo; // vFi:TpFIBFieldInfo; tn:string; ids:IFIBDataSet; begin if ObjSupports(vShablonDS,IFIBDataSet,ids) then with LstUpdFields,SelectSQLEdit.FStringer do begin FInsertSQL:=''; tmpStr:='';tmpStr1:=''; // ListTableInfo.Clear; tn:=ExtractWord(1,cmbTables.Text,[' ']); { vpFIBTableInfo:= pFIBDataSet ListTableInfo.GetTableInfo(FDatabase, tn ,False); } for j:=0 to Pred(Items.Count) do if Selected[j] then begin rfn:=ids.GetRelationFieldName(Items.Objects[j]); { vFi:=vpFIBTableInfo.FieldInfo(rfn); if (vFi=nil) or vFi.IsComputed or vFi.IsTriggered then Continue;} if SelectSQLEdit.FMetaExtractor.IsCalculatedField(tn,rfn,SelectSQLEdit.trTransaction) then Continue; rfn:=FormatIdentifier(GetDialect,rfn); pn :=FormatIdentifier(GetDialect,Items[j]); tmpStr :=tmpStr+ForceNewStr+rfn+','; tmpStr1:=tmpStr1+ForceNewStr+cmbParamSymbol.Text+pn+','; end; if (tmpStr<>'') and (tmpStr[Length(tmpStr)]=',') then SetLength(tmpStr,Length(tmpStr)-1); if (tmpStr1<>'') and (tmpStr1[Length(tmpStr1)]=',') then SetLength(tmpStr1,Length(tmpStr1)-1); FInsertSQL:= 'INSERT INTO '+FormatIdentifier(GetDialect, tn )+ '('+tmpStr+#13#10+')'#13#10+'VALUES('+tmpStr1+#13#10+')'; end; end; procedure TfDSSQLEdit.btnGenSqlClick(Sender: TObject); begin case cmbGenerateKind.ItemIndex of 0:begin GenerateInsertSQL; GenerateUpdateSQL; GenerateDeleteSQL; GenerateRefreshSQL; end; 1:GenerateInsertSQL; 2:GenerateUpdateSQL; 3:GenerateDeleteSQL; 4:GenerateRefreshSQL; end; ShowModifySQL ; pgCtrl.ActivePage:=shModifySQLs; if cmbGenerateKind.ItemIndex>0 then grSQLKind.ItemIndex:=cmbGenerateKind.ItemIndex-1 else grSQLKind.ItemIndex:=0; end; procedure TfDSSQLEdit.GenerateUpdateSQL; var j:integer; pn,rfn,tmpStr:string; { vpFIBTableInfo:TpFIBTableInfo; vFi:TpFIBFieldInfo;} PrimaryKey:string; tn:string; ids:IFIBDataSet; begin if ObjSupports(vShablonDS,IFIBDataSet,ids) then with LstUpdFields,ids, SelectSQLEdit.FStringer do begin FUpdateSQL:=''; tmpStr:=''; // ListTableInfo.Clear; tn:=ExtractWord(1,cmbTables.Text,[' ']); { vpFIBTableInfo:= ListTableInfo.GetTableInfo(FDatabase,tn,False); } for j:=0 to Pred(Items.Count) do begin rfn:=ids.GetRelationFieldName(Items.Objects[j]); { vFi:=vpFIBTableInfo.FieldInfo(rfn); if (vFi=nil) or vFi.IsComputed or vFi.IsTriggered then Continue;} if SelectSQLEdit.FMetaExtractor.IsCalculatedField(tn,rfn,SelectSQLEdit.trTransaction) then Continue; rfn:=FormatIdentifier(GetDialect,rfn); if (Pos('NEW_',Items[j])=1) or (Pos('OLD_',Items[j])=1) then pn :=FormatIdentifier(GetDialect,'NEW_'+Items[j]) else pn :=FormatIdentifier(GetDialect,Items[j]); if Selected[j] then begin if chNonUpdPrKey.Checked then PrimaryKey:= ';'+ SelectSQLEdit.FMetaExtractor.DBPrimaryKeys(tn,SelectSQLEdit.trTransaction)+';' else PrimaryKey:=''; if Pos(';'+rfn+';',PrimaryKey)=0 then tmpStr :=tmpStr+ForceNewStr+rfn+' = '+cmbParamSymbol.Text+pn+','; end; end; if tmpStr<>'' then if tmpStr[Length(tmpStr)]=',' then tmpStr :=Copy(tmpStr,1,Length(tmpStr)-1); FUpdateSQL:= 'UPDATE '+FormatIdentifier(GetDialect,tn)+#13#10+'SET '+ tmpStr+#13#10+'WHERE'+#13#10+WhereClause(False) end; end; function TfDSSQLEdit.WhereClause(withSyn: boolean): string; var i,j:integer; pn,rfn:string; ids:IFIBDataSet; begin if ObjSupports(vShablonDS,IFIBDataSet,ids) then with LstKeyFields,SelectSQLEdit.FStringer do begin i:=0; Result:=SpaceStr; for j:=0 to Pred(Items.Count) do begin if Selected[j] then begin Inc(i); if (Items.Objects[j]<>nil) and (TFieldDef(Items.Objects[j]).DataType=ftBlob) or (TFieldDef(Items.Objects[j]).DataType=ftMemo) or (TFieldDef(Items.Objects[j]).DataType=ftBytes) then Continue; rfn:=ids.GetRelationFieldName(Items.Objects[j]); rfn:=FormatIdentifier(Dialect,rfn); pn :=FormatIdentifier(Dialect,'OLD_'+Items[j]); if withSyn and (FUpdTableSynonym<>'') then Result:=Result+FUpdTableSynonym+'.'+rfn+' = '+cmbParamSymbol.Text+pn+ForceNewStr else Result:=Result+rfn+' = '+cmbParamSymbol.Text+pn+ForceNewStr; if i<SelCount then Result:=Result+'and ' end; end; end; end; function TfDSSQLEdit.GetDialect: integer; begin if Assigned(FDatabase ) then Result:=GetPropValue(FDatabase,'SQLDialect') else Result:=3 end; procedure TfDSSQLEdit.cmbTablesChange(Sender: TObject); begin with cmbTables,FDatabase do if ItemIndex>-1 then with SelectSQLEdit.FStringer do begin if WordCount(cmbTables.Text,[' '])=1 then FUpdTableSynonym:= FormatIdentifier(GetDialect,AliasForTable(SelectSQLEdit.SQLText,FormatIdentifier(GetDialect,cmbTables.Text))) else FUpdTableSynonym:= ExtractWord(2, cmbTables.Text,[' ']) ; if FUpdTableSynonym[1]='@' then FUpdTableSynonym:=''; end else FUpdTableSynonym:=''; LstKeyFields.Clear; LstUpdFields.Clear; btnGetFieldsClick(btnGetFields); end; procedure TfDSSQLEdit.GenerateDeleteSQL; begin with LstKeyFields,SelectSQLEdit.FStringer do begin FDeleteSQL:='DELETE FROM'#13#10+SpaceStr+FormatIdentifier(Dialect,ExtractWord(1,cmbTables.Text,[' ']))+#13#10+ 'WHERE'#13#10+SpaceStr+WhereClause(False); end; end; procedure TfDSSQLEdit.GenerateRefreshSQL; begin with SelectSQLEdit.FStringer do begin FRefreshSQL:=SetOrderClause(SelectSQLEdit.SQLText,''); FRefreshSQL:=AddToMainWhereClause(FRefreshSQL,WhereClause(True)) end end; procedure TfDSSQLEdit.viewSQLOnExit(Sender: TObject); begin case grSQLKind.ItemIndex of 0:FInsertSQL:=ModifySQLEdit.SQLText; 1:FUpdateSQL:=ModifySQLEdit.SQLText; 2:FDeleteSQL:=ModifySQLEdit.SQLText; 3:FRefreshSQL:=ModifySQLEdit.SQLText; end; end; procedure TfDSSQLEdit.ReadOptions; {$IFNDEF NO_REGISTRY} var v:Variant; i:integer; {$ENDIF} begin {$IFNDEF NO_REGISTRY} v:= DefReadFromRegistry(['Software',RegFIBRoot,RegFIBSQLEdOptions], ['WhereByPK', 'NotUpdatePK', 'Use?', 'Origins' ] ); if (VarType(v)<>varBoolean) then for i:=0 to 3 do if V[1,i] then case i of 0: chByPrimary.Checked :=V[0,i]; 1: chNonUpdPrKey.Checked :=V[0,i]; 2: if V[0,i] then cmbParamSymbol.ItemIndex:=1 else cmbParamSymbol.ItemIndex:=0; 3: chFieldOrigin.Checked :=V[0,i]; end; SelectSQLEdit.ReadOptions; ModifySQLEdit.ReadOptions; {$ENDIF} end; procedure TfDSSQLEdit.SaveOptions; begin {$IFNDEF NO_REGISTRY} DefWriteToRegistry(['Software',RegFIBRoot,RegFIBSQLEdOptions], ['WhereByPK', 'NotUpdatePK', 'Use?', 'Origins' ], [chByPrimary.Checked , chNonUpdPrKey.Checked, cmbParamSymbol.ItemIndex=1, chFieldOrigin.Checked ] ); SelectSQLEdit.SaveOptions; {$ENDIF} end; procedure TfDSSQLEdit.SelectSQLEditSpeedButton1Click(Sender: TObject); begin SelectSQLEdit.SpeedButton1Click(Sender); THackWinControl(ModifySQLEdit.viewSQL).Font:=THackWinControl(SelectSQLEdit.viewSQL).Font end; procedure TfDSSQLEdit.btnClearSQLsClick(Sender: TObject); begin FInsertSQL:=''; FUpdateSQL:=''; FDeleteSQL:=''; FRefreshSQL:=''; ShowModifySQL end; procedure TfDSSQLEdit.SelectSQLEditbtnGenSQLClick(Sender: TObject); begin SelectSQLEdit.btnGenSQLClick(Sender); end; procedure TfDSSQLEdit.Panel2MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin cmbTables.Hint :=cmbTables.Text end; procedure TfDSSQLEdit.SetProposal; var i:integer; ts,ts1:TStrings; DDLExtractor1:IFIBMetaDataExtractor; Stringer:IFIBStringer; b:variant; b1:boolean; begin if (SelectSQLEdit.FDatabase=nil) then begin // or not GetPropValue(fSQLEdit1.FDatabase,'Connected') SelectSQLEdit.iViewSQL.ISetProposalItems(DefProposalShadow[0],DefProposalShadow[1]); Exit; end; b:=GetPropValue(SelectSQLEdit.FDatabase,'Connected'); b1:=b; //D5 bugs variant conversion if not b1 then begin SelectSQLEdit.iViewSQL.ISetProposalItems(DefProposalShadow[0],DefProposalShadow[1]); Exit; end; { DDLExtractor1:=FIBClassesExporter.iGetMetaExtractor; DDLExtractor1.SetDatabase(SelectSQLEdit.FDatabase); DDLExtractor1.LoadObjectNames; Stringer:=FIBClassesExporter.iGetStringer; ts:=TStringList.Create; ts1:=TStringList.Create; with DDLExtractor1 do try ts.Assign(DefProposalShadow[0]); ts1.Assign(DefProposalShadow[1]); for i:=0 to Pred(TablesCount) do begin ts.Add('table '+ProposalDelimiterShadow+'M '+Stringer.FormatIdentifier(3,TableName[i])); ts1.Add(Stringer.FormatIdentifier(3,TableName[i])); end; for i:=0 to Pred(ViewsCount) do begin ts.Add('view '+ProposalDelimiterShadow+'O '+Stringer.FormatIdentifier(3,ViewName[i])); ts1.Add(Stringer.FormatIdentifier(3,ViewName[i])); end; for i:=0 to Pred(ProceduresCount) do begin ts.Add('procedure '+ProposalDelimiterShadow+'N '+Stringer.FormatIdentifier(3,ProcedureName[i])); ts1.Add(Stringer.FormatIdentifier(3,ProcedureName[i])); end; for i:=0 to Pred(UDFSCount) do begin ts.Add('udf '+ProposalDelimiterShadow+'T '+Stringer.FormatIdentifier(3,UDFName[i])); ts1.Add(Stringer.FormatIdentifier(3,UDFName[i])); end; SelectSQLEdit.iViewSQL.ISetProposalItems(ts,ts1); ModifySQLEdit.iViewSQL.ISetProposalItems(ts,ts1); // SynMemo.SetProposalItems(ts); finally ts.Free; ts1.Free; end} end; end.
{$codepage utf8} { by Plasmoxy } program quadratic; uses crt, sysutils, math, ucomplex; { ---- OBJ ---- } // najprv si zhotovim nastroj na pocitanie type SolveQuadratic = class private a,b,c,d : double; complexRoots : array of Complex; retarded : boolean; procedure addRoot(_root : double); procedure addComplexRoot(_croot : Complex); public roots : array of double; constructor create(_a,_b,_c : double); procedure printRoots(); function getDiscriminant() : double; function dtos(_value : double) : string; // double to string with 6 decimal points function dtos2(_value : double) : string; // 3 decimal points end; constructor SolveQuadratic.create(_a,_b,_c : double); begin a := _a; b := _b; c := _c; d := power(b, 2) - 4*a*c; if a=0 then begin if (b=0) then retarded := true else addRoot( -c/b ); end else begin if d<0 then begin addComplexRoot( (-b+csqrt( cinit(d, 0)) ) / (2*a) ); addComplexRoot( (-b-csqrt( cinit(d, 0)) ) / (2*a) ); end else if d=0 then addRoot( -b/(2*a) ) else if d>0 then begin addRoot( (-b+sqrt(d))/(2*a) ); addRoot( (-b-sqrt(d))/(2*a) ); end; end; end; procedure SolveQuadratic.addRoot(_root : double); begin setlength(roots, length(roots)+1); roots[length(roots)-1] := _root; end; procedure SolveQuadratic.addComplexRoot(_croot : Complex); begin setlength(complexRoots, length(complexRoots)+1); complexRoots[length(complexRoots)-1] := _croot; end; procedure SolveQuadratic.printRoots(); var it, len : integer; // iterator, length of array begin writeln('===[ '+dtos2(a)+'x^2 + '+dtos2(b)+'x + '+dtos2(c)+' = 0 ]==='); writeln; if retarded then begin writeln('=== NAPISALI STE RETARDOVANY VYRAZ PROSIM PEKNE :)))) ==='); exit(); end; writeln(' === REALNE KORENE ==='); len := length(roots); write('K(R) = {'); if len>0 then writeln; // cosmetic for it:=1 to len do begin write(' ' + dtos(roots[it-1])); if it<len then write(','); writeln; end; writeln('}'); writeln(' === KOMPLEXNE KORENE ==='); len := length(complexRoots); write('K(C) = {'); if len>0 then writeln; // cosmetic for it:=1 to len do begin write(' ' + cstr(complexRoots[it-1], 6, 6)); if it<len then write(','); writeln; end; writeln('}'); end; function SolveQuadratic.dtos(_value : double) : string; begin exit(FloatToStrF(_value, ffFixed, 6, 6)); end; function SolveQuadratic.dtos2(_value : double) : string; begin exit(FloatToStrF(_value, ffFixed, 2, 2)); end; function SolveQuadratic.getDiscriminant() : double; begin exit(d); end; { ------- PROGRAM -------- } // tu svoj nastroj vyuzijem const nl = slinebreak; // skratka pre zlom riadka var active : boolean; a,b,c : double; begin DefaultFormatSettings.DecimalSeparator := '.'; // nemam rad ciarku :( active := true; while active do begin clrscr; writeln( '======= OOP VYPOCET KORENOV KVADRATICKEJ ROVNICE ======' +nl+ '========= ( napisal Plasmoxy = Seb Petrík ) ===========' +nl ); writeln('Zadajte rovnicu podla vzoru ax^2 + bx + c :'); try write('a = '); readln(a); write('b = '); readln(b); write('c = '); readln(c); except on E: Exception do begin writeln('CHYBA VSTUPU, SKUSTE ESTE RAZ ! (stlac klaves)'); writeln('BTW desatinna ciarka je bodka = "." ( to kvoli citatelnosti )'); readkey; continue; end; end; writeln; try SolveQuadratic.create(a,b,c).printRoots(); except on E: Exception do writeln('Fatalna chyba pri vypocte.') end; writeln(nl + ' [ Stlac nejaky klaves pre obnovenie alebo ESC pre koniec] '); case readkey of #27: active := false; // esc end; end; // end while end.
{ Module of simple window manipulation routines. These routines all take * a window object as their first argument. } module gui_win; define gui_win_resize; define gui_win_root; define gui_win_child; define gui_win_clipto; define gui_win_clip; define gui_win_clip_push; define gui_win_clip_push_2d; define gui_win_clip_pop; define gui_win_delete; define gui_win_xf2d_set; define gui_win_draw; define gui_win_draw_all; define gui_win_draw_behind; define gui_win_erase; define gui_win_alloc_static; define gui_win_set_app_pnt; define gui_win_get_app_pnt; define gui_win_set_draw; define gui_win_set_delete; define gui_win_set_evhan; define gui_win_tofront; %include 'gui2.ins.pas'; const mem_pool_size_k = 8192; {size of window memory context fixed pools} mem_chunk_size_k = {max size allowed to allocate from fixed pool} mem_pool_size_k div 8; stack_block_size_k = 512; {stack mem allocation block size} { ************************************************************************* * * Subroutine GUI_WIN_CLIPTO (WIN) * * Set the GUI RENDlib clip state for this window set to the window WIN. * * *** WARNING *** * This routine must *never* be called from inside a window draw routine. * Use CLIP, CLIP_PUSH, and CLIP_POP inside window draw routines. } procedure gui_win_clipto ( {clip to win, use outside window draw only} in out win: gui_win_t); {window to set clip coor to} val_param; begin rend_set.clip_2dim^ ( {set clip rectangle to whole window} win.all_p^.rend_clip, {RENDlib clip window handle} win.pos.x, win.pos.x + win.rect.dx, {left and right limits} win.pos.y, win.pos.y + win.rect.dy, {top and bottom limits} true); {draw inside, clip outside} end; { ************************************************************************* * * Local subroutine GUI_WIN_CLIP_COMPUTE (WIN) * * Compute the resulting clip state, taking into account the stacked clip * state and the current app clipping region. This routine updates * the following fields: * * CLIP - Final resulting drawable region, RENDlib 2DIMI coordinates. * NOT_CLIPPED - TRUE if at least one pixel center is not clipped. } procedure gui_win_clip_compute ( {compute resulting drawable clip region} in out win: gui_win_t); {window object} val_param; internal; var ilx, irx, iby, ity: sys_int_machine_t; {last pixel coor within draw area} begin { * Make window pixel coordinates of draw region edges. } ilx := trunc(max(win.frame_clip_p^.rect.lx, win.clip_rect.lx) + 0.5); irx := trunc(min(win.frame_clip_p^.rect.rx, win.clip_rect.rx) - 0.5); iby := trunc(max(win.frame_clip_p^.rect.by, win.clip_rect.by) + 0.5); ity := trunc(min(win.frame_clip_p^.rect.ty, win.clip_rect.ty) - 0.5); { * Translate to RENDlib device coordinates. } ilx := win.pos.x + ilx; irx := win.pos.x + irx; iby := win.pos.y + win.rect.dy - 1 - iby; ity := win.pos.y + win.rect.dy - 1 - ity; { * Fill in CLIP field with RENDlib device 2DIM coordinates. } win.clip.x := ilx; win.clip.y := ity; win.clip.dx := max(0, irx - ilx + 1); win.clip.dy := max(0, iby - ity + 1); win.not_clipped := (win.clip.dx > 0) and (win.clip.dy > 0); end; { ************************************************************************* * * Local subroutine GUI_WIN_ADJUST (WIN, X, Y, DX, DY) * * This is the low level routine for adjusting a windows size and position. * This routine does not handle display updates. WIN must not be a root * window. } procedure gui_win_adjust ( {resize and move a window} in out win: gui_win_t; {window object} in x, y: real; {window corner within parent window} in dx, dy: real); {displacement from the corner at X,Y} val_param; internal; var pos: gui_win_childpos_t; {position into child window list} lx, rx, by, ty: real; {new window edge coordinates within parent} ilx, irx, iby, ity: sys_int_machine_t; {integer window edges} begin if dx >= 0.0 then begin {window extends right from corner point} lx := x; rx := x + dx; end else begin {window extends left from corner point} lx := x + dx; rx := x; end ; if dy >= 0.0 then begin {window extends up from corner point} by := y; ty := y + dy; end else begin {window extends down from corner point} by := y + dy; ty := y; end ; ilx := max(0, min(win.parent_p^.rect.dx, trunc(lx + 0.5))); irx := max(0, min(win.parent_p^.rect.dx, trunc(rx + 0.5))); iby := max(0, min(win.parent_p^.rect.dy, trunc(by + 0.5))); ity := max(0, min(win.parent_p^.rect.dy, trunc(ty + 0.5))); win.rect.x := ilx; {set new window position within parent} win.rect.dx := irx - ilx; win.rect.y := iby; win.rect.dy := ity - iby; win.pos.x := {update RENDlib 2DIM of window upper left} win.parent_p^.pos.x + win.rect.x; win.pos.y := win.parent_p^.pos.y + win.parent_p^.rect.dy - win.rect.y - win.rect.dy; win.clip_rect.lx := 0.0; {set clip region to whole window} win.clip_rect.rx := win.rect.dx; win.clip_rect.by := 0.0; win.clip_rect.ty := win.rect.dy; win.frame_clip_p^.rect := win.clip_rect; {init backstop clip to whole window} gui_win_clip_compute (win); {recompute resulting clip state} gui_win_childpos_first (win, pos); {init position to first window in child list} while pos.child_p <> nil do begin {once for each child window} gui_win_adjust ( {adjust this child window} pos.child_p^, {window to adjust} pos.child_p^.rect.x, pos.child_p^.rect.y, {bottom left corner} pos.child_p^.rect.dx, pos.child_p^.rect.dy); {displacement to upper right} gui_win_childpos_next (pos); {advance to next child in list} end; {back to adjust this next child window} end; { ************************************************************************* * * Local subroutine GUI_WIN_CREATE (WIN) * * This is the raw window object create routine. All other routines that * create a window object call this routine as part of their operation. * * The caller must previously fill in the following fields: * * PARENT_P - Pointer to parent window object, or NIL if this is a root * window. * RECT - This must not extend past the parent window, or the RENDlib * device area if this is a root window. * * After this routine returns, the caller must: * * If this is a root window, allocate and fill in the common data for * this window set pointed to by ALL_P. * * If this is a child window, then add it as a child to the parent window. } procedure gui_win_create ( {create bare window object} out win: gui_win_t); {returned initialized window object} val_param; internal; var mem_p: util_mem_context_p_t; {pointer to parent memory context} begin if win.parent_p = nil then begin {this is a root window} mem_p := addr(util_top_mem_context); {parent mem is root memory context} win.all_p := nil; {indicate window set data not created yet} win.pos.x := 0; {window is whole RENDlib device} win.pos.y := 0; end else begin {this is a child window} mem_p := win.parent_p^.mem_p; {parent mem context is from parent window} win.all_p := win.parent_p^.all_p; {copy pointer to window set common data} win.pos.x := {make RENDlib 2DIM of window upper left} win.parent_p^.pos.x + win.rect.x; win.pos.y := win.parent_p^.pos.y + win.parent_p^.rect.dy - win.rect.y - win.rect.dy; end ; util_mem_context_get (mem_p^, win.mem_p); {create memory context for this window} win.mem_p^.pool_size := mem_pool_size_k; {set our own mem pool parameters} win.mem_p^.max_pool_chunk := mem_chunk_size_k; win.n_child := 0; {init to no child windows} util_mem_grab ( {allocate mem for first child list block} sizeof(win.childblock_first_p^), {amount of mem to allocate} win.mem_p^, {memory context} false, {OK to use mem pool} win.childblock_first_p); {returned pointer to new memory} win.childblock_first_p^.prev_p := nil; win.childblock_first_p^.next_p := nil; {first block is end of blocks chain} win.childblock_last_p := win.childblock_first_p; {first block is last block} win.child_ind := 0; {first child block is completely empty} win.clip_rect.lx := 0.0; {set clip region to whole window} win.clip_rect.rx := win.rect.dx; win.clip_rect.by := 0.0; win.clip_rect.ty := win.rect.dy; util_stack_alloc (win.mem_p^, win.stack_clip); {create clip stack for this window} win.stack_clip^.stack_len := stack_block_size_k; {keep stack memory small} util_stack_push ( {create permanent backstop stack frame} win.stack_clip, {stack descriptor} sizeof(win.frame_clip_p^), {size of new stack frame} win.frame_clip_p); {returned pointer to new stack frame} win.frame_clip_p^.rect := win.clip_rect; {init backstop clip to whole window} win.draw := nil; {no draw routine installed} win.delete := nil; {no delete cleanup routine installed} win.evhan := nil; {no event handling routine installed} win.app_p := nil; {no pointer to private application data} win.draw_flag := []; {init all drawing flags to off} gui_win_clip_compute (win); {compute final resulting clip state} end; { ************************************************************************* * * Local function GUI_WIN_DRAWABLE (WIN) * * Returns TRUE if any window in the tree is drawable (has a draw routine * installed). } function gui_win_drawable ( {check for any part of window tree drawable} in out win: gui_win_t) {window object} :boolean; {TRUE if any window in tree has draw routine} var pos: gui_win_childpos_t; {position into child window list} begin gui_win_drawable := true; {init to some window in tree is drawable} if win.draw <> nil then return; {this window is drawable directly ?} gui_win_childpos_first (win, pos); {init to first child window in list} while pos.child_p <> nil do begin {once for each child window} if gui_win_drawable (pos.child_p^) then return; {this child tree drawable ?} gui_win_childpos_next (pos); {advance to next child window} end; {back to check next child tree} gui_win_drawable := false; {no window in tree has draw routine} end; { ************************************************************************* * * Subroutine GUI_WIN_RESIZE (WIN, X, Y, DX, DY) * * Change the size and position of an existing window. X,Y is one of the * new corners of the window, and DX,DY is the displacement from X,Y to * the opposite corner. } procedure gui_win_resize ( {resize and move a window} in out win: gui_win_t; {window object} in x, y: real; {window corner within parent window} in dx, dy: real); {displacement from the corner at X,Y} val_param; var drawable: boolean; {TRUE on window or children drawable} begin if win.parent_p = nil then return; {can't adjust root windows} drawable := gui_win_drawable (win); {TRUE if any window in tree has draw routine} if drawable then begin gui_win_erase (win); {erase window before moving it} end; gui_win_adjust (win, x, y, dx, dy); {adjust all windows in this tree} if drawable then begin gui_win_draw_all (win); {redisplay window with new size and position} end; end; { ************************************************************************* * * Local subroutine GUI_WIN_CHILD_ADD (WIN, CHILD) * * Add the window CHILD as a child window of WIN. } procedure gui_win_child_add ( {add child window to parent window} in out win: gui_win_t; {object of window to add child to} in out child: gui_win_t); {object of child window to add} val_param; internal; var pos: gui_win_childpos_t; {child list position object} begin gui_win_childpos_last (win, pos); {position to last child list entry} gui_win_childpos_next (pos); {make sure are past end of list} gui_win_childpos_wentry (pos, addr(child)); {add new child to end of list} end; { ************************************************************************* * * Local subroutine GUI_WIN_CHILD_DEL (WIN, CHILD) * * Remove window CHILD as a child window of WIN. Nothing is done if CHILD * is not a child of WIN. } procedure gui_win_child_del ( {remove child window} in out win: gui_win_t; {object of window to remove child from} in out child: gui_win_t); {object of child window to remove} val_param; internal; var to: gui_win_childpos_t; {destination child list block position} from: gui_win_childpos_t; {source child list block position} label found; begin { * Scan thru the list of child windows looking for the window to remove. } gui_win_childpos_first (win, to); {init position to first child list entry} while to.child_p <> nil do begin {once for each child window in the list} if to.child_p = addr(child) {found entry for this child window ?} then goto found; gui_win_childpos_next (to); {advance to next child list entry} end; {back to check this new list entry} return; {never found child in list} { * TO is positioned to the child list entry containing the window to * remove. } found: {found window to remove in child list} if win.n_child <= 1 then begin {removing the only child window ?} win.n_child := 0; win.child_ind := 0; return; end; { * Copy all the child list entries after this entry backwards one to * fill in the gap left by removing this entry. } from := to; gui_win_childpos_next (from); {init copy source to next list entry} while from.child_p <> nil do begin {once for each child list entry to move} gui_win_childpos_wentry (to, from.child_p); {copy entry from FROM to TO} gui_win_childpos_next (to); {advance destination position} gui_win_childpos_next (from); {advance source position} end; {back and copy this next entry} { * The list entries have been moved to fill the hole left by removing * the target child window. Now delete the last list entry. } win.child_ind := win.child_ind - 1; {update last index to last child list block} if win.child_ind <= 0 then begin {wrap back to start of previous block ?} win.child_ind := gui_childblock_size_k; win.childblock_last_p := win.childblock_last_p^.prev_p; end; win.n_child := win.n_child - 1; {count one less total child window} end; { ************************************************************************* * * Subroutine GUI_WIN_ROOT (WIN) * * Create the root GUI library window for the current RENDlib device. } procedure gui_win_root ( {create root window on curr RENDlib device} out win: gui_win_t); {returned window object} val_param; var dev_id: rend_dev_id_t; {RENDlib ID for current device} x_size, y_size: sys_int_machine_t; {size of RENDlib device in pixels} aspect: real; {RENDlib device aspect ratio} begin rend_set.enter_rend^; {push one level into graphics mode} rend_get.dev_id^ (dev_id); {get ID for current RENDlib device} rend_get.image_size^ (x_size, y_size, aspect); {get RENDlib device size} rend_set.exit_rend^; {pop one level back from graphics mode} win.parent_p := nil; {indicate this is a root window} win.rect.x := 0; {window covers whole RENDlib device} win.rect.y := 0; win.rect.dx := x_size; win.rect.dy := y_size; gui_win_create (win); {fill in and init rest of window object} util_mem_grab ( {allocate common state for this window set} sizeof(win.all_p^), {amount of memory to allocate} win.mem_p^, {memory context} false, {use pool if possible} win.all_p); {returned pointer to new memory} win.all_p^.root_p := addr(win); {set pointer to root window for this set} win.all_p^.rend_dev := dev_id; {save RENDlib device ID} rend_set.enter_rend^; {push one level into graphics mode} rend_get.clip_2dim_handle^ (win.all_p^.rend_clip); {get handle to new clip rect} rend_set.clip_2dim^ ( {set clip region to whole RENDlib device} win.all_p^.rend_clip, {clip rectangle handle} 0.0, x_size, {X limits} 0.0, y_size, {Y limits} true); {draw inside, clip outside} rend_set.exit_rend^; {pop one level back from graphics mode} win.all_p^.draw_high_p := nil; {init to no drawing in progress} win.all_p^.draw_low_p := nil; win.all_p^.drawing := false; end; { ************************************************************************* * * Subroutine GUI_WIN_CHILD (WIN, PARENT, X, Y, DX, DY) * * Create a child window to overlay an existing window. WIN will be returned * as the object for the new window. PARENT is the object for the window * to overlay. X, Y, DX, and DY describe the new window's position and size * in the parent window's coordinate space. The new window's actual size and * position is always clipped to the parent window. In other words, child * windows never exceed their parent windows. } procedure gui_win_child ( {create child window} out win: gui_win_t; {returned child window object} in out parent: gui_win_t; {object for parent window} in x, y: real; {a child window corner within parent space} in dx, dy: real); {child window dispacement from corner} val_param; var lx, rx, by, ty: real; {sorted window limits} ilx, irx, iby, ity: sys_int_machine_t; {integer window limits} begin win.parent_p := addr(parent); {set up as child window, identify parent} if dx >= 0.0 then begin {window extends right from corner point} lx := x; rx := x + dx; end else begin {window extends left from corner point} lx := x + dx; rx := x; end ; if dy >= 0.0 then begin {window extends up from corner point} by := y; ty := y + dy; end else begin {window extends down from corner point} by := y + dy; ty := y; end ; ilx := max(0, min(win.parent_p^.rect.dx, trunc(lx + 0.5))); irx := max(0, min(win.parent_p^.rect.dx, trunc(rx + 0.5))); iby := max(0, min(win.parent_p^.rect.dy, trunc(by + 0.5))); ity := max(0, min(win.parent_p^.rect.dy, trunc(ty + 0.5))); win.rect.x := ilx; {set new window position within parent} win.rect.dx := irx - ilx; win.rect.y := iby; win.rect.dy := ity - iby; gui_win_create (win); {fill in and init rest of window object} gui_win_child_add (parent, win) {add new window as child to parent window} end; { ************************************************************************* * * Function GUI_WIN_CLIP (WIN, LFT, RIT, BOT, TOP) * * Set a new clipping region for the window. This clip rectangle is merged with * the stacked clip state for the window. If any drawable pixels remain, * the RENDlib clip state is updated and the function returns TRUE. If * no drawable pixels are left, the RENDlib state is not altered and the * function returns FALSE. Note that the caller must inhibit whatever drawing * is associated with the clip region when the function returns FALSE, because * the RENDlib clip state is left in its previous condition. This routine * has no effect on the stacked clip state. } function gui_win_clip ( {set window clip region and update RENDlib} in out win: gui_win_t; {window object} in lft, rit, bot, top: real) {clip region rectangle coordinates} :boolean; {TRUE if any part enabled for current redraw} val_param; begin win.clip_rect.lx := lft; {save requested clip region in window obj} win.clip_rect.rx := rit; win.clip_rect.by := bot; win.clip_rect.ty := top; gui_win_clip_compute (win); {compute the final resulting clip region} if not win.not_clipped then begin {everything is clipped off ?} gui_win_clip := false; {indicate to inhibit drawing} return; end; gui_win_clip := true; {indicate draw region left, RENDlib clip set} rend_set.clip_2dim^ ( {set RENDlib clip rectangle} win.all_p^.rend_clip, {handle to clip rectangle} win.clip.x, {left X limit} win.clip.x + win.clip.dx, {right X limit} win.clip.y, {top Y limit} win.clip.y + win.clip.dy, {bottom Y limit} true); {draw inside, clip outside} end; { ************************************************************************* * * Function GUI_WIN_CLIP_PUSH (WIN, LFT, RIT, BOT, TOP) * * Push a new clip region onto the clip stack for this window if any pixels * remain drawable after the new clip region is taken into account. * * If drawable pixels remain, this routine: * * 1 - Pushes the clip region from the call arguments onto the clip stack * for this window. * * 2 - Sets the non-stacked clip region to the remaining drawable region. * The previous non-stacked clip region is irrelevant. * * 3 - Sets the RENDlib clip state to the new drawable region. * * 4 - Returns TRUE. * * If no drawable pixels remain, this routine: * * 1 - Does not alter the clip stack. * * 2 - Trashes the non-stacked clip region. * * 3 - Returns FALSE. This indicates to the caller to NOT perform a * corresponding POP of the clip stack, and to inhibit any drawing * associated with the clip region. The caller must do this explicitly * since the RENDlib clip state is not updated, and is essentially * invalid. } function gui_win_clip_push ( {push clip region onto stack, update RENDlib} in out win: gui_win_t; {window object} in lft, rit, bot, top: real) {clip region rectangle coordinates} :boolean; {TRUE if any part enabled for current redraw} val_param; var drawable: boolean; {TRUE if some pixels drawable after new clip} begin drawable := gui_win_clip (win, lft, rit, bot, top); {set as non-stacked clip first} gui_win_clip_push := drawable; {indicate whether drawable region after clip} if not drawable then return; {everything clipped off, nothing more to do ?} { * The new clip rectangle has been temporarily set as the non-stacked clip * region. Drawable pixels definitely remain, and the RENDlib clip state * has been updated accordingly. } win.clip_rect.lx := {set non-stacked to combined clip region} max(win.clip_rect.lx, win.frame_clip_p^.rect.lx); win.clip_rect.rx := min(win.clip_rect.rx, win.frame_clip_p^.rect.rx); win.clip_rect.by := max(win.clip_rect.by, win.frame_clip_p^.rect.by); win.clip_rect.ty := min(win.clip_rect.ty, win.frame_clip_p^.rect.ty); util_stack_push ( {create new frame on top of clip stack} win.stack_clip, sizeof(win.frame_clip_p^), win.frame_clip_p); win.frame_clip_p^.rect := win.clip_rect; {fill in new stack frame} end; { ************************************************************************* * * Function GUI_WIN_CLIP_PUSH_2D (WIN, LFT, RIT, BOT, TOP) * * Just like GUI_WIN_CLIP_PUSH, except that clip region is specified in * the current RENDlib 2D coordinate space instead of the GUI window * coordinate space. * * Clip regions are always rectangles that are axis aligned with the * window edges. The smallest clip region will be chosen that encompasses * all four corners of the 2D space rectangle specified by the call arguments. } function gui_win_clip_push_2d ( {push clip region onto stack, update RENDlib} in out win: gui_win_t; {window object} in lft, rit, bot, top: real) {clip region rectangle coor, RENDlib 2D space} :boolean; {TRUE if any part enabled for current redraw} val_param; var xmin, xmax: real; {2DIM X limits of clip region} ymin, ymax: real; {2DIM Y limits of clip region} p1, p2: vect_2d_t; {for transforming a point} begin p1.x := lft; {lower left corner} p1.y := bot; rend_get.xfpnt_2d^ (p1, p2); xmin := p2.x; xmax := p2.x; ymin := p2.y; ymax := p2.y; p1.x := rit; {lower right corner} rend_get.xfpnt_2d^ (p1, p2); xmin := min(xmin, p2.x); xmax := max(xmax, p2.x); ymin := min(ymin, p2.y); ymax := max(ymax, p2.y); p1.y := top; {upper right corner} rend_get.xfpnt_2d^ (p1, p2); xmin := min(xmin, p2.x); xmax := max(xmax, p2.x); ymin := min(ymin, p2.y); ymax := max(ymax, p2.y); p1.x := lft; {upper left corner} rend_get.xfpnt_2d^ (p1, p2); xmin := min(xmin, p2.x); xmax := max(xmax, p2.x); ymin := min(ymin, p2.y); ymax := max(ymax, p2.y); gui_win_clip_push_2d := gui_win_clip_push ( {do clip in GUI window coordinates} win, {window clipping within} xmin - win.pos.x, {left} xmax - win.pos.x, {right} win.rect.dy + win.pos.y - ymax, {bottom} win.rect.dy + win.pos.y - ymin); {top} end; { ************************************************************************* * * Subroutine GUI_WIN_CLIP_POP (WIN) * * Pop the top entry from the window's clip stack, and update the clip state * accordingly. The non-stacked clip region will be set to the maximum * drawable region allowed by the stacked clip state. The previous contents * of the non-stacked clip region are lost. * * Attempting to pop a stack frame that was not previously explicitly pushed * can result in all manner of destruction. Don't do this! } procedure gui_win_clip_pop ( {pop clip region from stack, update RENDlib} in out win: gui_win_t); {window object} val_param; begin util_stack_pop ( {remove top stack frame} win.stack_clip, sizeof(win.frame_clip_p^)); util_stack_last_frame ( {get pointer to new top stack frame} win.stack_clip, sizeof(win.frame_clip_p^), win.frame_clip_p); win.clip_rect := win.frame_clip_p^.rect; {set to max region allowed by stack} gui_win_clip_compute (win); {compute final RENDlib 2DIM clip region} rend_set.clip_2dim^ ( {set RENDlib clip rectangle} win.all_p^.rend_clip, {handle to clip rectangle} win.clip.x, {left X limit} win.clip.x + win.clip.dx, {right X limit} win.clip.y, {top Y limit} win.clip.y + win.clip.dy, {bottom Y limit} true); {draw inside, clip outside} end; { ************************************************************************* * * Subroutine GUI_WIN_DELETE (WIN) * * Delete the indicated window and all its children. The area underneath * the window will be repainted with the contents of the windows that were * "covered up". Nothing is redrawn if the root window is being deleted. } procedure gui_win_delete ( {delete a window and all its children} in out win: gui_win_t); {object for window to delete} val_param; var pos: gui_win_childpos_t; {child list position state} top: boolean; {TRUE if this is top DELETE call} begin top := not win.all_p^.drawing; {set flag if this is top level DELETE call} win.all_p^.drawing := true; {prevent all other calls from being top level} { * Delete all the child windows recursively. This makes sure all window * delete cleanup routines are run. } gui_win_childpos_last (win, pos); {start at last child window} while pos.child_p <> nil do begin {once for each child window} gui_win_delete (pos.child_p^); {delete the child window} gui_win_childpos_prev (pos); {advance to previous child window} end; {back and process this new child window} { * All child windows have been deleted. Now delete this window. } if top then begin {this is the top level DELETE call ?} win.all_p^.drawing := false; {reset top call interlock} gui_win_draw_behind ( {erase window by drawing what is underneath} win, {window to draw what is below of} 0.0, win.rect.dx, {X limits of redraw area} 0.0, win.rect.dy); {Y limits of redraw area} end; if win.delete <> nil then begin {this window has app delete cleanup routine ?} win.delete^ (addr(win), win.app_p); {call app delete cleanup routine} end; if win.parent_p = nil then begin {deleting the root window ?} rend_set.clip_2dim_delete^ ( {delete RENDlib clip window we were using} win.all_p^.rend_clip); end else begin {other windows in this set will remain} gui_win_child_del (win.parent_p^, win); {remove as child of parent window} end ; util_mem_context_del (win.mem_p); {deallocate all dynamically allocated memory} end; { ************************************************************************* * * Local subroutine GUI_WIN_DRAWFLAGS_CLEAR (WIN) * * Clear the drawing flags for the window tree starting at WIN, except * not for the window pointed to by DRAW_LOW_P or lower in the ALL block * for this window set. DRAW_LOW_P may be NIL to indicate unconditionally * clear the flag for all windows in the WIN tree. The LOW_REACHED * flag must be set to FALSE on entry and will be trashed. } procedure gui_win_drawflags_clear ( {clear draw flags in tree of windows} in out win: gui_win_t); {root window of tree to clear} val_param; internal; var pos: gui_win_childpos_t; {child list position state} begin if addr(win) = win.all_p^.draw_low_p then begin {hit low limit window ?} win.all_p^.low_reached := true; {indicate low limit has been reached} return; end; win.draw_flag := []; {clear draw flags for this window} gui_win_childpos_first (win, pos); {init position to first child window in list} while pos.child_p <> nil do begin {once for each child window} gui_win_drawflags_clear (pos.child_p^); {clear flags for this child tree} if win.all_p^.low_reached then return; {already hit low window limit ?} gui_win_childpos_next (pos); {advance to next child window in list} end; {back to process this new child window} end; { ************************************************************************* * * Subroutine GUI_WIN_XF2D_SET (WIN) * * Set the RENDlib 2D transform to set up the GUI library standard coordinate * space for the window WIN. The previous RENDlib 2D transform is lost. * * The GUI library standard coordinates for each window put 0,0 in the lower * left corner. X increases to the right and Y increases up. X and Y are * both in units of pixels. The RENDlib 2D transformation converts from * the application's 2D model coordinate space into a space where the * -1 to +1 X,Y square is centered and maximized within the device. } procedure gui_win_xf2d_set ( {set standard 2D coordinate space for window} in out win: gui_win_t); {window object} val_param; var x_size, y_size: sys_int_machine_t; {pixel size of RENDlib device} aspect: real; {width/height aspect ratio of RENDlib device} xb, yb, ofs: vect_2d_t; {2D transform} begin rend_set.enter_rend^; {push one level into graphics mode} xb.y := 0.0; {fill in fixed part of transform} yb.x := 0.0; rend_get.image_size^ (x_size, y_size, aspect); {get device size and aspect ratio} if aspect >= 1.0 then begin {device is wider than tall} xb.x := (2.0 * aspect) / x_size; yb.y := 2.0 / y_size; ofs.x := (-1.0 * aspect) + win.pos.x * xb.x; ofs.y := -1.0 + (y_size - win.pos.y - win.rect.dy) * yb.y; end else begin {device is taller than wide} xb.x := 2.0 / x_size; yb.y := (2.0 / aspect) / y_size; ofs.x := -1.0 + win.pos.x * xb.x; ofs.y := -1.0/aspect + (y_size - win.pos.y - win.rect.dy) * yb.y; end ; rend_set.xform_2d^ (xb, yb, ofs); {set new RENDlib transform for this window} rend_set.exit_rend^; {pop one level from graphics mode} end; { ************************************************************************* * * Subroutine GUI_WIN_DRAW_RAW (WIN, LX, RX, BY, TY) * * Just draw the indicated region of the window WIN. } procedure gui_win_draw_raw ( {low level window draw} in out win: gui_win_t; {object for window to draw contents of} in lx, rx: real; {left and right redraw region limits} in by, ty: real); {bottom and top redraw region limits} val_param; internal; var xb, yb, ofs: vect_2d_t; {saved copy of RENDlib 2D transform} begin if gui_wdraw_done_k in win.draw_flag {this window already drawn ?} then return; win.draw_flag := win.draw_flag + [gui_wdraw_done_k]; {prevent drawing twice} if win.draw = nil then return; {this window has no draw routine} if not gui_win_clip_push (win, lx, rx, by, ty) {everything is clipped away ?} then return; rend_set.enter_rend^; {push one level into graphics mode} rend_get.xform_2d^ (xb, yb, ofs); {save old RENDlib 2D transform} gui_win_xf2d_set (win); {set RENDlib 2D transform for this window} win.draw^ (addr(win), win.app_p); {draw this window} rend_set.xform_2d^ (xb, yb, ofs); {restore old RENDlib 2D transform} rend_set.exit_rend^; {pop one level from graphics mode} gui_win_clip_pop (win); {pop our redraw clip region} end; { ************************************************************************* * * Subroutine GUI_WIN_DRAW (WIN, LX, RX, BY, TY) * * Draw the indicated region of the window. Only this and lower windows * (decendents) will be drawn as appropriate. Only the rectangle indicated * by the last four call arguments will be drawn. } procedure gui_win_draw ( {draw window contents} in out win: gui_win_t; {object for window to draw contents of} in lx, rx: real; {left and right redraw region limits} in by, ty: real); {bottom and top redraw region limits} val_param; var pos: gui_win_childpos_t; {child list position state} top: boolean; {TRUE if this is top draw request} begin top := not win.all_p^.drawing; {TRUE if this is original draw request} if top then begin {need to set state for original draw ?} rend_dev_set (win.all_p^.rend_dev); {make sure right RENDlib device is current} win.all_p^.drawing := true; {indicate drawing is now in progress} win.all_p^.draw_high_p := addr(win); {don't draw any window above this one} win.all_p^.draw_low_p := nil; {no restriction on lowest drawable window} win.all_p^.low_reached := false; {indicate low limit window not reached yet} gui_win_drawflags_clear (win); {clear draw flags for all candidate windows} win.all_p^.low_reached := false; {reset flag trashed by DRAWFLAGS_CLEAR} end; if addr(win) = win.all_p^.draw_low_p then begin {not supposed to draw this win ?} win.all_p^.low_reached := true; {indicate low limit window has been reached} return; end; { * Draw this window if appropriate. } gui_win_draw_raw (win, lx, rx, by, ty); {draw the window contents} gui_win_childpos_first (win, pos); {init position to first child window in list} while pos.child_p <> nil do begin {once for each child window} gui_win_draw ( {draw this child window} pos.child_p^, {window to draw} lx - pos.child_p^.rect.x, {draw region in child window coordinates} rx - pos.child_p^.rect.x, by - pos.child_p^.rect.y, ty - pos.child_p^.rect.y); if win.all_p^.low_reached then exit; {tree traversal limit reached ?} gui_win_childpos_next (pos); {advance to next child window in list} end; {back to process this new child window} { * Done drawing all the windows. } if top then begin {completed entire original draw request ?} win.all_p^.drawing := false; {reset to no drawing in progress} end; end; { ************************************************************************* * * Subroutine GUI_WIN_DRAW_ALL (WIN) * * Draw the whole window. } procedure gui_win_draw_all ( {draw entire window contents} in out win: gui_win_t); {object for window to draw contents of} val_param; begin gui_win_draw ( win, {window to draw} 0.0, win.rect.dx, {left and right draw limits} 0.0, win.rect.dy); {bottom and top draw limits} end; { ************************************************************************* * * Subroutine GUI_WIN_DRAW_BEHIND (WIN, LX, RX, BY, TY) * * Draw the indicated region below the window. This causes the rectangle * to be refreshed with whatever the window WIN is drawn on top of. * GUI_WIN_DRAW_BEHIND is intended for use by windows that are not fully * opaque, and for use when a window is deleted. This routine essentially * erases the window WIN. } procedure gui_win_draw_behind ( {draw what is behind a window} in out win: gui_win_t; {object for window to draw behind of} in lx, rx: real; {left and right redraw region limits} in by, ty: real); {bottom and top redraw region limits} val_param; var dx, dy: real; {coor offset from this window to root window} top: boolean; {TRUE if this is top draw request} begin if win.parent_p = nil then return; {there is nothing behind top window} top := not win.all_p^.drawing; {TRUE if this is original draw request} with win.all_p^.root_p^: root do begin {ROOT is abbrev for root window} if top then begin {need to set state for original draw ?} rend_dev_set (win.all_p^.rend_dev); {make sure right RENDlib device is current} win.all_p^.drawing := true; {indicate drawing is now in progress} win.all_p^.draw_high_p := nil; {we can draw all the way up to the root win} win.all_p^.draw_low_p := addr(win); {stop before drawing this window} win.all_p^.low_reached := false; {indicate low limit window not reached yet} gui_win_drawflags_clear (root); {clear all drawing flags} win.all_p^.low_reached := false; {reset flag trashed by DRAWFLAGS_CLEAR} end; dx := win.pos.x - root.pos.x; {make offsets for translating to root window} dy := (root.pos.y + root.rect.dy) - (win.pos.y + win.rect.dy); gui_win_draw ( {redraw requested rectangle starting at root} root, {window at top of tree to redraw} lx + dx, rx + dx, {left and right redraw limits} by + dy, ty + dy); {bottom and top redraw limits} { * Done drawing all the windows. } if top then begin {completed entire original draw request ?} win.all_p^.drawing := false; {reset to no drawing in progress} end; end; {done with ROOT abbreviation} end; { ************************************************************************* * * Subroutine GUI_WIN_ERASE (WIN) * * Erase the window. } procedure gui_win_erase ( {draw what is behind entire window} in out win: gui_win_t); {object for window to draw behind of} val_param; begin gui_win_draw_behind ( {draw what is behind the window} win, {the window} 0.0, win.rect.dx, {left and right redraw limits} 0.0, win.rect.dy); {bottom and top redraw limits} end; { ************************************************************************* * * Subroutine GUI_WIN_ALLOC_STATIC (WIN, SIZE, P) * * Allocate new memory that will be automatically deallocated when the * window is deleted. It will not be possible to individually deallocate * this memory. } procedure gui_win_alloc_static ( {allocate static mem deleted on win delete} in out win: gui_win_t; {window object} in size: sys_int_adr_t; {amount of memory to allocate} out p: univ_ptr); {returned pointing to new memory} val_param; begin util_mem_grab ( {allocate memory} size, {amount of memory to allocate} win.mem_p^, {memory context} false, {use pool if possible} p); {returned pointer to the new memory} end; { ************************************************************************* * * Subroutine GUI_WIN_SET_APP_PNT (WIN, APP_P) * * Set pointer to application-specific data for this window. Any previous * app pointer is lost. The application-specific data can be used for any * purpose by the application, and will be passed to the draw and event * handler routines for this window. } procedure gui_win_set_app_pnt ( {set pointer to application private data} in out win: gui_win_t; {window object} in app_p: univ_ptr); {pointer to arbitrary application data} val_param; begin win.app_p := app_p; end; { ************************************************************************* * * Subroutine GUI_WIN_GET_APP_PNT (WIN, APP_P) * * Returns the pointer to the application-specific data for this window. } procedure gui_win_get_app_pnt ( {get pointer to application private data} in out win: gui_win_t; {window object} out app_p: univ_ptr); {returned pointer to arbitrary app data} val_param; begin app_p := win.app_p; end; { ************************************************************************* * * Subroutine GUI_WIN_SET_DRAW (WIN, ROUT_P) * * Set the routine to be called to redraw this window. } procedure gui_win_set_draw ( {set window's draw routine} in out win: gui_win_t; {window object} in rout_p: univ gui_draw_p_t); {pointer to window's new draw routine} val_param; begin win.draw := rout_p; end; { ************************************************************************* * * Subroutine GUI_WIN_SET_DELETE (WIN, ROUT_P) * * Set the routine to be called to redraw this window. } procedure gui_win_set_delete ( {set window's delete cleanup routine} in out win: gui_win_t; {window object} in rout_p: univ gui_delete_p_t); {pointer to window's new cleanup routine} val_param; begin win.delete := rout_p; end; { ************************************************************************* * * Subroutine GUI_WIN_SET_EVHAN (WIN, ROUT_P) * * Set the routine to be called to handle events for this window. } procedure gui_win_set_evhan ( {set window's event handler routine} in out win: gui_win_t; {window object} in rout_p: univ gui_evhan_p_t); {pointer to window's new event handler} val_param; begin win.evhan := rout_p; end; { ************************************************************************* * * Subroutine GUI_WIN_TOFRONT (WIN) * * Make this window the last window in the parent's child list. This has * the effect of bringing the window in front of all its other sibling * windows. } procedure gui_win_tofront ( {make last child in parent's child list} in out win: gui_win_t); {window object} val_param; var pos: gui_win_childpos_t; {child list position state} par_p: gui_win_p_t; {pointer to parent window} begin par_p := win.parent_p; {get pointer to parent window} if par_p = nil then return; {no parent window ?} gui_win_childpos_last (win, pos); {go to last entry in parent's child list} if pos.child_p = addr(win) {already last entry in child list ?} then return; { * The window is not currently the last child of the parent. } gui_win_child_del (par_p^, win); {remove from parent's child list} gui_win_child_add (par_p^, win); {add back at end of list} gui_win_draw_all (win); {update display of window moved to font} end;
unit GetProcAddressR; interface type FARPROC = function:Integer; function GetProcAddressR_(hModule:THandle;const lpProcName:PAnsiChar ):FARPROC;stdcall; implementation uses Windows,SysUtils; function DEREF_32(name:Cardinal):DWORD; begin Result:=PDWORD(name)^; end; function DEREF_16(name:Cardinal):Word; begin Result:=PWORD(name)^; end; function GetProcAddressR_(hModule:THandle;const lpProcName:PAnsiChar ):FARPROC;stdcall; var uiLibraryAddress:Cardinal; fpResult:FARPROC; pNtHeaders:PIMAGENTHEADERS; pDataDirectory:PIMAGEDATADIRECTORY; pExportDirectory:PIMAGEEXPORTDIRECTORY; uiAddressArray:Cardinal; uiNameArray:Cardinal; uiNameOrdinals:Cardinal; dwCounter:DWORD; I:Cardinal; cpExportedFunctionName:PAnsiChar; begin Result:= nil; if hModule = 0 then Exit; uiLibraryAddress:=hModule; try pNtHeaders := PIMAGENTHEADERS(uiLibraryAddress + PIMAGEDOSHEADER(uiLibraryAddress)._lfanew); pDataDirectory := PIMAGEDATADIRECTORY(Cardinal(@pNtHeaders.OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ])); pExportDirectory := PIMAGEEXPORTDIRECTORY( uiLibraryAddress + pDataDirectory.VirtualAddress ); uiAddressArray := ( uiLibraryAddress + Cardinal(pExportDirectory.AddressOfFunctions) ); uiNameArray:=(uiLibraryAddress + Cardinal(pExportDirectory.AddressOfNames) ); uiNameOrdinals := ( uiLibraryAddress + Cardinal(pExportDirectory.AddressOfNameOrdinals) ); if ((Cardinal(lpProcName) and $FFFF0000 ) = $0)then begin uiAddressArray :=uiAddressArray + ( ( ( Cardinal(lpProcName) - pExportDirectory.Base ) * SizeOf(DWORD) )); fpResult := FARPROC( uiLibraryAddress + DEREF_32(uiAddressArray) ); end else begin dwCounter:=pExportDirectory.NumberOfNames; if dwCounter = 0 then Exit; for I := dwCounter - 1 downto 0 do begin cpExportedFunctionName:=PAnsiChar(uiLibraryAddress + DEREF_32( uiNameArray )); if (StrComp(cpExportedFunctionName,lpProcName) = 0) then begin uiAddressArray :=uiAddressArray + ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) ); fpResult := FARPROC((uiLibraryAddress + DEREF_32( uiAddressArray ))); Break; end; uiNameArray :=uiNameArray + sizeof(DWORD); uiNameOrdinals :=uiNameOrdinals + sizeof(WORD); end; end; except end; end; end.
unit UpdateParamValueRec; interface uses System.Generics.Collections; type TUpdParamSubParam = class private FFamilyID: Integer; FParamSubParamID: Integer; public constructor Create(AFamilyID, AParamSubParamID: Integer); function IsSame(AUpdParam: TUpdParamSubParam): Boolean; property FamilyID: Integer read FFamilyID; property ParamSubParamID: Integer read FParamSubParamID; end; type TUpdParamSubParamList = class(TObjectList<TUpdParamSubParam>) public function Search(AFamilyID, AParamSubParamID: Integer): Integer; end; implementation function TUpdParamSubParamList.Search(AFamilyID, AParamSubParamID: Integer): Integer; var I: Integer; begin Assert(AFamilyID > 0); Assert(AParamSubParamID > 0); Result := -1; for I := 0 to Count - 1 do begin if (Items[I].FamilyID = AFamilyID) and (Items[I].ParamSubParamID = AParamSubParamID) then begin Result := I; Exit; end; end; end; constructor TUpdParamSubParam.Create(AFamilyID, AParamSubParamID: Integer); begin Assert(AFamilyID > 0); Assert(AParamSubParamID > 0); FFamilyID := AFamilyID; FParamSubParamID := AParamSubParamID; end; function TUpdParamSubParam.IsSame(AUpdParam: TUpdParamSubParam): Boolean; begin Assert(AUpdParam <> nil); Result := (FFamilyID = AUpdParam.FamilyID) and (FParamSubParamID = AUpdParam.ParamSubParamID); end; end.
unit ufrmAbout; interface {$I ThsERP.inc} uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmBase, Vcl.AppEvnts, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Samples.Spin // , dxGDIPlusClasses, ; type TfrmAbout = class(TfrmBase) lblArchitecture: TLabel; lblValArchitecture: TLabel; imgLogo: TImage; lblWindowsOSVersion: TLabel; lblValWindowsOSVersion: TLabel; lblDeveloper: TLabel; lblValDeveloper: TLabel; lblCompany: TLabel; lblValCompany: TLabel; lblCpuInfo: TLabel; lblValCpuInfo: TLabel; lblRamInfo: TLabel; lblValRamInfo: TLabel; procedure FormCreate(Sender: TObject);override; private { Private declarations } public end; implementation uses System.Win.Registry; {$R *.dfm} procedure TfrmAbout.FormCreate(Sender: TObject); var vMyOSver: _OSVERSIONINFOW; vMemoryStatus: _MEMORYSTATUSEX; vReg: TRegistry; begin inherited; btnClose.Visible := True; vMyOSver.dwOSVersionInfoSize := SizeOf(_OSVERSIONINFOW); GetVersionEx(vMyOSver); lblValArchitecture.Caption := TOSVersion.ToString; lblValWindowsOSVersion.Caption := vMyOSver.dwMajorVersion.ToString; //if give parameter KEY_READ dont need administration right vReg := TRegistry.Create(KEY_READ); try vReg.RootKey := HKEY_LOCAL_MACHINE; if vReg.OpenKey('\Hardware\Description\System\CentralProcessor\0', False) then begin lblValCpuInfo.Caption := vReg.ReadString('Identifier') + ' ' + vReg.ReadString('ProcessorNameString'); end; finally vReg.Free; end; vMemoryStatus.dwLength := SizeOf(vMemoryStatus); GlobalMemoryStatusEx(vMemoryStatus); lblValRamInfo.Caption := (Round((vMemoryStatus.ullTotalPhys/1024)/1024/1024)).ToString + ' GB'; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TfrmInfo = class(TForm) Label1: TLabel; lblAmbient: TLabel; lblDiffuse: TLabel; Label3: TLabel; lblSpecular: TLabel; Label4: TLabel; Label2: TLabel; lblRGB: TLabel; Label5: TLabel; Bevel1: TBevel; Label6: TLabel; Label7: TLabel; lblMatAmbient: TLabel; lblMatDiffuse: TLabel; Label10: TLabel; lblMatSpecular: TLabel; Label12: TLabel; Label8: TLabel; lblMatEmission: TLabel; Label9: TLabel; lblMatShininess: TLabel; procedure FormShow(Sender: TObject); procedure FormDeactivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmInfo: TfrmInfo; implementation uses frmMain; {$R *.DFM} procedure TfrmInfo.FormShow(Sender: TObject); begin lblAmbient.Caption := '(' + FloatToStr (frmGL.Ambient[0]) + '; ' + FloatToStr (frmGL.Ambient[1]) + '; ' + FloatToStr (frmGL.Ambient[2]) + ')'; lblDiffuse.Caption := '(' + FloatToStr (frmGL.Diffuse[0]) + '; ' + FloatToStr (frmGL.Diffuse[1]) + '; ' + FloatToStr (frmGL.Diffuse[2]) + ')'; lblSpecular.Caption := '(' + FloatToStr (frmGL.Specular[0]) + '; ' + FloatToStr (frmGL.Specular[1]) + '; ' + FloatToStr (frmGL.Specular[2]) + ')'; lblMatAmbient.Caption := '(' + FloatToStr (frmGL.MaterialAmbient[0]) + '; ' + FloatToStr (frmGL.MaterialAmbient[1]) + '; ' + FloatToStr (frmGL.MaterialAmbient[2]) + ')'; lblMatDiffuse.Caption := '(' + FloatToStr (frmGL.MaterialDiffuse[0]) + '; ' + FloatToStr (frmGL.MaterialDiffuse[1]) + '; ' + FloatToStr (frmGL.MaterialDiffuse[2]) + ')'; lblMatSpecular.Caption := '(' + FloatToStr (frmGL.MaterialSpecular[0]) + '; ' + FloatToStr (frmGL.MaterialSpecular[1]) + '; ' + FloatToStr (frmGL.MaterialSpecular[2]) + ')'; lblMatEmission.Caption := '(' + FloatToStr (frmGL.MaterialEmission[0]) + '; ' + FloatToStr (frmGL.MaterialEmission[1]) + '; ' + FloatToStr (frmGL.MaterialEmission[2]) + ')'; lblMatShininess.Caption := FloatToStr (frmGL.Shininess); end; procedure TfrmInfo.FormDeactivate(Sender: TObject); begin Close end; end.
unit MonthCalendarImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls; type TMonthCalendarX = class(TActiveXControl, IMonthCalendarX) private { Private declarations } FDelphiControl: TMonthCalendar; FEvents: IMonthCalendarXEvents; procedure ClickEvent(Sender: TObject); procedure DblClickEvent(Sender: TObject); procedure GetMonthInfoEvent(Sender: TObject; Month: Cardinal; var MonthBoldInfo: Cardinal); procedure KeyPressEvent(Sender: TObject; var Key: Char); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_AutoSize: WordBool; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Cursor: Smallint; safecall; function Get_Date: Double; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_EndDate: Double; safecall; function Get_FirstDayOfWeek: TxCalDayOfWeek; safecall; function Get_Font: IFontDisp; safecall; function Get_ImeMode: TxImeMode; safecall; function Get_ImeName: WideString; safecall; function Get_MaxDate: Double; safecall; function Get_MaxSelectRange: Integer; safecall; function Get_MinDate: Double; safecall; function Get_MultiSelect: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_ShowToday: WordBool; safecall; function Get_ShowTodayCircle: WordBool; safecall; function Get_Visible: WordBool; safecall; function Get_WeekNumbers: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_AutoSize(Value: WordBool); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_Date(Value: Double); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_EndDate(Value: Double); safecall; procedure Set_FirstDayOfWeek(Value: TxCalDayOfWeek); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_ImeMode(Value: TxImeMode); safecall; procedure Set_ImeName(const Value: WideString); safecall; procedure Set_MaxDate(Value: Double); safecall; procedure Set_MaxSelectRange(Value: Integer); safecall; procedure Set_MinDate(Value: Double); safecall; procedure Set_MultiSelect(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_ShowToday(Value: WordBool); safecall; procedure Set_ShowTodayCircle(Value: WordBool); safecall; procedure Set_Visible(Value: WordBool); safecall; procedure Set_WeekNumbers(Value: WordBool); safecall; end; implementation uses ComObj, About18; { TMonthCalendarX } procedure TMonthCalendarX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_MonthCalendarXPage); } end; procedure TMonthCalendarX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IMonthCalendarXEvents; end; procedure TMonthCalendarX.InitializeControl; begin FDelphiControl := Control as TMonthCalendar; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnGetMonthInfo := GetMonthInfoEvent; FDelphiControl.OnKeyPress := KeyPressEvent; end; function TMonthCalendarX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TMonthCalendarX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TMonthCalendarX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TMonthCalendarX.Get_AutoSize: WordBool; begin Result := FDelphiControl.AutoSize; end; function TMonthCalendarX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TMonthCalendarX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TMonthCalendarX.Get_Date: Double; begin Result := Double(FDelphiControl.Date); end; function TMonthCalendarX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TMonthCalendarX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TMonthCalendarX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TMonthCalendarX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TMonthCalendarX.Get_EndDate: Double; begin Result := Double(FDelphiControl.EndDate); end; function TMonthCalendarX.Get_FirstDayOfWeek: TxCalDayOfWeek; begin Result := Ord(FDelphiControl.FirstDayOfWeek); end; function TMonthCalendarX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TMonthCalendarX.Get_ImeMode: TxImeMode; begin Result := Ord(FDelphiControl.ImeMode); end; function TMonthCalendarX.Get_ImeName: WideString; begin Result := WideString(FDelphiControl.ImeName); end; function TMonthCalendarX.Get_MaxDate: Double; begin Result := Double(FDelphiControl.MaxDate); end; function TMonthCalendarX.Get_MaxSelectRange: Integer; begin Result := FDelphiControl.MaxSelectRange; end; function TMonthCalendarX.Get_MinDate: Double; begin Result := Double(FDelphiControl.MinDate); end; function TMonthCalendarX.Get_MultiSelect: WordBool; begin Result := FDelphiControl.MultiSelect; end; function TMonthCalendarX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TMonthCalendarX.Get_ShowToday: WordBool; begin Result := FDelphiControl.ShowToday; end; function TMonthCalendarX.Get_ShowTodayCircle: WordBool; begin Result := FDelphiControl.ShowTodayCircle; end; function TMonthCalendarX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TMonthCalendarX.Get_WeekNumbers: WordBool; begin Result := FDelphiControl.WeekNumbers; end; function TMonthCalendarX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TMonthCalendarX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TMonthCalendarX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TMonthCalendarX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TMonthCalendarX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TMonthCalendarX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TMonthCalendarX.AboutBox; begin ShowMonthCalendarXAbout; end; procedure TMonthCalendarX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TMonthCalendarX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TMonthCalendarX.Set_AutoSize(Value: WordBool); begin FDelphiControl.AutoSize := Value; end; procedure TMonthCalendarX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TMonthCalendarX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TMonthCalendarX.Set_Date(Value: Double); begin FDelphiControl.Date := TDate(Value); end; procedure TMonthCalendarX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TMonthCalendarX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TMonthCalendarX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TMonthCalendarX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TMonthCalendarX.Set_EndDate(Value: Double); begin FDelphiControl.EndDate := TDate(Value); end; procedure TMonthCalendarX.Set_FirstDayOfWeek(Value: TxCalDayOfWeek); begin FDelphiControl.FirstDayOfWeek := TCalDayOfWeek(Value); end; procedure TMonthCalendarX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TMonthCalendarX.Set_ImeMode(Value: TxImeMode); begin FDelphiControl.ImeMode := TImeMode(Value); end; procedure TMonthCalendarX.Set_ImeName(const Value: WideString); begin FDelphiControl.ImeName := TImeName(Value); end; procedure TMonthCalendarX.Set_MaxDate(Value: Double); begin FDelphiControl.MaxDate := TDate(Value); end; procedure TMonthCalendarX.Set_MaxSelectRange(Value: Integer); begin FDelphiControl.MaxSelectRange := Value; end; procedure TMonthCalendarX.Set_MinDate(Value: Double); begin FDelphiControl.MinDate := TDate(Value); end; procedure TMonthCalendarX.Set_MultiSelect(Value: WordBool); begin FDelphiControl.MultiSelect := Value; end; procedure TMonthCalendarX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TMonthCalendarX.Set_ShowToday(Value: WordBool); begin FDelphiControl.ShowToday := Value; end; procedure TMonthCalendarX.Set_ShowTodayCircle(Value: WordBool); begin FDelphiControl.ShowTodayCircle := Value; end; procedure TMonthCalendarX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TMonthCalendarX.Set_WeekNumbers(Value: WordBool); begin FDelphiControl.WeekNumbers := Value; end; procedure TMonthCalendarX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TMonthCalendarX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TMonthCalendarX.GetMonthInfoEvent(Sender: TObject; Month: Cardinal; var MonthBoldInfo: Cardinal); var TempMonthBoldInfo: Integer; begin TempMonthBoldInfo := Integer(MonthBoldInfo); if FEvents <> nil then FEvents.OnGetMonthInfo(Integer(Month), TempMonthBoldInfo); MonthBoldInfo := Cardinal(TempMonthBoldInfo); end; procedure TMonthCalendarX.KeyPressEvent(Sender: TObject; var Key: Char); var TempKey: Smallint; begin TempKey := Smallint(Key); if FEvents <> nil then FEvents.OnKeyPress(TempKey); Key := Char(TempKey); end; initialization TActiveXControlFactory.Create( ComServer, TMonthCalendarX, TMonthCalendar, Class_MonthCalendarX, 18, '{695CDB61-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/chain.h // Bitcoin file: src/chain.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TChain; interface type // /** An in-memory indexed chain of blocks. */ TChain = class private: std::vector<CBlockIndex*> vChain; public: // /** Returns the index entry for the genesis block of this chain, or nullptr if none. */ CBlockIndex *Genesis() const { return vChain.size() > 0 ? vChain[0] : nullptr; } // /** Returns the index entry for the tip of this chain, or nullptr if none. */ CBlockIndex *Tip() const { return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr; } // /** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */ CBlockIndex *operator[](int nHeight) const { if (nHeight < 0 || nHeight >= (int)vChain.size()) return nullptr; return vChain[nHeight]; } // /** Efficiently check whether a block is present in this chain. */ bool Contains(const CBlockIndex *pindex) const { return (*this)[pindex->nHeight] == pindex; } // /** Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */ CBlockIndex *Next(const CBlockIndex *pindex) const { if (Contains(pindex)) return (*this)[pindex->nHeight + 1]; else return nullptr; } // /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ int Height() const { return vChain.size() - 1; } // /** Set/initialize a chain with a given tip. */ void SetTip(CBlockIndex *pindex); // /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const; // /** Find the last common block between this chain and a block index entry. */ const CBlockIndex *FindFork(const CBlockIndex *pindex) const; // /** Find the earliest block with timestamp equal or greater than the given time and height equal or greater than the given height. */ CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const; end; implementation // /** // * CChain implementation // */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == nullptr) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == nullptr) { return nullptr; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const { std::pair<int64_t, int> blockparams = std::make_pair(nTime, height); std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams, [](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; }); return (lower == vChain.end() ? nullptr : *lower); } // /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } // /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } end.
unit Dbexcept; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, Db, DBTables; type TDbEngineErrorDlg = class(TForm) BasicPanel: TPanel; DetailsPanel: TPanel; BDELabel: TLabel; NativeLabel: TLabel; DbMessageText: TMemo; DbResult: TEdit; DbCatSub: TEdit; NativeResult: TEdit; BackBtn: TButton; NextBtn: TButton; ButtonPanel: TPanel; DetailsBtn: TButton; OKBtn: TButton; IconPanel: TPanel; IconImage: TImage; TopPanel: TPanel; ErrorText: TLabel; RightPanel: TPanel; procedure FormShow(Sender: TObject); procedure BackClick(Sender: TObject); procedure NextClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DetailsBtnClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FPrevOnException: TExceptionEvent; FDbException: EDbEngineError; FDetailsHeight, CurItem: Integer; FDetails: string; procedure HandleException(Sender: TObject; E: Exception); procedure SwitchDetails; procedure ShowError; public procedure HookExceptions; function ShowException(Error: EDbEngineError): TModalResult; property DbException: EDbEngineError read FDbException write FDbException; end; var DbEngineErrorDlg: TDbEngineErrorDlg; implementation {$R *.DFM} procedure TDbEngineErrorDlg.HandleException(Sender: TObject; E: Exception); begin if (E is EDbEngineError) and (DbException = nil) and not Application.Terminated then ShowException(EDbEngineError(E)) else if Assigned(FPrevOnException) then FPrevOnException(Sender, E) else Application.ShowException(E); end; procedure TDbEngineErrorDlg.SwitchDetails; const DetailsOn: array [Boolean] of string = ('%s >>', '<< %s'); var DEnabling: Boolean; begin DEnabling := not DetailsPanel.Visible; if DEnabling then ClientHeight := FDetailsHeight else ClientHeight := DetailsPanel.Top; DetailsPanel.Visible := DEnabling; ButtonPanel.Top := 0; DetailsBtn.Caption := Format(DetailsOn[DEnabling], [FDetails]); end; procedure TDbEngineErrorDlg.ShowError; var BDEError: TDbError; begin BackBtn.Enabled := CurItem > 0; NextBtn.Enabled := CurItem < DbException.ErrorCount - 1; BDEError := DbException.Errors[CurItem]; DbMessageText.Text := BDEError.Message; BDELabel.Enabled := True; DbResult.Text := IntToStr(BDEError.ErrorCode); DbCatSub.Text := Format('[%s%2x] [%0:s%2:2x]', [HexDisplayPrefix, BDEError.Category, BDEError.SubCode]); NativeLabel.Enabled := BDEError.NativeError <> 0; if NativeLabel.Enabled then NativeResult.Text := IntToStr(BDEError.NativeError) else NativeResult.Clear end; procedure TDbEngineErrorDlg.FormCreate(Sender: TObject); begin FDetailsHeight := ClientHeight; FDetails := DetailsBtn.Caption; SwitchDetails; end; procedure TDbEngineErrorDlg.FormDestroy(Sender: TObject); begin if Assigned(FPrevOnException) then Application.OnException := FPrevOnException; end; procedure TDbEngineErrorDlg.FormShow(Sender: TObject); begin ErrorText.Caption := DbException.Message; if DetailsPanel.Visible then begin CurItem := 0; ShowError; end; end; procedure TDbEngineErrorDlg.BackClick(Sender: TObject); begin Dec(CurItem); ShowError; end; procedure TDbEngineErrorDlg.NextClick(Sender: TObject); begin Inc(CurItem); ShowError; end; procedure TDbEngineErrorDlg.DetailsBtnClick(Sender: TObject); begin SwitchDetails; if DetailsPanel.Visible then begin CurItem := 0; ShowError; end; end; procedure TDbEngineErrorDlg.HookExceptions; begin FPrevOnException := Application.OnException; Application.OnException := HandleException; end; function TDbEngineErrorDlg.ShowException(Error: EDbEngineError): TModalResult; begin DbException := Error; Result := ShowModal; DbException := nil; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.DbxInterbase; interface uses Data.DBXDynalink, Data.DBXDynalinkNative, Data.DBXCommon, Data.DBXInterbaseReadOnlyMetaData, Data.DBXInterbaseMetaData; type TDBXInterBaseProperties = class(TDBXProperties) strict private const StrServerCharSet = 'ServerCharSet'; function GetDatabase: string; function GetPassword: string; function GetUserName: string; function GetServerCharSet: string; procedure SetServerCharSet(const Value: string); procedure SetDatabase(const Value: string); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); public constructor Create(DBXContext: TDBXContext); override; published property Database: string read GetDatabase write SetDatabase; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property ServerCharSet: string read GetServerCharSet write SetServerCharSet; end; TDBXInterBaseDriver = class(TDBXDynalinkDriverNative) public constructor Create(DBXDriverDef: TDBXDriverDef); override; end; TDBXIBToGoProperties = class(TDBXInterBaseProperties) public constructor Create(DBXContext: TDBXContext); override; end; TDBXIBToGoDriver = class(TDBXDynalinkDriverNative) public constructor Create(DBXDriverDef: TDBXDriverDef); override; end; {$IF (DEFINED(CPUARM) and DEFINED(IOS)) or DEFINED(ANDROID)} TDBXIBDriverLoader = class(TDBXDynalinkDriverLoader) strict protected function CreateMethodTable: TDBXMethodTable; override; function CreateDynalinkDriver: TDBXDynalinkDriver; override; end; TDBXIBMethodTable = class(TDBXNativeMethodTable) public procedure LoadMethods; override; end; {$ENDIF (CPUARM and IOS) or ANDROID} implementation uses Data.DBXCommonResStrs, Data.DBXPlatform, System.SysUtils {$IF (DEFINED(CPUARM) and DEFINED(IOS)) or DEFINED(ANDROID)} , Data.FmtBcd, Data.SqlTimSt {$ENDIF (CPUARM and IOS) or ANDROID} {$IFDEF ANDROID} , Posix.Stdlib, System.IOUtils {$ENDIF} ; const sDriverName = 'InterBase'; sToGoDriverName = 'IBToGo'; { TDBXInterBaseDriver } constructor TDBXInterBaseDriver.Create(DBXDriverDef: TDBXDriverDef); var Props: TDBXInterBaseProperties; I, Index: Integer; begin Props := TDBXInterBaseProperties.Create(DBXDriverDef.FDBXContext); if DBXDriverDef.FDriverProperties <> nil then begin for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do begin Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]); if Index > -1 then Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I]; end; Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties); DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties); end; inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props); end; { TDBXInterBaseProperties } constructor TDBXInterBaseProperties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXInterbase'; Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXInterBaseDriver' + PackageVersion + '.bpl'; Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXInterbaseMetaDataCommandFactory,DbxInterBaseDriver' + PackageVersion + '.bpl'; Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXInterbaseMetaDataCommandFactory,Borland.Data.DbxInterBaseDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverINTERBASE'; Values[TDBXPropertyNames.LibraryName] := 'dbxint.dll'; Values[TDBXPropertyNames.LibraryNameOsx] := 'libsqlib.dylib'; Values[TDBXPropertyNames.VendorLib] := 'gds32.dll'; Values[TDBXPropertyNames.VendorLibWin64] := 'ibclient64.dll'; Values[TDBXPropertyNames.VendorLibOsx] := 'libgds.dylib'; Values[TDBXPropertyNames.Database] := 'database.gdb'; Values[TDBXPropertyNames.UserName] := 'sysdba'; Values[TDBXPropertyNames.Password] := 'masterkey'; Values[TDBXPropertyNames.Role] := 'RoleName'; Values[TDBXPropertyNames.MaxBlobSize] := '-1'; Values[TDBXPropertyNames.ErrorResourceFile] := ''; Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000'; Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted'; Values['ServerCharSet'] := ''; Values['SQLDialect'] := '3'; Values['CommitRetain'] := 'False'; Values['WaitOnLocks'] := 'True'; Values['TrimChar'] := 'False'; Values['SEP'] := ''; Values['DisplayDriverName'] := 'InterBase Server'; end; function TDBXInterBaseProperties.GetDatabase: string; begin Result := Values[TDBXPropertyNames.Database]; end; function TDBXInterBaseProperties.GetPassword: string; begin Result := Values[TDBXPropertyNames.Password]; end; function TDBXInterBaseProperties.GetServerCharSet: string; begin Result := Values[StrServerCharSet]; end; function TDBXInterBaseProperties.GetUserName: string; begin Result := Values[TDBXPropertyNames.UserName]; end; procedure TDBXInterBaseProperties.SetDatabase(const Value: string); begin Values[TDBXPropertyNames.Database] := Value; end; procedure TDBXInterBaseProperties.SetPassword(const Value: string); begin Values[TDBXPropertyNames.Password] := Value; end; procedure TDBXInterBaseProperties.SetServerCharSet(const Value: string); begin Values[StrServerCharSet] := Value; end; procedure TDBXInterBaseProperties.SetUserName(const Value: string); begin Values[TDBXPropertyNames.UserName] := Value; end; { TDBXInterBaseToGoProperties } constructor TDBXIBToGoProperties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); Values[TDBXPropertyNames.VendorLib] := 'ibtogo.dll'; Values[TDBXPropertyNames.VendorLibWin64] := 'ibtogo64.dll'; Values[TDBXPropertyNames.VendorLibOsx] := 'libibtogo.dylib'; Values[TDBXPropertyNames.AutoUnloadDriver] := 'True'; Values['DisplayDriverName'] := 'IBLite/ToGo'; end; { TDBXInterBaseToGoDriver } constructor TDBXIBToGoDriver.Create(DBXDriverDef: TDBXDriverDef); var Props: TDBXIBToGoProperties; I, Index: Integer; begin Props := TDBXIBToGoProperties.Create(DBXDriverDef.FDBXContext); if DBXDriverDef.FDriverProperties <> nil then begin for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do begin Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]); if Index > -1 then Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I]; end; Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties); DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties); end; {$IF (DEFINED(CPUARM) and DEFINED(IOS)) or DEFINED(ANDROID)} inherited Create(DBXDriverDef, TDBXIBDriverLoader, Props); {$ELSE} inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props); {$ENDIF (CPUARM and IOS) or ANDROID} end; {$IF (DEFINED(CPUARM) and DEFINED(IOS)) or DEFINED(ANDROID)} const LibName = 'libsqlib.a'; VendorLib = 'ibtogo'; VendorLibDep = 'stdc++'; function DBXLoader_GetDriver(Count: Longint; Names: TWideStringArray; Values: TWideStringArray; ErrorMessage: TDBXWideStringBuilder; out pDriver: TDBXDriverHandle): TDBXErrorCode; cdecl; external LibName name 'DBXLoader_GetDriver' dependency VendorLib, LibCPP, VendorLibDep; function DBXBase_GetErrorMessageLength(Handle: TDBXCommonHandle; LastErrorCode: TDBXErrorCode; out ErrorLen: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXBase_GetErrorMessageLength' dependency VendorLib, LibCPP, VendorLibDep; function DBXBase_GetErrorMessage(Handle: TDBXCommonHandle; LastErrorCode: TDBXErrorCode; ErrorMessage: TDBXWideStringBuilder): TDBXErrorCode; cdecl; external LibName name 'DBXBase_GetErrorMessage' dependency VendorLib, LibCPP, VendorLibDep; function DBXBase_Close(Handle: TDBXCommonHandle): TDBXErrorCode; cdecl; external LibName name 'DBXBase_Close' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetString(Handle: TDBXRowHandle; Ordinal: Longint; Value: TDBXAnsiStringBuilder; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetString' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetWideString(Handle: TDBXRowHandle; Ordinal: Longint; Value: TDBXWideStringBuilder; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetWideString' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetBoolean(Handle: TDBXRowHandle; Ordinal: Longint; out Value: LongBool; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetBoolean' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetUInt8(Handle: TDBXRowHandle; Ordinal: Longint; out Value: Byte; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetUInt8' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetInt8(Handle: TDBXRowHandle; Ordinal: Longint; out Value: ShortInt; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetInt8' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetInt16(Handle: TDBXRowHandle; Ordinal: Longint; out Value: SmallInt; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetInt16' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetInt32(Handle: TDBXRowHandle; Ordinal: Longint; out Value: LongInt; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetInt32' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetInt64(Handle: TDBXRowHandle; Ordinal: Longint; out Value: Int64; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetInt64' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetSingle(Handle: TDBXRowHandle; Ordinal: Longint; out Value: single; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetSingle' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetDouble(Handle: TDBXRowHandle; Ordinal: Longint; out Value: double; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetDouble' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetBcd(Handle: TDBXRowHandle; Ordinal: Longint; out Value: TBcd; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetBcd' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetTimeStamp(Handle: TDBXRowHandle; Ordinal: Longint; out Value: TSQLTimeStamp; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetTimeStamp' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetTimeStampOffset(Handle: TDBXRowHandle; Ordinal: Longint; out Value: TSQLTimeStampOffset; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetTimeStampOffset' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetTime(Handle: TDBXRowHandle; Ordinal: Longint; out Value: TDBXTime; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetTime' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetDate(Handle: TDBXRowHandle; Ordinal: Longint; out Value: TDBXDate; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetDate' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetFixedBytes(Handle: TDBXRowHandle; Ordinal: Longint; const Value: array of Byte; ValueOffset: Longint; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetFixedBytes' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetByteLength(Handle: TDBXRowHandle; Ordinal: Longint; out Length: Int64; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetByteLength' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetBytes(Handle: TDBXRowHandle; Ordinal: Longint; Offset: Int64; Value: array of Byte; ValueOffset, Length: Int64; out ReturnLength: Int64; out IsNull: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetBytes' dependency VendorLib, LibCPP, VendorLibDep; function DBXRow_GetObjectTypeName(Handle: TDBXRowHandle; Ordinal: Longint; Value: TDBXWideStringBuilder; MaxLength: Integer): TDBXErrorCode; cdecl; external LibName name 'DBXRow_GetObjectTypeName' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetNull(Handle: TDBXWritableRowHandle; Ordinal: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetNull' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetString(Handle: TDBXWritableRowHandle; Ordinal: Longint; const Value: TDBXAnsiString; Length: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetString' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetWideString(Handle: TDBXWritableRowHandle; Ordinal: Longint; const Value: TDBXWideString; Length: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetWideString' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetBoolean(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetBoolean' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetUInt8(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: Byte): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetUInt8' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetInt8(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: ShortInt): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetInt8' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetInt16(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: SmallInt): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetInt16' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetInt32(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: LongInt): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetInt32' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetInt64(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetInt64' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetSingle(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: Single): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetSingle' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetDouble(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: Double): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetDouble' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetBcd(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: TBcd): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetBcd' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetTimeStamp(Handle: TDBXWritableRowHandle; Ordinal: Longint; var Value: TSQLTimeStamp): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetTimeStamp' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetTimeStampOffset(Handle: TDBXWritableRowHandle; Ordinal: Longint; var Value: TSQLTimeStampOffset): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetTimeStampOffset' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetTime(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: TDBXTime): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetTime' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetDate(Handle: TDBXWritableRowHandle; Ordinal: Longint; Value: TDBXDate): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetDate' dependency VendorLib, LibCPP, VendorLibDep; function DBXWritableRow_SetBytes(Handle: TDBXWritableRowHandle; Ordinal: Longint; BlobOffset: Int64; Value: TArray<Byte>; LastIndex: Longint; ValueOffset: Int64; Length: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXWritableRow_SetBytes' dependency VendorLib, LibCPP, VendorLibDep; function DBXDriver_CreateConnection(Handle: TDBXDriverHandle; out pConn: TDBXConnectionHandle): TDBXErrorCode; cdecl; external LibName name 'DBXDriver_CreateConnection' dependency VendorLib, LibCPP, VendorLibDep; function DBXDriver_GetVersion(Handle: TDBXDriverHandle; Version: TDBXWideStringBuilder; MaxLength: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXDriver_GetVersion' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_Connect(Handle: TDBXConnectionHandle; Count: Longint; Names, Values: TWideStringArray): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_Connect' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_Disconnect(Handle: TDBXConnectionHandle): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_Disconnect' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_SetCallbackEvent(Handle: TDBXConnectionHandle; CallbackHandle: DBXCallbackHandle; CallbackEvent: DBXTraceCallback): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_SetCallbackEvent' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_CreateCommand(Handle: TDBXConnectionHandle; const CommandType: TDBXWideString; out pCommand: TDBXCommandHandle): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_CreateCommand' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_BeginTransaction(Handle: TDBXConnectionHandle; out TransactionHandle: TDBXTransactionHandle; IsolationLevel: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_BeginTransaction' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_Commit(Handle: TDBXConnectionHandle; TransactionHandle: TDBXTransactionHandle): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_Commit' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_Rollback(Handle: TDBXConnectionHandle; TransactionHandle: TDBXTransactionHandle): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_Rollback' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_GetIsolation(Handle: TDBXConnectionHandle; out IsolationLevel: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_GetIsolation' dependency VendorLib, LibCPP, VendorLibDep; function DBXConnection_GetVendorProperty(Handle: TDBXConnectionHandle; Name: TDBXWideString; Value: TDBXWideStringBuilder; MaxLength: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXConnection_GetVendorProperty' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_CreateParameterRow(Handle: TDBXCommandHandle; out Parameters: TDBXRowHandle): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_CreateParameterRow' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_Prepare(Handle: TDBXCommandHandle; const SQL: TDBXWideString; Count: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_Prepare' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_Execute(Handle: TDBXCommandHandle; out Reader: TDBXReaderHandle): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_Execute' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_ExecuteImmediate(Handle: TDBXCommandHandle; const SQL: TDBXWideString; out Reader: TDBXReaderHandle): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_ExecuteImmediate' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_GetNextReader(Handle: TDBXCommandHandle; out Reader: TDBXReaderHandle): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_GetNextReader' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_GetRowsAffected(Handle: TDBXCommandHandle; out Rows: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_GetRowsAffected' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_SetMaxBlobSize(Handle: TDBXCommandHandle; MaxBlobSize: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_SetMaxBlobSize' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_SetRowSetSize(Handle: TDBXCommandHandle; RowSetSize: Int64): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_SetRowSetSize' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_GetParameterCount(Handle: TDBXCommandHandle; out ParameterCount: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_GetParameterCount' dependency VendorLib, LibCPP, VendorLibDep; function DBXCommand_GetParameterType(Handle: TDBXCommandHandle; Ordinal: Longint; out DBXType: Longint; out DBXSubType: Longint; out Size: Int64; out Precision: Int64; out Scale: Longint; out Nullable: LongBool): TDBXErrorCode; cdecl; external LibName name 'DBXCommand_GetParameterType' dependency VendorLib, LibCPP, VendorLibDep; function DBXParameterRow_SetParameterType(Handle: TDBXRowHandle; Ordinal: Longint; const Name: TDBXWideString; ChildPosition: Longint; ParamDirection: TDBXParameterDirection; DBXType: Longint; DBXSubType: Longint; Size: Int64; Precision: Int64; Scale: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXParameterRow_SetParameterType' dependency VendorLib, LibCPP, VendorLibDep; function DBXReader_GetColumnCount(Handle: TDBXReaderHandle; out ColumnCount: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXReader_GetColumnCount' dependency VendorLib, LibCPP, VendorLibDep; function DBXReader_GetColumnMetadata(Handle: TDBXReaderHandle; Ordinal: Longint; Name: TDBXWideStringBuilder; out ColumnType: Longint; out ColumnSubType: Longint; out Length: Longint; out Precision: Longint; out Scale: Longint; out flags: Longint): TDBXErrorCode; cdecl; external LibName name 'DBXReader_GetColumnMetadata' dependency VendorLib, LibCPP, VendorLibDep; function DBXReader_Next(Handle: TDBXReaderHandle): TDBXErrorCode; cdecl; external LibName name 'DBXReader_Next' dependency VendorLib, LibCPP, VendorLibDep; { TDBXIBDriverLoader } function TDBXIBDriverLoader.CreateMethodTable: TDBXMethodTable; begin Result := TDBXIBMethodTable.Create(FLibraryHandle); end; function TDBXIBDriverLoader.CreateDynalinkDriver: TDBXDynalinkDriver; begin Result := TDBXIBToGoDriver.Create(TDBXDriver(nil), FDriverHandle, FMethodTable); end; { TDBXIBMethodTable } procedure TDBXIBMethodTable.LoadMethods; begin FDBXLoader_GetDriver := DBXLoader_GetDriver; FDBXBase_GetErrorMessageLength := DBXBase_GetErrorMessageLength; FDBXBase_GetErrorMessage := DBXBase_GetErrorMessage; FDBXBase_Close := DBXBase_Close; FDBXRow_GetString := DBXRow_GetString; FDBXRow_GetWideString := DBXRow_GetWideString; FDBXRow_GetBoolean := DBXRow_GetBoolean; FDBXRow_GetUInt8 := DBXRow_GetUInt8; FDBXRow_GetInt8 := DBXRow_GetInt8; FDBXRow_GetInt16 := DBXRow_GetInt16; FDBXRow_GetInt32 := DBXRow_GetInt32; FDBXRow_GetInt64 := DBXRow_GetInt64; FDBXRow_GetSingle := DBXRow_GetSingle; FDBXRow_GetDouble := DBXRow_GetDouble; FDBXRow_GetBcd := DBXRow_GetBcd; FDBXRow_GetTimeStamp := DBXRow_GetTimeStamp; FDBXRow_GetTimeStampOffset := DBXRow_GetTimeStampOffset; FDBXRow_GetTime := DBXRow_GetTime; FDBXRow_GetDate := DBXRow_GetDate; FDBXRow_GetFixedBytes := DBXRow_GetFixedBytes; FDBXRow_GetByteLength := DBXRow_GetByteLength; FDBXRow_GetBytes := DBXRow_GetBytes; FDBXRow_GetObjectTypeName := DBXRow_GetObjectTypeName; FDBXWritableRow_SetNull := DBXWritableRow_SetNull; FDBXWritableRow_SetString := DBXWritableRow_SetString; FDBXWritableRow_SetWideString := DBXWritableRow_SetWideString; FDBXWritableRow_SetBoolean := DBXWritableRow_SetBoolean; FDBXWritableRow_SetUInt8 := DBXWritableRow_SetUInt8; FDBXWritableRow_SetInt8 := DBXWritableRow_SetInt8; FDBXWritableRow_SetInt16 := DBXWritableRow_SetInt16; FDBXWritableRow_SetInt32 := DBXWritableRow_SetInt32; FDBXWritableRow_SetInt64 := DBXWritableRow_SetInt64; FDBXWritableRow_SetSingle := DBXWritableRow_SetSingle; FDBXWritableRow_SetDouble := DBXWritableRow_SetDouble; FDBXWritableRow_SetBcd := DBXWritableRow_SetBcd; FDBXWritableRow_SetTimeStamp := DBXWritableRow_SetTimeStamp; FDBXWritableRow_SetTimeStampOffset := DBXWritableRow_SetTimeStampOffset; FDBXWritableRow_SetTime := DBXWritableRow_SetTime; FDBXWritableRow_SetDate := DBXWritableRow_SetDate; FDBXWritableRow_SetBytes := DBXWritableRow_SetBytes; FDBXDriver_CreateConnection := DBXDriver_CreateConnection; FDBXDriver_GetVersion := DBXDriver_GetVersion; FDBXConnection_Connect := DBXConnection_Connect; FDBXConnection_Disconnect := DBXConnection_Disconnect; FDBXConnection_SetCallbackEvent := DBXConnection_SetCallbackEvent; FDBXConnection_CreateCommand := DBXConnection_CreateCommand; FDBXConnection_BeginTransaction := DBXConnection_BeginTransaction; FDBXConnection_Commit := DBXConnection_Commit; FDBXConnection_Rollback := DBXConnection_Rollback; FDBXConnection_GetIsolation := DBXConnection_GetIsolation; // Ok if not implemented. // FDBXConnection_GetVendorProperty := DBXConnection_GetVendorProperty; FDBXCommand_CreateParameterRow := DBXCommand_CreateParameterRow; FDBXCommand_Prepare := DBXCommand_Prepare; FDBXCommand_Execute := DBXCommand_Execute; FDBXCommand_ExecuteImmediate := DBXCommand_ExecuteImmediate; FDBXCommand_GetNextReader := DBXCommand_GetNextReader; FDBXCommand_GetRowsAffected := DBXCommand_GetRowsAffected; FDBXCommand_SetMaxBlobSize := DBXCommand_SetMaxBlobSize; FDBXCommand_SetRowSetSize := DBXCommand_SetRowSetSize; FDBXCommand_GetParameterCount := DBXCommand_GetParameterCount; FDBXCommand_GetParameterType := DBXCommand_GetParameterType; FDBXParameterRow_SetParameterType := DBXParameterRow_SetParameterType; FDBXReader_GetColumnCount := DBXReader_GetColumnCount; FDBXReader_GetColumnMetadata := DBXReader_GetColumnMetadata; FDBXReader_Next := DBXReader_Next; end; {$ENDIF (CPUARM and IOS) or ANDROID} {$IFDEF ANDROID} procedure SetInterBaseVariable; var M: TMarshaller; begin setenv('INTERBASE', M.AsUtf8(TPath.GetDocumentsPath + PathDelim + 'interbase').ToPointer, 1); end; {$ENDIF} initialization TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXInterBaseDriver); TDBXDriverRegistry.RegisterDriverClass(sToGoDriverName, TDBXIBToGoDriver); {$IFDEF ANDROID} SetInterBaseVariable; {$ENDIF} finalization TDBXDriverRegistry.UnloadDriver(sDriverName); TDBXDriverRegistry.UnloadDriver(sToGoDriverName); end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit WSDLModelIntf; interface uses XmlSchema, Classes, TypInfo, WSDLBind, InvokeRegistry, UDDIHlprDesign, WSDLItems, xmldom; type { Describe a basic WSDLItem - Note some of the types, wiTypes and wiPortTypes, for example, are really for UI display - i.e. they serve no real purpose in the Model other than grouping } WSDLItemType = (wiUndefined, // 0 wiPortType, // 1 wiOperation, // 2 wiPart, // 3 wiType, // 4 wiTypes, // 5 wiPortTypes); // 6 ArrayOfString = array of string; ///<summary> /// Base interface of every element found in a WSDL File. ///</summary> IWSDLItem = interface ['{D4D73214-8431-43D0-BEA4-15B59F4ECA30}'] function GetName: DOMString; function GetLangName: DOMString; procedure SetLangName(const lName: DOMString); function GetDocumentation: DOMString; function GetWSDLItemType: WSDLItemType; function GetSelected: Boolean; procedure SetSelected(const Sel: Boolean); function GetNotes: ArrayOfString; procedure AddNote(const Note: string); procedure SetDocumentation(const doc: DOMString); procedure Rename(const NewName: DOMString); property Name: DOMString read GetName; property LangName: DOMString read GetLangName write SetLangName; property Documentation: DOMString read GetDocumentation write SetDocumentation; property ItemType: WSDLItemType read GetWSDLItemType; property Selected: Boolean read GetSelected write SetSelected; property Notes: ArrayOfString read GetNotes; end; { IWSDLItemArray } IWSDLItemArray = array of IWSDLItem; { IWSDLItemNS } IWSDLItemNS = interface(IWSDLItem) ['{86EFFCA7-F7A9-4292-AFC9-6582DD2EB81C}'] function GetNamespace: DOMString; procedure SetNamespace(const nspace: DOMString); property Namespace: DOMString read GetNamespace write SetNamespace; end; { Forward ref. all interfaces } IWSDLPart = interface; IWSDLOperation = interface; IWSDLPortType = interface; IWSDLType = interface; IWSDLImporter = interface; IWSDLTypes = interface; IWSDLPortTypes = interface; /// <summary> /// Flag the describes a part or parameter /// <summary> PartType = (pUnknown, pIn, pOut, pInOut, pReturn, pAttribute, pDefaultArray); TPartType = set of PartType; /// <summary> /// Flag that describes a WSDL part (or an XML element) /// </summary> /// PartFlag = (pfOptional, { minOccurs=0 or use="optional" } pfUnbounded, { maxOccurs="unbounded" or maxOccurs=n where n > 1 } pfNillable, { nillable ="true" } pfFormUnqualified, { form="unqualified" or elementFormDefault="unqualified" } pfText, { Maps to the text of the node - i.e. Simple content } pfAny, { Maps to xsd:any } pfRef, { Has 'ref' attribute } pfFormQualified { For Qualified attributes } ); TPartFlag = set of PartFlag; ArgumentType = (argIn, argOut, argInOut, argReturn); { IWSDLPart } IWSDLPart = interface(IWSDLItemNS) ['{55B4FF2E-F401-45E5-BBB6-51435634464D}'] function GetPartKind: PartType; procedure SetPartKind(const pt: PartType); function GetDataType: IWSDLType; procedure SetDataType(const DataType: IWSDLType); function GetPartFlags: TPartFlag; procedure SetPartFlags(const PartFlag: TPartFlag); function GetRequired: Boolean; procedure SetRequired(Flag: Boolean); function GetDefaultValue: DOMString; function GetRegInfo: DOMString; procedure SetRegInfo(const ARegInfo: DOMString); function Clone: IWSDLPart; property DataType: IWSDLType read GetDataType write SetDataType; property PartKind: PartType read GetPartKind write SetPartKind; property PartFlags: TPartFlag read GetPartFlags write SetPartFlags; property Required: Boolean read GetRequired write SetRequired; property DefaultValue: DOMString read GetDefaultValue; property RegInfo: DOMString read GetRegInfo write SetRegInfo; end; { IPartArray } IWSDLPartArray = array of IWSDLPart; IMIMEPart = interface ['{F2402663-322B-11D6-BFB2-00C04F79AB6E}'] function GetName: DOMString; procedure SetName(const AName: DOMString); function GetOperationName: DOMString; procedure SetOperationName(const OName: DOMString); function GetMessageName: DOMString; procedure SetMessageName(const Name: DOMString); function GetMIMEType: DOMString; procedure SetMIMEType(const MType: DOMString); function GetArgType: ArgumentType; procedure SetArgType(const AArgType: ArgumentType); property MIMEType: DOMString read GetMIMEType write SetMIMEType; property MessageName: DOMString read GetMessageName write SetMessageName; property Name: DOMString read GetName write SetName; property ArgType: ArgumentType read GetArgType write SetArgType; property OperationName: DOMString read GetOperationName write SetOperationName; end; IMIMEPartArray = array of IMIMEPart; { Indicates whether Unwinding is necessary/doable } UnwrapStatus = (usNotReq, {We don't need to unwrap - RPC|Encoded services, for example } usCan, { We can unwrap } usCannot); { Parts cannot be unwrapped} UnwrapStatusArray = array of UnwrapStatus; TweakPartOpt = (tpNone, tpUnwrapped); TTweakPartOpts = set of TweakPartOpt; CannotUnwrap = (cuInputMessageHasMoreThanOnePart, cuOutputMessageHasMoreThanOnePart, cuInputPartRefersToTypeNotElement, cuOutputPartRefersToTypeNotElement, cuInputWrapperElementNotSameAsOperationName, cuInputPartNotAComplexType, cuOutputPartNotAComplexType, cuMoreThanOneStrictlyOutMembersWereFound, cuTypeNeedsSpecialSerialization, cuOutputElementIsAPureCollection ); TCannotUnwrap = set of CannotUnwrap; { IWSDLOperation } IWSDLOperation = interface(IWSDLItem) ['{7D017A89-8319-4212-B9E0-A509FF223D35}'] function GetParts: IWSDLPartArray; function GetHeaders: IWSDLPartArray; function GetFaults: IWSDLPartArray; function IsOverloaded: Boolean; function GetSOAPAction: DOMString; function GetStyle: DOMString; function GetInputUse: DOMString; function GetInputNamespace: DOMString; function GetOuputUse: DOMString; function GetOuputNamespace: DOMString; function GetReturnIndex: integer; procedure SetOverloaded(const Value: Boolean); function GetCannotUnwrap: TCannotUnwrap; function GetInputWrapper: IWSDLPart; function GetOutputWrapper: IWSDLPart; { Used by PortType to unwrap literal } procedure TweakReturnParam(const Importer: IWSDLImporter; Opts: TTweakPartOpts); procedure HandleLiteralParams(UnwindStat: UnwrapStatus; UseLiteralParams: Boolean = False); function CanUnwrap(Input: Boolean): UnwrapStatus; property Parts: IWSDLPartArray read GetParts; property Headers: IWSDLPartArray read GetHeaders; property Faults: IWSDLPartArray read GetFaults; property Overloaded: Boolean read IsOverloaded write SetOverloaded; property Style: DOMString read GetStyle; property SOAPAction: DOMString read GetSOAPAction; property InputUse: DOMString read GetInputUse; property InputNamespace: DOMString read GetInputNamespace; property OutputUse: DOMString read GetOuputUse; property OutputNamespace: DOMString read GetOuputNamespace; property ReturnIndex: integer read GetReturnIndex; property CannotUnwrap: TCannotUnwrap read GetCannotUnwrap; property InputWrapper: IWSDLPart read GetInputWrapper; property OutputWrapper: IWSDLPart read GetOutputWrapper; end; { IOperationArray } IWSDLOperationArray = array of IWSDLOperation; PortTypeFlags = (ptfWasUnwrapped); TPortTypeFlags = set of PortTypeFlags; { TPortType } IWSDLPortType = interface(IWSDLItemNS) ['{57F2F8C6-55EF-49FA-B370-C0C8E2A7EE60}'] function GetOperationCount: integer; function GetOperations: IWSDLOperationArray; function GetGUID: TGUID; function GetBinding: DOMString; function GetService: DOMString; function GetPort: DOMString; function GetURL: DOMString; function GetStyle: DOMString; function GetUse: DOMString; function GetTransport: DOMString; function GetSOAPAction: DOMString; procedure SetSOAPAction(const soapAction: DOMString; All: Boolean); function GetHasDefaultSOAPAction: Boolean; function GetHasAllSOAPActions: Boolean; function GetInvokeOptions: TIntfInvokeOptions; function GetBaseInterfaceName: DOMString; procedure SetInvokeOptions(const InvOptions: TIntfInvokeOptions); function GetPortTypeFlags: TPortTypeFlags; property Operations: IWSDLOperationArray read GetOperations; property OperationCount: integer read GetOperationCount; property GUID: TGUID read GetGUID; property Binding: DOMString read GetBinding; property Service: DOMString read GetService; property Port: DOMString read GetPort; property URL: DOMString read GetURL; property Style: DOMString read GetStyle; property Use: DOMString read GetUse; property Transport: DOMString read GetTransport; property HasDefaultSOAPAction: Boolean read GetHasDefaultSOAPAction; property HasAllSOAPActions: Boolean read GetHasAllSOAPActions; property SOAPAction: DOMString read GetSOAPAction; property InvokeOptions: TIntfInvokeOptions read GetInvokeOptions write SetInvokeOptions; property BaseInterfaceName: DOMString read GetBaseInterfaceName; property Flags: TPortTypeFlags read GetPortTypeFlags; end; { TPortTypeArray } IWSDLPortTypeArray = array of IWSDLPortType; { ArrayOfIPortType } ArrayOfIPortType = array of IPortType; { Languge Type Binding of a type } WSDLTypeKind = (wtNotDefined, { Was not explicitly defined but referred to } wtDuplicate, { Type redefined - usually in another namespace } wtEnumeration, { Enumeration } wtAlias, { Type alias } wtArray, { Array } wtClass, { Structure/class } wtAttrGroup, { AttributeGroup } wtElemGroup); { ElementGroup } { Flag that describes what a type is used for } WSDLTypeFlag = (wfNone, wfLiteralParam, wfFault, wfHeader, wfArrayAsClass); XMLItemInfo = ( xtiGlobal, { XML Type is not anonymous - it's Global } xtiKnownType, { Refers to known type } xtiElement, { XML Type is an <element... > } xtiComplex, { XML Type is a <complexType... > } xtiSimple, { XML Type is a <simpleType... > } xtiAttribute, { XML Type is an <attribute... > } xtiAttrGroup, { XML Type is an <attributeGroup ... > } xtiElemGroup, { XML Type is a <group...> } xtiFakeUnboundedType, { Array Type created by importer } xtiFakeAliasType, { Alias Type created by importer } xtiForNillable, { Alias Type for nillable instances } xtiMixed { mixed="true" } ); TXMLItemInfo = set of XMLItemInfo; { Array of IWSDLType } IWSDLTypeArray = array of IWSDLType; { IWSDLTypes } IWSDLTypes = interface(IWSDLItem) ['{A4A3FFE7-A204-4001-99B1-E8229D1D5F59}'] function FindType(const Name, Namespace: DOMString; const HasThese: TXMLItemInfo; const DoesNotHaveThes: TXMLItemInfo; Create: Boolean = True): IWSDLType; function GenArrayType(const WSDLType: IWSDLType; const Tag: Boolean): IWSDLType; function GenAliasType(const WSDLType: IWSDLType; const Name: DOMString; const Namespace: DOMString): IWSDLType; function AddType(const Name, Namespace: DOMString; XMLItemInfo: TXMLItemInfo): IWSDLType; function GetTypes: IWSDLTypeArray; procedure Clear; function IndexOf(const WSDLType: IWSDLType): Integer; procedure Move(CurIndex: Integer; NewIndex: Integer); procedure Swap(Index1, Index2: Integer); function GetType(Index: Integer): IWSDLType; property Types: IWSDLTypeArray read GetTypes; property Items[Index: Integer]: IWSDLType read GetType; default; end; IProcessedTracker = interface ['{31502D87-7B77-4BA9-AB11-85F5F891502D}'] function ProcessedAlready(const Name: DOMString): Boolean; procedure AddProcessed(const Name: DOMString); procedure Clear; function GetCount: Integer; function GetItem(Index: Integer): DOMString; property Count: Integer read GetCount; property Items[Index: Integer]: DOMString read GetItem; default; end; { ISchemaTypeImporter } ISchemaTypeImporter = interface ['{49EADE0D-1BCB-40EE-BFEC-A3365BF3B705}'] { Import from WSDL } procedure GetTypes(const WSDLItems: TWSDLItems; const WSDLTypes: IWSDLTypes; const Name: DOMString; const Tracker: IProcessedTracker; const Reset: Boolean); overload; { Import from Schema } procedure GetTypes(const SchemaDef: IXMLSchemaDef; const WSDLTypes: IWSDLTypes; const Name: DOMString; const Tracker: IProcessedTracker); overload; end; { IWSDLPortTypes } IWSDLPortTypes = interface(IWSDLItem) ['{B7A3A3AD-59ED-4F13-9F2A-E060370A5304}'] procedure AddPortType(const WSDLPortType: IWSDLPortType); function GetPortTypes: IWSDLPortTypeArray; procedure Clear; property PortTypes: IWSDLPortTypeArray read GetPortTypes; end; { ICleanupIntf } ICleanupIntf = interface(IWSDLItemNS) ['{292F3737-9C98-4B04-B23D-5388507192BF}'] procedure Cleanup; end; { Holds information about a particular WSDL type } IWSDLType = interface(ICleanupIntf) ['{EFFA6C0C-6245-4605-8623-F1CE58E7D04C}'] function GetDataKind: WSDLTypeKind; function GetTypeFlag: WSDLTypeFlag; function GetTypeInfo: PTypeInfo; function GetEnumValues: IWSDLItemArray; function GetBaseType: IWSDLType; function GetMembers: IWSDLPartArray; function GetDimensions: integer; function GetIsUsed: Boolean; function GetXMLItemInfo: TXMLItemInfo; function GetRegInfo: string; procedure AddMember(const Member: IWSDLPart); procedure RemoveMember(const Member: IWSDLPart); procedure SetDataKind(const DataKind: WSDLTypeKind); procedure SetTypeFlag(const TypeFlag: WSDLTypeFlag); procedure SetTypeInfo(const TypeInfo: PTypeInfo); procedure SetEnumValues(const enumValues: IWSDLItemArray); procedure SetBaseType(const WSDLType: IWSDLType); procedure SetMembers(const membrs: IWSDLPartArray); procedure SetDimensions(dim: Integer); procedure SetIsUsed(Used: Boolean); procedure SetXMLItemInfo(const Flag: TXMLItemInfo); procedure SetRegInfo(const RegInfo: string); function GetSerializerOpt: TSerializationOptions; procedure SetSerializerOpt(const SOpt: TSerializationOptions); function GetAlternateType: IWSDLType; property DataKind: WSDLTypeKind read GetDataKind write SetDataKind; property TypeFlag: WSDLTypeFlag read GetTypeFlag write SetTypeFlag; property TypeInfo: PTypeInfo read GetTypeInfo write SetTypeInfo; property Dimensions: integer read GetDimensions write SetDimensions; property IsUsed: Boolean read GetIsUsed write SetIsUsed; property XMLItemInfo: TXMLItemInfo read GetXMLItemInfo write SetXMLItemInfo; { EnumValues - when DataKind = wtEnumeration } property EnumValues: IWSDLItemArray read GetEnumValues write SetEnumValues; { BaseTypeName - when DataKind = wtAlias, wtArray, wtComplexArray, wtClass } property BaseType: IWSDLType read GetBaseType write SetBaseType; { ClassMembers - when DataKind = wtClass, has attributes?? } property Members: IWSDLPartArray read GetMembers write SetMembers; property SerializationOpt: TSerializationOptions read GetSerializerOpt write SetSerializerOpt; { Alternalte type mapping } property AlternateType: IWSDLType read GetAlternateType; { Registration Information } property RegInfo: string read GetRegInfo write SetRegInfo; end; { Flags that describe general features encountered by importer. These flags control code generation } WSDLImporterOpts = ( woHasSOAPDM, // SOAP Data module in the WSDL woHasDocStyle, // Document style services woHasLiteralUse, // Literal use woHasOptionalElem, // Types with optional elements woHasUnboundedElem, // Types with unbounded elements woHasNillableElem, // Types with nillable elements woHasUnqualifiedElem, // Types with unqualified elements woHasAttribute, // Complex types with attributes woHasText, // Properties that map to 'text' nodes - not ntElement woHasAny, woHasRef, woHasQualifiedAttr, woHasOut ); TWSDLImporterOpts = set of WSDLImporterOpts; PTWSDLImporterOpts = ^TWSDLImporterOpts; TWriteProc = procedure (const Msg: string; const Args: array of const); IWSDLImporterOptions = interface ['{5373C97E-F282-4F99-B2C6-D3EC2BF68FB5}'] function GetOptions: TWSDLImporterOpts; procedure SetOptions(const Opts: TWSDLImporterOpts); property Options: TWSDLImporterOpts read GetOptions write SetOptions; end; PWSDLImportInfo = ^TWSDLImportInfo; TWSDLImportInfo = record SkipURLs: ArrayOfString; end; { IWSDLImporter } IWSDLImporter = interface(IWSDLImporterOptions) ['{C9AB297B-177D-47DE-9139-C49420AB5367}'] procedure Import(const FileName: DOMString; const Stream: TStream); function GetFileName: DOMString; function GetOutFile: DOMString; procedure SetOutFile(const OFile: DOMString); function GetEncoding: DOMString; function GetVersion: DOMString; function GetWSDLItems: TWSDLItems; function GetTypes: IWSDLTypeArray; function GetPortTypes: IWSDLPortTypeArray; function GetWSDLTypes: IWSDLTypes; function GetWSDLPortTypes: IWSDLPortTypes; procedure SelectItem(const WSDLItem: IWSDLItem); function FindType(const Name: DOMString; const Namespace: DOMString; const HasThese: TXMLItemInfo = []; const DoesNotHaveThes: TXMLItemInfo = []; Create: Boolean = True): IWSDLType; function SkipType(const WSDLType: IWSDLType; SkipAll: Boolean = False): Boolean; function CreateSerializer(const BaseType: IWSDLType; const NewTypeName: DOMString; const NewTypeNamespace: DOMString; const MemberName: DOMString; const SerialOpts: TSerializationOptions; UpdateReferences: Boolean): IWSDLType; procedure AddWarning(const Fmt: string; const Args: array of const); overload; function GetOnWrite: TWriteProc; procedure SetOnWrite(const WriteProc: TWriteProc); function GetDefName: DOMString; procedure SetDefName(const Name: DOMString); function GetImportList: IProcessedTracker; function GetWarningList: TStringList; function GetWSDLImportInfo: PWSDLImportInfo; procedure SetWSDLImportInfo(const ImportInfo: PWSDLImportInfo); property DefName: DOMString read GetDefName write SetDefName; property FileName: DOMString read GetFileName; property OutFile: DOMString read GetOutFile write SetOutFile; property Encoding: DOMString read GetEncoding; property Version: DOMString read GetVersion; property OnWrite: TWriteProc read GetOnWrite write SetOnWrite; property ImportList: IProcessedTracker read GetImportList; property WarningList: TStringList read GetWarningList; property WSDLTypes: IWSDLTypes read GetWSDLTypes; property WSDLPortTypes: IWSDLPortTypes read GetWSDLPortTypes; function FindMIMEPart(const PartName, AOperation, AMessage: DOMString; ArgType: ArgumentType): IMIMEPart; procedure GetMIMEParts(const BindingName: DOMString); procedure ClearMIMEParts; property WSDLImportInfo: PWSDLImportInfo read GetWSDLImportInfo write SetWSDLImportInfo; end; const WSDLTypeKindStr: array[WSDLTypeKind] of String = ('undefined', { Do not localize } 'duplicate', { Do not localize } 'enum', { Do not localize } 'alias', { Do not localize } 'array', { Do not localize } 'class', { Do not localize } 'attrGrp', { Do not localize } 'elemGrp'); { Do not localize } XMLItemInfoStr: array[XMLItemInfo] of String = ('global', { XML Type is not anonymous - it's Global } 'predefined',{ Refers to known type } 'element', { XML Type is an <element... > } 'complex', { XML Type is a <complexType... > } 'simple', { XML Type is a <simpleType... > } 'attribute', { XML Type is an <attribute... > } 'attrGroup', { XML Type is an <attributeGroup.. > } 'elemGroup', { XML Type is a <group ... > } 'fakeArray', { Fake created by importer } 'fakeAlias', { Fake alias created by importer } 'nillable', { Alias for nillable cases } 'mixed' { mixed="true" } ); PartFlagStr: array[PartFlag] of String = ('optional', { With attribute minOccurs="0" } 'unbounded', { With attribute maxOccurs="unbounded" } 'nillable', { With attribute nillable="true" } 'unqualified',{ With form="unqualified" } 'text', { Maps to node's text } 'any', 'ref', 'qual' ); WSDLTypeFlagStr: array[WSDLTypeFlag] of String = ('', 'Wrapper', 'Fault', 'Header', 'ArrayAsClass'); PartTypeStr: array[PartType] of String = ('pUnknown', 'pIn', 'pOut', 'pInOut', 'pReturn', 'pAttribute', 'pDefaultArray'); WSDLImpMajVer = 2; WSDLImpMinVer = 41; implementation end.
program examen2014; Const MAXFila = 10; type TipoCelda = record case vacia : boolean of true : (); false : (valor : integer); end; RangoIndice = 1 .. MAXFila; TipoFila = array [RangoIndice] of TipoCelda; procedure CorrerHaciaIzquierda(var fila : TipoFila; var cambios : boolean); var j : integer; begin j := 1; cambios := false; for i := 1 to MAXFila do begin if (fila[i].vacia = false) then begin fila[j].valor := fila[i].valor; if (j < i) then begin fila[i].vacia := true; cambios := true; end; j := j + 1; end end; end; // 8 * * 9 * 7 6 5 * 9 // 8 9 7 6 5 9 * * * * //cF cT cTcT cT
{: This example unit declares TMyItemList based on the _DZ_LIST_TEPLATE_ template storing TMyItem objects and implementing the IMyItemList interface } unit u_MyItemList; interface uses Classes, u_MyItem, u_dzQuickSort, i_MyItemList; {$DEFINE __DZ_OBJECT_LIST_TEMPLATE__} type {: This is the ancestor class for the template } _LIST_ANCESTOR_ = TInterfacedObject; {: This is the container type to store the items } _LIST_CONTAINER_ = TList; {: The native item type of the list container (Pointer for TList, IInterface for TInterfaceList} _LIST_CONTAINER_ITEM_TYPE_ = pointer; {: This is the object type to be stored in the list } _ITEM_TYPE_ = TMyItem; {$INCLUDE 't_dzObjectListTemplate.tpl'} type {: a list for storing TMyItem objects based on _DZ_LIST_TEMPLATE_ and implementing the IMyItemList interface. All code is already declared in the template. } TMyItemList = class(_DZ_OBJECT_LIST_TEMPLATE_, IMyItemList) end; implementation {$INCLUDE 't_dzObjectListTemplate.tpl'} end.
unit UI.Ani; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections, System.Rtti, System.SyncObjs, FMX.Ani, FMX.Utils, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Platform, IOUtils; type /// <summary> /// 动画类型 /// </summary> TFrameAniType = (None, DefaultAni {默认}, FadeInOut {淡入淡出}, MoveInOut {移进移出}, TopMoveInOut {顶部弹进弹出}, BottomMoveInOut {底部弹进弹出}, LeftSlideMenu {左边栏菜单}, RightSlideMenu {右边栏菜单} ); TNotifyEventA = reference to procedure (Sender: TObject); TDelayExecute = class(TAnimation) protected procedure ProcessAnimation; override; procedure FirstFrame; override; public procedure Start; override; procedure Stop; override; end; TFloatExAnimation = class(TFloatAnimation) protected function FindProperty: Boolean; public procedure Start; override; end; TInt64Animation = class(TCustomPropertyAnimation) private FStartValue: Int64; FStopValue: Int64; FStartFromCurrent: Boolean; protected procedure ProcessAnimation; override; procedure FirstFrame; override; public constructor Create(AOwner: TComponent); override; published property StartValue: Int64 read FStartValue write FStartValue stored True nodefault; property StopValue: Int64 read FStopValue write FStopValue stored True nodefault; property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False; end; TFrameAnimator = class private type TFrameAnimatorEvent = record OnFinish: TNotifyEvent; OnFinishA: TNotifyEventA; OnProcess: TNotifyEventA; end; TAnimationDestroyer = class private FOnFinishs: TDictionary<Integer, TFrameAnimatorEvent>; procedure DoAniProcess(Sender: TObject); procedure DoAniFinished(Sender: TObject); procedure DoAniFinishedEx(Sender: TObject; FreeSender: Boolean); public constructor Create(); destructor Destroy; override; procedure Add(Sender: TObject; AOnFinish: TNotifyEvent); overload; procedure Add(Sender: TObject; AOnFinish: TNotifyEventA); overload; procedure Add(Sender: TObject; AOnFinish, AOnProcess: TNotifyEventA); overload; end; private class var FDestroyer: TAnimationDestroyer; private class procedure CreateDestroyer; class procedure Uninitialize; public /// <summary> /// 延时执行任务 /// </summary> class procedure DelayExecute(const Owner: TFmxObject; AOnFinish: TNotifyEventA; Delay: Single = 1.0); class procedure AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEventA; AOnProcess: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateInt64(const Target: TFmxObject; const APropertyName: string; const NewValue: Int64; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEvent = nil; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; class procedure AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEventA; Duration: Single = 0.2; Delay: Single = 0.0; AType: TAnimationType = TAnimationType.In; AInterpolation: TInterpolationType = TInterpolationType.Linear); overload; end; function InterpolateInt64(const Start, Stop: Int64; const T: Single): Int64; implementation function InterpolateInt64(const Start, Stop: Int64; const T: Single): Int64; begin Result := Round(Start + (Stop - Start) * T); end; { TFrameAnimator } class procedure TFrameAnimator.AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TColorAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TColorAnimation.Create(Target); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateColor(const Target: TFmxObject; const APropertyName: string; NewValue: TAlphaColor; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TColorAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TColorAnimation.Create(Target); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TFloatAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TFloatAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TFloatAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TFloatAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateFloat(const Target: TFmxObject; const APropertyName: string; const NewValue: Single; AOnFinish, AOnProcess: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TFloatAnimation; begin TAnimator.StopPropertyAnimation(Target, APropertyName); CreateDestroyer; Animation := TFloatExAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish, AOnProcess); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.OnProcess := FDestroyer.DoAniProcess; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TIntAnimation; begin CreateDestroyer; TAnimator.StopPropertyAnimation(Target, APropertyName); Animation := TIntAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateInt(const Target: TFmxObject; const APropertyName: string; const NewValue: Integer; AOnFinish: TNotifyEventA; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TIntAnimation; begin CreateDestroyer; TAnimator.StopPropertyAnimation(Target, APropertyName); Animation := TIntAnimation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.AnimateInt64(const Target: TFmxObject; const APropertyName: string; const NewValue: Int64; AOnFinish: TNotifyEvent; Duration, Delay: Single; AType: TAnimationType; AInterpolation: TInterpolationType); var Animation: TInt64Animation; begin CreateDestroyer; TAnimator.StopPropertyAnimation(Target, APropertyName); Animation := TInt64Animation.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Target; Animation.AnimationType := AType; Animation.Interpolation := AInterpolation; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Duration; Animation.Delay := Delay; Animation.PropertyName := APropertyName; Animation.StartFromCurrent := True; Animation.StopValue := NewValue; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.CreateDestroyer; begin if FDestroyer = nil then FDestroyer := TAnimationDestroyer.Create; end; class procedure TFrameAnimator.DelayExecute(const Owner: TFmxObject; AOnFinish: TNotifyEventA; Delay: Single); var Animation: TDelayExecute; begin CreateDestroyer; Animation := TDelayExecute.Create(nil); FDestroyer.Add(Animation, AOnFinish); Animation.Parent := Owner; Animation.AnimationType := TAnimationType.In; Animation.Interpolation := TInterpolationType.Linear; Animation.OnFinish := FDestroyer.DoAniFinished; Animation.Duration := Delay; Animation.Delay := 0; Animation.Start; if not Animation.Enabled then FDestroyer.DoAniFinishedEx(Animation, False); end; class procedure TFrameAnimator.Uninitialize; begin FreeAndNil(FDestroyer); end; { TFrameAnimator.TAnimationDestroyer } procedure TFrameAnimator.TAnimationDestroyer.Add(Sender: TObject; AOnFinish: TNotifyEvent); var Item: TFrameAnimatorEvent; begin if not Assigned(AOnFinish) then Exit; Item.OnFinish := AOnFinish; Item.OnFinishA := nil; Item.OnProcess := nil; FOnFinishs.Add(Sender.GetHashCode, Item); end; procedure TFrameAnimator.TAnimationDestroyer.Add(Sender: TObject; AOnFinish: TNotifyEventA); var Item: TFrameAnimatorEvent; begin if not Assigned(AOnFinish) then Exit; Item.OnFinishA := AOnFinish; Item.OnFinish := nil; Item.OnProcess := nil; FOnFinishs.AddOrSetValue(Sender.GetHashCode, Item); end; procedure TFrameAnimator.TAnimationDestroyer.Add(Sender: TObject; AOnFinish, AOnProcess: TNotifyEventA); var Item: TFrameAnimatorEvent; begin if not Assigned(AOnFinish) then Exit; Item.OnFinishA := AOnFinish; Item.OnFinish := nil; Item.OnProcess := AOnProcess; FOnFinishs.AddOrSetValue(Sender.GetHashCode, Item); end; constructor TFrameAnimator.TAnimationDestroyer.Create; begin FOnFinishs := TDictionary<Integer, TFrameAnimatorEvent>.Create(13); end; destructor TFrameAnimator.TAnimationDestroyer.Destroy; begin FreeAndNil(FOnFinishs); inherited; end; procedure TFrameAnimator.TAnimationDestroyer.DoAniFinished(Sender: TObject); begin DoAniFinishedEx(Sender, True); end; procedure TFrameAnimator.TAnimationDestroyer.DoAniFinishedEx(Sender: TObject; FreeSender: Boolean); var Item: TFrameAnimatorEvent; Key: Integer; begin Key := Sender.GetHashCode; if FOnFinishs.TryGetValue(Key, Item) then begin FOnFinishs.Remove(Key); // UI操作,默认是单线程,不作同步处理 end else begin Item.OnFinish := nil; Item.OnFinishA := nil; Item.OnProcess := nil; end; if FreeSender then TAnimation(Sender).DisposeOf; try if Assigned(Item.OnFinish) then Item.OnFinish(Sender); if Assigned(Item.OnFinishA) then Item.OnFinishA(Sender); except end; end; procedure TFrameAnimator.TAnimationDestroyer.DoAniProcess(Sender: TObject); var Item: TFrameAnimatorEvent; begin if FOnFinishs.TryGetValue(Sender.GetHashCode, Item) then begin if Assigned(Item.OnProcess) then Item.OnProcess(Sender); end; end; { TDelayExecute } procedure TDelayExecute.FirstFrame; begin end; procedure TDelayExecute.ProcessAnimation; begin end; procedure TDelayExecute.Start; begin inherited Start; end; procedure TDelayExecute.Stop; begin inherited Stop; end; { TFloatExAnimation } function TFloatExAnimation.FindProperty: Boolean; begin Result := True; end; procedure TFloatExAnimation.Start; begin inherited Start; end; { TInt64Animation } constructor TInt64Animation.Create(AOwner: TComponent); begin inherited; end; procedure TInt64Animation.FirstFrame; begin inherited; end; procedure TInt64Animation.ProcessAnimation; var T: TRttiType; P: TRttiProperty; begin if FInstance <> nil then begin T := SharedContext.GetType(FInstance.ClassInfo); if T <> nil then begin P := T.GetProperty(FPath); if (P <> nil) and (P.PropertyType.TypeKind in [tkInt64]) then P.SetValue(FInstance, InterpolateInt64(FStartValue, FStopValue, NormalizedTime)); end; end; end; initialization finalization TFrameAnimator.Uninitialize; end.
unit CBRWaiterDeskPresenter; interface uses CustomPresenter, db, EntityServiceIntf, CoreClasses, CBRConst, UIClasses, UIStr; const ENT = 'CBR_WD_VIEW'; ENT_TBL = 'CBR_TBL'; COMMAND_ROOM_NEXT = '{AEDD37FF-27CE-422C-A271-7B0030EA9D6B}'; COMMAND_TABLE_INFO_SHOW = '{B8BF467A-774E-41E4-8CC1-DF575BEC6322}'; COMMAND_TABLE_INFO_HIDE = '{BBC9CB7F-CFEF-4E64-9D27-1D1B566EFEBB}'; COMMAND_ORDER_NEW = '{E327F129-EDE4-4A8D-B314-5220B4C89ABD}'; COMMAND_ORDER_ITEM = '{AF4A96CE-5A50-4C0D-AAAE-9456F78E2311}'; type ICBRWaiterDeskView = interface(ICustomView) ['{030E0E52-EF49-4287-A1E3-F4B81FEF3495}'] procedure LinkRoomsDataSet(ADataSet: TDataSet); procedure LinkTablesDataSet(ADataSet: TDataSet); procedure TableInfoShow(ATableInfo, AOrders: TDataSet); procedure TableInfoHide; end; TCBRWaiterDeskPresenter = class(TCustomPresenter) private function GetEVRooms: IEntityView; function GetEVTables: IEntityView; function GetEVTableInfo: IEntityView; function GetEVOrders: IEntityView; function View: ICBRWaiterDeskView; procedure UpdateCommandStatus; procedure CmdRoomNext(Sender: TObject); procedure CmdTableInfoShow(Sender: TObject); procedure CmdOrderNew(Sender: TObject); procedure CmdOrderItem(Sender: TObject); protected procedure OnViewReady; override; end; implementation { TCBRWaiterDeskPresenter } procedure TCBRWaiterDeskPresenter.CmdOrderItem(Sender: TObject); var activity: IActivity; cmd: ICommand; begin View.TableInfoHide; Sender.GetInterface(ICommand, cmd); // activity := WorkItem.Activities[ACTIVITY_ORDER_DESK_ITEM]; activity := WorkItem.Activities[ACTIVITY_ORDER_URI]; activity.Params['ID'] := cmd.Data['ID']; activity.Execute(WorkItem); end; procedure TCBRWaiterDeskPresenter.CmdOrderNew(Sender: TObject); var activity: IActivity; begin View.TableInfoHide; activity := WorkItem.Activities[ACTIVITY_ORDER_NEW]; activity.Params['TBL_ID'] := GetEVTableInfo.DataSet['ID']; activity.Execute(WorkItem); end; procedure TCBRWaiterDeskPresenter.CmdRoomNext(Sender: TObject); begin if not GetEVRooms.DataSet.Eof then GetEVRooms.DataSet.Next; if GetEVRooms.DataSet.Eof then GetEVRooms.DataSet.First; GetEVTables.Params.ParamValues['ROOM_ID'] := GetEVRooms.DataSet['ID']; GetEVTables.Load(true, '-'); UpdateCommandStatus; end; procedure TCBRWaiterDeskPresenter.CmdTableInfoShow(Sender: TObject); var cmd: ICommand; begin Sender.GetInterface(ICommand, cmd); GetEVTableInfo.Load([cmd.Data['TBL_ID']]); GetEVOrders.Load([cmd.Data['TBL_ID']]); View.TableInfoShow(GetEVTableInfo.DataSet, GetEVOrders.DataSet); end; function TCBRWaiterDeskPresenter.GetEVOrders: IEntityView; begin Result := (WorkItem.Services[IEntityService] as IEntityService). Entity[ENT].GetView('Orders', WorkItem); // Result.Load(false); end; function TCBRWaiterDeskPresenter.GetEVRooms: IEntityView; begin Result := (WorkItem.Services[IEntityService] as IEntityService). Entity[ENT].GetView('Rooms', WorkItem); Result.Load(false); end; function TCBRWaiterDeskPresenter.GetEVTableInfo: IEntityView; begin Result := (WorkItem.Services[IEntityService] as IEntityService). Entity[ENT].GetView('TableInfo', WorkItem); // Result.Load(false); end; function TCBRWaiterDeskPresenter.GetEVTables: IEntityView; begin Result := (WorkItem.Services[IEntityService] as IEntityService). Entity[ENT].GetView('Tables', WorkItem); GetEVTables.Params.ParamValues['ROOM_ID'] := GetEVRooms.DataSet['ID']; Result.Load(false, '-'); end; procedure TCBRWaiterDeskPresenter.OnViewReady; begin ViewTitle := 'Заказы'; View.LinkRoomsDataSet(GetEVRooms.DataSet); View.LinkTablesDataSet(GetEVTables.DataSet); WorkItem.Commands[COMMAND_ROOM_NEXT].SetHandler(CmdRoomNext); WorkItem.Commands[COMMAND_TABLE_INFO_SHOW].SetHandler(CmdTableInfoShow); WorkItem.Commands[COMMAND_ORDER_NEW].SetHandler(CmdOrderNew); WorkItem.Commands[COMMAND_ORDER_ITEM].SetHandler(CmdOrderItem); end; procedure TCBRWaiterDeskPresenter.UpdateCommandStatus; begin end; function TCBRWaiterDeskPresenter.View: ICBRWaiterDeskView; begin Result := GetView as ICBRWaiterDeskView; end; end.
unit int_not_i16; interface implementation var I: Int16; procedure Test; begin I := 16000; I := not I; end; initialization Test(); finalization Assert(I = -16001); end.
unit FC.StockChart.UnitTask.ValueSupport.Statistics; {$I Compiler.inc} interface uses SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation uses FC.StockChart.UnitTask.ValueSupport.StatisticsDialog; type TStockUnitTaskValueSupportStatistics = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskValueSupportStatistics } function TStockUnitTaskValueSupportStatistics.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorValueSupport); if result then aOperationName:='Get Statistics'; end; procedure TStockUnitTaskValueSupportStatistics.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); begin TfmValueSupportStatisticsDialog.Run(aIndicator as ISCIndicatorValueSupport,aStockChart); end; initialization StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskValueSupportStatistics.Create); end.
unit fODActive; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ORFn, uCore, StdCtrls, CheckLst, ComCtrls,ExtCtrls,rOrders,fOrders,uOrders, fFrame,ORCtrls,fAutoSz, VA508AccessibilityManager; type TfrmODActive = class(TfrmAutoSz) lblCaption: TLabel; pnlClient: TPanel; btnOK: TButton; btnCancel: TButton; hdControl: THeaderControl; lstActiveOrders: TCaptionListBox; procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lstActiveOrdersMeasureItem(Control: TWinControl; Index: Integer; var AaHeight: Integer); procedure lstActiveOrdersDrawItem(Control: TWinControl; Index: Integer; TheeRect: TRect; State: TOwnerDrawState); procedure hdControlSectionResize(HeaderControl: THeaderControl; Section: THeaderSection); private { Private declarations } FOrderView: TOrderView; FEvent: TOrderDelayEvent; FAutoAc: boolean; ActiveOrderList: TList; FDefaultEventOrder: string; function MeasureColumnHeight(TheOrderText: string; Index: Integer; Column: integer):integer; procedure LoadActiveOrders; procedure RetrieveVisibleOrders(AnIndex: Integer); procedure RedrawActiveList; public { Public declarations } property Event: TOrderDelayEvent read FEvent write FEvent; property OrderView: TOrderView read FOrderView write FOrderView; property AutoAc: boolean read FAutoAc; end; procedure CopyActiveOrdersToEvent(AnOrderView: TOrderView; AnEvent: TOrderDelayEvent); implementation uses VA2006Utils, System.UITypes; {$R *.DFM} const FM_DATE_ONLY = 7; procedure CopyActiveOrdersToEvent(AnOrderView: TOrderView; AnEvent: TOrderDelayEvent); var frmODActive: TfrmODActive; begin frmODActive := TfrmODActive.Create(Application); ResizeFormToFont(TForm(frmODActive)); frmODActive.Event := AnEvent; frmODActive.FOrderView := AnOrderView; frmODActive.FOrderView.Filter := 2; if Length(frmOrders.EventDefaultOrder)>0 then frmODActive.FDefaultEventOrder := frmOrders.EventDefaultOrder; frmODActive.lblCaption.Caption := frmODActive.lblCaption.Caption + ' Delayed ' + AnEvent.EventName + ':'; frmODActive.LoadActiveOrders; if frmODActive.lstActiveOrders.Items.Count < 1 then frmODActive.Close else frmODActive.ShowModal; end; procedure TfrmODActive.btnOKClick(Sender: TObject); const TX_NOSEL = 'No orders are highlighted. Select the orders' + CRLF + 'you wish to take action on.'; TC_NOSEL = 'No Orders Selected'; var i : integer; SelectedList: TStringList; TheVerify : boolean; DoesDestEvtOccur:boolean; begin try self.btnOK.Enabled := false; DoesDestEvtOccur := False; uAutoAC := True; frmFrame.UpdatePtInfoOnRefresh; SelectedList := TStringList.Create; try TheVerify := False; with lstActiveOrders do for i := 0 to Items.Count - 1 do if Selected[i] then SelectedList.Add(TOrder(Items.Objects[i]).ID); if ShowMsgOn(SelectedList.Count = 0, TX_NOSEL, TC_NOSEL) then Exit; if (Event.EventType = 'D') or ((not Patient.InPatient) and (Event.EventType = 'T')) then TransferOrders(SelectedList, Event, DoesDestEvtOccur, TheVerify) else if (not Patient.Inpatient) and (Event.EventType = 'A') then TransferOrders(SelectedList, Event, DoesDestEvtOccur, TheVerify) else CopyOrders(SelectedList, Event, DoesDestEvtOccur, TheVerify); if ( frmOrders <> nil ) and DoesDestEvtOccur then frmOrders.PtEvtCompleted(Event.PtEventIFN,Event.EventName); finally SelectedList.Free; uAutoAC := False; end; finally self.btnOK.Enabled := True; end; Close; end; procedure TfrmODActive.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmODActive.FormCreate(Sender: TObject); begin FixHeaderControlDelphi2006Bug(hdControl); ActiveOrderList := TList.Create; FOrderView := TOrderView.Create; FDefaultEventOrder := ''; end; procedure TfrmODActive.LoadActiveOrders; var AnOrder: TOrder; i: integer; AnOrderPtEvtId,AnOrderEvtId: string; begin LoadOrdersAbbr(ActiveOrderList,FOrderView,''); with ActiveOrderList do for i := Count - 1 downto 0 do begin AnOrder := TOrder(Items[i]); AnOrderPtEvtID := GetOrderPtEvtID(AnOrder.ID); if StrToIntDef(AnOrderPtEvtID,0)>0 then begin AnOrderEvtId := Piece(EventInfo(AnOrderPtEvtID),'^',2); if AnsiCompareText(AnOrderEvtID,IntToStr(FEvent.TheParent.ParentIFN))=0 then begin ActiveOrderList.Delete(i); continue; end; end; if (AnOrder.ID = FDefaultEventOrder) or (IsDCedOrder(AnOrder.ID)) then begin ActiveOrderList.Delete(i); end; end; SortOrders(ActiveOrderList, FOrderView.ByService, FOrderView.InvChrono); lstActiveOrders.Items.Clear; with ActiveOrderList do for i := 0 to Count - 1 do begin AnOrder := TOrder(Items[i]); lstActiveOrders.Items.AddObject(AnOrder.ID,AnOrder); end; end; procedure TfrmODActive.FormDestroy(Sender: TObject); begin ClearOrders(ActiveOrderList); ActiveOrderList.Free; lstActiveOrders.Clear; if FOrderView <> nil then FOrderView := nil ; end; procedure TfrmODActive.lstActiveOrdersMeasureItem(Control: TWinControl; Index: Integer; var AaHeight: Integer); var x,y: string; TextHeight, NewHeight, DateHeight: Integer; TheOrder: TOrder; begin inherited; NewHeight := AaHeight; with lstActiveOrders do if Index < Items.Count then begin TheOrder := TOrder(ActiveOrderList.Items[index]); if TheOrder <> nil then with TheOrder do begin if not TheOrder.Retrieved then RetrieveVisibleOrders(Index); {measure the height of order text} x := Text; TextHeight := MeasureColumnHeight(x,Index,1); {measure the height of Start/Stop date time} x := FormatFMDateTimeStr('mm/dd/yy hh:nn', StartTime); if IsFMDateTime(StartTime) and (Length(StartTime) = FM_DATE_ONLY) then x := Piece(x, #32, 1); if Length(x) > 0 then x := 'Start: ' + x; y := FormatFMDateTimeStr('mm/dd/yy hh:nn', StopTime); if IsFMDateTime(StopTime) and (Length(StopTime) = FM_DATE_ONLY) then y := Piece(y, #32, 1); if Length(y) > 0 then x := x + CRLF + 'Stop: ' + y; DateHeight := MeasureColumnHeight(x,Index,2); NewHeight := HigherOf(TextHeight, DateHeight); end; end; AaHeight := NewHeight; end; procedure TfrmODActive.lstActiveOrdersDrawItem(Control: TWinControl; Index: Integer; TheeRect: TRect; State: TOwnerDrawState); var x, y: string; ARect: TRect; AnOrder: TOrder; i,RightSide: integer; SaveColor: TColor; begin inherited; with lstActiveOrders do begin ARect := TheeRect; Canvas.FillRect(ARect); Canvas.Pen.Color := Get508CompliantColor(clSilver); Canvas.MoveTo(ARect.Left, ARect.Bottom - 1); Canvas.LineTo(ARect.Right, ARect.Bottom - 1); RightSide := -2; for i := 0 to 2 do begin RightSide := RightSide + hdControl.Sections[i].Width; Canvas.MoveTo(RightSide, ARect.Bottom - 1); Canvas.LineTo(RightSide, ARect.Top); end; if Index < Items.Count then begin AnOrder := TOrder(Items.Objects[Index]); if AnOrder <> nil then with AnOrder do for i := 0 to 3 do begin if i > 0 then ARect.Left := ARect.Right + 2 else ARect.Left := 2; ARect.Right := ARect.Left + hdControl.Sections[i].Width - 6; SaveColor := Canvas.Brush.Color; if i = 0 then begin x := DGroupName; if (Index > 0) and (x = TOrder(Items.Objects[Index - 1]).DGroupName) then x := ''; end; if i = 1 then x := Text; if i = 2 then begin x := FormatFMDateTimeStr('mm/dd/yy hh:nn', StartTime); if IsFMDateTime(StartTime) and (Length(StartTime) = FM_DATE_ONLY) then x := Piece(x, #32, 1); if Length(x) > 0 then x := 'Start: ' + x; y := FormatFMDateTimeStr('mm/dd/yy hh:nn', StopTime); if IsFMDateTime(StopTime) and (Length(StopTime) = FM_DATE_ONLY) then y := Piece(y, #32, 1); if Length(y) > 0 then x := x + CRLF + 'Stop: ' + y; end; if i = 3 then x := NameOfStatus(Status); if (i = 1) or (i = 2) then DrawText(Canvas.Handle, PChar(x), Length(x), ARect, DT_LEFT or DT_NOPREFIX or DT_WORDBREAK) else DrawText(Canvas.Handle, PChar(x), Length(x), ARect, DT_LEFT or DT_NOPREFIX ); Canvas.Brush.Color := SaveColor; ARect.Right := ARect.Right + 4; end; end; end; end; procedure TfrmODActive.RetrieveVisibleOrders(AnIndex: Integer); var i: Integer; tmplst: TList; AnOrder: TOrder; begin tmplst := TList.Create; for i := AnIndex to AnIndex + 100 do begin if i >= ActiveOrderList.Count then break; AnOrder := TOrder(ActiveOrderList.Items[i]); if not AnOrder.Retrieved then tmplst.Add(AnOrder); end; RetrieveOrderFields(tmplst, 2, -1); tmplst.Free; end; procedure TfrmODActive.hdControlSectionResize( HeaderControl: THeaderControl; Section: THeaderSection); begin inherited; RedrawSuspend(Self.Handle); RedrawActiveList; RedrawActivate(Self.Handle); lstActiveOrders.Invalidate; end; procedure TfrmODActive.RedrawActiveList; var i, SaveTop: Integer; AnOrder: TOrder; begin with lstActiveOrders do begin RedrawSuspend(Handle); SaveTop := TopIndex; Clear; for i := 0 to ActiveOrderList.Count - 1 do begin AnOrder := TOrder(ActiveOrderList.Items[i]); if (AnOrder.ID = FDefaultEventOrder) or (IsDCedOrder(AnOrder.ID)) then Continue; Items.AddObject(AnOrder.ID, AnOrder); end; TopIndex := SaveTop; RedrawActivate(Handle); end; end; function TfrmODActive.MeasureColumnHeight(TheOrderText: string; Index, Column: integer): integer; var ARect: TRect; begin ARect.Left := 0; ARect.Top := 0; ARect.Bottom := 0; ARect.Right := hdControl.Sections[Column].Width -6; Result := WrappedTextHeightByFont(lstActiveOrders.Canvas,lstActiveOrders.Font,TheOrderText,ARect); end; end.
unit ArchAccsFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, Db, DBTables, DBGrids, ExtCtrls, DBCtrls, BtrDS, Menus, AccountsFrm, SearchFrm, StdCtrls, ComCtrls, Common, Basbn, Utilits, CommCons; type TArchAccsForm = class(TDataBaseForm) DataSource: TDataSource; DBGrid: TDBGrid; EditMenu: TMainMenu; FuncItem: TMenuItem; FindItem: TMenuItem; ArchPopupMenu: TPopupMenu; ChildStatusBar: TStatusBar; BtnPanel: TPanel; NameLabel: TLabel; SearchIndexComboBox: TComboBox; N1: TMenuItem; DelItem: TMenuItem; N3: TMenuItem; DelAllAccItem: TMenuItem; ValueEdit: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FindItemClick(Sender: TObject); procedure SearchIndexComboBoxClick(Sender: TObject); procedure DelItemClick(Sender: TObject); procedure ValueEditChange(Sender: TObject); procedure ValueEditKeyPress(Sender: TObject; var Key: Char); procedure DelAllAccItemClick(Sender: TObject); private SearchForm: TSearchForm; public end; const ArchAccsForm: TArchAccsForm = nil; implementation {$R *.DFM} procedure TArchAccsForm.FormCreate(Sender: TObject); begin ObjList.Add(Self); DataSource.DataSet := GlobalBase(biAccArc); TakeMenuItems(FuncItem, ArchPopupMenu.Items); ArchPopupMenu.Images := EditMenu.Images; SearchForm := TSearchForm.Create(Self); DefineGridCaptions(DBGrid, PatternDir+'ArchAccs.tab'); SearchForm.SourceDBGrid := DBGrid; SearchIndexComboBox.ItemIndex := 0; SearchIndexComboBoxClick(Sender); end; procedure TArchAccsForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TArchAccsForm.FormDestroy(Sender: TObject); begin ObjList.Remove(Self); ArchAccsForm := nil; end; procedure TArchAccsForm.FindItemClick(Sender: TObject); begin SearchForm.ShowModal; end; procedure TArchAccsForm.SearchIndexComboBoxClick(Sender: TObject); begin (DataSource.DataSet as TBtrDataSet).IndexNum := SearchIndexComboBox.ItemIndex end; procedure TArchAccsForm.DelItemClick(Sender: TObject); const MesTitle: PChar = 'Удаление'; var N: Integer; begin if not DataSource.DataSet.IsEmpty then begin DBGrid.SelectedRows.Refresh; N := DBGrid.SelectedRows.Count; if (N<2) and (MessageBox(Handle, PChar('Остаток будет удален. Вы уверены?'), MesTitle, MB_YESNOCANCEL or MB_ICONQUESTION) = IDYES) or (N>=2) and (MessageBox(Handle, PChar('Будет удалено остатков: ' +IntToStr(DBGrid.SelectedRows.Count)+#13#10'Вы уверены?'), MesTitle, MB_YESNOCANCEL or MB_ICONQUESTION) = IDYES) then begin if N>0 then begin {ProtoMes(plInfo, MesTitle, 'Удаляется счет Id=' +IntToStr(PAccRec(DataSource.DataSet.ActiveBuffer)^.arIder));} DBGrid.SelectedRows.Delete; DBGrid.SelectedRows.Refresh; end else DataSource.DataSet.Delete; end; end; end; procedure TArchAccsForm.ValueEditChange(Sender: TObject); var K1: packed record kaDate: Word; { Дата } { 4, 2 k0.1 k1.2} kaIder: Longint; { Идер счета } { 0, 4 k0.2 k1.1} end; K2: packed record kaIder: Longint; { Идер счета } { 0, 4 k0.2 k1.1} kaDate: Word; { Дата } { 4, 2 k0.1 k1.2} end; P: Integer; S1, S2: string; begin S1 := ValueEdit.Text; P := Pos('/', S1); if P>0 then begin S2 := Copy(S1, P+1, Length(S1)-P); S1 := Copy(S1, 1, P-1); end else S2 := ''; case SearchIndexComboBox.ItemIndex of 0: begin try K1.kaDate := StrToBtrDate(S1); except K1.kaDate := 0; end; try K1.kaIder := StrToInt(S2); except K1.kaIder := 0; end; TBtrDataSet(DataSource.DataSet).LocateBtrRecordByIndex(K1, SearchIndexComboBox.ItemIndex, bsGe); end; 1: begin try K2.kaIder := StrToInt(S1); except K2.kaIder := 0; end; try K2.kaDate := StrToBtrDate(S2); except K2.kaDate := 0; end; TBtrDataSet(DataSource.DataSet).LocateBtrRecordByIndex(K2, SearchIndexComboBox.ItemIndex, bsGe); end; end; end; procedure TArchAccsForm.ValueEditKeyPress(Sender: TObject; var Key: Char); begin if not ((Key in ['0'..'9', '/', '.']) or (Key < #32)) then begin Key := #0; MessageBeep(0) end; end; procedure TArchAccsForm.DelAllAccItemClick(Sender: TObject); const MesTitle: PChar = 'Удаление истории счета'; var AccArcDataSet: TExtBtrDataSet; K2: packed record kaIder: Longint; { Идер счета } { 0, 4 k0.2 k1.1} kaDate: Word; { Дата } { 4, 2 k0.1 k1.2} end; P, I, Res, Len: Integer; AccArcRec: TAccArcRec; begin AccArcDataSet := DataSource.DataSet as TExtBtrDataSet; try I := StrToInt(ValueEdit.Text); except I := 0; end; K2.kaIder := I; K2.kaDate := 0; Len := SizeOf(AccArcRec); Res := AccArcDataSet.BtrBase.GetGE(AccArcRec, Len, K2, 1); if (Res=0) and (I=K2.kaIder) then begin if Application.MessageBox(PChar( 'Вы уверны что хотите удалить историю счета Id='+IntToStr(I) +#13#10'При этом будет пересчет проводок с даты '+BtrDateToStr(AccArcRec.aaDate) +#13#10'и возможно затяжное закрытие операционных дней'), MesTitle, MB_YESNOCANCEL or MB_ICONWARNING)=ID_YES then begin P := 0; while (Res=0) and (I=K2.kaIder) do begin Res := AccArcDataSet.BtrBase.Delete(1); if Res=0 then Inc(P) else Application.MessageBox(PChar('Ошибка удаления Date=' +BtrDateToStr(AccArcRec.aaDate)+' BtrErr='+IntToStr(Res)), MesTitle, MB_OK or MB_ICONERROR); Len := SizeOf(AccArcRec); Res := AccArcDataSet.BtrBase.GetNext(AccArcRec, Len, K2, 1); end; AccArcDataSet.First; Application.MessageBox(PChar('Всего удалено остатков '+IntToStr(P)), MesTitle, MB_OK or MB_ICONINFORMATION); end; end else Application.MessageBox(PChar('История по счету Id='+IntToStr(I) +'не найдена'), MesTitle, MB_OK or MB_ICONINFORMATION) end; end.
unit JWT.HS; interface uses System.Hash, System.SysUtils, JWT; type TJWTSigner_SHA2 = class abstract(TInterfacedObject, IJWTSigner) protected class function GetSHA2Version: THashSHA2.TSHA2Version; virtual; abstract; function Sign(Key, Input: TBytes): TBytes; function Validate(Key, Input, Signature: TBytes): Boolean; end; TJWTSigner_HS256 = class(TJWTSigner_SHA2) protected class function GetSHA2Version: THashSHA2.TSHA2Version; override; end; TJWTSigner_HS384 = class(TJWTSigner_SHA2) protected class function GetSHA2Version: THashSHA2.TSHA2Version; override; end; TJWTSigner_HS512 = class(TJWTSigner_SHA2) protected class function GetSHA2Version: THashSHA2.TSHA2Version; override; end; implementation uses JWKS; function TJWTSigner_SHA2.Sign(Key, Input: TBytes): TBytes; begin Result := THashSHA2.GetHMACAsBytes(Input, Key, GetSHA2Version); end; function TJWTSigner_SHA2.Validate(Key, Input, Signature: TBytes): Boolean; begin var R := Sign(Key, Input); Result := Length(R) = Length(Signature); if Result then begin for var i := Low(R) to High(R) do begin Result := R[i] = Signature[i]; if not Result then Exit; end; end; end; class function TJWTSigner_HS256.GetSHA2Version: THashSHA2.TSHA2Version; begin Result := THashSHA2.TSHA2Version.SHA256; end; class function TJWTSigner_HS384.GetSHA2Version: THashSHA2.TSHA2Version; begin Result := THashSHA2.TSHA2Version.SHA384; end; class function TJWTSigner_HS512.GetSHA2Version: THashSHA2.TSHA2Version; begin Result := THashSHA2.TSHA2Version.SHA512; end; initialization TJWTSigner.Register(HS256, TJWTSigner_HS256); TJWTSigner.Register(HS384, TJWTSigner_HS384); TJWTSigner.Register(HS512, TJWTSigner_HS512); end.
// // This unit is part of the GLScene Project, http://glscene.org // { : GLCoordinates<p> Coordinate related classes.<p> <b>History : </b><font size=-1><ul> <li>20/11/12 - PW - Added CPP compatibility: replaced direct access to some properties by a get.. and a set.. methods <li>30/06/11 - DaStr - Added TGLCustomCoordinates.Coordinate default property <li>05/09/10 - Yar - Fix notification in TGLCustomCoordinates.NotifyChange (thanks C4) <li>23/08/10 - Yar - Added OpenGLTokens to uses <li>05/10/08 - DanB - Created, from GLMisc.pas </ul></font> } unit GLCoordinates; interface uses System.Classes, System.SysUtils, //GLS GLVectorGeometry, GLVectorTypes, OpenGLTokens, GLBaseClasses, GLCrossPlatform; {$I GLScene.inc} type // TGLCoordinatesStyle // { : Identifie le type de données stockées au sein d'un TGLCustomCoordinates.<p> <ul><li>csPoint2D : a simple 2D point (Z=0, W=0) <ul><li>csPoint : un point (W=1) <li>csVector : un vecteur (W=0) <li>csUnknown : aucune contrainte </ul> } TGLCoordinatesStyle = (CsPoint2D, CsPoint, CsVector, CsUnknown); // TGLCustomCoordinates // { : Stores and homogenous vector.<p> This class is basicly a container for a TVector, allowing proper use of delphi property editors and editing in the IDE. Vector/Coordinates manipulation methods are only minimal.<br> Handles dynamic default values to save resource file space.<p> } TGLCustomCoordinates = class(TGLUpdateAbleObject) private { Private Declarations } FCoords: TVector; FStyle: TGLCoordinatesStyle; // NOT Persistent FPDefaultCoords: PVector; procedure SetAsPoint2D(const Value: TVector2f); procedure SetAsVector(const Value: TVector); procedure SetAsAffineVector(const Value: TAffineVector); function GetAsAffineVector: TAffineVector; function GetAsPoint2D: TVector2f; function GetAsString: String; function GetCoordinate(const AIndex: Integer): TGLFloat; procedure SetCoordinate(const AIndex: Integer; const AValue: TGLFloat); function GetDirectCoordinate(const Index: Integer): TGLFloat; procedure SetDirectCoordinate(const Index: Integer; const AValue: TGLFloat); protected { Protected Declarations } procedure SetDirectVector(const V: TVector); procedure DefineProperties(Filer: TFiler); override; procedure ReadData(Stream: TStream); procedure WriteData(Stream: TStream); public { Public Declarations } constructor CreateInitialized(AOwner: TPersistent; const AValue: TVector; const AStyle: TGLCoordinatesStyle = CsUnknown); destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure WriteToFiler(Writer: TWriter); procedure ReadFromFiler(Reader: TReader); procedure Initialize(const Value: TVector); procedure NotifyChange(Sender: TObject); override; { : Identifies the coordinates styles.<p> The property is NOT persistent, csUnknown by default, and should be managed by owner object only (internally).<p> It is used by the TGLCustomCoordinates for internal "assertion" checks to detect "misuses" or "misunderstandings" of what the homogeneous coordinates system implies. } property Style: TGLCoordinatesStyle read FStyle write FStyle; procedure Translate(const TranslationVector: TVector); overload; procedure Translate(const TranslationVector: TAffineVector); overload; procedure AddScaledVector(const Factor: Single; const TranslationVector: TVector); overload; procedure AddScaledVector(const Factor: Single; const TranslationVector: TAffineVector); overload; procedure Rotate(const AnAxis: TAffineVector; AnAngle: Single); overload; procedure Rotate(const AnAxis: TVector; AnAngle: Single); overload; procedure Normalize; procedure Invert; procedure Scale(Factor: Single); function VectorLength: TGLFloat; function VectorNorm: TGLFloat; function MaxXYZ: Single; function Equals(const AVector: TVector): Boolean; reintroduce; procedure SetVector(const X, Y: Single; Z: Single = 0); overload; procedure SetVector(const X, Y, Z, W: Single); overload; procedure SetVector(const V: TAffineVector); overload; procedure SetVector(const V: TVector); overload; procedure SetPoint(const X, Y, Z: Single); overload; procedure SetPoint(const V: TAffineVector); overload; procedure SetPoint(const V: TVector); overload; procedure SetPoint2D(const X, Y: Single); overload; procedure SetPoint2D(const Vector: TAffineVector); overload; procedure SetPoint2D(const Vector: TVector); overload; procedure SetPoint2D(const Vector: TVector2f); overload; procedure SetToZero; function AsAddress: PGLFloat; { : The coordinates viewed as a vector.<p> Assigning a value to this property will trigger notification events, if you don't want so, use DirectVector instead. } property AsVector: TVector read FCoords write SetAsVector; { : The coordinates viewed as an affine vector.<p> Assigning a value to this property will trigger notification events, if you don't want so, use DirectVector instead.<br> The W component is automatically adjustes depending on style. } property AsAffineVector: TAffineVector read GetAsAffineVector write SetAsAffineVector; { : The coordinates viewed as a 2D point.<p> Assigning a value to this property will trigger notification events, if you don't want so, use DirectVector instead. } property AsPoint2D: TVector2f read GetAsPoint2D write SetAsPoint2D; property X: TGLFloat index 0 read GetCoordinate write SetCoordinate; property Y: TGLFloat index 1 read GetCoordinate write SetCoordinate; property Z: TGLFloat index 2 read GetCoordinate write SetCoordinate; property W: TGLFloat index 3 read GetCoordinate write SetCoordinate; property Coordinate[const AIndex: Integer]: TGLFloat read GetCoordinate write SetCoordinate; default; { : The coordinates, in-between brackets, separated by semi-colons. } property AsString: String read GetAsString; // : Similar to AsVector but does not trigger notification events property DirectVector: TVector read FCoords write SetDirectVector; property DirectX: TGLFloat index 0 read GetDirectCoordinate write SetDirectCoordinate; property DirectY: TGLFloat index 1 read GetDirectCoordinate write SetDirectCoordinate; property DirectZ: TGLFloat index 2 read GetDirectCoordinate write SetDirectCoordinate; property DirectW: TGLFloat index 3 read GetDirectCoordinate write SetDirectCoordinate; end; { : A TGLCustomCoordinates that publishes X, Y properties. } TGLCoordinates2 = class(TGLCustomCoordinates) published property X stored False; property Y stored False; end; { : A TGLCustomCoordinates that publishes X, Y, Z properties. } TGLCoordinates3 = class(TGLCustomCoordinates) published property X stored False; property Y stored False; property Z stored False; end; // TGLCoordinates4 // { : A TGLCustomCoordinates that publishes X, Y, Z, W properties. } TGLCoordinates4 = class(TGLCustomCoordinates) published property X stored False; property Y stored False; property Z stored False; property W stored False; end; // TGLCoordinates // TGLCoordinates = TGLCoordinates3; // Actually Sender should be TGLCustomCoordinates, but that would require // changes in a some other GLScene units and some other projects that use // TGLCoordinatesUpdateAbleComponent IGLCoordinatesUpdateAble = interface(IInterface) ['{ACB98D20-8905-43A7-AFA5-225CF5FA6FF5}'] procedure CoordinateChanged(Sender: TGLCustomCoordinates); end; // TGLCoordinatesUpdateAbleComponent // TGLCoordinatesUpdateAbleComponent = class(TGLUpdateAbleComponent, IGLCoordinatesUpdateAble) public { Public Declarations } procedure CoordinateChanged(Sender: TGLCustomCoordinates); virtual; abstract; end; var // Specifies if TGLCustomCoordinates should allocate memory for // their default values (ie. design-time) or not (run-time) VUseDefaultCoordinateSets: Boolean = False; //--------------------------------------------------------------------- //--------------------------------------------------------------------- //--------------------------------------------------------------------- implementation //--------------------------------------------------------------------- //--------------------------------------------------------------------- //--------------------------------------------------------------------- const CsVectorHelp = 'If you are getting assertions here, consider using the SetPoint procedure'; CsPointHelp = 'If you are getting assertions here, consider using the SetVector procedure'; CsPoint2DHelp = 'If you are getting assertions here, consider using one of the SetVector or SetPoint procedures'; // ------------------ // ------------------ TGLCustomCoordinates ------------------ // ------------------ // CreateInitialized // constructor TGLCustomCoordinates.CreateInitialized(AOwner: TPersistent; const AValue: TVector; const AStyle: TGLCoordinatesStyle = CsUnknown); begin Create(AOwner); Initialize(AValue); FStyle := AStyle; end; // Destroy // destructor TGLCustomCoordinates.Destroy; begin if Assigned(FPDefaultCoords) then Dispose(FPDefaultCoords); inherited; end; // Initialize // procedure TGLCustomCoordinates.Initialize(const Value: TVector); begin FCoords := Value; if VUseDefaultCoordinateSets then begin if not Assigned(FPDefaultCoords) then New(FPDefaultCoords); FPDefaultCoords^ := Value; end; end; // Assign // procedure TGLCustomCoordinates.Assign(Source: TPersistent); begin if Source is TGLCustomCoordinates then FCoords := TGLCustomCoordinates(Source).FCoords else inherited; end; // WriteToFiler // procedure TGLCustomCoordinates.WriteToFiler(Writer: TWriter); var WriteCoords: Boolean; begin with Writer do begin WriteInteger(0); // Archive Version 0 if VUseDefaultCoordinateSets then WriteCoords := not VectorEquals(FPDefaultCoords^, FCoords) else WriteCoords := True; WriteBoolean(WriteCoords); if WriteCoords then Write(FCoords.V[0], SizeOf(FCoords)); end; end; // ReadFromFiler // procedure TGLCustomCoordinates.ReadFromFiler(Reader: TReader); var N: Integer; begin with Reader do begin ReadInteger; // Ignore ArchiveVersion if ReadBoolean then begin N := SizeOf(FCoords); Assert(N = 4 * SizeOf(Single)); Read(FCoords.V[0], N); end else if Assigned(FPDefaultCoords) then FCoords := FPDefaultCoords^; end; end; // DefineProperties // procedure TGLCustomCoordinates.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('Coordinates', ReadData, WriteData, not(Assigned(FPDefaultCoords) and VectorEquals(FPDefaultCoords^, FCoords))); end; // ReadData // procedure TGLCustomCoordinates.ReadData(Stream: TStream); begin Stream.Read(FCoords, SizeOf(FCoords)); end; // WriteData // procedure TGLCustomCoordinates.WriteData(Stream: TStream); begin Stream.Write(FCoords, SizeOf(FCoords)); end; // NotifyChange // procedure TGLCustomCoordinates.NotifyChange(Sender: TObject); var Int: IGLCoordinatesUpdateAble; begin if Supports(Owner, IGLCoordinatesUpdateAble, Int) then Int.CoordinateChanged(TGLCoordinates(Self)); inherited NotifyChange(Sender); end; // Translate // procedure TGLCustomCoordinates.Translate(const TranslationVector: TVector); begin FCoords.V[0] := FCoords.V[0] + TranslationVector.V[0]; FCoords.V[1] := FCoords.V[1] + TranslationVector.V[1]; FCoords.V[2] := FCoords.V[2] + TranslationVector.V[2]; NotifyChange(Self); end; // Translate // procedure TGLCustomCoordinates.Translate(const TranslationVector : TAffineVector); begin FCoords.V[0] := FCoords.V[0] + TranslationVector.V[0]; FCoords.V[1] := FCoords.V[1] + TranslationVector.V[1]; FCoords.V[2] := FCoords.V[2] + TranslationVector.V[2]; NotifyChange(Self); end; // AddScaledVector (hmg) // procedure TGLCustomCoordinates.AddScaledVector(const Factor: Single; const TranslationVector: TVector); var F: Single; begin F := Factor; CombineVector(FCoords, TranslationVector, F); NotifyChange(Self); end; // AddScaledVector (affine) // procedure TGLCustomCoordinates.AddScaledVector(const Factor: Single; const TranslationVector: TAffineVector); var F: Single; begin F := Factor; CombineVector(FCoords, TranslationVector, F); NotifyChange(Self); end; // Rotate (affine) // procedure TGLCustomCoordinates.Rotate(const AnAxis: TAffineVector; AnAngle: Single); begin RotateVector(FCoords, AnAxis, AnAngle); NotifyChange(Self); end; // Rotate (hmg) // procedure TGLCustomCoordinates.Rotate(const AnAxis: TVector; AnAngle: Single); begin RotateVector(FCoords, AnAxis, AnAngle); NotifyChange(Self); end; // Normalize // procedure TGLCustomCoordinates.Normalize; begin NormalizeVector(FCoords); NotifyChange(Self); end; // Invert // procedure TGLCustomCoordinates.Invert; begin NegateVector(FCoords); NotifyChange(Self); end; // Scale // procedure TGLCustomCoordinates.Scale(Factor: Single); begin ScaleVector(PAffineVector(@FCoords)^, Factor); NotifyChange(Self); end; // VectorLength // function TGLCustomCoordinates.VectorLength: TGLFloat; begin Result := GLVectorGeometry.VectorLength(FCoords); end; // VectorNorm // function TGLCustomCoordinates.VectorNorm: TGLFloat; begin Result := GLVectorGeometry.VectorNorm(FCoords); end; // MaxXYZ // function TGLCustomCoordinates.MaxXYZ: Single; begin Result := MaxXYZComponent(FCoords); end; // Equals // function TGLCustomCoordinates.Equals(const AVector: TVector): Boolean; begin Result := VectorEquals(FCoords, AVector); end; // SetVector (affine) // procedure TGLCustomCoordinates.SetVector(const X, Y: Single; Z: Single = 0); begin Assert(FStyle = CsVector, CsVectorHelp); GLVectorGeometry.SetVector(FCoords, X, Y, Z); NotifyChange(Self); end; // SetVector (TAffineVector) // procedure TGLCustomCoordinates.SetVector(const V: TAffineVector); begin Assert(FStyle = CsVector, CsVectorHelp); GLVectorGeometry.SetVector(FCoords, V); NotifyChange(Self); end; // SetVector (TVector) // procedure TGLCustomCoordinates.SetVector(const V: TVector); begin Assert(FStyle = CsVector, CsVectorHelp); GLVectorGeometry.SetVector(FCoords, V); NotifyChange(Self); end; // SetVector (hmg) // procedure TGLCustomCoordinates.SetVector(const X, Y, Z, W: Single); begin Assert(FStyle = CsVector, CsVectorHelp); GLVectorGeometry.SetVector(FCoords, X, Y, Z, W); NotifyChange(Self); end; // SetDirectVector // procedure TGLCustomCoordinates.SetDirectCoordinate(const Index: Integer; const AValue: TGLFloat); begin FCoords.V[index] := AValue; end; procedure TGLCustomCoordinates.SetDirectVector(const V: TVector); begin FCoords.V[0] := V.V[0]; FCoords.V[1] := V.V[1]; FCoords.V[2] := V.V[2]; FCoords.V[3] := V.V[3]; end; // SetToZero // procedure TGLCustomCoordinates.SetToZero; begin FCoords.V[0] := 0; FCoords.V[1] := 0; FCoords.V[2] := 0; if FStyle = CsPoint then FCoords.V[3] := 1 else FCoords.V[3] := 0; NotifyChange(Self); end; // SetPoint // procedure TGLCustomCoordinates.SetPoint(const X, Y, Z: Single); begin Assert(FStyle = CsPoint, CsPointHelp); MakePoint(FCoords, X, Y, Z); NotifyChange(Self); end; // SetPoint (TAffineVector) // procedure TGLCustomCoordinates.SetPoint(const V: TAffineVector); begin Assert(FStyle = CsPoint, CsPointHelp); MakePoint(FCoords, V); NotifyChange(Self); end; // SetPoint (TVector) // procedure TGLCustomCoordinates.SetPoint(const V: TVector); begin Assert(FStyle = CsPoint, CsPointHelp); MakePoint(FCoords, V); NotifyChange(Self); end; // SetPoint2D // procedure TGLCustomCoordinates.SetPoint2D(const X, Y: Single); begin Assert(FStyle = CsPoint2D, CsPoint2DHelp); GLVectorGeometry.MakeVector(FCoords, X, Y, 0); NotifyChange(Self); end; // SetPoint2D (TAffineVector) // procedure TGLCustomCoordinates.SetPoint2D(const Vector: TAffineVector); begin Assert(FStyle = CsPoint2D, CsPoint2DHelp); MakeVector(FCoords, Vector); NotifyChange(Self); end; // SetPoint2D (TVector) // procedure TGLCustomCoordinates.SetPoint2D(const Vector: TVector); begin Assert(FStyle = CsPoint2D, CsPoint2DHelp); MakeVector(FCoords, Vector); NotifyChange(Self); end; // SetPoint2D (TVector2f) // procedure TGLCustomCoordinates.SetPoint2D(const Vector: TVector2f); begin Assert(FStyle = CsPoint2D, CsPoint2DHelp); MakeVector(FCoords, Vector.V[0], Vector.V[1], 0); NotifyChange(Self); end; // AsAddress // function TGLCustomCoordinates.AsAddress: PGLFloat; begin Result := @FCoords; end; // SetAsVector // procedure TGLCustomCoordinates.SetAsVector(const Value: TVector); begin FCoords := Value; case FStyle of CsPoint2D: begin FCoords.V[2] := 0; FCoords.V[3] := 0; end; CsPoint: FCoords.V[3] := 1; CsVector: FCoords.V[3] := 0; else Assert(False); end; NotifyChange(Self); end; // SetAsAffineVector // procedure TGLCustomCoordinates.SetAsAffineVector(const Value: TAffineVector); begin case FStyle of CsPoint2D: MakeVector(FCoords, Value); CsPoint: MakePoint(FCoords, Value); CsVector: MakeVector(FCoords, Value); else Assert(False); end; NotifyChange(Self); end; // SetAsPoint2D // procedure TGLCustomCoordinates.SetAsPoint2D(const Value: TVector2f); begin case FStyle of CsPoint2D, CsPoint, CsVector: begin FCoords.V[0] := Value.V[0]; FCoords.V[1] := Value.V[1]; FCoords.V[2] := 0; FCoords.V[3] := 0; end; else Assert(False); end; NotifyChange(Self); end; // GetAsAffineVector // function TGLCustomCoordinates.GetAsAffineVector: TAffineVector; begin GLVectorGeometry.SetVector(Result, FCoords); end; // GetAsPoint2D // function TGLCustomCoordinates.GetAsPoint2D: TVector2f; begin Result.V[0] := FCoords.V[0]; Result.V[1] := FCoords.V[1]; end; // SetCoordinate // procedure TGLCustomCoordinates.SetCoordinate(const AIndex: Integer; const AValue: TGLFloat); begin FCoords.V[AIndex] := AValue; NotifyChange(Self); end; // GetCoordinate // function TGLCustomCoordinates.GetCoordinate(const AIndex: Integer): TGLFloat; begin Result := FCoords.V[AIndex]; end; function TGLCustomCoordinates.GetDirectCoordinate( const Index: Integer): TGLFloat; begin Result := FCoords.V[index] end; // GetAsString // function TGLCustomCoordinates.GetAsString: String; begin case Style of CsPoint2D: Result := Format('(%g; %g)', [FCoords.V[0], FCoords.V[1]]); CsPoint: Result := Format('(%g; %g; %g)', [FCoords.V[0], FCoords.V[1], FCoords.V[2]]); CsVector: Result := Format('(%g; %g; %g; %g)', [FCoords.V[0], FCoords.V[1], FCoords.V[2], FCoords.V[3]]); else Assert(False); end; end; initialization RegisterClasses([TGLCoordinates2, TGLCoordinates3, TGLCoordinates4]); end.
unit SearchComponentGroup; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap; type TSearchComponentGroupW = class(TDSWrap) private FComponentGroup: TFieldWrap; FID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ComponentGroup: TFieldWrap read FComponentGroup; property ID: TFieldWrap read FID; end; TQuerySearchComponentGroup = class(TQueryBase) private FW: TSearchComponentGroupW; { Private declarations } public constructor Create(AOwner: TComponent); override; procedure Append(const AComponentGroup: string); function SearchByID(const AID: Integer; const ATestResult: Boolean = False): Integer; function SearchByValue(const AComponentGroup: string): Integer; property W: TSearchComponentGroupW read FW; { Public declarations } end; implementation {$R *.dfm} uses StrHelper, System.Math; constructor TQuerySearchComponentGroup.Create(AOwner: TComponent); begin inherited; FW := TSearchComponentGroupW.Create(FDQuery); end; procedure TQuerySearchComponentGroup.Append(const AComponentGroup: string); begin Assert(not AComponentGroup.IsEmpty); W.TryAppend; W.ComponentGroup.F.Value := AComponentGroup; W.TryPost; end; function TQuerySearchComponentGroup.SearchByID(const AID: Integer; const ATestResult: Boolean = False): Integer; begin Assert(AID > 0); // Èùåì Result := SearchEx([TParamRec.Create(W.ID.FullName, AID)], IfThen(ATestResult, 1, -1)); end; function TQuerySearchComponentGroup.SearchByValue(const AComponentGroup : string): Integer; begin Assert(not AComponentGroup.IsEmpty); // Èùåì Result := SearchEx([TParamRec.Create(W.ComponentGroup.FullName, AComponentGroup, ftWideString, True)]); end; constructor TSearchComponentGroupW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FComponentGroup := TFieldWrap.Create(Self, 'ComponentGroup'); end; end.
unit uDemo; interface uses System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, // GLS GLScene, GLTeapot, GLCoordinates, GLObjects, GLGeomObjects, GLMaterial, GLSimpleNavigation, GLCadencer, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLFBORenderer, GLHUDObjects, GLSCUDA, GLSCUDAGraphics, GLSCUDACompiler, GLSCUDAContext, GLState, GLRenderContextInfo, GLContext, GLCustomShader, GLSLShader, GLTexture, OpenGLTokens; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCadencer1: TGLCadencer; GLSimpleNavigation1: TGLSimpleNavigation; GLMaterialLibrary1: TGLMaterialLibrary; GLCamera1: TGLCamera; GLTeapot1: TGLTeapot; GLLightSource1: TGLLightSource; RenderRoot: TGLDummyCube; GLCylinder1: TGLCylinder; RenderToTexture: TGLFBORenderer; GLSCUDADevice1: TGLSCUDADevice; GLSCUDA1: TGLSCUDA; GLSCUDACompiler1: TGLSCUDACompiler; MainModule: TCUDAModule; processedTextureMapper: TCUDAGLImageResource; CallPostProcess: TGLDirectOpenGL; GLCapsule1: TGLCapsule; ResultShader: TGLSLShader; processedTextureArray: TCUDAMemData; outputBuffer: TCUDAMemData; inputBuffer: TCUDAMemData; CommonShader: TGLSLShader; GLSphere1: TGLSphere; TrackBar1: TTrackBar; GLHUDSprite1: TGLHUDSprite; cudaProcess: TCUDAFunction; cudaProcess_k_g_data: TCUDAFuncParam; cudaProcess_k_g_odata: TCUDAFuncParam; cudaProcess_k_imgw: TCUDAFuncParam; cudaProcess_k_imgh: TCUDAFuncParam; cudaProcess_k_tilew: TCUDAFuncParam; cudaProcess_k_r: TCUDAFuncParam; cudaProcess_k_threshold: TCUDAFuncParam; cudaProcess_k_highlight: TCUDAFuncParam; procedure FormResize(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure cudaProcessParameterSetup(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CallPostProcessRender(Sender: TObject; var rci: TRenderContextInfo); procedure ResultShaderApply(Shader: TGLCustomGLSLShader); procedure RenderToTextureBeforeRender(Sender: TObject; var rci: TRenderContextInfo); procedure RenderToTextureAfterRender(Sender: TObject; var rci: TRenderContextInfo); procedure TrackBar1Change(Sender: TObject); procedure GLSCUDA1OpenGLInteropInit(out Context: TGLContext); private { Private declarations } public { Public declarations } Radius: Integer; Threshold: Single; Highlight: SIngle; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin Radius := 8; Threshold := 0.8; Highlight := 0.4; with GLMaterialLibrary1.TextureByName('processedTexture') do begin TGLBlankImage(Image).ColorFormat := GL_RGB_INTEGER; Disabled := false; end; GLHUDSprite1.Visible := True; end; procedure TForm1.CallPostProcessRender(Sender: TObject; var rci: TRenderContextInfo); begin processedTextureMapper.MapResources; processedTextureMapper.BindArrayToTexture(processedTextureArray, 0, 0); processedTextureArray.CopyTo(inputBuffer); cudaProcess.Launch; outputBuffer.CopyTo(processedTextureArray); processedTextureMapper.UnMapResources; end; procedure TForm1.cudaProcessParameterSetup(Sender: TObject); begin with cudaProcess do begin SharedMemorySize := (BlockShape.SizeX+(2*Radius))*(BlockShape.SizeY+(2*Radius))*sizeof(Integer); SetParam(inputBuffer); SetParam(outputBuffer); with GLMaterialLibrary1.TextureByName('processedTexture') do begin SetParam(TexWidth); SetParam(TexHeight); end; SetParam(BlockShape.SizeX + 2*Radius); SetParam(Radius); SetParam(Threshold); SetParam(Highlight); end; end; procedure TForm1.FormResize(Sender: TObject); begin GLCamera1.SceneScale := GLSceneViewer1.Width / GLSceneViewer1.Height; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin GLSceneViewer1.Invalidate; end; procedure TForm1.RenderToTextureBeforeRender(Sender: TObject; var rci: TRenderContextInfo); begin CommonShader.Apply(rci, Self); end; procedure TForm1.GLSCUDA1OpenGLInteropInit(out Context: TGLContext); begin Context := GLSceneViewer1.Buffer.RenderingContext; end; procedure TForm1.RenderToTextureAfterRender(Sender: TObject; var rci: TRenderContextInfo); begin CommonShader.UnApply(rci); end; procedure TForm1.ResultShaderApply(Shader: TGLCustomGLSLShader); begin with CurrentGLContext.GLStates do begin Disable(stDepthTest); DepthWriteMask := False; end; Shader.Param['TexUnit0'].AsTexture[0] := GLMaterialLibrary1.TextureByName('processedTexture'); end; procedure TForm1.TrackBar1Change(Sender: TObject); begin Radius := TrackBar1.Position; end; end.
unit ufrmAnsiToUnicodeMain; (* * by: David E. Cornelius * of: Cornelius Concepts * on: Feburary, 2010 * in: Delphi 2009 * to: convert a whole folder of Windows ANSI files to Unicode *) interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ActnList, StdActns, ImgList, CheckLst, ComCtrls; type TfrmAnsiToUnicode = class(TForm) pnlConfig: TPanel; edtSourcePath: TButtonedEdit; Label1: TLabel; Label2: TLabel; edtDestinationPath: TButtonedEdit; imlBtnEdit: TImageList; aclMain: TActionList; imlActions: TImageList; actSelectSourceFolder: TBrowseForFolder; actSelectDestFolder: TBrowseForFolder; btnStop: TButton; btnStart: TButton; actConvertStart: TAction; actConvertStop: TAction; edtAnsiExt: TLabeledEdit; edtUniExt: TLabeledEdit; pnlFiles: TGridPanel; cbOverwrite: TCheckBox; clbSource: TCheckListBox; lbDest: TListBox; BalloonHint: TBalloonHint; cbStripBOM: TCheckBox; StatusBar: TStatusBar; InfoSpeedButton: TSpeedButton; procedure edtSourcePathClick(Sender: TObject); procedure actConvertStartExecute(Sender: TObject); procedure actConvertStopExecute(Sender: TObject); procedure edtDestinationPathClick(Sender: TObject); procedure edtExtExit(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure InfoSpeedButtonClick(Sender: TObject); private const INIKEY_SavedSettings = 'SavedSettings'; INIVAL_SourcePath = 'SourcePath'; INIVAL_DestPath = 'DestinationPath'; INIVAL_SourceExt = 'SourceExtension'; INIVAL_DestExt = 'DestinationExtension'; INIVAL_OverwriteDest = 'OverwriteDestination'; INIVal_StripBOM = 'StripByteOrderMark'; INIKEY_Layout = 'Layout'; INIVAL_ScreenTop = 'ScreenTop'; INIVAL_ScreenLeft = 'ScreenLeft'; INIVAL_ScreenWidth = 'ScreenWidth'; INIVAL_ScreenHeight = 'ScreenHeight'; type TNoPreambleUnicode = class(TUnicodeEncoding) public function GetPreamble: TBytes; override; end; var FCanceled: Boolean; function BuildIniFilename: string; procedure PutInfoButtonOnStatusBar; procedure LoadSettings; procedure SaveSettings; procedure ListFiles; procedure ConvertFiles; procedure SetEditsAndCancel(AEnable: Boolean); end; var frmAnsiToUnicode: TfrmAnsiToUnicode; implementation {$R *.dfm} uses IniFiles; procedure TfrmAnsiToUnicode.actConvertStartExecute(Sender: TObject); begin FCanceled := False; SetEditsAndCancel(False); try ListFiles; if (not FCanceled) and (clbSource.Items.Count > 0) then ConvertFiles else MessageBox(Handle, PChar('No files found to convert.'), PChar(Application.Title), MB_OK + MB_ICONASTERISK + MB_TASKMODAL); finally SetEditsAndCancel(True); end; end; procedure TfrmAnsiToUnicode.actConvertStopExecute(Sender: TObject); begin FCanceled := True; end; procedure TfrmAnsiToUnicode.ConvertFiles; var i: Integer; sl: TStringList; src_path: string; dest_path: string; // this is the key part in the unicode conversion uni: TUnicodeEncoding; begin Screen.Cursor := crAppStart; try lbDest.Clear; // save these settings in local variables for readability and speed src_path := IncludeTrailingPathDelimiter(edtSourcePath.Text); dest_path := IncludeTrailingPathDelimiter(edtDestinationPath.Text); if cbStripBOM.Checked then uni := TNoPreambleUnicode.Create else uni := TUnicodeEncoding.Create; try // use a string list for ease of dealing with text files and converting sl := TStringList.Create; try for i := 0 to clbSource.Items.Count - 1 do begin // list the file that will be converted in the destination listbox lbDest.Items.Add(clbSource.Items[i]); // update the screen to show the next file being processed lbDest.Update; // read in the file sl.LoadFromFile(src_path + clbSource.Items[i]); // save it out to the destination path with the new encoding sl.SaveToFile(ChangeFileExt(dest_path + clbSource.Items[i], edtUniExt.Text), uni); // check it off in the source list clbSource.Checked[i] := True; // clear the string list for the next file sl.Clear; // allow window messages to process Application.ProcessMessages; // was the Abort button clicked? if FCanceled then Break; end; finally uni.Free; end; finally sl.Free; end; finally Screen.Cursor := crDefault; end; end; function TfrmAnsiToUnicode.BuildIniFilename: string; var SettingsFolder: string; begin // settings are in the standard user folder SettingsFolder := GetEnvironmentVariable('APPDATA'); Result := IncludeTrailingPathDelimiter(SettingsFolder) + ChangeFileExt(ExtractFileName(Application.ExeName), '.ini'); end; procedure TfrmAnsiToUnicode.edtExtExit(Sender: TObject); var edt: TLabeledEdit; begin edt := (Sender as TLabeledEdit); if Pos('.', edt.Text) = 0 then edt.Text := '.' + edt.Text; end; procedure TfrmAnsiToUnicode.edtDestinationPathClick(Sender: TObject); // call a standard Browse Folder action to select the destination path begin actSelectDestFolder.RootDir := edtDestinationPath.Text; if actSelectDestFolder.Execute then edtDestinationPath.Text := actSelectDestFolder.Folder; end; procedure TfrmAnsiToUnicode.ListFiles; // list all the files from the source folder that will be converted var found: Boolean; sr: TSearchRec; begin Screen.Cursor := crHourGlass; try clbSource.Clear; found := FindFirst(IncludeTrailingPathDelimiter(edtSourcePath.Text) + '*' + edtAnsiExt.Text, faAnyFile, sr) = 0; while found and (not FCanceled) do begin clbSource.Items.Add(sr.Name); clbSource.Update; Application.ProcessMessages; found := FindNext(sr) = 0; end; FindClose(sr); finally Screen.Cursor := crDefault; end; end; procedure TfrmAnsiToUnicode.LoadSettings; var ini: TIniFile; begin ini := TIniFile.Create(BuildIniFilename); try // restore screen layout, default is current dimensions Top := ini.ReadInteger(INIKEY_Layout, INIVAL_ScreenTop, Top); Left := ini.ReadInteger(INIKEY_Layout, INIVAL_ScreenLeft, Left); Width := ini.ReadInteger(INIKEY_Layout, INIVAL_ScreenWidth, Width); Height := ini.ReadInteger(INIKEY_Layout, INIVAL_ScreenHeight, Height); // restore last used settings edtSourcePath.Text := ini.ReadString(INIKEY_SavedSettings, INIVAL_SourcePath, EmptyStr); edtDestinationPath.Text := ini.ReadString(INIKEY_SavedSettings, INIVAL_DestPath, EmptyStr); edtAnsiExt.Text := ini.ReadString(INIKEY_SavedSettings, INIVAL_SourceExt, EmptyStr); edtUniExt.Text := ini.ReadString(INIKEY_SavedSettings, INIVAL_DestExt, EmptyStr); cbOverwrite.Checked := ini.ReadBool(INIKEY_SavedSettings, INIVAL_OverwriteDest, True); cbStripBOM.Checked := ini.ReadBool(INIKEY_SavedSettings, INIVal_StripBOM, False); finally ini.Free; end; end; procedure TfrmAnsiToUnicode.PutInfoButtonOnStatusBar; begin InfoSpeedButton.Parent := StatusBar; InfoSpeedButton.Top := 1; InfoSpeedButton.Left := 1; end; procedure TfrmAnsiToUnicode.SaveSettings; var ini: TIniFile; begin ini := TIniFile.Create(BuildIniFilename); try // save current screen layout ini.WriteInteger(INIKEY_Layout, INIVAL_ScreenTop, Top); ini.WriteInteger(INIKEY_Layout, INIVAL_ScreenLeft, Left); ini.WriteInteger(INIKEY_Layout, INIVAL_ScreenWidth, Width); ini.WriteInteger(INIKEY_Layout, INIVAL_ScreenHeight, Height); // save settings for convenience in case of reuse next time ini.WriteString(INIKEY_SavedSettings, INIVAL_SourcePath, edtSourcePath.Text); ini.WriteString(INIKEY_SavedSettings, INIVAL_DestPath, edtDestinationPath.Text); ini.WriteString(INIKEY_SavedSettings, INIVAL_SourceExt, edtAnsiExt.Text); ini.WriteString(INIKEY_SavedSettings, INIVAL_DestExt, edtUniExt.Text); ini.WriteBool(INIKEY_SavedSettings, INIVAL_OverwriteDest, cbOverwrite.Checked); ini.WriteBool(INIKEY_SavedSettings, INIVal_StripBOM, cbStripBOM.Checked); finally ini.Free; end; end; procedure TfrmAnsiToUnicode.SetEditsAndCancel(AEnable: Boolean); var i: Integer; begin for i := 0 to pnlConfig.ControlCount - 1 do if pnlConfig.Controls[i].Tag = 1 then pnlConfig.Controls[i].Enabled := AEnable else if pnlConfig.Controls[i].Tag = 2 then pnlConfig.Controls[i].Enabled := not AEnable; Application.ProcessMessages; end; procedure TfrmAnsiToUnicode.edtSourcePathClick(Sender: TObject); // call a standard Browse Folder action to select the source path begin actSelectSourceFolder.RootDir := edtSourcePath.Text; if actSelectSourceFolder.Execute then edtSourcePath.Text := actSelectSourceFolder.Folder; end; procedure TfrmAnsiToUnicode.FormActivate(Sender: TObject); begin LoadSettings; PutInfoButtonOnStatusBar; end; procedure TfrmAnsiToUnicode.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; Action := caFree; end; procedure TfrmAnsiToUnicode.InfoSpeedButtonClick(Sender: TObject); const InfoText = 'This program converts standard Windows text files from ANSI encoding (standard 1252 code page) to Unicode encoding. ' + 'There are many Unicode formats, but this one assumes you just want to do what Notepad would do if you select "Unicode" ' + 'during a Save As. This turns out to be a UTF-16 "little endian" format, the most common. ' + 'There are no command-line paramters and no separate documentation.'#13#13#10 + 'Written by David E. Cornelius of Cornelius Concepts, February, 2010.'; begin MessageBox(Handle, PChar(InfoText), PChar(Application.Title), MB_OK + MB_ICONINFORMATION + MB_APPLMODAL); end; { TfrmAnsiToUnicode.TNoPreambleUnicode } function TfrmAnsiToUnicode.TNoPreambleUnicode.GetPreamble: TBytes; begin SetLength(Result, 0); end; end.
unit set_1; interface implementation type TEnum = (v1 = 1, v2, v3, v4, v5); TSet = set of TEnum; var S1, S2: TSet; procedure Test; begin S1 := [v2, v3]; S2 := S1; end; initialization Test(); finalization Assert(S2 = S1); end.
unit DelphiSpec.DataTable; interface uses SysUtils, Classes, Generics.Collections; type IDataTable = interface function GetColumns(const Name: string): TStrings; function GetRowCount: Integer; function GetColCount: Integer; function GetName(I: Integer): string; property Columns[const Name: string]: TStrings read GetColumns; default; property Names[I: Integer]: string read GetName; property RowCount: Integer read GetRowCount; property ColCount: Integer read GetColCount; end; EDataTableException = class(Exception); TDataTable = class(TInterfacedObject, IDataTable) private FColNames: TStringList; FColByIndex: TObjectList<TStringList>; FColByName: TDictionary<string, TStringList>; function GetColumns(const Name: string): TStrings; function GetName(I: Integer): string; function GetRowCount: Integer; function GetColCount: Integer; public constructor Create(const ColNames: array of string); reintroduce; destructor Destroy; override; procedure AddRow(const Values: array of string); property Columns[const Name: string]: TStrings read GetColumns; default; property Names[I: Integer]: string read GetName; property RowCount: Integer read GetRowCount; property ColCount: Integer read GetColCount; end; implementation { TDataTable } procedure TDataTable.AddRow(const Values: array of string); var I: Integer; begin if Length(Values) <> FColByIndex.Count then raise EDataTableException.Create('Column count mismatch'); for I := 0 to High(Values) do FColByIndex[I].Add(Values[I]); end; constructor TDataTable.Create(const ColNames: array of string); var I: Integer; Row: TStringList; begin inherited Create; FColNames := TStringList.Create; FColByIndex := TObjectList<TStringList>.Create(True); FColByName := TDictionary<string, TStringList>.Create; for I := Low(ColNames) to High(ColNames) do begin Row := TStringList.Create; FColByIndex.Add(Row); FColByName.Add(AnsiLowerCase(ColNames[I]), Row); FColNames.Add(ColNames[I]); end; end; destructor TDataTable.Destroy; begin FColNames.Free; FColByName.Free; FColByIndex.Free; inherited; end; function TDataTable.GetColCount: Integer; begin Result := FColNames.Count; end; function TDataTable.GetColumns(const Name: string): TStrings; begin Result := FColByName[AnsiLowerCase(Name)]; end; function TDataTable.GetRowCount: Integer; begin Result := FColByIndex[0].Count; end; function TDataTable.GetName(I: Integer): string; begin Result := FColNames[I]; end; end.
{ Shengjin's Formulas Univariate cubic equation aX ^ 3 + bX ^ 2 + cX + d = 0, (a, b, c, d < R, and a!= 0). Multiple root discriminant: delta1 = b^2-3*a*c; delta2 = b*c-9*a*d; delta3 = c^2-3*b*d, The total discriminant is delta=delta2^2-4*delta1*delta3. When delta1 = delta2 = 0, Shengjin Formula (1): X1=X2=X3=-b/(3*a)=-c/b=-3d/c. When delta=B^2-4*A*C>0, Shengjin Formula II: Y1= delta1*b + 3*a *((-B + (delta)^1/2))/ 2. Y2= delta1*b + 3*a *((-B - (delta)^1/2))/ 2. x1=(-b-Y1^(1/3) - Y1^(1/3)/(3*a); X2=(-2*b+Y1^(1/3)+Y2^(1/3)/(6*a)+3^(1/2)* (Y1^(1/3)-Y2^(1/3)/(6a)i, X3=(-2*b+Y1^(1/3)+Y2^(1/3)/(6*a)-3^(1/2)* (Y1^(1/3)-Y2^(1/3)/(6a)i, When delta=B^2-4AC=0, Shengjin Formula 3: X1=-b/a+K; X2=X3=-K/2, K = delta2/delta1, (A<>0). When delta=B^2-4AC<0, Shengjin Formula 4: X1= (-b-2*sqrt(delta1)*cos(theta/3))/(3*a); X2= (-b+sqrt(delta1)*(cos(theta/3)+sqrt(3)*sin(theta/3)))/(3*a); X3= (-b+sqrt(delta1)*(cos(theta/3)-sqrt(3)*sin(theta/3)))/(3*a) theta=arccosT,T=(2Ab-3aB)/(2A^(3/2)) Shengjin's Distinguishing Means (1)A = B = 0, the equation has a triple real root. (2) When delta =B^2-4AC>0, the equation has a real root and a pair of conjugate complex roots. (3) When delta=B^2-4AC=0, the equation has three real roots, one of which has two double roots. (4) When delta=B^2-4AC<0, the equation has three unequal real roots. } program cubic1(input,output); const PI=3.14159265359; type roottype=(UniReal,OneRPairComplex,TwoReal,UnequalReal,NotCubic); var a,b,c,d:real;{Coefficient of cubic Equation} delta1,delta2,delta3,delta:real; Y1,Y2,expY1,expY2:real; K,theta,T:real; rt:roottype; begin writeln('Input Coefficient of cubic Equation:a b c d'); readln(a,b,c,d); delta1 := b*b-3*a*c; delta2 := b*c-9*a*d; delta3 := c*c-3*b*d; delta := delta2*delta2-4*delta1*delta3; if (delta1=0 )and (delta2=0) then rt:=UniReal else if delta>0 then rt:=OneRPairComplex else if delta=0 then rt:=TwoReal else if delta<0 then rt:=UnequalReal; if a=0 then rt:=NotCubic; case rt of UniReal : begin writeln('the equation has a triple real root.'); writeln('x1=x2=x3=',-b/3/a:0:5) end; OneRPairComplex : begin writeln(' the equation has a real root and a pair of conjugate complex roots.'); Y1 := delta1*b + 3*a *((-delta2 + sqrt(delta)))/2; Y2 := delta1*b + 3*a *((-delta2 - sqrt(delta)))/2; if Y1>0 then expY1 := exp((1/3)*ln(Y1)) else if Y1=0 then expY1 := 0 else expY1 := (-1)*exp((1/3)*ln(abs(Y1))); if Y2>0 then expY2 := exp((1/3)*ln(Y2)) else if Y2=0 then expY2 := 0 else expY2 := (-1)*exp((1/3)*ln(abs(Y2))); writeln('x1=',(-b-expY1 - expY2)/(3*a):0:5); writeln('x2=',(-2*b+expY1 +expY2)/(6*a):0:5,'+',sqrt(3.0)* (expY1-expY2)/(6*a):0:5,'i'); writeln('x3=',(-2*b+expY1 +expY2)/(6*a):0:5,'-',sqrt(3.0)* (expY1-expY2)/(6*a):0:5,'i') end; TwoReal : begin writeln('the equation has three real roots, one of which has two double roots.'); K :=delta2/delta1; writeln('X1=X2=',-K/2:0:5); writeln('X3=',-b/a+K:0:5) end; UnequalReal : begin writeln('the equation has three unequal real roots.'); T:=(2*delta1*b-3*a*delta2)/(2*sqrt(delta1*delta1*delta1)); if T=0 then theta:=PI/2.0 else theta:=arctan(sqrt(1-T*T)/T); { theta:=arccos(T); } if theta<0 then theta:=PI+theta; writeln('X1=',(-b-2*sqrt(delta1)*cos(theta/3.0))/(3*a):0:5); writeln('X2=',(-b+sqrt(delta1)*(cos(theta/3.0)+sqrt(3.0)*sin(theta/3)))/(3*a):0:5); writeln('X3=',(-b+sqrt(delta1)*(cos(theta/3.0)-sqrt(3.0)*sin(theta/3)))/(3*a):0:5) end; NotCubic : begin writeln('the equation is not a cubic equation.'); end; end; {end of case} end.
{ GS1 interface library for FPC and Lazarus Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit lp_ship_goods; {$mode objfpc}{$H+} interface uses Classes, SysUtils, JSONObjects, AbstractSerializationObjects; type { TChildren } TChildren = class(TJSONSerializationObject) private FProductDescription: string; FUITCode: string; procedure SetProductDescription(AValue: string); procedure SetUITCode(AValue: string); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public destructor Destroy; override; public published property UITCode:string read FUITCode write SetUITCode; property ProductDescription:string read FProductDescription write SetProductDescription; end; TChildrens = specialize GXMLSerializationObjectList<TChildren>; { TProduct } TProduct = class(TJSONSerializationObject) private FChildren: TChildrens; FCountChildren: Integer; FProductCost: Double; FProductDescription: string; FProductTax: Double; FUITCode: string; FUITUCode: string; procedure SetCountChildren(AValue: Integer); procedure SetProductCost(AValue: Double); procedure SetProductDescription(AValue: string); procedure SetProductTax(AValue: Double); procedure SetUITCode(AValue: string); procedure SetUITUCode(AValue: string); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public destructor Destroy; override; public published property UITCode:string read FUITCode write SetUITCode; property UITUCode:string read FUITUCode write SetUITUCode; property ProductDescription:string read FProductDescription write SetProductDescription; property ProductCost:Double read FProductCost write SetProductCost; property ProductTax:Double read FProductTax write SetProductTax; property CountChildren:Integer read FCountChildren write SetCountChildren; property Children:TChildrens read FChildren; end; TProducts = specialize GXMLSerializationObjectList<TProduct>; { TShipGoods } TShipGoods = class(TJSONSerializationObject) private FDocumentDate: string; FDocumentNum: string; FProducts: TProducts; FReceiver: string; FReceiverInn: string; FRequestType: string; FSale: Boolean; FSender: string; FSenderInn: string; FStContractId: string; FToNotParticipant: Boolean; FTransferDate: string; FTurnoverType: string; FWithdrawalFromTurnover: Boolean; procedure SetDocumentDate(AValue: string); procedure SetDocumentNum(AValue: string); procedure SetReceiver(AValue: string); procedure SetReceiverInn(AValue: string); procedure SetRequestType(AValue: string); procedure SetSale(AValue: Boolean); procedure SetSender(AValue: string); procedure SetSenderInn(AValue: string); procedure SetStContractId(AValue: string); procedure SetToNotParticipant(AValue: Boolean); procedure SetTransferDate(AValue: string); procedure SetTurnoverType(AValue: string); procedure SetWithdrawalFromTurnover(AValue: Boolean); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public destructor Destroy; override; public published property Sale:Boolean read FSale write SetSale; property TurnoverType:string read FTurnoverType write SetTurnoverType; property RequestType:string read FRequestType write SetRequestType; property SenderInn:string read FSenderInn write SetSenderInn; property DocumentNum:string read FDocumentNum write SetDocumentNum; property DocumentDate:string read FDocumentDate write SetDocumentDate; property WithdrawalFromTurnover:Boolean read FWithdrawalFromTurnover write SetWithdrawalFromTurnover; property TransferDate:string read FTransferDate write SetTransferDate; property ReceiverInn:string read FReceiverInn write SetReceiverInn; property ToNotParticipant:Boolean read FToNotParticipant write SetToNotParticipant; property Sender:string read FSender write SetSender; property Receiver:string read FReceiver write SetReceiver; property StContractId:string read FStContractId write SetStContractId; property Products:TProducts read FProducts; end; implementation { TChildren } procedure TChildren.SetProductDescription(AValue: string); begin if FProductDescription=AValue then Exit; FProductDescription:=AValue; ModifiedProperty('ProductDescription'); end; procedure TChildren.SetUITCode(AValue: string); begin if FUITCode=AValue then Exit; FUITCode:=AValue; ModifiedProperty('UITCode'); end; procedure TChildren.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('UITCode', 'uit_code', [], '', -1, -1); RegisterProperty('ProductDescription', 'product_description', [], '', -1, -1); end; procedure TChildren.InternalInitChilds; begin inherited InternalInitChilds; end; destructor TChildren.Destroy; begin inherited Destroy; end; { TProduct } procedure TProduct.SetCountChildren(AValue: Integer); begin if FCountChildren=AValue then Exit; FCountChildren:=AValue; ModifiedProperty('CountChildren'); end; procedure TProduct.SetProductCost(AValue: Double); begin if FProductCost=AValue then Exit; FProductCost:=AValue; ModifiedProperty('ProductCost'); end; procedure TProduct.SetProductDescription(AValue: string); begin if FProductDescription=AValue then Exit; FProductDescription:=AValue; ModifiedProperty('ProductDescription'); end; procedure TProduct.SetProductTax(AValue: Double); begin if FProductTax=AValue then Exit; FProductTax:=AValue; ModifiedProperty('ProductTax'); end; procedure TProduct.SetUITCode(AValue: string); begin if FUITCode=AValue then Exit; FUITCode:=AValue; ModifiedProperty('UITCode'); end; procedure TProduct.SetUITUCode(AValue: string); begin if FUITUCode=AValue then Exit; FUITUCode:=AValue; ModifiedProperty('UITUCode'); end; procedure TProduct.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('UITCode', 'uit_code', [], '', -1, -1); RegisterProperty('UITUCode', 'uitu_code', [], '', -1, -1); RegisterProperty('ProductDescription', 'product_description', [], '', -1, -1); RegisterProperty('ProductCost', 'product_cost', [], '', -1, -1); RegisterProperty('ProductTax', 'product_tax', [], '', -1, -1); RegisterProperty('CountChildren', 'count_children', [], '', -1, -1); RegisterProperty('Children', 'children', [], '', -1, -1); end; procedure TProduct.InternalInitChilds; begin inherited InternalInitChilds; FChildren:=TChildrens.Create; end; destructor TProduct.Destroy; begin FreeAndNil(FChildren); inherited Destroy; end; { TShipGoods } procedure TShipGoods.SetDocumentDate(AValue: string); begin if FDocumentDate=AValue then Exit; FDocumentDate:=AValue; ModifiedProperty('DocumentDate'); end; procedure TShipGoods.SetDocumentNum(AValue: string); begin if FDocumentNum=AValue then Exit; FDocumentNum:=AValue; ModifiedProperty('DocumentNum'); end; procedure TShipGoods.SetReceiver(AValue: string); begin if FReceiver=AValue then Exit; FReceiver:=AValue; ModifiedProperty('Receiver'); end; procedure TShipGoods.SetReceiverInn(AValue: string); begin if FReceiverInn=AValue then Exit; FReceiverInn:=AValue; ModifiedProperty('ReceiverInn'); end; procedure TShipGoods.SetRequestType(AValue: string); begin if FRequestType=AValue then Exit; FRequestType:=AValue; ModifiedProperty('RequestType'); end; procedure TShipGoods.SetSale(AValue: Boolean); begin if FSale=AValue then Exit; FSale:=AValue; ModifiedProperty('Sale'); end; procedure TShipGoods.SetSender(AValue: string); begin if FSender=AValue then Exit; FSender:=AValue; ModifiedProperty('Sender'); end; procedure TShipGoods.SetSenderInn(AValue: string); begin if FSenderInn=AValue then Exit; FSenderInn:=AValue; ModifiedProperty('SenderInn'); end; procedure TShipGoods.SetStContractId(AValue: string); begin if FStContractId=AValue then Exit; FStContractId:=AValue; ModifiedProperty('StContractId'); end; procedure TShipGoods.SetToNotParticipant(AValue: Boolean); begin if FToNotParticipant=AValue then Exit; FToNotParticipant:=AValue; ModifiedProperty('ToNotParticipant'); end; procedure TShipGoods.SetTransferDate(AValue: string); begin if FTransferDate=AValue then Exit; FTransferDate:=AValue; ModifiedProperty('TransferDate'); end; procedure TShipGoods.SetTurnoverType(AValue: string); begin if FTurnoverType=AValue then Exit; FTurnoverType:=AValue; ModifiedProperty('TurnoverType'); end; procedure TShipGoods.SetWithdrawalFromTurnover(AValue: Boolean); begin if FWithdrawalFromTurnover=AValue then Exit; FWithdrawalFromTurnover:=AValue; ModifiedProperty('WithdrawalFromTurnover'); end; procedure TShipGoods.InternalRegisterPropertys; begin inherited InternalRegisterPropertys; RegisterProperty('Sale', 'sale', [], '', -1, -1); RegisterProperty('TurnoverType', 'turnover_type', [], '', -1, -1); RegisterProperty('RequestType', 'request_type', [], '', -1, -1); RegisterProperty('SenderInn', 'sender_inn', [], '', -1, -1); RegisterProperty('DocumentNum', 'document_num', [], '', -1, -1); RegisterProperty('DocumentDate', 'document_date', [], '', -1, -1); RegisterProperty('WithdrawalFromTurnover', 'withdrawal_from_turnover', [], '', -1, -1); RegisterProperty('TransferDate', 'transfer_date', [], '', -1, -1); RegisterProperty('ReceiverInn', 'receiver_inn', [], '', -1, -1); RegisterProperty('ToNotParticipant', 'to_not_participant', [], '', -1, -1); RegisterProperty('Sender', 'sender', [], '', -1, -1); RegisterProperty('Receiver', 'receiver', [], '', -1, -1); RegisterProperty('StContractId', 'st_contract_id', [], '', -1, -1); RegisterProperty('Products', 'products', [], '', -1, -1); end; procedure TShipGoods.InternalInitChilds; begin inherited InternalInitChilds; FProducts:=TProducts.Create; end; destructor TShipGoods.Destroy; begin FreeAndNil(FProducts); inherited Destroy; end; end.
program myTableTop; type Rectangle = object private length, width: integer; public procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; TableTop = object (Rectangle) private material: string; public function getmaterial(): string; procedure setmaterial( m: string); procedure displaydetails; procedure draw; end; var tt1: TableTop; procedure Rectangle.setlength(l: integer); begin length := l; end; procedure Rectangle.setwidth(w: integer); begin width :=w; end; function Rectangle.getlength(): integer; begin getlength := length; end; function Rectangle.getwidth():integer; begin getwidth := width; end; procedure Rectangle.draw; var i, j: integer; begin for i:= 1 to length do begin for j:= 1 to width do write(' * '); writeln; end; end; function TableTop.getmaterial(): string; begin getmaterial := material; end; procedure TableTop.setmaterial( m: string); begin material := m; end; procedure TableTop.displaydetails; begin writeln('Table Top: ', self.getlength(), ' by ' , self.getwidth()); writeln('Material: ', self.getmaterial()); end; procedure TableTop.draw(); var i, j: integer; begin for i:= 1 to length do begin for j:= 1 to width do write(' * '); writeln; end; writeln('Material: ', material); end; begin tt1.setlength(3); tt1.setwidth(7); tt1.setmaterial('Wood'); tt1.displaydetails(); writeln; writeln('Calling the Draw method'); tt1.draw(); end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.ParseMetaTypes; interface uses System.Classes, System.SysUtils, System.JSON, REST.Backend.Providers, REST.Backend.MetaTypes, REST.Backend.ParseProvider, REST.Backend.ParseApi; type /// <summary>Describe a backend object</summary> TMetaObject = class(TInterfacedObject, IBackendMetaObject) private FObjectID: TParseAPI.TObjectID; protected function GetObjectID: string; function GetCreatedAt: TDateTime; function GetUpdatedAt: TDateTime; function GetClassName: string; public constructor Create(const AObjectID: TParseAPI.TObjectID); property ObjectID: TParseAPI.TObjectID read FObjectID; end; /// <summary>Define MetaObject with ObjectID and CreatedAt properties</summary> TMetaCreatedObject = class(TMetaObject, IBackendMetaObject, IBackendObjectID, IBackendClassName, IBackendCreatedAt) end; /// <summary>Define MetaObject with ObjectID and BackendClassName properties</summary> TMetaClassObject = class(TMetaObject, IBackendMetaObject, IBackendClassName, IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt) end; /// <summary>Define MetaObject with UpdatedAt properties</summary> TMetaUpdatedObject = class(TInterfacedObject, IBackendMetaObject) private FUpdatedAt: TParseAPI.TUpdatedAt; protected function GetObjectID: string; function GetUpdatedAt: TDateTime; function GetClassName: string; public constructor Create(const AUpdatedAt: TParseAPI.TUpdatedAt); property ObjectID: TParseAPI.TUpdatedAt read FUpdatedAt; end; /// <summary>Describe a user object</summary> TMetaUser = class(TInterfacedObject, IBackendMetaObject) private FUser: TParseAPI.TUser; protected function GetObjectID: string; function GetCreatedAt: TDateTime; function GetUpdatedAt: TDateTime; function GetUserName: string; public constructor Create(const AUser: TParseAPI.TUser); property User: TParseAPI.TUser read FUser; end; /// <summary>Describe an uploaded file</summary> TMetaFile = class(TInterfacedObject, IBackendMetaObject) private FFile: TParseAPI.TFile; protected function GetDownloadURL: string; function GetFileName: string; function GetFileID: string; public constructor Create(const AFile: TParseAPI.TFile); overload; constructor Create(const AFileID: string); overload; property FileValue: TParseAPI.TFile read FFile; end; /// <summary>Define MetaObject with ObjectID</summary> TMetaObjectID = class(TMetaObject, IBackendMetaObject, IBackendObjectID) end; /// <summary>Define MetaObject with ObjectID and BackendClassName properties</summary> TMetaUserObject = class(TMetaUser, IBackendMetaObject, IBackendObjectID) end; /// <summary>Describe a logged in user</summary> TMetaLogin = class(TMetaUser) private FLogin: TParseAPI.TLogin; protected function GetAuthTOken: string; public constructor Create(const ALogin: TParseAPI.TLogin); property Login: TParseAPI.TLogin read FLogin; end; TMetaFoundObject = class(TMetaObject, IBackendMetaObject, IBackendClassName, IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt) end; TMetaUploadedFile = class(TMetaFile, IBackendMetaObject, IBackendFileID, IBackendFileName, IBackendDownloadURL) end; TMetaFileObject = class(TMetaFile, IBackendMetaObject, IBackendFileID) end; /// <summary> Define MetaObject with UpdatedAt properties</summary> TMetaUpdatedUser = class(TMetaUser, IBackendMetaObject, IBackendUpdatedAt, IBackendUserName) end; TMetaFoundUser = class(TMetaUser, IBackendMetaObject, IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt, IBackendUserName) end; TMetaLoginUser = class(TMetaLogin, IBackendMetaObject, IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt, IBackendUserName, IBackendAuthToken) end; TMetaSignupUser = class(TMetaLogin, IBackendMetaObject, IBackendObjectID, IBackendCreatedAt, IBackendUserName, IBackendAuthToken) end; /// <summary>Describe a backend storage class</summary> TMetaClass = class(TInterfacedObject, IBackendMetaObject) private FClassName: string; FDataType: string; protected function GetClassName: string; function GetDataType: string; public constructor Create(const AClassName: string); overload; constructor Create(const ADataType, AClassName: string); overload; end; /// <summary>Define backend class with ClassName property</summary> TMetaClassName = class(TMetaClass, IBackendMetaClass, IBackendClassName) end; /// <summary>Defined backend class with ClassName and DataType property</summary> TMetaDataType = class(TMetaClass, IBackendMetaClass, IBackendClassName, IBackendDataType) end; TMetaFactory = class(TInterfacedObject, IBackendMetaFactory, IBackendMetaClassFactory, IBackendMetaClassObjectFactory, IBackendMetaDataTypeFactory, IBackendMetaFileFactory) protected { IBackendMetaClassFactory } function CreateMetaClass(const AClassName: string): TBackendMetaClass; { IBackendMetaClassObjectFactory } function CreateMetaClassObject(const AClassName, AObjectID: string): TBackendEntityValue; { IBackendMetaDataTypeFactory } function CreateMetaDataType(const ADataType, ABackendClassName: string): TBackendMetaClass; { IBackendMetaFileFactory } function CreateMetaFileObject(const AFileID: string): TBackendEntityValue; end; TParseMetaFactory = class public // Class class function CreateMetaClass(const AClassName: string): TBackendMetaClass; static; class function CreateMetaDataType(const ADataType, AClassName: string): TBackendMetaClass; overload; static; // Object class function CreateMetaClassObject(const AClassName, AObjectID: string): TBackendEntityValue; overload;static; class function CreateMetaClassObject(const AObjectID: TParseAPI.TObjectID): TBackendEntityValue; overload;static; class function CreateMetaCreatedObject( const AObjectID: TParseAPI.TObjectID): TBackendEntityValue; static; class function CreateMetaFoundObject(const AObjectID: TParseAPI.TObjectID): TBackendEntityValue; static; class function CreateMetaUpdatedObject(const AUpdatedAt: TParseAPI.TUpdatedAt): TBackendEntityValue; static; // User class function CreateMetaUpdatedUser(const AUpdatedAt: TParseAPI.TUpdatedAt): TBackendEntityValue; overload; static; class function CreateMetaSignupUser(const ALogin: TParseAPI.TLogin): TBackendEntityValue; overload; static; class function CreateMetaLoginUser(const ALogin: TParseAPI.TLogin): TBackendEntityValue; overload; static; class function CreateMetaFoundUser(const AUser: TParseAPI.TUser): TBackendEntityValue; static; // Files class function CreateMetaUploadedFile(const AFile: TParseAPI.TFile): TBackendEntityValue; static; class function CreateMetaFileObject(const AFileID: string): TBackendEntityValue; end; implementation { TMetaCreatedObject } constructor TMetaObject.Create(const AObjectID: TParseAPI.TObjectID); begin inherited Create; FObjectID := AObjectID; end; function TMetaObject.GetCreatedAt: TDateTime; begin Result := FObjectID.CreatedAt; end; function TMetaObject.GetObjectID: string; begin Result := FObjectID.ObjectID; end; function TMetaObject.GetUpdatedAt: TDateTime; begin Result := FObjectID.UpdatedAt; end; function TMetaObject.GetClassName: string; begin Result := FObjectID.BackendClassName; end; { TMetaClass } constructor TMetaClass.Create(const AClassName: string); begin inherited Create; FClassName := AClassName; end; constructor TMetaClass.Create(const ADataType, AClassName: string); begin Create(AClassName); FDataType := ADataType; end; function TMetaClass.GetClassName: string; begin Result := FClassName; end; function TMetaClass.GetDataType: string; begin Result := FDataType; end; { TMetaFactory } function TMetaFactory.CreateMetaClass( const AClassName: string): TBackendMetaClass; begin Result := TParseMetaFactory.CreateMetaClass(AClassName); end; function TMetaFactory.CreateMetaClassObject( const AClassName: string; const AObjectID: string): TBackendEntityValue; begin Result := TParseMetaFactory.CreateMetaClassObject(AClassName, AObjectID); end; function TMetaFactory.CreateMetaDataType(const ADataType, ABackendClassName: string): TBackendMetaClass; begin Result := TParseMetaFactory.CreateMetaDataType(ADataType, ABackendClassName); end; function TMetaFactory.CreateMetaFileObject( const AFileID: string): TBackendEntityValue; begin Result := TParseMetaFactory.CreateMetaFileObject(AFileID); end; { TParseMetaFactory } class function TParseMetaFactory.CreateMetaClass( const AClassName: string): TBackendMetaClass; var LIntf: IBackendMetaClass; begin LIntf := TMetaClassName.Create(AClassName); Assert(Supports(LIntf, IBackendClassName)); Result := TBackendMetaClass.Create(LIntf); end; class function TParseMetaFactory.CreateMetaClassObject( const AClassName: string; const AObjectID: string): TBackendEntityValue; var LObjectID: TParseAPI.TObjectID; begin LObjectID := TParseAPI.TObjectID.Create(AClassName, AObjectID); Result := CreateMetaClassObject(LObjectID); end; class function TParseMetaFactory.CreateMetaClassObject( const AObjectID: TParseAPI.TObjectID): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaClassObject.Create(AObjectID); Assert(Supports(LIntf, IBackendClassName)); Assert(Supports(LIntf, IBackendObjectID)); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaCreatedObject( const AObjectID: TParseAPI.TObjectID): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaCreatedObject.Create(AObjectID); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaDataType(const ADataType, AClassName: string): TBackendMetaClass; var LIntf: IBackendMetaClass; begin LIntf := TMetaDataType.Create(ADataType, AClassName); Result := TBackendMetaClass.Create(LIntf); end; class function TParseMetaFactory.CreateMetaFileObject( const AFileID: string): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaFileObject.Create(AFileID); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaFoundObject( const AObjectID: TParseAPI.TObjectID): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaFoundObject.Create(AObjectID); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaFoundUser( const AUser: TParseAPI.TUser): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaFoundUser.Create(AUser); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaLoginUser( const ALogin: TParseAPI.TLogin): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaLoginUser.Create(ALogin); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaSignupUser( const ALogin: TParseAPI.TLogin): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaSignupUser.Create(ALogin); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaUpdatedObject( const AUpdatedAt: TParseAPI.TUpdatedAt): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaUpdatedObject.Create(AUpdatedAt); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaUpdatedUser( const AUpdatedAt: TParseAPI.TUpdatedAt): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaUpdatedObject.Create(AUpdatedAt); Result := TBackendEntityValue.Create(LIntf); end; class function TParseMetaFactory.CreateMetaUploadedFile( const AFile: TParseAPI.TFile): TBackendEntityValue; var LIntf: IBackendMetaObject; begin LIntf := TMetaUploadedFile.Create(AFile); Result := TBackendEntityValue.Create(LIntf); end; { TMetaUpdateObject } constructor TMetaUpdatedObject.Create(const AUpdatedAt: TParseAPI.TUpdatedAt); begin FUpdatedAt := AUpdatedAt; end; function TMetaUpdatedObject.GetClassName: string; begin Result := FUpdatedAt.BackendClassName; end; function TMetaUpdatedObject.GetObjectID: string; begin Result := FUpdatedAt.ObjectID; end; function TMetaUpdatedObject.GetUpdatedAt: TDateTime; begin Result := FUpdatedAt.UpdatedAt; end; { TMetaUser } constructor TMetaUser.Create(const AUser: TParseAPI.TUser); begin FUser := AUser; end; function TMetaUser.GetCreatedAt: TDateTime; begin Result := FUser.CreatedAt; end; function TMetaUser.GetObjectID: string; begin Result := FUser.ObjectID; end; function TMetaUser.GetUpdatedAt: TDateTime; begin Result := FUser.UpdatedAt; end; function TMetaUser.GetUserName: string; begin Result := FUser.UserName; end; { TMetaLogin } constructor TMetaLogin.Create(const ALogin: TParseAPI.TLogin); begin inherited Create(ALogin.User); FLogin := ALogin; end; function TMetaLogin.GetAuthTOken: string; begin Result := FLogin.SessionToken; end; { TMetaFile } constructor TMetaFile.Create(const AFile: TParseAPI.TFile); begin FFile := AFile; end; function TMetaFile.GetFileID: string; begin Result := FFile.Name; end; function TMetaFile.GetFileName: string; begin Result := FFile.FileName; end; constructor TMetaFile.Create(const AFileID: string); begin FFile := TParseAPI.TFile.Create(AFileID); end; function TMetaFile.GetDownloadURL: string; begin Result := FFile.DownloadURL; end; end.
unit FC.Trade.Alerter.Factory; {$I Compiler.inc} interface uses Windows,Classes,SysUtils, Baseutils, Serialization, Generics.Collections, Collections.List,Collections.Map, FC.Definitions,FC.Trade.Alerter.Base; type TStockAlerterInfo = class (TInterfacedObject,IStockAlerterInfo) private FName: string; FIID: TGUID; FCategory: string; FClass : TStockAlerterClass; public property Class_: TStockAlerterClass read FClass; function IID : TGUID; function Category: string; function Name : string; constructor Create(const aCategory, aName: string; aClass: TStockAlerterClass;aIID : TGUID); destructor Destroy; override; end; IStockAlerterFactoryEx = interface (IStockAlerterFactory) ['{3DB61007-BD94-4ADC-A3C3-97593FBF5C99}'] //Регистрация класса трейдера. Указывается категория, имя, класс трейдера, идентифкатор интерфейса procedure RegisterAlerter(const aCategory, aName: string; aClass: TStockAlerterClass; aIID: TGUID; aHidden: boolean=false); function FindAlerter(const aCategory, aName: string; aClass: TStockAlerterClass): IStockAlerterInfo; end; TStockAlerterFactory = class (TInterfacedObject,IStockAlerterFactory, IStockAlerterFactoryEx, Serialization.IClassFactory) private type TStockAlerterInfoContainer = TInterfacedObjectContainer<TStockAlerterInfo>; private FAlerterList: TOwnedOjectList<TStockAlerterInfoContainer>; FAlerterMap : TOwnedObjectValueMap<TGUID,TStockAlerterInfoContainer>; function GetAlerterInfoImpl(index: integer) : TStockAlerterInfo; protected //from Serialization.IClassFactory function CreateInstance(const aClassName: string): TObject; constructor Create; public destructor Destroy; override; //from IStockAlerterFactoryEx function GetImplObject:TStockAlerterFactory; //From IStockAlerterFactory function AlerterCount: integer; function GetAlerterInfo(index: integer) : IStockAlerterInfo; procedure GetAllAlerterCategories(aList: TStrings); procedure GetAlAlertersForCategory(const aCategory: string; aList: TList<integer>); function CreateAlerter(index: integer): IStockAlerter; overload; function CreateAlerter(const aIID: TGUID): IStockAlerter; overload; procedure RegisterAlerter(const aCategory, aName: string; aClass: TStockAlerterClass; aIID: TGUID; aHidden: boolean=false); function FindAlerter(const aCategory, aName: string; aClass: TStockAlerterClass): IStockAlerterInfo; property Alerters[index: integer]: TStockAlerterInfo read GetAlerterInfoImpl; end; function AlerterFactory: IStockAlerterFactoryEx; implementation uses FC.Singletons; function AlerterFactory: IStockAlerterFactoryEx; begin result:=(FC.Singletons.AlerterFactory as IStockAlerterFactoryEx); end; { TStockAlerterInfo } constructor TStockAlerterInfo.Create(const aCategory, aName: string;aClass: TStockAlerterClass; aIID: TGUID); begin inherited Create; FCategory:=aCategory; FName:=aName; FClass:=aClass; FIID:=aIID; end; function TStockAlerterInfo.Category: string; begin result:=FCategory; end; function TStockAlerterInfo.IID: TGUID; begin result:=FIID; end; function TStockAlerterInfo.Name: string; begin result:=FName; end; destructor TStockAlerterInfo.Destroy; begin inherited; end; { TStockAlerterFactory } constructor TStockAlerterFactory.Create; begin FAlerterList:=TOwnedOjectList<TStockAlerterInfoContainer>.Create; FAlerterMap:=TOwnedObjectValueMap<TGUID,TStockAlerterInfoContainer>.Create; FAlerterMap.AllowAppendRewrite:=false; Serialization.TClassFactory.RegisterClassFactory(self); end; destructor TStockAlerterFactory.Destroy; begin FAlerterList.Free; FAlerterMap.Free; inherited; end; function TStockAlerterFactory.FindAlerter(const aCategory, aName: string; aClass: TStockAlerterClass): IStockAlerterInfo; var i: integer; begin result:=nil; for I := 0 to AlerterCount-1 do begin if (Alerters[i].Category=aCategory) and (Alerters[i].Name=aName) and (Alerters[i].Class_=aClass) then begin result:=Alerters[i]; break; end; end; end; function TStockAlerterFactory.AlerterCount: integer; begin result:=FAlerterList.Count; end; function TStockAlerterFactory.CreateAlerter(index: integer): IStockAlerter; var aInfo : TStockAlerterInfo; aRes : TStockAlerterBase; begin aInfo:=Alerters[index]; aRes:=aInfo.Class_.Create; aRes.IID:=aInfo.IID; aRes.SetCategory(aInfo.Category); aRes.SetName(aInfo.Name); result:=aRes; end; function TStockAlerterFactory.CreateAlerter(const aIID: TGUID): IStockAlerter; var aInfoContainer: TStockAlerterInfoContainer; aInfo: TStockAlerterInfo; aRes : TStockAlerterBase; begin if not FAlerterMap.Lookup(aIID,aInfoContainer) then raise EStockError.Create(Format('Alerter %s not found',[GUIDToString(aIID)])); aInfo:=aInfoContainer.Value; aRes:=aInfo.Class_.CreateNaked; //Naked! aRes.IID:=aInfo.IID; aRes.SetCategory(aInfo.Category); aRes.SetName(aInfo.Name); result:=aRes; end; procedure TStockAlerterFactory.RegisterAlerter(const aCategory, aName: string;aClass: TStockAlerterClass; aIID: TGUID; aHidden: boolean=false); var aInfoContainer: TStockAlerterInfoContainer; aInfo: TStockAlerterInfo; begin if FAlerterMap.Lookup(aIID,aInfoContainer) then raise EStockError.CreateFmt('Duplicate IID. Same value was set to %s',[aInfoContainer.Value.FName]); aInfo:=TStockAlerterInfo.Create(aCategory,aName, aClass,aIID); if not aHidden then FAlerterList.Add(TStockAlerterInfoContainer.Create(aInfo)); FAlerterMap.Add(aIID,TStockAlerterInfoContainer.Create(aInfo)); end; function TStockAlerterFactory.GetAlerterInfo(index: integer): IStockAlerterInfo; begin result:=GetAlerterInfoImpl(index); end; procedure TStockAlerterFactory.GetAllAlerterCategories(aList: TStrings); var i: integer; begin for i:=0 to AlerterCount-1 do begin if aList.IndexOf(Alerters[i].Category)=-1 then aList.Add(Alerters[i].Category) end; end; procedure TStockAlerterFactory.GetAlAlertersForCategory(const aCategory: string; aList: TList<integer>); var i: integer; begin for i:=0 to AlerterCount-1 do begin if AnsiSameText(aCategory,Alerters[i].Category) then aList.Add(i); end; end; function TStockAlerterFactory.GetAlerterInfoImpl(index: integer): TStockAlerterInfo; begin result:=FAlerterList[index].Value; end; function TStockAlerterFactory.GetImplObject: TStockAlerterFactory; begin result:=self; end; function TStockAlerterFactory.CreateInstance(const aClassName: string): TObject; var aInfo: TStockAlerterInfo; it : TMapIterator<TGUID,TStockAlerterInfoContainer>; begin result:=nil; FAlerterMap.GetFirst(it); while it.Valid do begin aInfo:=it.Value.Value; if (aInfo.Class_.ClassName=aClassName) then begin result:=aInfo.Class_.CreateNaked; break; end; FAlerterMap.GetNext(it); end; end; initialization FC.Singletons.SetAlerterFactory(TStockAlerterFactory.Create); end.
// ==================================================================== // // Unit uDSProcessMgmtWCUtils.pas // // This unit contains utilities for redading the class of the warrior // (player). This unit, like the uDSProcessMgmtNameUtils, is separated // just for a clear coding. // // Esta unit contém utilidades para leitura da classe do guerreiro. // Ela está separada, como uDSProcessMgmtNameUtils, porque fica mais // fácil a compreensão com o código limpo. // // =================================================================== unit uDSProcessMgmtWCUtils; interface uses Windows, SysUtils, uDSProcessMgmtUtils, uWarrior; // These functions just read the class of the warrior (player). One for each player. // Estas funções apenas leem a classe do guerreiro. Uma para cada guerreiro. function GetDefaultPlayerWarriorClass: TWarriorClass; function GetRedPhantomWarriorClass: TWarriorClass; function GetBluePhantomWarriorClass: TWarriorClass; function GetWhitePhantomWarriorClass: TWarriorClass; function GetWarriorClassByID(AId: Integer): TWarriorClass; implementation function GetWarriorClassByID(AId: Integer): TWarriorClass; begin Result := wcNone; case AId of 0: Result := wcWarrior; 1: Result := wcKnight; 2: Result := wcWanderer; 3: Result := wcThief; 4: Result := wcBandit; 5: Result := wcHunter; 6: Result := wcSorcerer; 7: Result := wcPyromancer; 8: Result := wcCleric; 9: Result := wcDeprived; end; end; function GetDefaultPlayerWarriorClass: TWarriorClass; var wHandle: hwnd; hProcess: integer; pId: integer; Value: Cardinal; Read: NativeUInt; P: Pointer; begin Result := wcNone; if not IsDarkSoulsRunning then Exit; wHandle := FindWindow(nil,'DARK SOULS'); GetWindowThreadProcessId(wHandle,@pId); if wHandle <> 0 then begin hProcess := OpenProcess(PROCESS_ALL_ACCESS,False,pId); ReadProcessMemory(hProcess, Ptr($13DED50), Addr(Value), 4, Read); P := Ptr(Value); ReadProcessMemory(hProcess, Pointer(Pointer(IntegeR(p) + $8)), Addr(Value), 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $C6), Addr(Value), 1, Read); Result := GetWarriorClassByID(Byte(Value)); end; end; function GetRedPhantomWarriorClass: TWarriorClass; begin //TODO: Implementar Result := wcNone; end; function GetBluePhantomWarriorClass: TWarriorClass; begin //TODO: Implementar Result := wcNone; end; function GetWhitePhantomWarriorClass: TWarriorClass; begin //TODO: Implementar Result := wcNone; end; end.
{****************************************************************** JEDI-VCL Demo Copyright (C) 2004 Project JEDI Original author: Florent Ouchet [ouchet dott florent att laposte dott net] Contributor(s): You may retrieve the latest version of this file at the JEDI-JVCL home page, located at http://jvcl.delphi-jedi.org The contents of this file are used with permission, subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1_1Final.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. ******************************************************************} unit JvFullColorCircleDialogMainForm; {$mode objfpc}{$H+} interface uses SysUtils, Variants, Classes, Graphics, Controls, Types, Forms, Dialogs, ExtCtrls, StdCtrls, JvFullColorSpaces, JvFullColorCircleForm, JvFullColorDialogs, JvFullColorRotate; type { TJvFullColorCircleDlgMainFrm } TJvFullColorCircleDlgMainFrm = class(TForm) Image: TImage; Bevel: TBevel; Label1: TLabel; LabelImage: TLabel; cmbFileName: TComboBox; JvFullColorCircleDialog: TJvFullColorCircleDialog; procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cmbFileNameSelect(Sender: TObject); procedure JvFullColorCircleDialogApply(Sender: TObject); private procedure FormatLabel(ALabel: TLabel; const Delta: TJvColorDelta); function MeasureLabels: TSize; public Images: array [0..6] of TImage; Memos: array [0..6] of TMemo; Labels: array[0..6] of TLabel; procedure CustomizeDblClick(Sender: TObject); procedure RotateCustomValues; // procedure FormatMemo(AMemo: TMemo; const Delta: TJvColorDelta); end; var JvFullColorCircleDlgMainFrm: TJvFullColorCircleDlgMainFrm; implementation {$R *.lfm} uses LCLIntf, LCLType, Math, Contnrs; resourcestring RsCustomize = 'Dbl-click to customize'; var ImgDir: String = ''; type TJvColorDeltaList = class (TObjectList) private function GetItems(Index: Integer): TJvColorDelta; procedure SetItems(Index: Integer; const Value: TJvColorDelta); public property Items[Index: Integer]: TJvColorDelta read GetItems write SetItems; default; end; var ColorDeltas: TJvColorDeltaList; procedure TJvFullColorCircleDlgMainFrm.FormCreate(Sender: TObject); var LSearchRec: TSearchRec; begin ImgDir := IncludeTrailingPathDelimiter(GetCurrentDir) + '../../design/JvCtrls/images/'; if FindFirst(ImgDir + '*.png', faAnyFile, LSearchRec) = 0 then repeat cmbFileName.Items.Add(LSearchRec.Name); until FindNext(LSearchRec) <> 0; FindClose(LSearchRec); end; function TJvFullColorCircleDlgMainFrm.MeasureLabels: TSize; var i, j: Integer; axIndex: TJvAxisIndex; ColorSpc: TJvColorSpace; L: TStrings; s: String; bmp: TBitmap; R: TRect; begin Result := Size(0, 0); ColorSpc := ColorSpaceManager.ColorSpace[csCMY]; L := TStringList.Create; try L.Add(Format('%s (%s)',[ColorSpc.Name, ColorSpc.ShortName])); for axIndex := Low(TJvAxisIndex) to High(TJvAxisIndex) do L.Add(Format('%s : %d, %d, %d',[ColorSpc.AxisName[axIndex], 255, 255, 255])); s := L.Text; finally L.Free; end; bmp := TBitmap.Create; try bmp.SetSize(1, 1); bmp.Canvas.Brush.Color := clWhite; bmp.Canvas.FillRect(0, 0, 1, 1); bmp.Canvas.Font.Assign(Label1.Font); R := Rect(0, 0, MaxInt, MaxInt); DrawText(bmp.Canvas.Handle, PChar(s), Length(s), R, DT_WORDBREAK or DT_CALCRECT or DT_NOCLIP); Result.CX := Max(Result.CX, R.Right); Result.CY := Max(Result.CY, R.Bottom); finally bmp.Free; end; end; procedure TJvFullColorCircleDlgMainFrm.FormActivate(Sender: TObject); var X, Y: Integer; PitchX, PitchY: Integer; LabelSize: TSize; Index: Integer; lBevel: TBevel; lImage: TImage; lLabel: TLabel; h: Integer; begin LabelSize := MeasureLabels; h := Label1.Canvas.Textheight('Tg'); PitchX := LabelSize.CX + 32; PitchY := LabelSize.CY + Bevel.Height + 16; Label1.Left := 8; Label1.Width := LabelSize.CX; Bevel.Left := Label1.Left + (Label1.Width - Bevel.Width) div 2; Index := 0; for Y := 0 to 1 do for X := 0 to 3 do if (X <> 0) or (Y <> 0) then begin lBevel := TBevel.Create(Self); lBevel.Parent := Self; lBevel.Style := bsRaised; lBevel.SetBounds(Bevel.Left + X*PitchX, Bevel.Top + Y*PitchY, Bevel.Width, Bevel.Height); lImage := TImage.Create(Self); lImage.Parent := Self; lImage.Stretch := false; lImage.Center := true; lImage.SetBounds(Image.Left + X*PitchX, Image.Top + Y*PitchY, Image.Width, Image.Height); lLabel := TLabel.Create(Self); lLabel.Parent := Self; lLabel.AutoSize := false; lLabel.WordWrap := true; lLabel.Alignment := taCenter; // lLabel.SetBounds(Label1.Left + X*PitchX, Label1.Top + Y*PitchY, LabelSize.CX, LabelSize.CY); lLabel.Left := Label1.Left + X*PitchX; lLabel.Top := Label1.Top + Y*PitchY; lLabel.Width := LabelSize.CX; lLabel.Height := LabelSize.CY + Y*h; if (X = 3) and (Y = 1) then begin lImage.OnDblClick := @CustomizeDblClick; lLabel.OnDblClick := @CustomizeDblClick; ClientWidth := lBevel.Left + lBevel.Width + Bevel.Left; ClientHeight := lLabel.Top + lLabel.Height + cmbFileName.Top; end; Images[Index] := lImage; Labels[Index] := lLabel; Inc(Index); end; cmbFileName.ItemIndex := 0; cmbFileNameSelect(cmbFileName); end; (* var X, Y: Integer; PitchX, PitchY: Integer; LImage: TImage; LMemo: TMemo; LBevel: TBevel; Index: Integer; begin PitchX := Memo.Width + 32; PitchY := Memo.Top + Memo.Height - Image.Top + 31; Index := 0; for X := 0 to 3 do for Y := 0 to 1 do if (X <> 0) or (Y <> 0) then begin LBevel := TBevel.Create(Self); LBevel.Parent := Self; LBevel.Style := bsRaised; LBevel.SetBounds(Bevel.Left+X*PitchX, Bevel.Top+Y*PitchY, Bevel.Width, Bevel.Height); LImage := TImage.Create(Self); LImage.Parent := Self; LImage.Stretch := False; LImage.Center := true; LImage.SetBounds(Image.Left+X*PitchX, Image.Top+Y*PitchY, Image.Width, Image.Height); LMemo := TMemo.Create(Self); LMemo.Parent := Self; LMemo.BorderStyle := bsNone; LMemo.ParentColor := True; LMemo.OnKeyDown := @MemoKeyDown; LMemo.OnKeyPress := @MemoKeyPress; LMemo.SetBounds(Memo.Left+X*PitchX, Memo.Top+Y*PitchY, Memo.Width, Memo.Height); LMemo.Alignment := taCenter; if (X = 3) and (Y = 1) then begin LImage.OnDblClick := @CustomizeDblClick; LMemo.OnDblClick := @CustomizeDblClick; ClientWidth := LMemo.Left+LMemo.Width-1+Memo.Left; ClientHeight := LMemo.Top+LMemo.Height-1+cmbFileName.Top; end; Memos[Index] := LMemo; Images[Index] := LImage; Inc(Index); end; cmbFileName.ItemIndex := 0; ComboBoxFileNameSelect(cmbFileName); end; *) procedure TJvFullColorCircleDlgMainFrm.CustomizeDblClick(Sender: TObject); begin if JvFullColorCircleDialog.Execute then RotateCustomValues; end; procedure TJvFullColorCircleDlgMainFrm.cmbFileNameSelect(Sender: TObject); var Index: Integer; fn: String; begin if cmbFileName.ItemIndex = -1 then exit; if Image.Picture.Bitmap <> nil then begin fn := ImgDir + cmbFileName.Items[cmbFileName.ItemIndex]; if FileExists(fn) then Image.Picture.LoadFromFile(fn) else MessageDlg(Format('File "%s" not found.', [fn]), mtError, [mbOK], 0); end; // Image.Picture.Bitmap := TBitmap.Create; // Image.Picture.Bitmap.LoadFromFile(cmbFileName.Items[cmbFileName.ItemIndex]); Labels[6].Caption := RsCustomize; { with Memos[6].Lines do begin Clear; Add(RsCustomize); end; } Images[6].Picture.Bitmap.FreeImage; for Index := Low(Images) to High(Images)-1 do begin Images[Index].Picture.Bitmap.FreeImage; RotateBitmap(Image.Picture.Bitmap,Images[Index].Picture.Bitmap,ColorDeltas[Index]); FormatLabel(Labels[Index], ColorDeltas[Index]); // FormatMemo(Memos[Index], ColorDeltas[Index]); end; RotateCustomValues; end; procedure TJvFullColorCircleDlgMainFrm.RotateCustomValues; begin RotateBitmap(Image.Picture.Bitmap,Images[6].Picture.Bitmap,JvFullColorCircleDialog.Delta); FormatLabel(Labels[6], JvFullColorCircleDialog.Delta); // FormatMemo(Memos[6],JvFullColorCircleDialog.Delta); end; procedure TJvFullColorCircleDlgMainFrm.FormatLabel(ALabel: TLabel; const Delta: TJvColorDelta); var Index: TJvAxisIndex; L: TStringList; begin L := TStringList.Create; try with ColorSpaceManager, ColorSpace[Delta.ColorID] do begin L.Add(Format('%s (%s)', [Name, ShortName])); for Index := Low(TJvAxisIndex) to High(TJvAxisIndex) do L.Add(Format('%s: %d, %d, %d', [ AxisName[Index], Delta.AxisRed[Index].Value, Delta.AxisGreen[Index].Value, Delta.AxisBlue[Index].Value ])); if ALabel = Labels[6] then L.Add(RsCustomize); end; ALabel.Caption := L.Text; finally L.Free; end; end; (* procedure TJvFullColorCircleDlgMainFrm.FormatMemo(AMemo: TMemo; const Delta: TJvColorDelta); var Index: TJvAxisIndex; begin AMemo.Lines.Clear; with ColorSpaceManager, ColorSpace[Delta.ColorID], AMemo.Lines do begin Add(Format('%s (%s)',[Name, ShortName])); for Index := Low(TJvAxisIndex) to High(TJvAxisIndex) do Add(Format('%s : %d, %d, %d',[AxisName[Index],Delta.AxisRed[Index].Value, Delta.AxisGreen[Index].Value,Delta.AxisBlue[Index].Value])); if AMemo = Memos[6] then Add(RsCustomize); end; end; *) { TJvColorDeltaList } function TJvColorDeltaList.GetItems(Index: Integer): TJvColorDelta; begin Result := TJvColorDelta(TObjectList(Self).Items[Index]); end; procedure TJvColorDeltaList.SetItems(Index: Integer; const Value: TJvColorDelta); begin TObjectList(Self).Items[Index] := Value; end; procedure FillColorDeltas; var Delta : TJvColorDelta; begin Delta := TJvColorDelta.Create; Delta.ColorID := csRGB; Delta.AxisRed[axIndex0].Value := 100; Delta.AxisRed[axIndex0].SaturationMethod := smRange; Delta.AxisRed[axIndex1].Value := 0; Delta.AxisRed[axIndex1].SaturationMethod := smRange; Delta.AxisRed[axIndex2].Value := 0; Delta.AxisRed[axIndex2].SaturationMethod := smRange; Delta.AxisGreen[axIndex0].Value := 0; Delta.AxisGreen[axIndex0].SaturationMethod := smRange; Delta.AxisGreen[axIndex1].Value := 0; Delta.AxisGreen[axIndex1].SaturationMethod := smRange; Delta.AxisGreen[axIndex2].Value := 0; Delta.AxisGreen[axIndex2].SaturationMethod := smRange; Delta.AxisBlue[axIndex0].Value := 0; Delta.AxisBlue[axIndex0].SaturationMethod := smRange; Delta.AxisBlue[axIndex1].Value := 0; Delta.AxisBlue[axIndex1].SaturationMethod := smRange; Delta.AxisBlue[axIndex2].Value := 50; Delta.AxisBlue[axIndex2].SaturationMethod := smRange; ColorDeltas.Add(Delta); Delta := TJvColorDelta.Create; Delta.ColorID := csHLS; Delta.AxisRed[axIndex0].Value := 0; Delta.AxisRed[axIndex0].SaturationMethod := smRange; Delta.AxisRed[axIndex1].Value := 0; Delta.AxisRed[axIndex1].SaturationMethod := smRange; Delta.AxisRed[axIndex2].Value := 0; Delta.AxisRed[axIndex2].SaturationMethod := smRange; Delta.AxisGreen[axIndex0].Value := 40; Delta.AxisGreen[axIndex0].SaturationMethod := smRange; Delta.AxisGreen[axIndex1].Value := 0; Delta.AxisGreen[axIndex1].SaturationMethod := smRange; Delta.AxisGreen[axIndex2].Value := 0; Delta.AxisGreen[axIndex2].SaturationMethod := smRange; Delta.AxisBlue[axIndex0].Value := 0; Delta.AxisBlue[axIndex0].SaturationMethod := smRange; Delta.AxisBlue[axIndex1].Value := 0; Delta.AxisBlue[axIndex1].SaturationMethod := smRange; Delta.AxisBlue[axIndex2].Value := 0; Delta.AxisBlue[axIndex2].SaturationMethod := smRange; ColorDeltas.Add(Delta); Delta := TJvColorDelta.Create; Delta.ColorID := csHSV; Delta.AxisRed[axIndex0].Value := 0; Delta.AxisRed[axIndex0].SaturationMethod := smRange; Delta.AxisRed[axIndex1].Value := -176; Delta.AxisRed[axIndex1].SaturationMethod := smRange; Delta.AxisRed[axIndex2].Value := -180; Delta.AxisRed[axIndex2].SaturationMethod := smRange; Delta.AxisGreen[axIndex0].Value := 0; Delta.AxisGreen[axIndex0].SaturationMethod := smRange; Delta.AxisGreen[axIndex1].Value := 0; Delta.AxisGreen[axIndex1].SaturationMethod := smRange; Delta.AxisGreen[axIndex2].Value := 0; Delta.AxisGreen[axIndex2].SaturationMethod := smRange; Delta.AxisBlue[axIndex0].Value := 0; Delta.AxisBlue[axIndex0].SaturationMethod := smRange; Delta.AxisBlue[axIndex1].Value := 0; Delta.AxisBlue[axIndex1].SaturationMethod := smRange; Delta.AxisBlue[axIndex2].Value := 0; Delta.AxisBlue[axIndex2].SaturationMethod := smRange; ColorDeltas.Add(Delta); Delta := TJvColorDelta.Create; Delta.ColorID := csYUV; Delta.AxisRed[axIndex0].Value := 0; Delta.AxisRed[axIndex0].SaturationMethod := smRange; Delta.AxisRed[axIndex1].Value := 38; Delta.AxisRed[axIndex1].SaturationMethod := smRange; Delta.AxisRed[axIndex2].Value := 0; Delta.AxisRed[axIndex2].SaturationMethod := smRange; Delta.AxisGreen[axIndex0].Value := 0; Delta.AxisGreen[axIndex0].SaturationMethod := smRange; Delta.AxisGreen[axIndex1].Value := 68; Delta.AxisGreen[axIndex1].SaturationMethod := smRange; Delta.AxisGreen[axIndex2].Value := 0; Delta.AxisGreen[axIndex2].SaturationMethod := smRange; Delta.AxisBlue[axIndex0].Value := 0; Delta.AxisBlue[axIndex0].SaturationMethod := smRange; Delta.AxisBlue[axIndex1].Value := 0; Delta.AxisBlue[axIndex1].SaturationMethod := smRange; Delta.AxisBlue[axIndex2].Value := 0; Delta.AxisBlue[axIndex2].SaturationMethod := smRange; ColorDeltas.Add(Delta); Delta := TJvColorDelta.Create; Delta.ColorID := csHLS; Delta.AxisRed[axIndex0].Value := 0; Delta.AxisRed[axIndex0].SaturationMethod := smRange; Delta.AxisRed[axIndex1].Value := -30; Delta.AxisRed[axIndex1].SaturationMethod := smRange; Delta.AxisRed[axIndex2].Value := 0; Delta.AxisRed[axIndex2].SaturationMethod := smRange; Delta.AxisGreen[axIndex0].Value := 0; Delta.AxisGreen[axIndex0].SaturationMethod := smRange; Delta.AxisGreen[axIndex1].Value := -30; Delta.AxisGreen[axIndex1].SaturationMethod := smRange; Delta.AxisGreen[axIndex2].Value := 0; Delta.AxisGreen[axIndex2].SaturationMethod := smRange; Delta.AxisBlue[axIndex0].Value := 0; Delta.AxisBlue[axIndex0].SaturationMethod := smRange; Delta.AxisBlue[axIndex1].Value := -30; Delta.AxisBlue[axIndex1].SaturationMethod := smRange; Delta.AxisBlue[axIndex2].Value := 0; Delta.AxisBlue[axIndex2].SaturationMethod := smRange; ColorDeltas.Add(Delta); Delta := TJvColorDelta.Create; Delta.ColorID := csXYZ; Delta.AxisRed[axIndex0].Value := 0; Delta.AxisRed[axIndex0].SaturationMethod := smRange; Delta.AxisRed[axIndex1].Value := 0; Delta.AxisRed[axIndex1].SaturationMethod := smRange; Delta.AxisRed[axIndex2].Value := 0; Delta.AxisRed[axIndex2].SaturationMethod := smRange; Delta.AxisGreen[axIndex0].Value := 0; Delta.AxisGreen[axIndex0].SaturationMethod := smRange; Delta.AxisGreen[axIndex1].Value := 0; Delta.AxisGreen[axIndex1].SaturationMethod := smRange; Delta.AxisGreen[axIndex2].Value := 0; Delta.AxisGreen[axIndex2].SaturationMethod := smRange; Delta.AxisBlue[axIndex0].Value := 80; Delta.AxisBlue[axIndex0].SaturationMethod := smRange; Delta.AxisBlue[axIndex1].Value := 0; Delta.AxisBlue[axIndex1].SaturationMethod := smRange; Delta.AxisBlue[axIndex2].Value := 0; Delta.AxisBlue[axIndex2].SaturationMethod := smRange; ColorDeltas.Add(Delta); end; procedure TJvFullColorCircleDlgMainFrm.JvFullColorCircleDialogApply(Sender: TObject); begin RotateCustomValues; end; initialization ColorDeltas := TJvColorDeltaList.Create; FillColorDeltas; finalization ColorDeltas.Free; end.
{ Double Commander ------------------------------------------------------------------------- Thread-safe asynchronous call queue. It allows queueing methods that should be called by GUI thread. Copyright (C) 2009-2011 Przemysław Nagay (cobines@gmail.com) 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 uGuiMessageQueue; {$mode objfpc}{$H+} interface uses Classes, SysUtils, syncobjs; type TGuiMessageProc = procedure (Data: Pointer) of object; PMessageQueueItem = ^TMessageQueueItem; TMessageQueueItem = record Method: TGuiMessageProc; Data : Pointer; Next : PMessageQueueItem; end; TGuiMessageQueueThread = class(TThread) private FWakeThreadEvent: PRTLEvent; FMessageQueue: PMessageQueueItem; FMessageQueueLastItem: PMessageQueueItem; FMessageQueueLock: TCriticalSection; FFinished: Boolean; {en This method executes some queued functions. It is called from main thread through Synchronize. } procedure CallMethods; public constructor Create(CreateSuspended: Boolean = False); reintroduce; destructor Destroy; override; procedure Terminate; procedure Execute; override; {en @param(AllowDuplicates If @false then if the queue already has AMethod with AData parameter then it is not queued for a second time. If @true then the same methods with the same parameters are allowed to exists multiple times in the queue.) } procedure QueueMethod(AMethod: TGuiMessageProc; AData: Pointer; AllowDuplicates: Boolean = True); end; procedure InitializeGuiMessageQueue; procedure FinalizeGuiMessageQueue; var GuiMessageQueue: TGuiMessageQueueThread; implementation uses uDebug, uExceptions; const // How many functions maximum to call per one Synchronize. MaxMessages = 10; constructor TGuiMessageQueueThread.Create(CreateSuspended: Boolean = False); begin FWakeThreadEvent := RTLEventCreate; FMessageQueue := nil; FMessageQueueLastItem := nil; FMessageQueueLock := TCriticalSection.Create; FFinished := False; FreeOnTerminate := False; inherited Create(CreateSuspended, DefaultStackSize); end; destructor TGuiMessageQueueThread.Destroy; var item: PMessageQueueItem; begin // Make sure the thread is not running anymore. Terminate; FMessageQueueLock.Acquire; while Assigned(FMessageQueue) do begin item := FMessageQueue^.Next; Dispose(FMessageQueue); FMessageQueue := item; end; FMessageQueueLock.Release; RTLeventdestroy(FWakeThreadEvent); FreeAndNil(FMessageQueueLock); inherited Destroy; end; procedure TGuiMessageQueueThread.Terminate; begin inherited Terminate; // Wake after setting Terminate to True. RTLeventSetEvent(FWakeThreadEvent); end; procedure TGuiMessageQueueThread.Execute; begin try while not Terminated do begin if Assigned(FMessageQueue) then // Call some methods. Synchronize(@CallMethods) else // Wait for messages. RTLeventWaitFor(FWakeThreadEvent); end; finally FFinished := True; end; end; procedure TGuiMessageQueueThread.QueueMethod(AMethod: TGuiMessageProc; AData: Pointer; AllowDuplicates: Boolean = True); var item: PMessageQueueItem; begin FMessageQueueLock.Acquire; try if AllowDuplicates = False then begin // Search the queue for this method and parameter. item := FMessageQueue; while Assigned(item) do begin if (item^.Method = AMethod) and (item^.Data = AData) then Exit; item := item^.Next; end; end; New(item); item^.Method := AMethod; item^.Data := AData; item^.Next := nil; if not Assigned(FMessageQueue) then FMessageQueue := item else FMessageQueueLastItem^.Next := item; FMessageQueueLastItem := item; RTLeventSetEvent(FWakeThreadEvent); finally FMessageQueueLock.Release; end; end; procedure TGuiMessageQueueThread.CallMethods; var MessagesCount: Integer = MaxMessages; item: PMessageQueueItem; begin while Assigned(FMessageQueue) and (MessagesCount > 0) do begin try // Call method with parameter. FMessageQueue^.Method(FMessageQueue^.Data); except on e: Exception do begin HandleException(e, Self); end; end; FMessageQueueLock.Acquire; try item := FMessageQueue^.Next; Dispose(FMessageQueue); FMessageQueue := item; // If queue is empty then reset wait event (must be done under lock). if not Assigned(FMessageQueue) then RTLeventResetEvent(FWakeThreadEvent); finally FMessageQueueLock.Release; end; Dec(MessagesCount, 1); end; end; // ---------------------------------------------------------------------------- procedure InitializeGuiMessageQueue; begin DCDebug('Starting GuiMessageQueue'); {$IF (fpc_version<2) or ((fpc_version=2) and (fpc_release<5))} GuiMessageQueue := TGuiMessageQueueThread.Create(True); GuiMessageQueue.Resume; {$ELSE} GuiMessageQueue := TGuiMessageQueueThread.Create(False); {$ENDIF} end; procedure FinalizeGuiMessageQueue; begin GuiMessageQueue.Terminate; DCDebug('Finishing GuiMessageQueue'); {$IF (fpc_version<2) or ((fpc_version=2) and (fpc_release<5))} If (MainThreadID=GetCurrentThreadID) then while not GuiMessageQueue.FFinished do CheckSynchronize(100); {$ENDIF} GuiMessageQueue.WaitFor; FreeAndNil(GuiMessageQueue); end; initialization InitializeGuiMessageQueue; finalization FinalizeGuiMessageQueue; end.
unit XRootWindow; {$mode objfpc}{$H+} interface uses Classes, X, XLib, XAtom, XFrames, ctypes, BaseWM, NetAtoms, XAtoms; type { TWMRootWindow } TWMRootWindow = class(TObject) private fIsRealRoot: Boolean; fOwner: TBaseWindowManager; fFrames: TXFrameList; fScreen: PScreen; fRootWindow: TWindow; function GetHeight: Integer; function GetWidth: Integer; procedure SetICCCMHints; procedure SetNETHints; procedure UnSetICCCMHints; procedure UnSetNETHints; protected fSupportWindow: TWindow; public constructor Create(AOwner: TBaseWindowManager; AScreen: PScreen; AWindow: TWindow); destructor Destroy; override; function AddNewClient(AWindow: TWindow; AX, AY, AWidth, AHeight: Integer; AOverrideDirect: TBool): TXFrame; procedure GrabExistingWindows; procedure SetHints; procedure UnSetHints; property Frames: TXFrameList read fFrames; property IsRealRoot: Boolean read fIsRealRoot; property Owner: TBaseWindowManager read fOwner; property RootWindow: TWindow read fRootWindow; property Screen: PScreen read fScreen; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; { TWMRootWindowList } TWMRootWindowList = class(TList) private function GetRootWindow(AIndex: Integer): TWMRootWindow; procedure SetRootWindow(AIndex: Integer; const AValue: TWMRootWindow); public procedure Clear; override; function FrameListFromWindow(const AWindow: TXFrame): TXFrameList; function RootWindowFromXWindow(const ARootWindow: TWindow): TWMRootWindow; property Windows[AIndex: Integer]: TWMRootWindow read GetRootWindow write SetRootWindow; end; implementation uses XWM; type // a hack to get around a recursive uses TXWM = class(TXWindowManager) end; { TWMRootWindow } // this should initialize procedure TWMRootWindow.SetICCCMHints; begin // TODO Set mandatory ICCCM hints on the rootwindow end; function TWMRootWindow.GetHeight: Integer; var Attr: TXWindowAttributes; begin Result := 0; if IsRealRoot then Exit(XHeightOfScreen(Screen)); if XGetWindowAttributes(TXWM(Owner).Display, RootWindow, @Attr) <> 0 then Result := Attr.height; end; function TWMRootWindow.GetWidth: Integer; var Attr: TXWindowAttributes; begin Result := 0; if IsRealRoot then Exit(XWidthOfScreen(Screen)); if XGetWindowAttributes(TXWM(Owner).Display, RootWindow, @Attr) <> 0 then Result := Attr.width; end; procedure TWMRootWindow.SetNETHints; var WM: TXWM; DeskCount: Cardinal = 1; DeskCurrent: Cardinal = None; DeskActive: TWindow = None; DeskViewPort: array[0..1] of Cardinal; DeskGeom: array [0..1] of Integer; DeskWorkArea: array [0..3] of Integer; Attr: TXSetWindowAttributes; Atoms: array [0..10] of TAtom; begin DeskViewPort[0] := 0; DeskViewPort[1] := 0; DeskWorkArea[0] := 0; // X DeskWorkArea[1] := 0; // Y DeskWorkArea[2] := Width; DeskWorkArea[3] := Height; Attr.override_redirect := TBool(True); fSupportWindow := XCreateWindow(TXWM(Owner).Display, RootWindow, 0, 0, // X, Y 1, 1, // Width, Height 0, // border width 0, // Depth InputOnly, // class nil, // visual CWOverrideRedirect, // mask @Attr); WM := TXWM(Owner); exit; with WM do begin // Set the atoms on the RootWindow WindowChangeProperty(Self.RootWindow, _NET[_CLIENT_LIST], XA_WINDOW, 32, PropModeReplace, nil, 0); WindowChangeProperty(Self.RootWindow, _NET[_CLIENT_LIST_STACKING], XA_WINDOW, 32, PropModeReplace, nil, 0); WindowChangeProperty(Self.RootWindow, _NET[_NUMBER_OF_DESKTOPS], XA_CARDINAL, 32, PropModeReplace, @DeskCount, 1); WindowChangeProperty(Self.RootWindow, _NET[_DESKTOP_GEOMETRY], XA_CARDINAL, 32, PropModeReplace, @DeskGeom, 2); WindowChangeProperty(Self.RootWindow, _NET[_DESKTOP_VIEWPORT], XA_CARDINAL, 32, PropModeReplace, @DeskViewPort, 2); WindowChangeProperty(Self.RootWindow, _NET[_CURRENT_DESKTOP], XA_CARDINAL, 32, PropModeReplace, @DeskCurrent, 1); WindowChangeProperty(Self.RootWindow, _NET[_ACTIVE_WINDOW], XA_WINDOW, 32, PropModeReplace, @DeskActive, 1); WindowChangeProperty(Self.RootWindow, _NET[_WORKAREA], XA_CARDINAL, 32, PropModeReplace, @DeskWorkArea, 4); WindowChangeProperty(Self.RootWindow, _NET[_SUPPORTING_WM_CHECK], XA_WINDOW, 32, PropModeReplace, @fSupportWindow, 1); // Set the atoms on the support window WindowChangeProperty(Self.fSupportWindow, _NET[_SUPPORTING_WM_CHECK], XA_WINDOW, 32, PropModeReplace, @fSupportWindow, 1); WindowChangeProperty(fSupportWindow, _NET[_WM_NAME], UTF8_STRING, 8, PropModeReplace, PChar('fpwm'), 7); Atoms[0] := _NET[_CLIENT_LIST]; Atoms[1] := _NET[_CLIENT_LIST_STACKING]; Atoms[2] := _NET[_NUMBER_OF_DESKTOPS]; Atoms[3] := _NET[_DESKTOP_GEOMETRY]; Atoms[4] := _NET[_DESKTOP_VIEWPORT]; Atoms[5] := _NET[_CURRENT_DESKTOP]; Atoms[6] := _NET[_ACTIVE_WINDOW]; Atoms[7] := _NET[_WORKAREA]; Atoms[8] := _NET[_SUPPORTING_WM_CHECK]; Atoms[9] := _NET[_WM_NAME]; Atoms[10] := _NET[_CLOSE_WINDOW]; // Now mark that we support _NET atoms WindowChangeProperty(Self.RootWindow, _NET[_SUPPORTED], XA_ATOM, 32, PropModeReplace, @Atoms, 11); end; end; procedure TWMRootWindow.UnSetICCCMHints; begin end; procedure TWMRootWindow.UnSetNETHints; var WM: TXWM; begin WM := TXWM(Owner); with WM do begin WindowDeleteProperty(RootWindow, _NET[_SUPPORTED]); WindowDeleteProperty(RootWindow, _NET[_CLIENT_LIST]); WindowDeleteProperty(RootWindow, _NET[_CLIENT_LIST_STACKING]); WindowDeleteProperty(RootWindow, _NET[_NUMBER_OF_DESKTOPS]); WindowDeleteProperty(RootWindow, _NET[_DESKTOP_GEOMETRY]); WindowDeleteProperty(RootWindow, _NET[_DESKTOP_VIEWPORT]); WindowDeleteProperty(RootWindow, _NET[_CURRENT_DESKTOP]); WindowDeleteProperty(RootWindow, _NET[_ACTIVE_WINDOW]); WindowDeleteProperty(RootWindow, _NET[_WORKAREA]); WindowDeleteProperty(RootWindow, _NET[_SUPPORTING_WM_CHECK]); WindowDeleteProperty(fSupportWindow, _NET[_SUPPORTING_WM_CHECK]); WindowDeleteProperty(fSupportWindow, _NET[_WM_NAME]); XDestroyWindow(Display, fSupportWindow); end; end; constructor TWMRootWindow.Create(AOwner: TBaseWindowManager; AScreen: PScreen; AWindow: TWindow); begin fOwner := AOwner; fRootWindow := AWindow; fScreen := AScreen; fFrames := TXFrameList.Create; SetHints; end; destructor TWMRootWindow.Destroy; begin UnSetHints; fFrames.Free; inherited Destroy; end; function TWMRootWindow.AddNewClient(AWindow: TWindow; AX, AY, AWidth, AHeight: Integer; AOverrideDirect: TBool): TXFrame; begin WriteLn('Maybe Creating New Window Frame for; ', AWindow, 'X =' , Ax, 'Y = ', Ay, ' Width =', AWidth,' Height = ', AHeight); Result := TXWM(fOwner).CreateNewWindowFrame(Self, fScreen, AWindow, AX, AY, AWidth, AHeight, AOverrideDirect); if Result <> nil then Frames.Add(Result); if Result = nil then WriteLn('Didn''t create Frame'); end; procedure TWMRootWindow.GrabExistingWindows; var I: Integer; WindowCount: cuint; WindowsRoot, WindowsParent: TWindow; ChildrenList: PWindow; WindowAttributes: TXWindowAttributes; Frame: TXFrame; WM: TXWM; begin WM := TXWM(Owner); if XQueryTree(TXWM(fOwner).Display, fRootWindow, @WindowsRoot, @WindowsParent, @ChildrenList, @WindowCount) <> 0 then begin // find out if we are a real root window or a mdi root if fRootWindow = WindowsRoot then fIsRealRoot := True else fIsRealRoot := False; // this finds out if the window want's to be managed or not. for I := 0 to WindowCount-1 do begin //WriteLn('Possibly mapping window'); XGetWindowAttributes(TXWM(fOwner).Display, ChildrenList[I], @WindowAttributes); // override_redirect are windows like menus or hints that appear with no border // we don't manage them if (WindowAttributes.override_redirect = TBool(False)) and (WindowAttributes.map_state = IsViewable) then begin Frame := AddNewClient(ChildrenList[I], WindowAttributes.x, WindowAttributes.y, WindowAttributes.width, WindowAttributes.height, WindowAttributes.override_redirect); if Frame <> nil then Frame.MapWindow; end; end; XFree(ChildrenList); end; end; procedure TWMRootWindow.SetHints; begin SetICCCMHints; SetNETHints; // and any hints specific to our windowmanager here end; procedure TWMRootWindow.UnSetHints; begin UnSetNETHints; UnSetICCCMHints; // and then our hints end; { TWMRootWindowList } function TWMRootWindowList.GetRootWindow(AIndex: Integer): TWMRootWindow; begin Result := TWMRootWindow(Items[AIndex]); end; procedure TWMRootWindowList.SetRootWindow(AIndex: Integer; const AValue: TWMRootWindow); begin Items[AIndex] := AValue; end; procedure TWMRootWindowList.Clear; var I: Integer; begin for I := 0 to Count-1 do Windows[I].Free; inherited Clear; end; function TWMRootWindowList.RootWindowFromXWindow(const ARootWindow: TWindow ): TWMRootWindow; var I: Integer; begin //WriteLn('Window Count = ',Count); Result := nil; for I := 0 to Count-1 do begin if ARootWindow = Windows[I].RootWindow then Exit(Windows[I]); end; end; function TWMRootWindowList.FrameListFromWindow(const AWindow: TXFrame ): TXFrameList; var I: Integer; begin Result := nil; for I := 0 to Count-1 do begin if Windows[I].Frames.IndexOf(AWindow) > -1 then begin Result := Windows[I].Frames; Exit; end; end; end; end.
unit Nathan.Resources.ResourceManager; interface uses System.Classes, System.Types; type /// <summary> /// https://msdn.microsoft.com/de-de/library/system.resources.resourcemanager(v=vs.110).aspx /// https://msdn.microsoft.com/en-us/library/system.resources(v=vs.110).aspx /// https://msdn.microsoft.com/en-us/library/system.resources.resourcemanager(v=vs.110).aspx /// </summary> TResourceManager = record public class function GetStream(const Name: string): TStream; overload; static; class function GetStream(const Name: string; const ResType: PChar): TStream; overload; static; class function GetString(const Name: string): string; overload; static; class function GetString(const Name: string; const ResType: PChar): string; overload; static; class procedure SaveResource(const ResName, SaveToFilename: string; const ResType: PChar = RT_RCDATA); static; class procedure SaveToFile(const ResName, SaveToFilename: string; const ResType: PChar = RT_RCDATA); static; end; ResourceManager = TResourceManager; implementation uses System.SysUtils, System.IOUtils; { TResourceManager } class function TResourceManager.GetStream(const Name: string): TStream; begin Result := GetStream(Name, RT_RCDATA); end; class function TResourceManager.GetStream(const Name: string; const ResType: PChar): TStream; begin Result := TResourceStream.Create(HInstance, Name, ResType); end; class function TResourceManager.GetString(const Name: string): string; begin Result := GetString(Name, RT_RCDATA); end; class function TResourceManager.GetString(const Name: string; const ResType: PChar): string; var RawStream: TResourceStream; StringStream: TStringStream; begin RawStream := TResourceStream.Create(HInstance, Name, ResType); try StringStream := TStringStream.Create(''); try RawStream.SaveToStream(StringStream); StringStream.Position := 0; Result := StringStream.DataString; finally StringStream.Free(); end; finally RawStream.Free(); end; end; class procedure TResourceManager.SaveResource(const ResName, SaveToFilename: string; const ResType: PChar); var RS: TResourceStream; begin if TDirectory.Exists(TPath.GetFileName(SaveToFilename)) then TDirectory.CreateDirectory(TPath.GetFileName(SaveToFilename)); RS := nil; try RS := TResourceStream.Create(HInstance, ResName, ResType); RS.SaveToFile(SaveToFileName); finally FreeAndNil(RS); end; end; class procedure TResourceManager.SaveToFile(const ResName, SaveToFilename: string; const ResType: PChar); begin TResourceManager.SaveResource(ResName, SaveToFilename, ResType); end; end.
unit Variant_18_2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm22 = class(TForm) Edit1: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form22: TForm22; implementation {$R *.dfm} const Eps = 1E-5; var A, B, R: Real; function F(X: Real): Real; begin F := X*X - 4; end; function DF(X: Real): Real; begin DF := 2*X; end; procedure Combo(A,B: Real; var R: Real); var X: Real; begin while Abs(A-B) > Eps do begin B := B - F(B) * (B-A) / (F(B) - F(A)); A := A - F(A) / DF(A); R := (A + B)/2; end; end; procedure TForm22.Button1Click(Sender: TObject); begin Combo(-3, 0, R); Edit1.Text := FloatToStr(R); end; procedure TForm22.Button2Click(Sender: TObject); begin Combo(-3, 0, R); Edit1.Text := FormatFloat('0E+0', F(R)); end; end.
unit Global; interface uses Windows, Classes; const //Имя файла настроек INI_NAME = 'EDITITEM.INI'; //Количество свойств по умолчанию DEFAULT_COUNT_PROP = 0; // Количество физических параметров в свойстве COUNT_FYS_PROP = 4; // Количество дополнительных параметров в свойстве COUNT_ADD_PROP = 2; // Количество точек полифигур MAX_POINTS = 100; // Элемент не найден NOT_FIND = -1; // Смещение символа CHAR_OFFSET = 3; // Выравнивания TextAlignHorizontal: array [0..2] of Cardinal = (DT_LEFT, DT_RIGHT, DT_CENTER); TextAlignVertical: array [0..2] of Cardinal = (DT_TOP, DT_VCENTER, DT_BOTTOM); type TDrawShape = (gfLine, gfRectangle, gfRoundRectangle, gfCircle, gfEllipse, gfPolyLine, gfPolygon, gfBezier, gfText); TTrackerState = (tsNormal, tsSelected, tsActive); PPoints = ^TPoints; TPoints = array[0..0] of TPoint; TDrawPoint = array of TPoint; var // Контекст виртуального окна mDC: HDC; // Битовая карта виртуального окна mBM: HBITMAP; // Начальный путь PATH_BEGIN: String; implementation end.
unit VistaAltFixUnit; interface uses Windows, Classes; type TVistaAltFix = class(TComponent) private FInstalled: Boolean; function VistaWithTheme: Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; procedure Register; implementation uses Messages, Themes; procedure Register; begin RegisterComponents('MEP', [TVistaAltFix]); end; var FInstallCount: Integer = 0; FCallWndProcHook: Cardinal = 0; { TVistaAltFix } function CallWndProcFunc( nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var p: PCWPSTRUCT; begin if nCode = HC_ACTION then begin p := PCWPSTRUCT(lParam); if p.message = WM_UPDATEUISTATE then begin InvalidateRect(p.hwnd, nil, True); end; end; Result := CallNextHookEx(FCallWndProcHook, nCode, wParam, lParam); end; constructor TVistaAltFix.Create(AOwner: TComponent); begin inherited; if VistaWithTheme and not (csDesigning in ComponentState) then begin Inc(FInstallCount); // Allow more than 1 instance, assume single threaded as VCL is not thread safe anyway if FInstallCount = 1 then FCallWndProcHook := SetWindowsHookEx(WH_CALLWNDPROC, CallWndProcFunc, 0, GetCurrentThreadID); FInstalled := True; end; end; destructor TVistaAltFix.Destroy; begin if FInstalled then begin Dec(FInstallCount); if FInstallCount = 0 then begin UnhookWindowsHookEx(FCallWndProcHook); FCallWndProcHook := 0; end; end; inherited Destroy; end; function TVistaAltFix.VistaWithTheme: Boolean; var OSVersionInfo: TOSVersionInfo; begin OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo); if GetVersionEx(OSVersionInfo) and (OSVersionInfo.dwMajorVersion >= 6) and ThemeServices.ThemesEnabled then Result := True else Result := False; end; end.
unit matrix; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Grids, Dialogs, Math; const sirka : integer = 300; vyska : integer = 200; type TSimplePole = array of real; TPole = array of array of real; { TMatrix } TMatrix = class Pole: Tpole; constructor Create(x, y: integer); procedure prirad(m: TMatrix); procedure prirad(p: TSimplePole); end; TMatrixPole = array of TMatrix; { TVykreslovanie } TVykreslovanie = class kamera, light: TMatrix; farba : TColor; Body: array of TMatrix; Polynomy: array of array of integer; constructor Create; procedure vykresli1(Obr: TCanvas; trans, view: TMatrix; culling, shading, wires : boolean); function scale(a: TMatrix; x, y, z: real): TMatrix; function nasobenie(a, b: TMatrix): TMatrix; function translate(a: TMatrix; x, y, z: real): TMatrix; function RotaciaX(a: TMatrix; stupnov: real): TMatrix; function RotaciaY(a: TMatrix; stupnov: real): TMatrix; function RotaciaZ(a: TMatrix; stupnov: real): TMatrix; function normalsurface(a: array of TMatrix; view: TMatrix): TMatrix; function middlepoint(view, lights: TMatrix): TMatrixPole; function dotproduct(normal, Camera: TMatrix): real; function normallize(a: TMatrix): TMatrix; function normalvectors(view: TMatrix): TMatrixPole; function vektor(a, b: TMatrix): TMatrix; procedure loadFromFile(s: string); end; implementation { TVykreslovanie } constructor TVykreslovanie.Create; begin kamera := TMatrix.Create(1, 4); kamera.pole[0][2] := 1; kamera.pole[0][3] := 1; light := TMatrix.Create(1, 4); light.pole[0][3] := 1; setlength(body, 0); setlength(polynomy, 0); farba := clWhite; end; procedure TVykreslovanie.vykresli1(Obr: TCanvas; trans, view: TMatrix; culling, shading, wires: boolean); var pom, viewReport: TMatrix; i, j: integer; normals, middlepoints: array of TMatrix; vertex: array of TPoint; r, g, b: byte; skalar: real; begin Obr.Pen.Style := psSolid; Obr.Pen.Color := clSilver; obr.line(0, vyska, obr.Width, vyska); obr.line(sirka, 0, sirka, obr.Height); Obr.Pen.Color := clBlack; viewReport := nasobenie(trans, view); normals := normalvectors(viewReport); middlepoints := middlepoint(viewReport, light); pom := TMatrix.Create(1, 4); for i := 0 to length(Polynomy) - 1 do begin if (not(culling) or (dotproduct(normals[i], kamera) >= 0)) then begin setlength(vertex, length(polynomy[i])); for j := 0 to length(vertex) - 1 do begin pom := nasobenie(body[Polynomy[i][j] - 1], viewReport); vertex[j].X := round(pom.pole[0][0]) + sirka; vertex[j].Y := -round(pom.pole[0][1]) + vyska; end; Obr.Brush.Color := farba; skalar := dotproduct(normals[i], middlepoints[i]); if ((skalar > 0) and (shading)) then begin r := round(red(Obr.Brush.Color) * skalar); g := round(green(Obr.Brush.Color) * skalar); b := round(blue(Obr.Brush.Color) * skalar); Obr.Brush.Color := RGBToColor(r, g, b); end else if shading then Obr.Brush.Color := clBlack; if wires then Obr.Pen.Style := psSolid else Obr.Pen.Style := psClear; if culling then Obr.Brush.Style := bsSolid else Obr.Brush.Style := bsClear; Obr.Polygon(vertex); end; end; Obr.Brush.Style := bsSolid; Obr.Brush.Color := clWhite; end; function TVykreslovanie.scale(a: TMatrix; x, y, z: real): TMatrix; var pom: TMatrix; i: integer; begin pom := TMatrix.Create(length(a.Pole), length(a.pole[high(a.pole)])); for i := 0 to length(pom.pole) - 1 do pom.pole[i][i] := 1; pom.Pole[0][0] := x; pom.Pole[1][1] := y; pom.Pole[2][2] := z; Result := nasobenie(a, pom); end; function TVykreslovanie.nasobenie(a, b: TMatrix): TMatrix; var pom: TMatrix; i, j, k: integer; sum: real; policko: TSimplePole; begin if (length(a.pole[high(a.pole)]) = length(b.pole)) then begin setlength(policko, 0); Pom := TMatrix.Create(length(a.pole), length(b.pole[high(b.pole)])); for i := 0 to length(a.pole) - 1 do begin for j := 0 to length(b.pole[high(b.pole)]) - 1 do begin sum := 0; for k := 0 to length(a.pole[high(a.pole)]) - 1 do Sum := Sum + a.pole[i][k] * b.pole[k][j]; setlength(policko, length(policko) + 1); policko[i * length(a.pole) + j] := sum; end; end; Pom.prirad(policko); Result := Pom; end; end; function TVykreslovanie.translate(a: TMatrix; x, y, z: real): TMatrix; var pom: TMatrix; i: integer; begin pom := TMatrix.Create(4, 4); for i := 0 to length(pom.pole) - 1 do pom.pole[i][i] := 1; pom.pole[3, 0] := x; pom.pole[3, 1] := y; pom.pole[3, 2] := z; Result := nasobenie(a, pom); end; function TVykreslovanie.RotaciaZ(a: TMatrix; stupnov: real): TMatrix; var pom: TMatrix; i: integer; begin pom := TMatrix.Create(4, 4); for i := 0 to length(pom.pole) - 1 do pom.pole[i][i] := 1; pom.pole[0, 0] := cos(degtorad(stupnov)); pom.pole[0, 1] := sin(degtorad(stupnov)); pom.pole[1, 0] := -sin(degtorad(stupnov)); pom.pole[1, 1] := cos(degtorad(stupnov)); Result := nasobenie(a, pom); end; function TVykreslovanie.normalsurface(a: array of TMatrix; view: TMatrix): TMatrix; var i: integer; pom, current, Next: TMatrix; begin pom := TMatrix.Create(1, 4); pom.pole[0][3] := 1; for i := 0 to length(a) - 1 do begin current := nasobenie(a[i], view); Next := nasobenie(a[(i + 1) mod length(a)], view); pom.pole[0][0] := pom.pole[0][0] + ((current.pole[0][1] - Next.pole[0][1]) * (current.pole[0][2] + Next.pole[0][2])); pom.pole[0][1] := pom.pole[0][1] + ((current.pole[0][2] - Next.pole[0][2]) * (current.pole[0][0] + Next.pole[0][0])); pom.pole[0][2] := pom.pole[0][2] + ((current.pole[0][0] - Next.pole[0][0]) * (current.pole[0][1] + Next.pole[0][1])); end; Result := pom; end; function TVykreslovanie.middlepoint(view, lights: TMatrix): TMatrixPole; var i, j: integer; normals: array of TMatrix; pom: TMatrix; begin pom := TMatrix.Create(1, 4); pom.pole[0][3] := 1; for i := 0 to length(Polynomy) - 1 do begin pom.pole[0][0] := 0; pom.pole[0][1] := 0; pom.pole[0][2] := 0; for j := 0 to length(Polynomy[i]) - 1 do begin pom.pole[0][0] := pom.pole[0][0] + body[polynomy[i][j] - 1].pole[0][0]; pom.pole[0][1] := pom.pole[0][1] + body[polynomy[i][j] - 1].pole[0][1]; pom.pole[0][2] := pom.pole[0][2] + body[polynomy[i][j] - 1].pole[0][2]; end; pom.pole[0][0] := pom.pole[0][0] / length(Polynomy[i]); pom.pole[0][1] := pom.pole[0][1] / length(Polynomy[i]); pom.pole[0][2] := pom.pole[0][2] / length(Polynomy[i]); setlength(normals, length(normals) + 1); pom := nasobenie(pom, view); normals[high(normals)] := normallize(vektor(lights, pom)); end; Result := normals; end; function TVykreslovanie.dotproduct(normal, Camera: TMatrix): real; var i: integer; sum: real; begin sum := 0; for i := 0 to high(normal.pole[0]) - 1 do sum := sum + normal.pole[0][i] * camera.pole[0][i]; Result := sum; end; function TVykreslovanie.normallize(a: TMatrix): TMatrix; var dlzka: real; pom: TMatrix; i: integer; begin pom := TMatrix.Create(1, 4); for i := 0 to length(a.pole[0]) - 1 do pom.pole[0][i] := a.pole[0][i]; dlzka := sqrt((a.Pole[0][0] * a.Pole[0][0]) + (a.Pole[0][1] * a.Pole[0][1]) + (a.Pole[0][2] * a.Pole[0][2])); if dlzka = 0 then exit; pom.Pole[0][0] := a.pole[0][0] / dlzka; pom.Pole[0][1] := a.pole[0][1] / dlzka; pom.Pole[0][2] := a.pole[0][2] / dlzka; Result := pom; end; function TVykreslovanie.normalvectors(view: TMatrix): TMatrixPole; var i, j: integer; normals, vertices: array of TMatrix; begin for i := 0 to length(Polynomy) - 1 do begin setlength(vertices, length(Polynomy[i])); for j := 0 to length(Polynomy[i]) - 1 do vertices[j] := body[polynomy[i][j] - 1]; setlength(normals, length(normals) + 1); normals[high(normals)] := normallize(normalsurface(vertices, view)); end; Result := normals; end; function TVykreslovanie.vektor(a, b: TMatrix): TMatrix; var pom: TMatrix; begin pom := TMatrix.Create(1, 4); pom.pole[0][0] := a.pole[0][0] - b.pole[0][0]; pom.pole[0][1] := a.pole[0][1] - b.pole[0][1]; pom.pole[0][2] := a.pole[0][2] - b.pole[0][2]; pom.pole[0][3] := 1; Result := pom; end; function TVykreslovanie.RotaciaY(a: TMatrix; stupnov: real): TMatrix; var pom: TMatrix; i: integer; begin pom := TMatrix.Create(4, 4); for i := 0 to length(pom.pole) - 1 do pom.pole[i][i] := 1; pom.pole[0, 0] := cos(degtorad(stupnov)); pom.pole[0, 2] := -sin(degtorad(stupnov)); pom.pole[2, 0] := sin(degtorad(stupnov)); pom.pole[2, 2] := cos(degtorad(stupnov)); Result := nasobenie(a, pom); end; function TVykreslovanie.RotaciaX(a: TMatrix; stupnov: real): TMatrix; var pom: TMatrix; i: integer; begin pom := TMatrix.Create(4, 4); for i := 0 to length(pom.pole) - 1 do pom.pole[i][i] := 1; pom.pole[1, 1] := cos(degtorad(stupnov)); pom.pole[2, 1] := -sin(degtorad(stupnov)); pom.pole[1, 2] := sin(degtorad(stupnov)); pom.pole[2, 2] := cos(degtorad(stupnov)); Result := nasobenie(a, pom); end; procedure TVykreslovanie.loadFromFile(S: string); var T: TextFile; Text: string; pom: TStringList; i: integer; begin AssignFile(T, S + '.obj'); Reset(T); Pom := TStringList.Create; Pom.Delimiter := ' '; repeat readln(T, Text); if length(Text) > 0 then begin case Text[1] of 'v': begin Pom.DelimitedText := Text; setlength(Body, length(Body) + 1); Body[high(Body)] := TMatrix.Create(1, 4); Body[high(Body)].Pole[0][0] := StrToFloat(StringReplace(pom[1], '.', ',', [rfReplaceAll, rfIgnoreCase])); Body[high(Body)].Pole[0][1] := StrToFloat(StringReplace(pom[2], '.', ',', [rfReplaceAll, rfIgnoreCase])); Body[high(Body)].Pole[0][2] := StrToFloat(StringReplace(pom[3], '.', ',', [rfReplaceAll, rfIgnoreCase])); Body[high(Body)].Pole[0][3] := 1; Pom.Clear; end; 'f': begin Pom.DelimitedText := Text; setlength(Polynomy, length(Polynomy) + 1); setlength(Polynomy[high(Polynomy)], Pom.Count - 1); for i := 0 to Pom.Count - 2 do Polynomy[high(Polynomy)][i] := StrToInt(pom[i + 1]); Pom.Clear; end; end; end; until EOF(T); CloseFile(T); end; { TMatrix } constructor TMatrix.Create(x, y: integer); var i: integer; begin setlength(pole, x); for i := 0 to x - 1 do begin setlength(pole[i], y); if (x = y) then pole[i][i] := 1; end; pole[x - 1][y - 1] := 1; end; procedure TMatrix.prirad(m: TMatrix); var x, y: integer; begin for y := 0 to length(m.Pole) - 1 do for x := 0 to length(m.Pole[y]) - 1 do Pole[y][x] := m.Pole[y][x]; end; procedure TMatrix.prirad(p: TSimplePole); var x, y: integer; begin if (length(p) = (length(pole) * length(pole[high(pole)]))) then begin for y := 0 to length(pole) - 1 do for x := 0 to length(pole[y]) - 1 do pole[y][x] := p[y * length(pole) + x]; end; end; end.
unit XMLClipboard; interface function DataSetToXML(Data:TObject;Columns:String='';PutClipboard:Boolean=True):String; procedure XMLToDataSet(Data:TObject;AllowPlain:Boolean); implementation uses DB,DBGrids,Classes,JvSimpleXml,SysUtils,Clipbrd,DBClient,dbClipImport; type TRecordColumn = record Visible: Boolean; Exportable: Boolean; ColumnName: string; Column: TColumn; Field: TField; end; TXMLComponent = class(TComponent) private FColumnCount: Integer; FRecordColumns: array of TRecordColumn; LastResult:String; function ClassNameNoT(AField: TField): string; function ExportField(AField: TField): Boolean; public procedure CheckVisibleColumn(Grid:TDBGrid); function DoExport(Grid:TDBGrid): String; published property XML:String read LastResult write LastResult; end; function TXMLComponent.ExportField(AField: TField): Boolean; begin Result := not (AField.DataType in [ftUnknown, ftBlob, ftGraphic, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, ftVariant, ftInterface, ftIDispatch, ftGuid]); end; procedure TXMLComponent.CheckVisibleColumn(Grid:TDBGrid); var I: Integer; begin FColumnCount := Grid.Columns.Count; SetLength(FRecordColumns, FColumnCount); for I := 0 to FColumnCount - 1 do begin FRecordColumns[I].Column := Grid.Columns[I]; FRecordColumns[I].Visible := Grid.Columns[I].Visible; FRecordColumns[I].ColumnName := Grid.Columns[I].FieldName; FRecordColumns[I].Field := Grid.Columns[I].Field; if FRecordColumns[I].Visible and (FRecordColumns[I].Field <> nil) then FRecordColumns[I].Exportable := ExportField(FRecordColumns[I].Field) else FRecordColumns[I].Exportable := False; end; end; function TXMLComponent.ClassNameNoT(AField: TField): string; begin Result := AField.ClassName; if Result[1] = 'T' then Delete(Result, 1, 1); if SameText('Field', Copy(Result, Length(Result) - 4, 5)) then { do not localize } Delete(Result, Length(Result) - 4, 5); Result:=LowerCase(Result); if SameText(Result,'WideString') then result:='string' else if SameText(Result,'FixedChar') then result:='string' else if SameText(Result,'Smallint') then result:='i2' else if SameText(Result,'Integer') then result:='i4' else if SameText(Result,'LargeInt') then result:='i8' else if SameText(Result,'Word') then result:='r8' else if SameText(Result,'Float') then result:='r8' else if SameText(Result,'Currency') then result:='r8' else if SameText(Result,'SQLTimeStamp') then result:='datetime' else if SameText(Result,'BCD') then result:='fixed' else if SameText(Result,'FMTBCD') then result:='fixed' else if SameText(Result,'Bytes') then result:='bin.hex' else if SameText(Result,'VarBytes') then result:='bin.hex' else if SameText(Result,'Blob') then result:='bin.hex' else if SameText(Result,'Memo') then result:='bin.hex' else if SameText(Result,'Graphic') then result:='bin.hex' else if SameText(Result,'TypedBinary') then result:='bin.hex' else if SameText(Result,'FmtMemo') then result:='bin.hex' else if SameText(Result,'ParadoxOle') then result:='bin.hex' else if SameText(Result,'dBaseOle') then result:='bin.hex'; end; function TXMLComponent.DoExport(Grid:TDBGrid): String; var FXML: TJvSimpleXML; I: Integer; // ARecNo, lRecCount: Integer; lBookmark: TBookmark; lRootNode: TJvSimpleXmlElemClassic; lDataNode: TJvSimpleXmlElem; lFieldsNode: TJvSimpleXmlElem; lRecordNode: TJvSimpleXmlElem; begin CheckVisibleColumn(Grid); FXML := TJvSimpleXML.Create(nil); try FXML.Options := [sxoAutoCreate, sxoAutoIndent]; FXML.Prolog.StandAlone:=True; FXML.Root.Clear; // create root node FXML.Root.Name := 'DATAPACKET'; lRootNode := FXML.Root; lRootNode.Properties.Add('version', '2.0'); // add column header and his property lDataNode := lRootNode.Items.Add('METADATA'); lFieldsNode := lDataNode.Items.Add('FIELDS'); for I := 0 to FColumnCount - 1 do with FRecordColumns[I] do if Visible and (Field <> nil) then begin with lFieldsNode.Items.Add('FIELD') do begin Properties.Add('attrname', ColumnName); Properties.Add('fieldtype', ClassNameNoT(Field)); Properties.Add('width', Column.Width); end; end; // now add all the record lRecordNode := lRootNode.Items.Add('ROWDATA'); with Grid.DataSource.DataSet do begin // ARecNo := 0; // lRecCount := RecordCount; //DoProgress(0, lRecCount, ARecNo, Caption); DisableControls; lBookmark := GetBookmark; First; try while not Eof do begin with lRecordNode.Items.Add('ROW') do begin for I := 0 to FColumnCount - 1 do if FRecordColumns[I].Exportable and not FRecordColumns[I].Field.IsNull then with FRecordColumns[I] do Properties.Add(ColumnName, Field.AsString); end; Next; // Inc(ARecNo); // if not DoProgress(0, lRecCount, ARecNo, Caption) then Last; end; // DoProgress(0, lRecCount, lRecCount, Caption); finally if (lBookmark <> nil) and BookmarkValid(lBookmark) then GotoBookmark(lBookmark); if lBookmark <> nil then FreeBookmark(lBookmark); EnableControls; end; end; Result:=FXML.XMLData; LastResult:=Result; finally FXML.Free; end; end; function DataSetToXML(Data:TObject;Columns:String='';PutClipboard:Boolean=True):String; var Grid:TDBGrid; DataSource:TDataSource; XML:TXMLComponent; C:TStringList; I:Integer; begin if (Data is TDBGrid) and TDBGrid(Data).ReadOnly then Exit; XML:=TXMLComponent.Create(nil); try XML.Name:='XMLComponent'; XML.Tag:=1; if (Columns<>'') and (Data is TDBGrid) then Data:=TDBGrid(Data).DataSource; if Data is TDataSet then begin DataSource:=TDataSource.Create(XML); DataSource.DataSet:=TDataSet(Data); Data:=DataSource; end; if Data is TDataSource then begin Grid:=TDBGrid.Create(XML); Grid.DataSource:=TDataSource(Data); if Columns<>'' then begin C:=TStringList.Create; try C.CommaText:=Columns; for I:=0 to C.Count-1 do begin Grid.Columns.Add.FieldName:=C[I]; end; finally C.Free; end; end; Data:=Grid; end; if Data is TDBGrid then begin Grid:=TDBGrid(Data); Result:=XML.DoExport(Grid); if PutClipBoard then begin ClipBoard.Open; try ClipBoard.AsText:=ExportToString(Grid); ClipBoard.SetComponent(XML); finally Clipboard.Close; end; end; end; finally XML.Free; end; end; procedure XMLToDataSet; var C:TComponent; CDS:TClientDataSet; Src,Dest:array of TField; D:TDataSet; Cnt,I:Integer; begin if Data is TDBGrid then Data:=TDBGrid(Data).DataSource; if Data is TDataSource then Data:=TDataSource(Data).DataSet; if not (Data is TDataSet) then Exit; D:=TDataSet(Data); C:=ClipBoard.GetComponent(nil,nil); try if C is TXMLComponent then begin if C.Tag=1 then begin CDS:=TClientDataSet.Create(C); CDS.XMLData:=TXMLComponent(C).XML; Cnt:=0; for I:=0 to CDS.Fields.Count-1 do begin if D.FindField(CDS.Fields[I].FieldName)<>nil then Cnt:=Cnt+1; end; if Cnt>0 then begin SetLength(Src,Cnt); SetLength(Dest,Cnt); Cnt:=0; for I:=0 to CDS.Fields.Count-1 do if D.FindField(CDS.Fields[I].FieldName)<>nil then begin Dest[Cnt]:=D.FieldByName(CDS.Fields[I].FieldName); Src[Cnt]:=CDS.Fields[I]; Cnt:=Cnt+1; end; CDS.First; while not CDS.Eof do begin D.Append; for I:=0 to Length(Src)-1 do if not Src[I].IsNull then Dest[I].AsString:=Src[I].AsString; D.CheckBrowseMode; CDS.Next; end; end; end; end else if AllowPlain then ImportFromClipBoard(D); finally C.Free; end; end; initialization RegisterClasses([TXMLComponent]); end.
unit ccsqlbulkcopy; { BulkCopy - Delphi / Lazarus Library ------------------------------------ Author : Tigor M Manurung Email : tigor@tigorworks.com Library for copying table data from source to destination (same / different server) } interface uses sysutils,classes,ccbulkdbcore,ccbulkinsert; type PCCFieldMapRecord = ^TCCFieldMapRecord; TCCFieldMapRecord = record SourceField,DestinationField: string; end; TCCColumnMapping = class private FList: TList; function GetCount: integer; public constructor Create; destructor Destroy; procedure Add(ASourceField,ADestinationField: string); function GetItemMapping(i: integer): PCCFieldMapRecord; property Count: integer read GetCount; end; TCCSQLBulkCopy = class private FSourceConnection: ICCDataset; FDestinationTableName: string; FSourceTableName: string; FColumnMapping: TCCColumnMapping; FSQL: string; public constructor Create(ADBConnection: ICCDataset); destructor Destroy; procedure WriteToServer(ADBDestination: ICCDataset);overload; procedure WriteToServer;overload; procedure CollectData; //column mapping property ColumnMapping: TCCColumnMapping read FColumnMapping write FColumnMapping; //destination table name property DestinationTableName: string read FDestinationTableName write FDestinationTableName; //source table name property SourceTableName: string read FSourceTableName write FSourceTableName; end; implementation { TCCSQLBulkCopy } procedure TCCSQLBulkCopy.CollectData; var sSourceColumn,sDestinationColumn: string; ssql1: string; i: integer; ABulkInsert: TCCBulkInsert; ADatasetReader: TDatasetReader; begin FSQL := ''; ABulkInsert := TCCBulkInsert.Create; try for i := 0 to FColumnMapping.Count - 1 do begin sSourceColumn := sSourceColumn + FColumnMapping.GetItemMapping(i).SourceField + ','; ABulkInsert.ColumnNames.Add(FColumnMapping.GetItemMapping(i).DestinationField); end; Delete(sSourceColumn,Length(sSourceColumn),1); Delete(sDestinationColumn,Length(sDestinationColumn),1); FSourceConnection.OpenQuery(Format('select %s from %s',[sSourceColumn,FSourceTableName])); FSourceConnection.getDataset.First; ABulkInsert.SingleStatement := True; ABulkInsert.Tablename := DestinationTableName; ABulkInsert.StartRow := 0; ABulkInsert.StartCol := 0; ABulkInsert.UpdateIfRecordExists := False; ADatasetReader := TDatasetReader.Create; ABulkInsert.Reader := ADatasetReader; ABulkInsert.ObjectSource := FSourceConnection.getDataset; FSQL := ABulkInsert.getSQL; finally FreeAndNil(ABulkInsert); end; end; constructor TCCSQLBulkCopy.Create(ADBConnection: ICCDataset); begin FSourceConnection := ADBConnection; FColumnMapping := TCCColumnMapping.Create; FSQL := ''; end; procedure TCCSQLBulkCopy.WriteToServer(ADBDestination: ICCDataset); begin if Trim(FSQL) = '' then CollectData; ADBDestination.ExecuteNonQuery(FSQL); end; destructor TCCSQLBulkCopy.Destroy; begin FreeAndNil(FColumnMapping); end; procedure TCCSQLBulkCopy.WriteToServer; begin WriteToServer(FSourceConnection); end; { TCCColumnMapping } procedure TCCColumnMapping.Add(ASourceField, ADestinationField: string); var AMap: PCCFieldMapRecord; begin new(AMap); // AMap := TCCFieldMapRecord.Create; AMap.SourceField := ASourceField; AMap.DestinationField := ADestinationField; FList.Add(AMap); end; constructor TCCColumnMapping.Create; begin FList := TList.Create; end; destructor TCCColumnMapping.Destroy; begin FreeAndNil(FList); end; function TCCColumnMapping.GetCount: integer; begin Result := FList.Count; end; function TCCColumnMapping.GetItemMapping(i: integer): PCCFieldMapRecord; begin Result := PCCFieldMapRecord(FList[i]); end; end. //love u my little angle caca :) :*
unit StringValidators; interface // String validators ----------------------------------------------------------- const csSpecial = ['-', ' ', '''', '.']; csDigit = ['0'..'9']; csLetterU = ['A'..'Z']; csLetterL = ['a'..'z']; csAccentedL = ['á', 'à', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç']; csAccentedU = ['Á', 'À', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç']; csLetter = csLetterU + csLetterL + csAccentedU + csAccentedL; csCodeSet = csLetter + csDigit; csNameSet = csLetter + csDigit + csSpecial; function ValidStationCode(AString: String): Boolean; // pre: True // ret: AString in csCodeSet+ function ValidStationName(AString: String): Boolean; // pre: True // ret: AString in csNameSet+ function ValidLineCode(AString: String): Boolean; // pre: True // ret: AString in csCodeSet+ function ValidLineName(AString: String): Boolean; // pre: True // ret: AString in csNameSet+ function ValidMapName(AString: String): Boolean; // pre: True // post: AString in csNameSet+ function ValidNetworkName(AString: String): Boolean; // pre: True // ret: Astring in csNameSet+ function ValidLandmarkCode(AString: String): Boolean; // pre: True // ret: Astring in csCodeSet+ function ValidTextCode(AString: String): Boolean; // pre: True // ret: Astring in csCodeSet+ implementation type TCharSet = set of Char; function AuxValid(AString: String; ACharSet: TCharSet): Boolean; // ret: AString in ACharSet+ var I: Integer; begin Result := Length(AString) > 0; for I := 1 to Length(AString) do if not (AString[I] in ACharSet) then Result := False; end; function ValidStationCode(AString: String): Boolean; // ret: AString in csCodeSet+ begin Result := AuxValid(AString, csCodeSet); end; function ValidStationName(AString: String): Boolean; // ret: AString in csNameSet+ begin Result := AuxValid(AString, csNameSet); end; function ValidLineCode(AString: String): Boolean; // ret: AString in csCodeSet+ begin Result := AuxValid(AString, csCodeSet); end; function ValidLineName(AString: String): Boolean; // ret: AString in csNameSet+ begin Result := AuxValid(AString, csNameSet); end; function ValidMapName(AString: String): Boolean; // ret: AString in csNameSet+ begin Result := AuxValid(AString, csNameSet); end; function ValidNetworkName(AString: String): Boolean; // ret: AString in csNameSet+ begin Result := AuxValid(AString, csNameSet); end; function ValidLandmarkCode(AString: String): Boolean; // ret: AString in csCodeSet+ begin Result := AuxValid(AString, csCodeSet); end; function ValidTextCode(AString: String): Boolean; // ret: AString in csCodeSet+ begin Result := AuxValid(AString, csCodeSet); end; end.
unit classXTaxTable; interface uses XMLWorks2, Classes; type TXTaxLkpCollectionItem = class(TXMLCollectionItem) private FIncomeFrom: currency; FIncomeTo: currency; FTaxAmt: currency; FTaxPerc: integer; FIsOver65: boolean; FIsAnnual: boolean; procedure SetIncomeFrom(const Value: currency); procedure SetIncomeTo(const Value: currency); procedure SetTaxAmt(const Value: currency); procedure SetTaxPerc(const Value: integer); published property IncomeFrom : currency read FIncomeFrom write SetIncomeFrom; property IncomeTo : currency read FIncomeTo write SetIncomeTo; property TaxAmt : currency read FTaxAmt write SetTaxAmt; property TaxPerc : integer read FTaxPerc write SetTaxPerc; end; type TXTaxTableCollection = class(TXMLCollection) private FRebate65: currency; FRebatePrim: currency; FTaxYear: integer; FIsOver65: boolean; FIsAnnual: boolean; procedure SetRebate65(const Value: currency); procedure SetRebatePrim(const Value: currency); procedure SetTaxYear(const Value: integer); function LocateTaxLkp(cTaxIncome : Currency) : TXTaxLkpCollectionItem; procedure SetIsAnnual(const Value: boolean); procedure SetIsOver65(const Value: boolean); public property IsOver65 : boolean read FIsOver65 write SetIsOver65; property IsAnnual : boolean read FIsAnnual write SetIsAnnual; procedure ImportTextTable(sFileName : string); function LookupTax(cTaxable: Currency) : real; published property TaxYear : integer read FTaxYear write SetTaxYear; property RebatePrim : currency read FRebatePrim write SetRebatePrim; property Rebate65 : currency read FRebate65 write SetRebate65; end; var TheTaxTable : TXTaxTableCollection; implementation uses SysUtils, Math; { TXTaxLkpCollectionItem } { TXTaxTable } procedure TXTaxTableCollection.ImportTextTable(sFileName: string); var aStrings : TStringList; aXTaxItem : TXTaxLkpCollectionItem; iIndex : integer; iPos : integer; begin if not FileExists(sFileName) then Abort; Clear; try aStrings := TStringList.Create; aStrings.LoadFromFile(sFileName); iPos := 0; for iIndex := 0 to aStrings.Count -1 do begin case iIndex of 0 : TaxYear := StrToInt(aStrings[iIndex]); 4 : RebatePrim := StrToCurr(aStrings[iIndex]); 5 : Rebate65 := StrToCurr(aStrings[iIndex]); 9..999 : if iPos = 0 then begin aXTaxItem := TXTaxLkpCollectionItem.Create(TheTaxTable); aXTaxItem.IncomeFrom := StrToCurr(aStrings[iIndex]); Inc(iPos); aXTaxItem.IncomeTo := StrToCurr(aStrings[iIndex+iPos]); Inc(iPos); aXTaxItem.TaxAmt := StrToCurr(aStrings[iIndex+iPos]); Inc(iPos); aXTaxItem.TaxPerc := StrToInt(aStrings[iIndex+iPos]); end else Dec(iPos); end; end; finally aStrings.Free; end; end; function TXTaxTableCollection.LocateTaxLkp( cTaxIncome: Currency): TXTaxLkpCollectionItem; var iIndex : integer; begin for iIndex := 0 to Self.Count-1 do begin Result := TXTaxLkpCollectionItem(Items[iIndex]); if (cTaxIncome >= Result.IncomeFrom) and (cTaxIncome <= Result.IncomeTo) then exit; end; end; function TXTaxTableCollection.LookupTax(cTaxable: Currency): real; var iIndex : integer; aTaxLkp : TXTaxLkpCollectionItem; cAnnualInc : Currency; 6begin Result := -1; if IsAnnual then cAnnualInc := cTaxable else cAnnualInc := cTaxable * 12; if (((cAnnualInc >= Self.RebatePrim) and (not IsOver65)) or ((cAnnualInc >= Self.Rebate65) and (IsOver65))) then begin aTaxLkp := LocateTaxLkp(cAnnualInc); Result := aTaxLkp.TaxAmt; Result := Result + ((cAnnualInc - aTaxLkp.IncomeFrom -1) * aTaxLkp.TaxPerc / 100); Result := Result - Self.RebatePrim; if IsOver65 then Result := Result - Self.Rebate65; if not IsAnnual then Result := Result / 12; end else Result := 0; if Result < 0 then Result := 0; end; procedure TXTaxTableCollection.SetIsAnnual(const Value: boolean); begin FIsAnnual := Value; end; procedure TXTaxTableCollection.SetIsOver65(const Value: boolean); begin FIsOver65 := Value; end; procedure TXTaxTableCollection.SetRebate65(const Value: currency); begin FRebate65 := Value; end; procedure TXTaxTableCollection.SetRebatePrim(const Value: currency); begin FRebatePrim := Value; end; procedure TXTaxTableCollection.SetTaxYear(const Value: integer); begin FTaxYear := Value; end; { TXTaxLkpCollectionItem } procedure TXTaxLkpCollectionItem.SetIncomeFrom(const Value: currency); begin FIncomeFrom := Value; end; procedure TXTaxLkpCollectionItem.SetIncomeTo(const Value: currency); begin FIncomeTo := Value; end; procedure TXTaxLkpCollectionItem.SetTaxAmt(const Value: currency); begin FTaxAmt := Value; end; procedure TXTaxLkpCollectionItem.SetTaxPerc(const Value: integer); begin FTaxPerc := Value; end; initialization TheTaxTable := TXTaxTableCollection.Create(TXTaxLkpCollectionItem); finalization TheTaxTable.Clear; TheTaxTable.Free; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Teradata metadata } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.TDataMeta; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Consts, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator; type TFDTDataSessionMode = (tmTeradata, tmANSI); /// <summary> IFDPhysTDataConnectionMetadata interface provides FireDAC Teradata /// driver specific metadata extension. </summary> IFDPhysTDataConnectionMetadata = interface (IUnknown) ['{CB231063-11DB-4E0D-A8FF-C25795997A1C}'] // private function GetSessionMode: TFDTDataSessionMode; // public property SessionMode: TFDTDataSessionMode read GetSessionMode; end; /// <summary> TFDPhysTDataMetadata class implements FireDAC Teradata /// driver specific metadata provider. </summary> TFDPhysTDataMetadata = class (TFDPhysConnectionMetadata, IFDPhysTDataConnectionMetadata) private FColumnOriginProvided: Boolean; FSessionMode: TFDTDataSessionMode; FCharacterSet: String; protected // IFDPhysConnectionMetadata function GetKind: TFDRDBMSKind; override; function GetTxAtomic: Boolean; override; function GetIdentityInsertSupported: Boolean; override; function GetInlineRefresh: Boolean; override; function GetIdentityInWhere: Boolean; override; function GetParamNameMaxLength: Integer; override; function GetNameParts: TFDPhysNameParts; override; function GetNameQuotedCaseSensParts: TFDPhysNameParts; override; function GetDefValuesSupported: TFDPhysDefaultValues; override; function GetSelectOptions: TFDPhysSelectOptions; override; function GetAsyncAbortSupported: Boolean; override; function GetAsyncNativeTimeout: Boolean; override; function GetArrayExecMode: TFDPhysArrayExecMode; override; function GetColumnOriginProvided: Boolean; override; procedure DefineMetadataStructure(ATable: TFDDatSTable; AKind: TFDPhysMetaInfoKind); override; function GetResultSetFields(const ASQLKey: String): TFDDatSView; override; function InternalEscapeBoolean(const AStr: String): String; override; function InternalEscapeDate(const AStr: String): String; override; function InternalEscapeDateTime(const AStr: String): String; override; function InternalEscapeFloat(const AStr: String): String; override; function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override; function InternalEscapeTime(const AStr: String): String; override; function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override; // IFDPhysTDataConnectionMetadata function GetSessionMode: TFDTDataSessionMode; public constructor Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String; AColumnOriginProvided: Boolean; ASessionMode: TFDTDataSessionMode; const ACharacterSet: String); end; /// <summary> TFDPhysTDataCommandGenerator class implements FireDAC Teradata /// driver specific SQL command generator. </summary> TFDPhysTDataCommandGenerator = class(TFDPhysCommandGenerator) protected function GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; override; function GetPessimisticLock: String; override; function GetTruncate: String; override; function GetCall(const AName: String): String; override; function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String; AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds; AOverload: Word): String; override; function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; override; function GetColumnType(AColumn: TFDDatSColumn): String; override; function GetColumnDef(AColumn: TFDDatSColumn): String; override; function GetCreateTable(const ATab, ACols: String): String; override; function GetMerge(AAction: TFDPhysMergeAction): String; override; end; const C_FD_TDataINTO: String = '/*' + C_FD_SysNamePrefix + 'INTO'; implementation uses System.SysUtils, Data.DB, FireDAC.Stan.Util, FireDAC.Stan.Param; {-------------------------------------------------------------------------------} { TFDPhysTDataMetadata } {-------------------------------------------------------------------------------} constructor TFDPhysTDataMetadata.Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String; AColumnOriginProvided: Boolean; ASessionMode: TFDTDataSessionMode; const ACharacterSet: String); begin inherited Create(AConnectionObj, AServerVersion, AClientVersion, True); if ACSVKeywords <> '' then FKeywords.CommaText := ACSVKeywords; FColumnOriginProvided := AColumnOriginProvided; FSessionMode := ASessionMode; FCharacterSet := ACharacterSet; // OCTET_LENGTH for ASCII characters must return 1 if SameText(FCharacterSet, 'UTF16') then FCharacterSet := 'UTF8'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.Teradata; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetTxAtomic: Boolean; begin Result := FSessionMode = tmTeradata; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetIdentityInsertSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetInlineRefresh: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetIdentityInWhere: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetParamNameMaxLength: Integer; begin if GetServerVersion >= tvTData1410 then Result := 128 else Result := 30; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetNameParts: TFDPhysNameParts; begin Result := [npSchema, npBaseObject, npObject]; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetDefValuesSupported: TFDPhysDefaultValues; begin Result := dvDefVals; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetSelectOptions: TFDPhysSelectOptions; begin Result := [soWithoutFrom, soInlineView]; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetAsyncAbortSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetAsyncNativeTimeout: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetArrayExecMode: TFDPhysArrayExecMode; begin Result := aeOnErrorUndoAll; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetColumnOriginProvided: Boolean; begin Result := FColumnOriginProvided; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetSessionMode: TFDTDataSessionMode; begin Result := FSessionMode; end; {-------------------------------------------------------------------------------} procedure TFDPhysTDataMetadata.DefineMetadataStructure(ATable: TFDDatSTable; AKind: TFDPhysMetaInfoKind); begin inherited DefineMetadataStructure(ATable, AKind); case AKind of mkResultSetFields: begin AddMetadataCol(ATable, 'TABLE_NAME', dtWideString); AddMetadataCol(ATable, 'COLUMN_NAME', dtWideString); AddMetadataCol(ATable, 'ISIDENTITY', dtSByte); AddMetadataCol(ATable, 'HASDEFAULT', dtSByte); AddMetadataCol(ATable, 'IN_PKEY', dtSByte); end; end; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.GetResultSetFields(const ASQLKey: String): TFDDatSView; begin Result := inherited GetResultSetFields(ASQLKey); Result.Mechanisms.AddSort('TABLE_NAME;COLUMN_NAME'); end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalEscapeBoolean(const AStr: String): String; begin if CompareText(AStr, S_FD_True) = 0 then Result := '1' else Result := '0'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalEscapeDate(const AStr: String): String; begin Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''') + ', ''YYYY-MM-DD'')'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalEscapeDateTime(const AStr: String): String; begin Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''') + ', ''YYYY-MM-DD HH24:MI:SS'')'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalEscapeTime(const AStr: String): String; begin Result := 'TIME ' + AnsiQuotedStr(AStr, ''''); end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalEscapeFloat(const AStr: String): String; begin Result := 'TO_NUMBER(' + AnsiQuotedStr(AStr, '''') + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; var sName: String; A1, A2, A3, A4: String; i: Integer; function AddArgs: string; begin Result := '(' + AddEscapeSequenceArgs(ASeq) + ')'; end; begin sName := ASeq.FName; if Length(ASeq.FArgs) >= 1 then begin A1 := ASeq.FArgs[0]; if Length(ASeq.FArgs) >= 2 then begin A2 := ASeq.FArgs[1]; if Length(ASeq.FArgs) >= 3 then A3 := ASeq.FArgs[2]; if Length(ASeq.FArgs) >= 4 then A4 := ASeq.FArgs[3]; end; end; case ASeq.FFunc of // the same // char efASCII, efCHAR_LENGTH, efLENGTH, // numeric efACOS, efASIN, efATAN, efATAN2, efABS, efCOS, efDEGREES, efEXP, efRADIANS, efSIN, efSQRT, efTAN: Result := sName + AddArgs; // character efBIT_LENGTH: begin Result := '(OCTET_LENGTH(' + A1; if FCharacterSet <> '' then Result := Result + ', ' + FCharacterSet; Result := Result + ') * 8)'; end; efCHAR: Result := 'CHR' + AddArgs; efCONCAT: Result := '((' + A1 + ') || (' + A2 + '))'; efINSERT: Result := '(SUBSTRING(' + A1 + ' FROM 1 FOR (' + A2 + ') - 1) || ' + A4 + ' || SUBSTRING(' + A1 + ' FROM (' + A2 + ' + ' + A3 + ')))'; efLCASE: Result := 'LOWER' + AddArgs; efLEFT: Result := 'SUBSTRING(' + A1 + ' FROM 1 FOR ' + A2 + ')'; efOCTET_LENGTH: begin Result := 'OCTET_LENGTH(' + A1; if FCharacterSet <> '' then Result := Result + ', ' + FCharacterSet; Result := Result + ')'; end; efPOSITION, efLOCATE: begin if Length(ASeq.FArgs) >= 3 then UnsupportedEscape(ASeq); Result := 'POSITION(' + A1 + ' IN ' + A2 + ')'; end; efLTRIM: Result := 'TRIM(LEADING FROM ' + A1 + ')'; efREPEAT: Result := 'CASE ' + ' WHEN ' + A2 + ' = 1 THEN ' + A1 + ' WHEN ' + A2 + ' = 2 THEN ' + A1 + ' || ' + A1 + ' WHEN ' + A2 + ' = 3 THEN ' + A1 + ' || ' + A1 + ' || ' + A1 + ' WHEN ' + A2 + ' = 4 THEN ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' WHEN ' + A2 + ' = 5 THEN ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' WHEN ' + A2 + ' = 6 THEN ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' WHEN ' + A2 + ' = 7 THEN ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' WHEN ' + A2 + ' = 8 THEN ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' || ' + A1 + ' ELSE '''' END'; efREPLACE: Result := 'OREPLACE' + AddArgs; efRIGHT: Result := 'SUBSTRING(' + A1 + ' FROM LENGTH(' + A1 + ') + 1 - (' + A2 + '))'; efRTRIM: Result := 'TRIM(TRAILING FROM ' + A1 + ')'; efSPACE: Result := 'SUBSTR('' '', 1, ' + A1 + ')'; efSUBSTRING: Result := 'SUBSTR' + AddArgs; efUCASE: Result := 'UPPER' + AddArgs; // numeric efCEILING: if GetServerVersion >= tvTData1400 then Result := 'CEIL' + AddArgs else UnsupportedEscape(ASeq); efCOT: Result := '(1 / TAN(' + A1 + '))'; efFLOOR: if GetServerVersion >= tvTData1400 then Result := 'FLOOR' + AddArgs else UnsupportedEscape(ASeq); efLOG: Result := 'LN' + AddArgs; efLOG10: Result := 'LOG' + AddArgs; efMOD: Result := '((' + A1 + ') MOD (' + A2 + '))'; efPOWER: Result := '((' + A1 + ') ** (' + A2 + '))'; efSIGN: Result := 'CASE WHEN ' + A1 + ' > 0 THEN 1 WHEN ' + A1 + ' < 0 THEN -1 ELSE 0 END'; efPI: Result := S_FD_Pi; efRANDOM: Result := 'RANDOM(0, 2147483647)'; efROUND: if GetServerVersion >= tvTData1400 then Result := 'ROUND' + AddArgs else Result := 'CAST(' + A1 + ', DECIMAL(18, ' + A2 + ')'; efTRUNCATE: Result := 'TRUNC' + AddArgs; // date and time efCURDATE: Result := 'CURRENT_DATE'; efCURTIME: Result := 'CURRENT_TIME'; efDAYNAME: Result := 'CAST(CAST(' + A1 + ' AS FORMAT''E4'') AS VARCHAR(10))'; efDAYOFMONTH: Result := 'EXTRACT(DAY FROM ' + A1 + ')'; efDAYOFWEEK: Result := '(((' + A1 + ') - DATE ''1900-01-01'' + 2) MOD 7)'; efDAYOFYEAR: Result := '((' + A1 + ') - CAST(TRIM(EXTRACT(YEAR FROM ' + A1 + ')) || ''/01/01'' AS DATE FORMAT ''YYYY/MM/DD'') + 1)'; efEXTRACT: Result := 'EXTRACT(' + UpperCase(FDUnquote(Trim(A1), '''')) + ' FROM ' + A2 + ')'; efHOUR: Result := 'EXTRACT(HOUR FROM ' + A1 + ')'; efMINUTE: Result := 'EXTRACT(MINUTE FROM ' + A1 + ')'; efMONTH: Result := 'EXTRACT(MONTH FROM ' + A1 + ')'; efMONTHNAME: Result := 'CAST(CAST(' + A1 + ' AS FORMAT''M4'') AS VARCHAR(10))'; efNOW: Result := 'CURRENT_TIMESTAMP'; efQUARTER: Result := 'CAST(EXTRACT(MONTH FROM ' + A1 + ') / 3 + 1 AS INTEGER)'; efSECOND: Result := 'EXTRACT(SECOND FROM ' + A1 + ')'; efWEEK: Result := '(((' + A1 + ') - ((EXTRACT(YEAR FROM (' + A1 + ')) - 1900) * 10000 + 0101 (DATE))) - (((' + A1 + ') - DATE ''0001-01-07'') MOD 7) + 13) / 7'; efYEAR: Result := 'EXTRACT(YEAR FROM ' + A1 + ')'; efTIMESTAMPADD: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); A2 := Trim(A2); if A1 = 'YEAR' then Result := 'ADD_MONTHS(' + A3 + ', 12 * (' + A2 + '))' else if A1 = 'MONTH' then Result := 'ADD_MONTHS(' + A3 + ', ' + A2 + ')' else if A1 = 'WEEK' then Result := '(' + A3 + ' + INTERVAL ''' + IntToStr(StrToInt(A2) * 7) + ''' DAY)' else if A1 = 'DAY' then Result := '(' + A3 + ' + INTERVAL ''' + A2 + ''' DAY)' else if A1 = 'HOUR' then Result := '(' + A3 + ' + INTERVAL ''' + A2 + ''' HOUR)' else if A1 = 'MINUTE' then Result := '(' + A3 + ' + INTERVAL ''' + A2 + ''' MINUTE)' else if A1 = 'SECOND' then Result := '(' + A3 + ' + INTERVAL ''' + A2 + ''' SECOND)' else if A1 = 'FRAC_SECOND' then Result := '(' + A3 + ' + INTERVAL ''' + A2 + ''' FRACTION)' else UnsupportedEscape(ASeq); end; efTIMESTAMPDIFF: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'YEAR' then Result := 'CAST(((' + A3 + ') - (' + A2 + ') YEAR(4)) AS INTEGER)' else if A1 = 'MONTH' then Result := 'CAST(((' + A3 + ') - (' + A2 + ') MONTH(3)) AS INTEGER)' else if A1 = 'WEEK' then Result := 'CAST(((' + A3 + ') - (' + A2 + ')) / 7 AS INTEGER)' else if A1 = 'DAY' then Result := 'CAST((' + A3 + ') - (' + A2 + ') AS INTEGER)' else if A1 = 'HOUR' then Result := 'CAST(((' + A3 + ') - (' + A2 + ')) * 24.0 AS INTEGER)' else if A1 = 'MINUTE' then Result := 'CAST(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0) AS INTEGER)' else if A1 = 'SECOND' then Result := 'CAST(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0) AS INTEGER)' else if A1 = 'FRAC_SECOND' then Result := 'CAST(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0 * 1000000.0) AS INTEGER)' else UnsupportedEscape(ASeq); end; // system efCATALOG: Result := ''''''; efSCHEMA: Result := 'USER'; efIFNULL: Result := 'CASE WHEN ' + A1 + ' IS NULL THEN ' + A2 + ' ELSE ' + A1 + ' END'; efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END'; efDECODE: begin Result := 'CASE ' + ASeq.FArgs[0]; i := 1; while i < Length(ASeq.FArgs) - 1 do begin Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1]; Inc(i, 2); end; if i = Length(ASeq.FArgs) - 1 then Result := Result + ' ELSE ' + ASeq.FArgs[i]; Result := Result + ' END'; end; // convert efCONVERT: begin A2 := UpperCase(FDUnquote(Trim(A2), '''')); if A2 = 'BIT' then A2 := 'BYTEINT' else if A2 = 'BIGINT' then A2 := 'INTEGER' else if A2 = 'BINARY' then A2 := 'BYTE' else if A2 = 'GUID' then A2 := 'CHAR(38)' else if A2 = 'LONGVARBINARY' then A2 := 'VARBYTE' else if A2 = 'LONGVARCHAR' then A2 := 'LONG VARCHAR' else if A2 = 'VARBINARY' then A2 := 'VARBYTE' else if A2 = 'WCHAR' then A2 := 'CHAR CHARACTER SET UNICODE' else if A2 = 'WLONGVARCHAR' then A2 := 'LONG VARCHAR CHARACTER SET UNICODE' else if A2 = 'WVARCHAR' then A2 := 'VARCHAR CHARACTER SET UNICODE' else if A2 = 'DATETIME' then A2 := 'TIMESTAMP'; Result := 'CAST(' + A1 + ' AS ' + A2 + ')'; end; else UnsupportedEscape(ASeq); end; end; {-------------------------------------------------------------------------------} function TFDPhysTDataMetadata.InternalGetSQLCommandKind( const ATokens: TStrings): TFDPhysCommandKind; var sToken: String; begin sToken := ATokens[0]; if (sToken = 'CALL') or (sToken = 'EXECUTE') then Result := skExecute else if sToken = 'BEGIN' then if ATokens.Count = 1 then Result := skNotResolved else if ATokens[1] = 'TRANSACTION' then Result := skStartTransaction else Result := skOther else if sToken = 'BT' then Result := skStartTransaction else if sToken = 'END' then if ATokens.Count = 1 then Result := skNotResolved else if ATokens[1] = 'TRANSACTION' then Result := skCommit else Result := skOther else if sToken = 'ET' then Result := skCommit else if sToken = 'ABORT' then Result := skRollback else if sToken = 'DATABASE' then Result := skSetSchema else if (sToken = 'SHOW') or (sToken = 'HELP') or (sToken = 'SEL') or (sToken = 'EXPLAIN') then Result := skSelect else if sToken = 'LOCKING' then Result := skSelectForLock else if (sToken = 'REPLACE') or (sToken = 'MODIFY') then Result := skAlter else if sToken = 'DEL' then Result := skDelete else if sToken = 'UPSERT' then Result := skMerge else Result := inherited InternalGetSQLCommandKind(ATokens); end; {-------------------------------------------------------------------------------} { TFDPhysTDataCommandGenerator } {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; var sRet, sCol: String; oView: TFDDatSView; oCols: TFDDatSColumnList; oRow: TFDDatSRow; oCol: TFDDatSColumn; i, j: Integer; rName: TFDPhysParsedName; lFound, lIdentity: Boolean; begin lFound := False; lIdentity := True; sRet := ''; oCols := FTable.Columns; FConnMeta.DecodeObjName(GetFrom(), rName, nil, [doUnquote, doNormalize]); oView := FConnMeta.GetResultSetFields(rName.FObject); try oView.Sort := 'RECNO'; for i := 0 to oView.Rows.Count - 1 do begin oRow := oView.Rows[i]; sCol := ''; for j := 0 to oCols.Count - 1 do begin oCol := oCols[j]; if ColumnStorable(oCol) and ColumnReqRefresh(ARequest, oCol) and (CompareText(FConnMeta.UnQuoteObjName(oCol.OriginTabName), oRow.GetData('TABLE_NAME')) = 0) and (CompareText(FConnMeta.UnQuoteObjName(oCol.OriginColName), oRow.GetData('COLUMN_NAME')) = 0) then begin lFound := True; if not (caAutoInc in oCol.ActualAttributes) then lIdentity := False; sCol := oCol.SourceName; Break; end; end; if sRet <> '' then sRet := sRet + ';'; sRet := sRet + sCol; end; finally FDClearMetaView(oView, FOptions.FetchOptions); end; Result := AStmt; if lFound then begin Result := Result + BRK + C_FD_TDataINTO + ' '; if lIdentity then Result := Result + '# ' else Result := Result + '* '; Result := Result + sRet + '*/'; FCommandKind := skSelectForLock; end; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetPessimisticLock: String; var lNeedFrom: Boolean; begin Result := 'LOCKING ROW FOR WRITE '; if not FOptions.UpdateOptions.LockWait then Result := Result + 'MODE NOWAIT '; Result := Result + BRK + 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK + 'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False); FCommandKind := skSelectForLock; ASSERT(lNeedFrom); end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetTruncate: String; begin Result := 'DELETE FROM ' + GetFrom + ' ALL'; FCommandKind := skDelete; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetCall(const AName: String): String; begin Result := 'CALL ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String; AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds; AOverload: Word): String; var oParam: TFDParam; oTDataConnMeta: IFDPhysTDataConnectionMetadata; begin case AKind of mkResultSetFields: begin Supports(FConnMeta, IFDPhysTDataConnectionMetadata, oTDataConnMeta); Result := 'SELECT CAST(NULL AS INTEGER) AS RECNO, UPPER(TRIM(TRAILING FROM C.TableName)) AS RESULTSET_KEY, ' + 'TRIM(TRAILING FROM C.TableName) AS TABLE_NAME, TRIM(TRAILING FROM C.ColumnName) AS COLUMN_NAME, ' + 'CASE WHEN C.IdColType = ''GA'' OR C.IdColType = ''GD'' THEN 1 ELSE 0 END AS ISIDENTITY, ' + 'CASE WHEN C.DefaultValue IS NOT NULL THEN 1 ELSE 0 END AS HASDEFAULT, ' + 'CASE WHEN I.ColumnPosition IS NOT NULL THEN 1 ELSE 0 END AS IN_PKEY ' + 'FROM DBC.ColumnsX C LEFT OUTER JOIN DBC.IndicesX I ON ' + 'C.DatabaseName = I.DatabaseName AND ' + 'C.TableName = I.TableName AND ' + 'C.ColumnName = I.ColumnName AND ' + 'I.IndexType = ''K'' ' + 'WHERE '; if oTDataConnMeta.SessionMode = tmTeradata then Result := Result + 'C.DatabaseName = DATABASE AND C.TableName = ? ' else Result := Result + 'UPPER(C.DatabaseName) = UPPER(DATABASE) AND UPPER(C.TableName) = UPPER(?) '; Result := Result + 'ORDER BY C.ColumnID'; oParam := GetParams.Add; oParam.Name := 'OBJ'; oParam.DataType := ftString; oParam.Size := 128; end; else Result := inherited GetSelectMetaInfo(AKind, ACatalog, ASchema, ABaseObject, AObject, AWildcard, AObjectScopes, ATableKinds, AOverload); end; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; var s: String; iAfter: Integer; begin if (ASkip + ARows <> MAXINT) and FDStartsWithKW(ASQL, 'SELECT', iAfter) and not FDStartsWithKW(ASQL, 'SELECT TOP', iAfter) then begin Result := 'SELECT TOP '; s := UpperCase(ASQL); // Teradata: does not support TOP 0 and returns "syntax error" if ARows = 0 then Result := 'SELECT * FROM (' + BRK + ASQL + BRK + ') A' + BRK + 'WHERE 0 = 1' else if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or FDHasKW(s, 'EXCEPT') or FDHasKW(s, 'DISTINCT') then if GetSQLOrderByPos > 0 then Result := Result + IntToStr(ASkip + ARows) + ' * FROM (' + BRK + Copy(ASQL, 1, GetSQLOrderByPos - 1) + BRK + ') A' + BRK + Copy(ASQL, GetSQLOrderByPos, MAXINT) else Result := Result + IntToStr(ASkip + ARows) + ' * FROM (' + BRK + ASQL + BRK + ') A' else Result := Result + IntToStr(ASkip + ARows) + Copy(ASQL, iAfter, MAXINT); end else begin Result := ASQL; AOptions := []; end; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String; begin case AColumn.DataType of dtBoolean: Result := 'BYTEINT'; dtSByte: Result := 'BYTEINT'; dtInt16, dtByte: Result := 'SMALLINT'; dtInt32, dtUInt16: Result := 'INTEGER'; dtUInt32: Result := 'DECIMAL(10, 0)'; dtInt64: Result := 'DECIMAL(19, 0)'; dtUInt64: Result := 'DECIMAL(20, 0)'; dtSingle, dtDouble, dtExtended: Result := 'FLOAT'; dtCurrency: Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, 18, 4); dtBCD, dtFmtBCD: Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, FOptions.FormatOptions.MaxBcdPrecision, 0); dtDateTime, dtDateTimeStamp: Result := 'TIMESTAMP'; dtTime: Result := 'TIME'; dtDate: Result := 'DATE'; dtTimeIntervalYM: Result := 'INTERVAL YEAR TO MONTH'; dtTimeIntervalFull, dtTimeIntervalDS: Result := 'INTERVAL DAY TO SECOND'; dtAnsiString: begin if caFixedLen in AColumn.ActualAttributes then Result := 'CHAR' else Result := 'VARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtWideString: begin if caFixedLen in AColumn.ActualAttributes then Result := 'CHAR' else Result := 'VARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1) + ' CHARACTER SET UNICODE'; end; dtByteString: begin if caFixedLen in AColumn.ActualAttributes then Result := 'BYTE' else Result := 'VARBYTE'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtBlob, dtHBlob, dtHBFile: Result := 'BLOB'; dtMemo, dtHMemo: Result := 'CLOB'; dtWideMemo, dtWideHMemo: Result := 'CLOB CHARACTER SET UNICODE'; dtXML: if FConnMeta.ServerVersion >= tvTData1300 then Result := 'XML' else Result := 'CLOB CHARACTER SET UNICODE'; dtGUID: Result := 'CHAR(38)'; dtUnknown, dtRowSetRef, dtCursorRef, dtRowRef, dtArrayRef, dtParentRowRef, dtObject: Result := ''; end; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetColumnDef(AColumn: TFDDatSColumn): String; begin Result := inherited GetColumnDef(AColumn); if (Result <> '') and (caAutoInc in AColumn.ActualAttributes) then Result := Result + ' GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1 NO CYCLE)'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetCreateTable(const ATab, ACols: String): String; begin Result := 'CREATE MULTISET TABLE ' + ATab + ' (' + BRK + ACols + BRK + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysTDataCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String; begin case AAction of maInsertUpdate: Result := GenerateUpdate() + BRK + 'ELSE ' + GenerateInsert(); maInsertIgnore: Result := inherited GetMerge(AAction); end; end; {-------------------------------------------------------------------------------} initialization FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.Teradata, S_FD_TData_RDBMS); end.
unit SearchBodyVariationQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap; type TSearchBodyVariationW = class(TDSWrap) private FIDBody: TFieldWrap; FIDBodyData: TFieldWrap; FIDBodyKind: TFieldWrap; FIDS: TFieldWrap; FVariations: TFieldWrap; public constructor Create(AOwner: TComponent); override; property IDBody: TFieldWrap read FIDBody; property IDBodyData: TFieldWrap read FIDBodyData; property IDBodyKind: TFieldWrap read FIDBodyKind; property IDS: TFieldWrap read FIDS; property Variations: TFieldWrap read FVariations; end; TQrySearchBodyVariation = class(TQueryBase) private FW: TSearchBodyVariationW; { Private declarations } public constructor Create(AOwner: TComponent); override; function SearchVariation(const ABodyVariation: String): Integer; property W: TSearchBodyVariationW read FW; { Public declarations } end; implementation uses StrHelper; constructor TSearchBodyVariationW.Create(AOwner: TComponent); begin inherited; FIDS := TFieldWrap.Create(Self, 'IDS', '', True); FIDBodyData := TFieldWrap.Create(Self, 'IDBodyData'); FVariations := TFieldWrap.Create(Self, 'Variations'); FIDBody := TFieldWrap.Create(Self, 'IDBody'); FIDBodyKind := TFieldWrap.Create(Self, 'IDBodyKind'); end; constructor TQrySearchBodyVariation.Create(AOwner: TComponent); begin inherited; FW := TSearchBodyVariationW.Create(FDQuery); end; function TQrySearchBodyVariation.SearchVariation(const ABodyVariation: String): Integer; begin Assert(not ABodyVariation.IsEmpty); Result := SearchEx([TParamrec.Create(W.Variations.FullName, '%,' + ABodyVariation + ',%', ftWideString, True, 'like')]); end; {$R *.dfm} end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSHosting.EdgePayload; {$HPPEMIT LINKUNIT} interface uses System.Classes, System.SysUtils, System.Generics.Collections; type TStringKeyValue = TPair<string, string>; TStringKeyValues = TArray<TStringKeyValue>; IEdgeRequest = interface ['{561B2566-0DEA-40B9-9E6D-9588A9102A37}'] function GetMethod: string; function GetPath: string; function GetSessionToken: string; function GetQuery: TStringKeyValues; function GetBasePath: string; function GetServerHost: string; function GetTenantId: string; property Method: string read GetMethod; property Path: string read GetPath; property Query: TStringKeyValues read GetQuery; property SessionToken: string read GetSessionToken; property BasePath: string read GetBasePath; property ServerHost: string read GetServerHost; property TenantId: string read GetTenantId; end; TEdgeRequest = class(TInterfacedObject, IEdgeRequest) private FMethod: string; FPath: string; FBasePath: string; FServerHost: string; FSessionToken: string; FTenantId: string; FQuery: TStringKeyValues; protected function GetMethod: string; function GetPath: string; function GetSessionToken: string; function GetQuery: TStringKeyValues; function GetBasePath: string; function GetServerHost: string; function GetTenantId: string; public constructor Create(const AMethod, AServerhost, ABasePath, APath: string; const AQuery: TStringKeyValues; const ASessionToken, ATenantId: string); end; IEdgeRequestReader = interface ['{FDC7D9B1-DCE8-4D97-98B7-3CBB5E9B9636}'] function ReadRequest: IEdgeRequest; function ReadContentType(out AContentType: string; out AContentLength: Integer): Boolean; procedure ReadContent(const ALength: Integer; out ABody: string); overload; procedure ReadContent(const ALength: Integer; out ABytes: TBytes); overload; procedure ReadContent(const ALength: Int64; const AStream: TStream); overload; end; IEdgeResponse = interface ['{7DDF5C07-A4DD-481A-99C8-4AAB309C9E57}'] function GetStatusCode: UInt16; function GetStatusText: string; property StatusCode: UInt16 read GetStatusCode; property StatusText: string read GetStatusText; end; TEdgeResponse = class(TInterfacedObject, IEdgeResponse) private FStatusText: string; FStatusCode: UInt16; function GetStatusText: string; function GetStatusCode: UInt16; public constructor Create(const AStatusCode: UInt16; const AStatusText: string); end; IEdgeResponseWriter = interface ['{91E2C804-A926-4F3D-A382-79855AB383E6}'] procedure WriteResponse(const AResponse: IEdgeResponse); procedure WriteContent(const AContentType, ABody: string); overload; procedure WriteContent(const AContentType: string; const AStream: TStream); overload; procedure WriteContent(const AContentType: string; const ABody: TBytes); overload; end; TEdgeVersion = record private FMajor: UInt8; FMinor: UInt8; public constructor Create(AMajor, AMinor: UInt8); property Minor: UInt8 read FMinor; property Major: UInt8 read FMajor; end; TEdgeReaderWriterFactory = class public type ICreateRequestReader = interface function TryCreateReader(const AVersion: TEdgeVersion; const AStream: TStream; out AReader: IEdgeRequestReader): Boolean; end; ICreateResponseWriter = interface function TryCreateWriter(const AVersion: TEdgeVersion; const AStream: TStream; out AReader: IEdgeResponseWriter): Boolean; end; private FRequestReaders: TDictionary<Integer, ICreateRequestReader>; FResponseWriters: TDictionary<Integer, ICreateResponseWriter>; private class var FInstance: TEdgeReaderWriterFactory; function ReadVersion(const AStream: TStream): TEdgeVersion; procedure RaiseDuplicate; procedure RaiseNotFound; var FID: Integer; public constructor Create; destructor Destroy; override; function RegisterRequestReader(const AReader: ICreateRequestReader): Integer; procedure UnregisterRequestReader(AID: Integer); function RegisterResponseWriter(const AWriter: ICreateResponseWriter): Integer; procedure UnregisterResponseWriter(AID: Integer); function TryCreateResponseWriter(const AStream: TStream; out AWriter: IEdgeResponseWriter; const AVersion: TEdgeVersion): Boolean; overload; function TryCreateResponseWriter(const AStream: TStream; out AWriter: IEdgeResponseWriter): Boolean; overload; function TryCreateRequestReader(const AStream: TStream; out AReader: IEdgeRequestReader): Boolean; function CreateResponseWriter(const AStream: TStream; const AVersion: TEdgeVersion): IEdgeResponseWriter; overload; function CreateResponseWriter(const AStream: TStream): IEdgeResponseWriter; overload; function CreateRequestReader(const AStream: TStream): IEdgeRequestReader; class property Instance: TEdgeReaderWriterFactory read FInstance; end; TEdgeStreamReader = class private FStream: TStream; procedure RaiseContentError; procedure RaiseReadEOFError; public constructor Create(const AStream: TStream); function ReadVersion: TEdgeVersion; function ReadShortUInt: UInt16; function ReadUInt: UInt32; function ReadShortString: string; function ReadStringKeyValues: TStringKeyValues; function CanReadShortString: Boolean; procedure ReadBytes(const ABytes: TBytes; AOffset: Integer); overload; procedure ReadBytes(const ABytes: TBytes); overload; procedure ReadStream(const AStream: TStream; ACount: Int64); overload; function CanRead(ACount: Integer): Boolean; property Stream: TStream read FStream; end; TEdgeStreamWriter = class private FStream: TStream; public constructor Create(const AStream: TStream); procedure WriteVersion(const AVersion: TEdgeVersion); procedure WriteShortUInt(ALength: UInt16); procedure WriteUInt(ALength: UInt32); procedure WriteStringKeyValues(const APairs: TStringKeyValues); procedure WriteShortString(const AValue: string); procedure WriteBytes(const ABytes: TBytes); procedure WriteStream(const AStream: TStream); property Stream: TStream read FStream; end; EEdgeReadError = class(Exception); EEdgeReaderWriterFactoryError = class(Exception); EEdgeReaderVersionError = class(Exception); const EdgePayloadVersion10: TEdgeVersion = (FMajor: 1; FMinor: 0); EdgePayloadVersion20: TEdgeVersion = (FMajor: 2; FMinor: 0); implementation { TStreamWriter } uses EMSHosting.Consts; constructor TEdgeStreamWriter.Create(const AStream: TStream); begin FStream := AStream; end; procedure TEdgeStreamWriter.WriteVersion(const AVersion: TEdgeVersion); var LVersion: string; LBytes: TBytes; begin LVersion := Format('%.2d.%.2d', [AVersion.Major, AVersion.Minor]); Assert(Length(LVersion) = 5); LBytes := TEncoding.UTF8.GetBytes(LVersion); Assert(Length(LBytes) = 5); FStream.Write(LBytes, Length(LBytes)); end; procedure TEdgeStreamWriter.WriteShortString(const AValue: string); var LBytes: TBytes; begin LBytes := TEncoding.UTF8.GetBytes(AValue); WriteShortUInt(Length(LBytes)); Stream.Write(LBytes, 0, Length(LBytes)); end; procedure TEdgeStreamWriter.WriteStringKeyValues(const APairs: TStringKeyValues); var LPair: TStringKeyValue; begin WriteShortUInt(Length(APairs)); for LPair in APairs do begin WriteShortString(LPair.Key); WriteShortString(LPair.Value); end; end; procedure TEdgeStreamWriter.WriteShortUInt(ALength: UInt16); var LBuffer: TBytes; begin LBuffer := TEncoding.UTF8.GetBytes(IntToHex(ALength, 4)); Assert(Length(LBuffer) = 4); Stream.Write(LBuffer, 0, Length(LBuffer)); end; procedure TEdgeStreamWriter.WriteStream(const AStream: TStream); begin WriteUInt(AStream.Size); Stream.CopyFrom(AStream, AStream.Size) end; procedure TEdgeStreamWriter.WriteBytes(const ABytes: TBytes); begin WriteUInt(Length(ABytes)); Stream.Write(ABytes, 0, Length(ABytes)); end; procedure TEdgeStreamWriter.WriteUInt(ALength: UInt32); var LBuffer: TBytes; begin LBuffer := TEncoding.UTF8.GetBytes(IntToHex(ALength, 8)); Assert(Length(LBuffer) = 8); Stream.Write(LBuffer, 0, Length(LBuffer)); end; { TStreamReader } function TEdgeStreamReader.CanRead(ACount: Integer): Boolean; begin Result := FStream.Position + ACount <= FStream.Size; end; constructor TEdgeStreamReader.Create(const AStream: TStream); begin FStream := AStream; end; function TEdgeStreamReader.ReadVersion: TEdgeVersion; var LBuffer: TBytes; LMajor: Integer; LMinor: Integer; begin SetLength(LBuffer, 5); try ReadBytes(LBuffer); except RaiseContentError; end; if LBuffer[2] <> Byte('.') then RaiseContentError; if not TryStrToInt(TEncoding.UTF8.GetString(LBuffer, 0, 2), LMajor) then RaiseContentError; if (LMajor <= 0) and (LMajor >= 256) then RaiseContentError; if not TryStrToInt(TEncoding.UTF8.GetString(LBuffer, 3, 2), LMinor) then RaiseContentError; if (LMinor < 0) and (LMinor >= 256) then RaiseContentError; Result := TEdgeVersion.Create(LMajor, LMinor); end; procedure TEdgeStreamReader.RaiseReadEOFError; begin raise EEdgeReadError.Create(sEdgeEOFError); end; procedure TEdgeStreamReader.RaiseContentError; begin raise EEdgeReadError.Create(sEdgeContentError); end; procedure TEdgeStreamReader.ReadBytes(const ABytes: TBytes; AOffset: Integer); begin if FStream.Read(ABytes, AOffset, Length(ABytes)-AOffset) <> Length(ABytes) - AOffset then RaiseReadEOFError; end; procedure TEdgeStreamReader.ReadBytes(const ABytes: TBytes); begin ReadBytes(ABytes, 0); end; procedure TEdgeStreamReader.ReadStream(const AStream: TStream; ACount: Int64); begin if AStream.CopyFrom(FStream, ACount) < ACount then RaiseReadEOFError; end; function TEdgeStreamReader.CanReadShortString: Boolean; begin Result := CanRead(4); end; function TEdgeStreamReader.ReadShortString: string; var LLength: Integer; LBuffer: TBytes; begin LLength := ReadShortUInt; Assert(LLength >= 0); SetLength(LBuffer, LLength); ReadBytes(LBuffer); Result := TEncoding.UTF8.GetString(LBuffer); end; function TEdgeStreamReader.ReadShortUInt: UInt16; var LBuffer: TBytes; S: string; begin SetLength(LBuffer, 5); LBuffer[0] := Byte('$'); ReadBytes(LBuffer, 1); S := TEncoding.UTF8.GetString(LBuffer); Result := StrToInt(S); end; function TEdgeStreamReader.ReadUInt: UInt32; var LBuffer: TBytes; S: string; begin SetLength(LBuffer, 9); LBuffer[0] := Byte('$'); ReadBytes(LBuffer, 1); S := TEncoding.UTF8.GetString(LBuffer); Result := StrToInt(S); end; function TEdgeStreamReader.ReadStringKeyValues: TStringKeyValues; var LCount: Integer; I: Integer; LKey, LValue: string; begin LCount := ReadShortUInt; Assert(LCount >= 0); SetLength(Result, LCount); for I := 0 to LCount - 1 do begin LKey := ReadShortString; LValue := ReadShortString; Result[I] := TStringKeyValue.Create(LKey, LValue); end; end; { TReaderWriterFactory } constructor TEdgeReaderWriterFactory.Create; begin FRequestReaders := TDictionary<Integer, ICreateRequestReader>.Create; FResponseWriters := TDictionary<Integer, ICreateResponseWriter>.Create; end; destructor TEdgeReaderWriterFactory.Destroy; begin FRequestReaders.Free; FResponseWriters.Free; inherited; end; function TEdgeReaderWriterFactory.RegisterRequestReader( const AReader: ICreateRequestReader): Integer; begin Inc(FID); FRequestReaders.Add(FID, AReader); Result := FID; end; function TEdgeReaderWriterFactory.RegisterResponseWriter( const AWriter: ICreateResponseWriter): Integer; begin Inc(FID); FResponseWriters.Add(FID, AWriter); Result := FID; end; function TEdgeReaderWriterFactory.ReadVersion(const AStream: TStream): TEdgeVersion; begin AStream.Position := 0; with TEdgeStreamReader.Create(AStream) do try Result := ReadVersion; finally AStream.Position := 0; Free; end; end; procedure TEdgeReaderWriterFactory.RaiseDuplicate; begin raise EEdgeReaderWriterFactoryError.Create(sEdgeFactoryDuplicate); end; procedure TEdgeReaderWriterFactory.RaiseNotFound; begin raise EEdgeReaderWriterFactoryError.Create(sEdgeFactoryNotFound); end; function TEdgeReaderWriterFactory.TryCreateRequestReader(const AStream: TStream; out AReader: IEdgeRequestReader): Boolean; var LIntf: ICreateRequestReader; LVersion: TEdgeVersion; begin LVersion := ReadVersion(AStream); Result := False; for LIntf in FRequestReaders.Values do if LIntf.TryCreateReader(LVersion, AStream, AReader) then begin if Result then RaiseDuplicate; Result := True; end; end; function TEdgeReaderWriterFactory.CreateRequestReader(const AStream: TStream): IEdgeRequestReader; begin if not TryCreateRequestReader(AStream, Result) then RaiseNotFound; end; function TEdgeReaderWriterFactory.TryCreateResponseWriter(const AStream: TStream; out AWriter: IEdgeResponseWriter; const AVersion: TEdgeVersion): Boolean; var LIntf: ICreateResponseWriter; begin Result := False; for LIntf in FResponseWriters.Values do if LIntf.TryCreateWriter(AVersion, AStream, AWriter) then begin if Result then RaiseDuplicate; Result := True; end; end; function TEdgeReaderWriterFactory.CreateResponseWriter(const AStream: TStream; const AVersion: TEdgeVersion): IEdgeResponseWriter; begin if not TryCreateResponseWriter(AStream, Result, AVersion) then RaiseNotFound; end; function TEdgeReaderWriterFactory.TryCreateResponseWriter(const AStream: TStream; out AWriter: IEdgeResponseWriter): Boolean; begin Result := TryCreateResponseWriter(AStream, AWriter, EdgePayloadVersion20); end; function TEdgeReaderWriterFactory.CreateResponseWriter(const AStream: TStream): IEdgeResponseWriter; begin if not TryCreateResponseWriter(AStream, Result) then RaiseNotFound; end; procedure TEdgeReaderWriterFactory.UnregisterRequestReader(AID: Integer); begin Assert(FRequestReaders.ContainsKey(AID)); FRequestReaders.Remove(AID); end; procedure TEdgeReaderWriterFactory.UnregisterResponseWriter(AID: Integer); begin Assert(FResponseWriters.ContainsKey(AID)); FResponseWriters.Remove(AID); end; { TVersion } constructor TEdgeVersion.Create(AMajor, AMinor: UInt8); begin FMajor := AMajor; FMinor := AMinor; end; { TRequest } constructor TEdgeRequest.Create(const AMethod, AServerhost, ABasePath, APath: string; const AQuery: TStringKeyValues; const ASessionToken, ATenantId: string); begin FMethod := AMethod; FPath := APath; FBasePath := ABasePath.Replace(FPath, ''); FServerHost := AServerhost; FQuery := AQuery; FSessionToken := ASessionToken; FTenantId := ATenantId; end; function TEdgeRequest.GetBasePath: string; begin Result := FBasePath; end; function TEdgeRequest.GetServerHost: string; begin Result := FServerHost; end; function TEdgeRequest.GetSessionToken: string; begin Result := FSessionToken; end; function TEdgeRequest.GetTenantId: string; begin Result := FTenantId; end; function TEdgeRequest.GetQuery: TStringKeyValues; begin Result := FQuery; end; function TEdgeRequest.GetMethod: string; begin Result := FMethod; end; function TEdgeRequest.GetPath: string; begin Result := FPath; end; { TResponse } constructor TEdgeResponse.Create(const AStatusCode: UInt16; const AStatusText: string); begin FStatusCode := AStatusCode; FStatusText := AStatusText; end; function TEdgeResponse.GetStatusCode: UInt16; begin Result := FStatusCode; end; function TEdgeResponse.GetStatusText: string; begin Result := FStatusText; end; type TRequestReader = class(TInterfacedObject, IEdgeRequestReader) private FStreamReader: TEdgeStreamReader; function ReadRequest: IEdgeRequest; function ReadContentType(out AContentType: string; out AContentLength: Integer): Boolean; procedure ReadContent(const ALength: Integer; out ABody: string); overload; procedure ReadContent(const ALength: Integer; out ABytes: TBytes); overload; procedure ReadContent(const ALength: Int64; const AStream: TStream); overload; public constructor Create(const AStream: TStream); destructor Destroy; override; end; TResponseWriter = class(TInterfacedObject, IEdgeResponseWriter) private FStreamWriter: TEdgeStreamWriter; procedure WriteResponse(const AResponse: IEdgeResponse); procedure WriteContent(const AContentType, ABody: string); overload; procedure WriteContent(const AContentType: string; const AStream: TStream); overload; procedure WriteContent(const AContentType: string; const ABody: TBytes); overload; public constructor Create(const AStream: TStream); destructor Destroy; override; end; function SupportsVersion(const AVersion: TEdgeVersion): Boolean; begin Result := AVersion.Major = EdgePayloadVersion20.Major; end; function SupportsOldVersion(const AVersion: TEdgeVersion): Boolean; begin Result := AVersion.Major = EdgePayloadVersion10.Major; end; { TRequestReader } constructor TRequestReader.Create(const AStream: TStream); begin FStreamReader := TEdgeStreamReader.Create(AStream); end; destructor TRequestReader.Destroy; begin FStreamReader.Free; inherited; end; procedure TRequestReader.ReadContent(const ALength: Integer; out ABody: string); var LBuffer: TBytes; begin SetLength(LBuffer, ALength); FStreamReader.ReadBytes(LBuffer); ABody := TEncoding.UTF8.GetString(LBuffer); end; procedure TRequestReader.ReadContent(const ALength: Integer; out ABytes: TBytes); begin SetLength(ABytes, ALength); FStreamReader.ReadBytes(ABytes); end; procedure TRequestReader.ReadContent(const ALength: Int64; const AStream: TStream); begin FStreamReader.ReadStream(AStream, ALength); end; function TRequestReader.ReadContentType(out AContentType: string; out AContentLength: Integer): Boolean; begin Result := FStreamReader.CanReadShortString; if Result then begin AContentType := FStreamReader.ReadShortString; if Result then AContentLength := FStreamReader.ReadUInt; end; end; function TRequestReader.ReadRequest: IEdgeRequest; var LMethod, LPath, LSessionToken, LBasePath, LServerHost, LTenantId: string; LVersion: TEdgeVersion; LQuery: TStringKeyValues; begin LVersion := FStreamReader.ReadVersion; if not SupportsVersion(LVersion) then if SupportsOldVersion(LVersion) then raise EEdgeReaderVersionError.Create(sEdgeOldVersionError) else raise EEdgeReaderVersionError.Create(sEdgeVersionError); LMethod := FStreamReader.ReadShortString; LPath := FStreamReader.ReadShortString; LQuery := FStreamReader.ReadStringKeyValues; LSessionToken := FStreamReader.ReadShortString; LBasePath := FStreamReader.ReadShortString; LServerHost := FStreamReader.ReadShortString; LTenantId := FStreamReader.ReadShortString; Result := TEdgeRequest.Create(LMethod, LServerHost, LBasePath, LPath, LQuery, LSessionToken, LTenantId); end; { TResponseWriter } constructor TResponseWriter.Create(const AStream: TStream); begin FStreamWriter := TEdgeStreamWriter.Create(AStream); end; destructor TResponseWriter.Destroy; begin FStreamWriter.Free; inherited; end; procedure TResponseWriter.WriteContent(const AContentType, ABody: string); var LBytes: TBytes; begin LBytes := TEncoding.UTF8.GetBytes(ABody); WriteContent(AContentType, LBytes); end; procedure TResponseWriter.WriteContent(const AContentType: string; const ABody: TBytes); begin FStreamWriter.WriteShortString(AContentType); FStreamWriter.WriteBytes(ABody); end; procedure TResponseWriter.WriteContent(const AContentType: string; const AStream: TStream); begin FStreamWriter.WriteShortString(AContentType); FStreamWriter.WriteStream(AStream); end; procedure TResponseWriter.WriteResponse(const AResponse: IEdgeResponse); begin FStreamWriter.WriteVersion(EdgePayloadVersion20); FStreamWriter.WriteShortUInt(AResponse.StatusCode); FStreamWriter.WriteShortString(AResponse.StatusText); end; type TReaderWriterCreators = class(TInterfacedObject, TEdgeReaderWriterFactory.ICreateRequestReader, TEdgeReaderWriterFactory.ICreateResponseWriter) private function TryCreateReader(const AVersion: TEdgeVersion; const AStream: TStream; out AReader: IEdgeRequestReader): Boolean; overload; function TryCreateWriter(const AVersion: TEdgeVersion; const AStream: TStream; out AReader: IEdgeResponseWriter): Boolean; overload; end; function TReaderWriterCreators.TryCreateReader(const AVersion: TEdgeVersion; const AStream: TStream; out AReader: IEdgeRequestReader): Boolean; begin Result := SupportsVersion(AVersion); if Result then AReader := TRequestReader.Create(AStream); end; function TReaderWriterCreators.TryCreateWriter(const AVersion: TEdgeVersion; const AStream: TStream; out AReader: IEdgeResponseWriter): Boolean; begin Result := SupportsVersion(AVersion); if Result then AReader := TResponseWriter.Create(AStream); end; var LID1: Integer; LID2: Integer; initialization TEdgeReaderWriterFactory.FInstance := TEdgeReaderWriterFactory.Create; LID1 := TEdgeReaderWriterFactory.Instance.RegisterRequestReader(TReaderWriterCreators.Create); LID2 := TEdgeReaderWriterFactory.Instance.RegisterResponseWriter(TReaderWriterCreators.Create); finalization TEdgeReaderWriterFactory.Instance.UnregisterRequestReader(LID1); TEdgeReaderWriterFactory.Instance.UnregisterResponseWriter(LID2); FreeAndNil(TEdgeReaderWriterFactory.FInstance); end.
{ @abstract(Sets for GMLib.) @author(Xavier Martinez (cadetill) <cadetill@gmail.com>) @created(Septembre 30, 2015) @lastmod(Septembre 30, 2015) The GMSets unit contains all sets used by GMLib. } unit GMSets; interface type // @include(..\docs\GMSets.TGMLang.txt) TGMLang = (// unknown exception language lnUnknown, // Spanish exception language lnEspanol, // English exception language lnEnglish, // French exception language lnFrench); // @include(..\docs\GMSets.TGoogleAPIVer.txt) TGoogleAPIVer = (api321, api322, api323, api324, apiNewest); // @include(..\docs\GMSets.TGMAPILang.txt) TGMAPILang = (lArabic, lBulgarian, lBengali, lCatalan, lCzech, lDanish, lGerman, lGreek, lEnglish, lEnglish_Aust, lEnglish_GB, lSpanish, lBasque, lFarsi, lFinnish, lFilipino, lFrench, lGalician, lGujarati, lHindi, lCroatian, lHungarian, lIndonesian, lItalian, lHebrew, lJapanese, lKannada, lKorean, lLithuanian, lLatvian, lMalayalam, lMarathi, lDutch, lNorwegian, lPolish, lPortuguese, lPortuguese_Br, lPortuguese_Ptg, lRomanian, lRussian, lSlovak, lSlovenian, lSerbian, lSwedish, lTamil, lTelugu, lThai, lTagalog, lTurkish, lUkrainian, lVietnamese, lChinese_Simp, lChinese_Trad, lUndefined); // @include(..\docs\GMSets.TGMMapTypeId.txt) TGMMapTypeId = (mtHYBRID, mtROADMAP, mtSATELLITE, mtTERRAIN, mtOSM); // @include(..\docs\GMSets.TGMMapTypeIds.txt) TGMMapTypeIds = set of TGMMapTypeId; // @include(..\docs\GMSets.TGMControlPosition.txt) TGMControlPosition = (cpBOTTOM_CENTER, cpBOTTOM_LEFT, cpBOTTOM_RIGHT, cpLEFT_BOTTOM, cpLEFT_CENTER, cpLEFT_TOP, cpRIGHT_BOTTOM, cpRIGHT_CENTER, cpRIGHT_TOP, cpTOP_CENTER, cpTOP_LEFT, cpTOP_RIGHT); // @include(..\docs\GMSets.TGMMapTypeControlStyle.txt) TGMMapTypeControlStyle = (mtcDEFAULT, mtcDROPDOWN_MENU, mtcHORIZONTAL_BAR); // @include(..\docs\GMSets.TGMScaleControlStyle.txt) TGMScaleControlStyle = (scDEFAULT); // @include(..\docs\GMSets.TGMMapTypeStyleElementType.txt) TGMMapTypeStyleElementType = (setALL, setGEOMETRY, setGEOMETRY_FILL, setGEOMETRY_STROKE, setLABELS, setLABELS_ICON, setLABELS_TEXT, setLABELS_TEXT_FILL, setLABELS_TEXT_STROKE); // @include(..\docs\GMSets.TGMMapTypeStyleFeatureType.txt) TGMMapTypeStyleFeatureType = (sftADMINISTRATIVE, sftADMINISTRATIVE_COUNTRY, sftADMINISTRATIVE_LAND__PARCEL, sftADMINISTRATIVE_LOCALITY, sftADMINISTRATIVE_NEIGHBORHOOD, sftADMINISTRATIVE_PROVINCE, sftALL, sftLANDSCAPE, sftLANDSCAPE_MAN__MADE, sftLANDSCAPE_NATURAL, sftLANDSCAPE_NATURAL_LANDCOVER, sftLANDSCAPE_NATURAL_TERRAIN, sftPOI, sftPOI_ATTRACTION, sftPOI_BUSINESS, sftPOI_GOVERNMENT, sftPOI_MEDICAL, sftPOI_PARK, sftPOI_PLACE__OF__WORSHIP, sftPOI_SCHOOL, sftPOI_SPORTS__COMPLEX, sftROAD, sftROAD_ARTERIAL, sftROAD_HIGHWAY, sftROAD_HIGHWAY_CONTROLLED__ACCESS, sftROAD_LOCAL, sftTRANSIT, sftTRANSIT_LINE, sftTRANSIT_STATION, sftTRANSIT_STATION_AIRPORT, sftTRANSIT_STATION_BUS, sftTRANSIT_STATION_RAIL, sftWATER); // @include(..\docs\GMSets.TGMVisibility.txt) TGMVisibility = (vOn, vOff, vSimplified); // @include(..\docs\GMSets.TGMZoomControlStyle.txt) TGMZoomControlStyle = (zcDEFAULT, zcLARGE, zcSMALL); implementation end.
unit procs; { Etienne van Delden, 0618959, 07-11-2006 } interface //**CONSTANT DEFINITION ********** const { Maxima } MaxnRijen = 25; // Het maximale aantal rijen in een matrix MaxnKolommen = 20; // Het maximale aantal Kolommen in een matrix MaxWaarde = 99; // De maximale waarde die een vak kan hebben MaxSomPad = (MaxnRijen + MaxnKolommen) * MaxWaarde; // De allergrootste sompad is het maximale // aantal rijen en het maximale aantal // kolommen waar de maximale waarde instaat CellWidth = 3; // De breedte van een schrijf veld in de output // (evt. * niet meegerekend) //** TYPE DEFINITION ************* type TVeldWaarde = 0 .. MaxWaarde; // De velwaardes lopen van 0 tot het maximum TRijIndex = 1 .. MaxnRijen; // Het aantal rijen loopt van 1 tot het maximum TKolIndex = 1 .. MaxnKolommen; // Het aantal kolommen loopt vna 1 tot het max TSomPad = 0 .. MaxSomPad; // En het sompad loopt van 0 tot het max // (1 vak met waarde 0 is het minimum) Kaart = record // De kaart .. nRijen: 1 .. MaxnRijen; // .. bevat een aantal rijen nKolommen: 1 .. MaxnKolommen; // .. bevat een aantal kolommen energie: array [TRijIndex, TKolIndex] of TVeldWaarde; // .. bevat op ieder // veld een bepaalde energiewaardee end; // end record: Kaart TAntwoord = record // Het antwoord.. map: Kaart; // .. bevat een kaart max: TSomPad; // .. bevat een maximale energiewaarde voor // de mogelijke paden pad: array [TRijIndex, TKolIndex] of Boolean; // hetzelfde kaartje, maar nu // met vakjes of er op het vakje gelopen word end; // end recond: TAntwoord //** INTERFACE: PROCEDURES *************** procedure ReadMap (var input: Text; var map: Kaart); // Lees de kaart uit een input { pre: input is geopend voor lezen en de leeskop staat voor de kaart gegevens post: map bevat de data uit input, de leeskop staat achteraan } procedure ComputeAnswer (const map: Kaart; var antwoord: TAntwoord); // Bereken mbv de gegevens in map wat het pad is waarvan je het meeste // energie krijgt { pre: de hele kaart is ingelezen post: het pad waarvan je de meeste energie krijgt is berekend } procedure WriteAnswer (var output: Text; const map: Kaart; const antwoord: TAntwoord); { pre: output is geopend om te schrijven, het maximale pad is berekend post: de gegevens in antwoord zijn weggeschreven naar output } implementation //** FUNCTIONS **************** function maximum( k,l: Integer ): Integer; { pre: 2 integers ret: de grootste van de 2 } begin if k < l then // als de een groter is dan de andere begin Result := l // word hij het resulataat end else if k > l then // dit was niet het geval begin Result := k // dus wordt de andere het resultaat end else if k = l then // 2 gelijke getallen begin Result := k // 1 van de 2 word het resultaat end; end; // end maximum //**PROCEDURES***************** procedure ReadMap (var input: Text; var map: Kaart); { zie interface } var leesRij: TRijIndex; // teller var voor huidige rij leesKolom: TKolIndex; // teller var voor huidige kolom begin // Lees het aantal rijen en het aantal kolommen read( input, map.nRijen, map.nKolommen ); // Lees alle veldwaarden } for leesRij := 1 to map.nRijen do begin for leesKolom := 1 to map.nKolommen do begin read( input, map.energie[ leesRij, leesKolom ] ); // veldwaarden end; // end for kolommen end; // end for rijen end; //procedure ReadMap procedure ComputeAnswer (const map: Kaart; var antwoord: TAntwoord); { zie interface } var maxMap: array[ TRijIndex, TKolIndex ] of TSomPad; // alle opgetelde waardes huidigRij: TRijIndex; // hulp var voor de huidige rij huidigKolom: TKolIndex; // hulp var voor de huidige kolom somRechts: TSomPad; // bepaal de groote van het vakje rechts van ons somOnder: TSomPad; // bepaal de groote van het vakje onder ons grensRechts: Boolean; // om te kijken of iets op de rechtergrens ligt grensOnder: Boolean; // om te kijken of iets op de ondergrens ligt begin // Genereer de maximale padsom vanuit rechtsonder voor iedere positie somOnder := 0; for huidigRij := map.nRijen downto 1 do // doorloop voor alle rijen begin somRechts := 0; // de som vanaf rechts is 0 for huidigKolom := map.nKolommen downto 1 do //voor alle kolommen begin if huidigRij < map.nRijen then // als we niet bij de laatste rij zijn begin somOnder := maxMap[ huidigRij + 1, huidigKolom ]; // pak dan de waarde van het vakje onder ons, in dezelfde kolom end; if huidigKolom < map.nKolommen then // als we neit bij de laatste kolom zijn begin somRechts := maxMap[ huidigRij, huidigKolom + 1 ]; // pak dan de waarde van het vakje orechts, in dezelfde rij end; maxMap[ huidigRij, huidigKolom ] := map.energie[ huidigRij, huidigKolom ] + maximum( somRechts, somOnder ); // de maximale waarde op het huidge vakje, word zijn energie waarde, // plus de grootste onder of rechts van ons end; // end for end; antwoord.map := map; // Geef de huidige map door aan het antwoord antwoord.max := maxMap[ 1, 1 ]; // De grootste hoeveelheid energie { Genereer het pad } with antwoord, map do begin // Reset en/of Initialisatie van variabelen huidigRij := 1; // terug naar rij 1 huidigKolom := 1; // terug naar kolom 1 somOnder := 0; // reset van var somRechts := 0; // reset van var grensRechts := False; // we gaan ervan uit dat we niet bij de grens zijn grensOnder := False; // we gaan ervan uit dat we niet bij de grens zijn pad [1, 1] := True; // linksboven is het eerste vak waar we lopen // we gaan nu kijken waar we lopen while (huidigRij < nRijen) or (huidigKolom < nKolommen) do begin if huidigRij < nRijen then // als we niet bij de laatste rij zijn begin somOnder := maxMap [huidigRij + 1, huidigKolom]; end else begin grensOnder := True; // we zitten aan de grens end; if huidigKolom < nKolommen then begin // als we neit bij de laatste kolom zijn somRechts := maxMap [huidigRij, huidigKolom + 1]; end else begin grensRechts := True; // we zitten aan de grens end; // als we naar onderen kunnen gaan if grensRechts or ((not grensOnder) and (somOnder > somRechts)) then begin huidigRij := huidigRij + 1; // naar de volgende rij end else begin huidigKolom := huidigKolom + 1; // naar de volgende kolom end; pad [huidigRij, huidigKolom] := True; // we hebben op dit pad gelopen end; end; end; //procedure ComputeAnswer procedure WriteAnswer (var output: Text; const map: Kaart; const antwoord: TAntwoord); { zie interface } var schrijfRij: TRijIndex; // iterator voor de huidige rij schrijfKolom: TKolIndex; // iterator voor de huidige kolom begin writeln( output, antwoord.max); writeln( output ); with antwoord, map do begin for schrijfRij := 1 to nRijen do // voor iedere rij begin for schrijfKolom := 1 to nKolommen do // en voor iedere kolom begin write( output, energie[ schrijfRij, schrijfKolom ]: CellWidth ); if pad[ schrijfRij, schrijfKolom] then begin // zitten we op het pad? write( output, '*' ); // dan een extra sterretje scchrijven end else if schrijfKolom < nKolommen then begin // als we niet op laatste kolom zitten write( output, ' ' ); // maak een scheidings-spatie end; // end if path end; //en for huidigKolom writeln( output ); end; // end for huidigRij end; // end with: answer, map end; // endprocedure Writeantwoord end. // end procs.pas
unit ExStrLib; interface uses SysUtils , Variants , Controls , StrUtils , Dialogs ,Classes , ExLibrary ; //============================================================================== // 암호화에 사용되는 기본 키값 //============================================================================== //const MYKEY_old = 7756; ENCKEY_old = 9089; DECKEY_old = 1441; //---- 입력된 문자가 공백인지 확인하는 펑션 function ExIsEmpty_old ( Value : String ): Boolean ; overload; function ExIsEmpty_old ( Value : String ; Default : String ): String ; overload; function ExLenSize ( Value : String ): Integer ; overload; function ExLenSize ( Value : String ; LenSize : Byte ) : Boolean; overload; function ExIsPairs ( Pare1 , Pare2 : Variant ; UpperType : Boolean = False ) : Boolean ; function ExNumbText_old ( value , Default : Variant ; OnlyNumb : Boolean = False ) : String ; function ExCommaStr ( Value : String ; ValueSite : Integer ) : String ; function ExSqlQuery_old ( Value : String ) : String ; //function ExReturns ( TrueValue , FalseValue : Integer ; RetBool : Boolean ) : Integer ; overload ; //---- 문자 변환용 펑션 function ExVarToStr_old ( Value : Variant; DefValue : String = '' ) : String ; function ExVarToInt_old ( Value : Variant; DefValue : Integer = 0 ) : Integer ; function ExVarToDob_old ( Value : Variant; DefValue : Double = 0 ) : Double ; function ExVarToBol_old ( Value : Variant; DefValue : Boolean = False ) : Boolean ; function ExVarToWon_old ( Value : Variant; DefValue : Double = 0 ) : String ; //---- function ExMakeText_old ( CharText : Char; TextSize : Integer ) : String; function ExPlusText_old ( CharText : Char; TextSize : Integer ; Value : Variant ) : String; function ExEncoding_old ( Const Value : String ; Key : Word = 7756 ) : String; function ExDecoding_old ( Const Value : String ; Key : Word = 7756 ) : String; function ExStrToSql_old ( Const Value : String ; StrWrite : Boolean ) : String; overload; function ExStrToSql_old ( Const Value : String ; DefIndex , RtlIndex : Integer ) : String; overload; function ExStrToSql_old ( Const Value : String ; TextArry : array of String ) : String; overload; function ExStrToSql_old ( Const Value : String ; TextArry : array of String; SqlWrite : Boolean ) : String; overload; function ExStrToSql_old ( Const Value : String ; FromDate , Todate : TDateTime ) : String; overload; function ExStrToSql_old ( Const Value : String ; FromDate , Todate : TDateTime ; StrWrite : Boolean ) : String; overload; function ExChrToHex ( Const Value : Char ) : Byte ; function ExStrToHex ( Const Value : String ) : Byte ; function ExRanToKey ( KeySize : Byte = 4 ) : Integer ; //function ExStrToEnc ( Const Value : string; Key : Word = MYKEY ) : String; //function ExStrToDec ( const Value : string; Key : Word = MYKEY ) : string; function ExDateTime ( const Value : String = 'YYYY-MM-DD HH:NN:SS' ) : String ; function ExStrToDateMask ( const Value : string ) : string; function ExStrToTimeMask ( const Value : string; CopyByte : Byte = 2) : string; function ExDayIndex ( DateText : String ) : String ; // function ExTextCopy ( Value : String ; Index , Count : Integer ; HanCheck : Boolean = False ) : String ; implementation //============================================================================== // 입력된 문자열이 공백인지 확인한다. 공백일 경우 참을 그렇지 않을 경우 거짓을 넘겨준다. //============================================================================== function ExIsEmpty_old ( Value : String ) : Boolean; overload; begin if Trim( Value ) = '' then Result := True else Result := False ; end; //============================================================================== // 입력된 문자열이 공백인지 확인한다. 공백일 경우 디폴트 값을 넘겨준다. //============================================================================== function ExIsEmpty_old( Value : String; Default : String ) : String; overload; begin if Trim( Value ) = '' then Result := Default else Result := Value; end; //============================================================================== // 문자열을 입력 받아 문자열의 사이즈를 넘겨준다. //============================================================================== function ExLenSize ( Value : String ) : Integer ; overload; begin if not ExIsEmpty_old ( Value ) then begin Result := Length ( Trim ( Value ) ) ; end else Result := 0 ; end; //============================================================================== // 문자열을 입력 받고 사이즈를 입력 받은뒤 문자열의 사이즈와 요청한 사이즈가 동일한지 비교한다. //============================================================================== function ExLenSize ( Value : String ; LenSize : Byte ) : Boolean; overload; begin if ExLenSize( Value ) = LenSize then Result := True else Result := False; end; //============================================================================== // 두 문자가 동일한지 입력된 문자열이 공백인지 확인한다. 공백일 경우 참을 그렇지 않을 경우 거짓을 넘겨준다. ? //============================================================================== function ExIsPairs ( Pare1 , Pare2 : Variant; UpperType : Boolean = False ) : Boolean ; begin if UpperType then begin Result := ExIsPairs(UpperCase(VarToStr(Pare1)),Uppercase(VarToStr(Pare2)), False ); end else if Pare1 = Pare2 then Result := True else Result := False; end; //============================================================================== // 가변형을 받아 숫자형 문자만 출력해 준다. //============================================================================== function ExNumbText_old ( value , Default : Variant; OnlyNumb : Boolean = False ) : String ; var i : Integer; IvBuff , RvBuff : String; begin RvBuff := '' ; Result := Default ; try IvBuff := VarToStr ( value ) ; if not ExIsEmpty_old ( IvBuff ) then begin for i := 1 to Length ( IvBuff ) do begin if IvBuff[i] In [ '0'..'9','-','.' ] then begin if OnlyNumb then begin if IvBuff[i] In [ '0'..'9' ] then RvBuff := RvBuff + IvBuff[i] end else RvBuff := RvBuff + IvBuff[i] ; end; end; end; finally Result := RvBuff ; end; end; //============================================================================== // 두 문자가 동일한지 입력된 문자열이 공백인지 확인한다. 공백일 경우 참을 그렇지 않을 경우 거짓을 넘겨준다. ? //============================================================================== function ExCommaStr ( Value : String ; ValueSite : Integer ) : String ; var StringList : TStringList ; begin Result := ''; if not ExIsEmpty_old ( Value ) then begin StringList := TStringList.Create ; try StringList.Clear; try with StringList do begin Clear; CommaText := Value ; if (StringList.Count > 0) and (Count >= ValueSite) then begin try Result := Strings[ValueSite-1] ; except Result := '' end; end; end; finally StringList.Free; end; except end; end; end; //============================================================================== // 가변형을 받아 문자 형태로 넘겨준다. //============================================================================== function ExVarToStr_old ( Value : Variant; DefValue : String = '' ) : String ; begin Result := Defvalue ; try Result := VarToStr ( Value ); if Trim( Result) = '' then Result := DefValue; except Result := DefValue;end; end; //============================================================================== // 가변형을 받아 문자 형태로 넘겨준다. //============================================================================== function ExVarToWon_old ( Value : Variant; DefValue : Double = 0 ) : String ; const Suh : Array [1..9] of String = ( '일','이','삼','사','오','육','칠','팔','구'); won : Array [1..9] of String = ( '' ,'십','백','천','만','십','백','천','억'); var TempBuff : Double ; TempText : String; TextSize , TextSite , TextNumb : Integer ; begin TempBuff := ExVarToDob( Value , 0 ) ; if ( TempBuff > 0 ) and ( TempBuff < 1000000000 ) then begin TempText := ExNumbText( TempBuff ,0 , True ) ; Result :='금_'; TextSite := 1; TextSize := Length(TempText); while TextSize > 0 do begin if TempText[TextSite] <> '0' then begin TextNumb := StrToInt(TempText[TextSite]); Result := Result+Suh[TextNumb]+Won[TextSize]; end; Dec ( TextSize ) ; inc ( TextSite ) ; end; Result := Result +'원정'; end else Result := '?'; end; //============================================================================== // 가변형을 받아 숫자 형태로 넘겨준다. //============================================================================== function ExVarToInt_old ( Value : Variant; DefValue : Integer = 0 ) : Integer ; begin if not ExFindText( VarToStr( Value ) , [ 'TRUE' , 'FALSE' ] , True ) then begin try Result := StrToInt ( ExVarToStr ( Value , IntToStr(DefValue) ) ); except Result := DefValue; end; end else if ExFindText( VarToStr( Value ) , ['TRUE' ] , True ) then begin Result := 1 ; end else if ExFindText( VarToStr( Value ) , ['FALSE' ] , True ) then begin Result := 0 ; end ; end; //============================================================================== // 가변형을 받아 실수 형태로 넘겨준다. //============================================================================== function ExVarToDob_old ( Value : Variant; DefValue : Double = 0 ) : Double ; begin try Result := StrToFloat( ExVarToStr ( Value , FloatToStr( DefValue ) ) ); except Result := DefValue; end; end; //============================================================================== // 가변형을 받아 블린 형태로 넘겨준다. //============================================================================== function ExVarToBol_old ( Value : Variant; DefValue : Boolean = False ) : Boolean ; var TempText : String ; begin try TempText := UpperCase ( Trim( ExVarToStr( Value , BoolToStr ( DefValue ) ) ) ); Result := ExFindText( TempText, [ 'Y' , 'YES' , 'T' , 'TRUE' , '1', '참' ] ); except Result := DefValue; end; end; { //============================================================================== // 문자열을 받아 암호화 한다. //============================================================================== function ExStrToEnc ( Const Value : String; Key : Word = MYKEY ) : String; var i : Byte; AscChar : Char; EncStr , EncHex : string; begin EncStr := ''; if Key = 0 Then Key := MYKEY; for i := 1 to Length( Value ) do begin EncStr := EncStr + Char ( Byte ( Value [i] ) xor ( Key shr 8 ) ); Key := ( Byte ( EncStr [i] ) + Key ) * ENCKEY + DECKEY ; end; EncHex := ''; for i := 1 to Length( EncStr ) do begin // 암호화된 이진 문자열을 ASCII 숫자로 변경 AscChar := EncStr[i]; // ShowMessage ( IntToStr ( Byte( AscChar ) ) ); EncHex := EncHex + IntToHex ( Byte(AscChar) , 2 ); // 한문자당 2자리씩 end; Result := EncHex; end; //============================================================================== // 암호화된 문자열을 해독한다. //============================================================================== function ExStrToDec ( const Value : string; Key : Word = MYKEY ) : string; var i : Byte; HexStr : Char ; DecStr , DecAsc : string; begin // ExHexToInt ( Const Value : Char ) : Byte ; DecAsc := ''; i := 1; repeat DecAsc := DecAsc + Char( ExChrToHex( Value[i] ) Shl 4 or ExChrToHex( Value[i+1]) ) ; i := i + 2; until i > Length( Value ); DecStr := ''; if Key = 0 Then Key := MYKEY; for i := 1 to Length( DecAsc ) do begin DecStr := DecStr + Char ( Byte ( DecAsc [i] ) xor ( Key shr 8 ) ); Key := ( Byte ( DecAsc [i] ) + Key ) * ENCKEY + DECKEY ; end; Result := DecStr; end; } // Char ( Copy( Value, i, 1 ) ) ; // HexStr := ( Byte ( Copy( Value, i, 1) ) shr 4 ) or Byte ( Copy( Value, i, 1) ) ; // Result := ( x Shl 4 ) or y ; // 한문자당 3자리 숫자로 저장되어 있다 // DecAsc := DecAsc + Chr( StrToIntDef ( HexStr, 0 ) ) ; // ASCII값을 구한다 //============================================================================== // 랜덤으로 4자리 수를 받아온다. //============================================================================== function ExRanToKey ( KeySize : Byte = 4 ) : Integer ; var Buf : Integer ; key : String ; begin Key := IntToStr ( StrToInt( FormatDateTime( 'ZZZSS', now ))) ; repeat Buf := Random( 9 ) ; if Buf <> 0 then Key := Key + IntToStr ( Buf ) ; until KeySize <= Length( Key ); Result := StrToInt(Copy(Key,1,KeySize)) ; end; { k := Random ( 9 ) ; repeat j := 0 ; i := StrToInt(FormatDateTime( 'SS', now )) + k ; repeat k := Random ( 9 ) ; if k <> 0 then Inc( j ) ; until i <= j ; Key := Key + IntToStr ( k ) ; until 4 <= Length( Key ); Result := StrToInt(Key) ; } //Key := IntToStr ( StrToInt ( FormatDateTime ( 'SS', now )) ); { repeat Buf := Copy( FormatDateTime ( 'ZZZ', now ),3,1); if Buf <> '0' then begin StrToInt( Random( 9 ) ); Key := Key + Buf ; end; until 4 <= Length( Key); } //============================================================================== // 문자열을 받아 암호화 한다. //============================================================================== function ExEncoding_old ( Const Value : String; Key : Word = MYKEY ) : String; var i : Byte; AscChar : Char; EncStr , EncAsc : string; begin EncStr := ''; if Key = 0 Then Key := MYKEY; for i := 1 to Length( Value ) do begin EncStr := EncStr + Char ( Byte ( Value [i] ) xor ( Key shr 8 ) ); Key := ( Byte ( EncStr [i] ) + Key ) * ENCKEY + DECKEY ; end; EncAsc := ''; for i := 1 to Length( EncStr ) do begin // 암호화된 이진 문자열을 ASCII 숫자로 변경 AscChar := EncStr[i]; EncAsc := EncAsc + format('%.3d', [Ord(AscChar)]); // 한문자당 3자리씩 end; Result := EncAsc; end; //============================================================================== // 암호화된 문자열을 받아 암호를 헤제한다. //============================================================================== function ExDecoding_old ( const Value : string; Key : Word = MYKEY ) : string; var i : Byte; AscStr : string; DecStr , DecAsc : string; begin DecAsc := ''; i := 1; repeat AscStr := Copy( Value, i, 3); // 한문자당 3자리 숫자로 저장되어 있다 DecAsc := DecAsc + Chr( StrToIntDef ( AscStr, 0 ) ) ; // ASCII값을 구한다 i := i + 3; until i > Length( Value ); DecStr := ''; if Key = 0 Then Key := MYKEY; for i := 1 to Length( DecAsc ) do begin DecStr := DecStr + Char ( Byte ( DecAsc [i] ) xor ( Key shr 8 ) ); Key := ( Byte ( DecAsc [i] ) + Key ) * ENCKEY + DECKEY ; end; Result := DecStr; end; //============================================================================== // 특정 캐랙터를 받아 입력 받은 수 만큼의 문자열을 만들어 준다. // 특정 문자로 이루어진 문자열을 만들때 사용한다. // ex ( 5 , C ) = 'CCCCC' 예제 ( 4 , '0' ) = '0000' //============================================================================== function ExMakeText_old ( CharText : Char; TextSize : Integer ) : String; begin Result := ''; if 0 < TextSize then begin if TextSize > 255 then TextSize := 255; SetLength( Result , TextSize ); FillChar ( Result[1] , Length(Result), CharText ); end; end; //============================================================================== // 숫자와 자리수를 받아 자리수 만큼의 의 문자열을 만들어 주는 함수 ( 0으로 채움 ) // 항상 지정된 자리수 만큼의 문자열을 사용할때 사용한다. // ex ( KS , -4 , 'A' ) = 'AAKS'; ( KS , -5 , '0' ) = '000KS'; // ex ( KS , 4 , 'A' ) = 'KSAA'; ( KS , 5 , '0' ) = 'KS000'; //============================================================================== function ExPlusText_old ( CharText : Char; TextSize : Integer; Value : Variant ) : String; begin try Result := VarToStr ( Value ); if TextSize > 0 then begin Result := Result + ExMakeText( CharText , TextSize - Length( Result ) ) ; end else if TextSize < 0 then begin Result := ExMakeText( CharText , ( TextSize * -1 ) - Length( Result ) ) + Result ; end; finally end; end; //============================================================================== // 한 문자열을 받아 받아 Hex 값으로 넘겨준다. //============================================================================== function ExChrToHex ( Const Value : Char ) : Byte ; begin Case Value of '1' : Result := $1; '2' : Result := $2; '3' : Result := $3; '4' : Result := $4; '5' : Result := $5; '6' : Result := $6; '7' : Result := $7; '8' : Result := $8; '9' : Result := $9; 'A','a': Result := $A; 'B','b': Result := $B; 'C','c': Result := $C; 'D','d': Result := $D; 'E','e': Result := $E; 'F','f': Result := $F; else Result := $0; end; end; //============================================================================== // 2개의 문자를 문다 HEX 값으로 변형한다. //============================================================================== function ExStrToHex ( Const Value : String ) : Byte ; begin Result := ( ExChrToHex( Value[1] ) Shl 4 ) or ExChrToHex( Value[2] ) ; //ExChrToHex( Value[1] ); end; { function ExHexToStr( Const Value : Byte ) : String ; begin Result := ( ExChrToHex( Value[1] ) Shl 4 ) or ExChrToHex( Value[2] ) ; //ExChrToHex( Value[1] ); end; function ExHexToStr( Const Value : Word ) : String ; begin Result := ( ExChrToHex( Value[1] ) Shl 4 ) or ExChrToHex( Value[2] ) ; //ExChrToHex( Value[1] ); end; } { if Length(Value) = 1 then begin end; // Char '0' x := $0E ; y := $03 ; } { //DelSpace SQLSpaces function SqlDelSpace ( SqlStr : String ) : String; var TextSize : integer ; TempBuff : String ; CharBuff , TempChar : Char ; CharByte , LoopByte : Integer ; begin Result := '' ; TempBuff := '' ; CharBuff := ' '; TempChar := ' '; CharByte := 0 ; LoopByte := 0 ; TextSize := Length( SqlStr ); while LoopByte <= TextSize do begin Inc(LoopByte); TempChar := CharBuff ; CharBuff := SqlStr[LoopByte] ; if CharBuff = ' ' then begin // 한자리를 읽은뒤 공백이면 Inc(CharByte); if CharByte = 1 then if TempChar <> ',' then TempBuff := TempBuff + ' '; end else begin CharByte := 0 ; if (CharBuff = ',') and (TempChar = ' ' ) then begin TempBuff := Copy ( TempBuff , 1, Length ( TempBuff ) -1 ) + CharBuff ; end else TempBuff := TempBuff + CharBuff; end; end; Result := TempBuff ; end; } function ExSqlQuery_old ( Value : String ) : String ; var TextSize : integer ; TempBuff : String ; CharBuff , TempChar : Char ; CharByte , LoopByte : Integer ; begin Result := '' ; TempBuff := '' ; CharBuff := ' '; TempChar := ' '; CharByte := 0 ; LoopByte := 0 ; TextSize := Length( Value ); if TextSize > 0 then begin while LoopByte <= TextSize do begin Inc(LoopByte); TempChar := CharBuff ; CharBuff := Value[LoopByte] ; if CharBuff = ' ' then begin // 한자리를 읽은뒤 공백이면 Inc(CharByte); if CharByte = 1 then if TempChar <> ',' then TempBuff := TempBuff + ' '; end else begin CharByte := 0 ; if (CharBuff = ',') and (TempChar = ' ' ) then begin TempBuff := Copy ( TempBuff , 1, Length ( TempBuff ) -1 ) + CharBuff ; end else TempBuff := TempBuff + CharBuff; end; end; Result := TempBuff ; end ; end; //============================================================================== // Where 문장을 넣어준다. //============================================================================== function ExStrToSql_old ( Const Value : String ; TextArry : Array of String; SqlWrite : Boolean ) : String; overload; var i : Integer ; FlagBuff , TextBuff : String ; begin Result := '' ; try FlagBuff := Trim ( UpperCase( TextArry[Low(TextArry)]) ); if SqlWrite and not ExIsEmpty_old ( FlagBuff ) then begin // if High ( TextArry ) > 0 then begin // 배열의 크기가 0보다 크면 if ExFindText( FlagBuff , ['FIX', 'NUM', 'AND', 'ORS', 'ORM', 'ORE', 'LIKE' , 'LLK' , 'RLK' ,'DLK' ] ) then begin if (FlagBuff = 'FIX') then begin Result := Value + QuotedStr ( TextArry[1] ) ; // StrWrite 유무 관계없이 무조건 넣어준다. 고정값으로 판정 end else if not ExIsEmpty_old ( TextArry [1] ) then begin //if FlagBuff = 'FIX' then begin Result := Value + QuotedStr ( TextArry[1] ) ; end else if FlagBuff = 'NUM' then begin Result := Value + TextArry[1] ; end else if FlagBuff = 'AND' then begin Result := Value + QuotedStr ( TextArry[1] ) ; end else if FlagBuff = 'ORS' then begin Result := ' AND (1=2 '+ Value + QuotedStr ( TextArry[1] ); end else if FlagBuff = 'ORM' then begin Result := Value + QuotedStr ( TextArry[1] ) ; end else if FlagBuff = 'ORE' then begin Result := Value + QuotedStr ( TextArry[1] ) + ' ) ' ; end else if FlagBuff = 'LLK' then begin Result := Value + ' LIKE ''%' + TextArry[1] + ''' ' ; end else if FlagBuff = 'RLK' then begin Result := Value + ' LIKE ''' + TextArry[1] + '%'' ' ; end else if FlagBuff = 'DLK' then begin Result := Value + ' LIKE ''%' + TextArry[1] + '%'' ' ; end else if FlagBuff = 'LIKE' then begin Result := Value + ' LIKE ''%' + TextArry[1] + '%'' ' ; end; end else begin if FlagBuff = 'ORS' then begin Result := ' AND ( 1 = 2 ' ; end else if FlagBuff = 'ORE' then begin Result := ' ) ' ; end; end; end else if ExFindText ( FlagBuff , ['IN'] ) then begin if High (TextArry) = 1 then begin if not ExIsEmpty_old ( TextArry[1] ) then begin Result := Value + ' = ' + QuotedStr ( TextArry[1] ); end; end else if High (TextArry) > 1 then begin FlagBuff := ''; TextBuff := ''; for i := Low(TextArry) + 1 to High (TextArry) do begin // ShowMessage( TextArry[i] ); TextBuff := TextBuff + FlagBuff + QuotedStr ( TextArry[i] ) ; FlagBuff := ',' ; end; Result := Value + ' IN ( ' + TextBuff + ' ) ' ; end ; end else if not ExIsEmpty_old( TextArry[0] ) and not ExIsEmpty_old(TextArry [1] ) then begin Result := Value + ' BETWEEN ' + QuotedStr( TextArry[0]) +' AND '+ QuotedStr(TextArry[1] ) ; end; end else Result := Value + QuotedStr ( TextArry[0] ) ; end; finally if Trim ( Result ) <> '' then Result := Result + #13#10; end; end; //============================================================================== // Where 문장을 넣어준다. //============================================================================== function ExStrToSql_old ( Const Value : String ; TextArry : Array of String ) : String; overload; begin Result := ExStrToSql_old ( Value , TextArry , True ) ; end; //============================================================================== // Where 문장을 넣어준다. //============================================================================== function ExStrToSql_old ( Const Value : String ; StrWrite : Boolean ) : String; overload; begin if StrWrite then Result := Value else Result := ''; end; function ExStrToSql_old ( Const Value : String ; DefIndex , RtlIndex : Integer ) : String; overload; begin Result := ExStrToSql_old ( Value , (DefIndex = RtlIndex) ); end; //============================================================================== // Where 문장을 넣어준다. //============================================================================== function ExStrToSql_old ( Const Value : String ; FromDate , ToDate : TDateTime ) : String; overload; begin Result := Value + ' BETWEEN ''' + FormatDateTime( 'YYYY-MM-DD' , FromDate ) + ''' AND ''' + FormatDateTime( 'YYYY-MM-DD' , ToDate ) + ''' ' + #13#10 ; end; //============================================================================== // Where 문장을 넣어준다. //============================================================================== function ExStrToSql_old ( Const Value : String ; FromDate , ToDate : TDateTime ; StrWrite : Boolean ) : String; overload; begin if StrWrite then Result := ExStrToSql_old ( Value , FromDate , ToDate ) else Result := ''; end; { //============================================================================== // SQL 문장을 만든다. //============================================================================== function ExStrToSql ( var fSql , lSql : String ; Sqls , OSqls , Comma : String ) : String ; begin Result := if end; } function ExDateTime ( const Value : String = 'YYYY-MM-DD HH:NN:SS') : String ; begin Result := FormatDateTime ( Value , now ) ; end; //============================================================================== // 시간을 이용하여 유일한 인덱스 번호를 만든다. //============================================================================== function ExDayIndex ( DateText : String ) : String ; var TempByte : Byte ; TempDate , TempBuff : String ; begin TempBuff := Char( StrToInt( Copy( DateText,5,2) ) + 64 ) ; // 월 MM TempByte := StrToInt( Copy( DateText,7,2) ) ; case TempByte of 1..9 : TempBuff := TempBuff + Char( TempByte + 47 ) ; // 일 DD else TempBuff := TempBuff + Char( TempByte + 64 ) ; // 일 DD end; Result := TempBuff ; end; // ============================================================================= // function fnHanChk (Str : String; Cnt : Integer) : String; // 복사할 경우 마지막 자릿수에 한글이 올경우 마지막 한글자리에 공백으로대치하는 함수 // 인자설명 인자1:해당문자, 인자2:전체자릿수 // Return : 전체자릿수만큼 마자막자 특수문자면 Space로 대치함. // ============================================================================= { function ExHanToCopy ( BuffText : String; Cnt : Integer) : String; var i : Integer ; fText , rText : String ; j : Integer; mystr,Rc : String; begin if ( Length ( BuffText ) >= Cnt then begin end else Result := BuffText ; if( length( BuffText ) >=Cnt ) then begin mystr := copy(Str,1,Cnt); j := 1; while ( j <= Cnt ) do begin if isDBCSLeadByte(Byte(mystr[j])) then begin //첫바이트가 한글이면 If j < Cnt Then begin Rc := Rc + copy( mystr,j ,2 ); end Else begin Rc := Rc + ' '; End; j:=j+2; end else begin Rc := Rc + copy( mystr, j , 1 ); j:=j+1; end; end; result := Rc; end else result := Str; end; } //============================================================================== // 문자열을 받아 데이트 형태로 만든다. //============================================================================== function ExStrToDateMask ( const Value : string ) : string; var TempBuff : String ; begin Result := ''; TempBuff := ExNumbText ( value , '' , True ) ; // 숫자 타입의 문자열만 뽑아온다. if not ExIsEmpty_old ( TempBuff ) then begin Result := format( '%4s-%2s-%2s' , [ Copy(TempBuff,1,4) , Copy(TempBuff,5,2) , Copy(TempBuff,7,2) ] ); end; end; //============================================================================== // 문자열을 받아 데이트 형태로 만든다. //============================================================================== function ExStrToTimeMask ( const Value : string; CopyByte : Byte = 2 ) : string; var NextByte : Integer ; TempBuff , CopyBuff : String ; MaskFlag , FullText : String ; begin Result := ''; NextByte := 1 ; TempBuff := ExNumbText ( value , '' , True ) ; // 숫자 타입의 문자열만 뽑아온다. repeat CopyBuff := Copy ( TempBuff , NextByte , CopyByte ) ; if not ExIsEmpty_old ( CopyBuff ) then begin FullText := FullText + MaskFlag + CopyBuff ; MaskFlag := ':'; end; NextByte := NextByte + 2 until ExIsEmpty_old ( CopyBuff ) ; Result := FullText ; end; { //============================================================================== // 문자열을 받아 참과 거짓일 때 문자열을 넘겨준다. //============================================================================== function ExRetToStr ( TrueValue , FalseValue : Integer;RetBool : Boolean ) : Integer ; overload ; begin if RetBool then Result := TrueValue else Result := FalseValue ; end; } end.
{**********************************************************} { } { Borland Visibroker for Delphi } { } { Copyright (C) 1999-2001 Borland Software Corporation } { } {**********************************************************} unit Corba; interface uses SysUtils, OrbPas45, Classes, VarUtils, Variants; type _Object = System.IUnknown; Any = System.Variant; TypeCode = ORBPAS45.ITypeCode; TCommandLine = ORBPAS45.TArgv; StructMemberSeq = ORBPAS45.TStructMembers; UnionMemberSeq = ORBPAS45.TUnionMembers; RegistrationScope = ORBPAS45._RegistrationScope; PExceptionProxy = ORBPAS45.PUserExceptionProxy; PExceptionDescription = ORBPAS45.PExceptionDescription; InputStream = interface; OutputStream = interface; Principal = class; TCorbaThreadModel = (tmMultiThreaded, tmSingleThread); CompletionStatus = (COMPLETED_YES, COMPLETED_NO, COMPLETED_MAYBE); TCKind = (tk_null, tk_void, tk_short, tk_long, tk_ushort, tk_ulong, tk_float, tk_double, tk_boolean, tk_char, tk_octet, tk_any, tk_TypeCode, tk_Principal, tk_objref, tk_struct, tk_union, tk_enum, tk_string, tk_sequence, tk_array, tk_alias, tk_except, tk_longlong, tk_ulonglong, tk_longdouble, tk_wchar, tk_wstring, tk_fixed{not supported in Delphi}); TAnyHelper = class public class function TypeCode(const A: Any): TypeCode; end; SystemException = class(Exception) private FMinor: Integer; FCompleted: CompletionStatus; public constructor Create(Minor: Integer = 0; Completed: CompletionStatus = COMPLETED_NO); property Minor: Integer read FMinor write FMinor; property Completed: CompletionStatus read FCompleted write FCompleted; end; ECorbaDispatch = class(Exception); UNKNOWN = class(SystemException) end; BAD_PARAM = class(SystemException) end; NO_MEMORY = class(SystemException) end; IMP_LIMIT = class(SystemException) end; COMM_FAILURE = class(SystemException) end; INV_OBJREF = class(SystemException) end; NO_PERMISSION = class(SystemException) end; INTERNAL = class(SystemException) end; MARSHAL = class(SystemException) end; INITIALIZE = class(SystemException) end; NO_IMPLEMENT = class(SystemException) end; BAD_TYPECODE = class(SystemException) end; BAD_OPERATION = class(SystemException) end; NO_RESOURCES = class(SystemException) end; NO_RESPONSE = class(SystemException) end; PERSIST_STORE = class(SystemException) end; BAD_INV_ORDER = class(SystemException) end; TRANSIENT = class(SystemException) end; FREE_MEM = class(SystemException) end; INV_IDENT = class(SystemException) end; INV_FLAG = class(SystemException) end; INTF_REPOS = class(SystemException) end; BAD_CONTEXT = class(SystemException) end; OBJ_ADAPTER = class(SystemException) end; DATA_CONVERSION = class(SystemException) end; OBJECT_NOT_EXIST = class(SystemException) end; UserException = class(Exception) protected FProxy: PExceptionProxy; procedure _Copy(const InBuf: ORBPAS45.MarshalInBufferProxy); public constructor Create; procedure Copy(const Input: InputStream); virtual; abstract; procedure WriteExceptionInfo(var Output : OutputStream); virtual; abstract; procedure Throw; property Proxy: PExceptionProxy read FProxy; end; BindOptions = record DeferBind: Boolean; EnableRebind: Boolean; MaxBindTries: Integer; SendTimeOut: Cardinal; ReceiveTimeOut: Cardinal; ConnectionTimeOut: Cardinal; end; CORBAObject = interface ['{B5467DDF-8003-11D2-AAF6-00C04FB16F42}'] function _Clone: CORBAObject; procedure _CreateRequest(const Operation: string; ResponseExpected: Boolean; out Output: OutputStream); function _GetBindOptions: BindOptions; function _GetInterface: PCorbaInterfaceDef; function _Hash(Maximum: Cardinal): Cardinal; function _InterfaceName: string; procedure _Invoke(const Output: OutputStream; out Input: InputStream); function _IsA(const LogicalTypeId: string): Boolean; function _IsBound: Boolean; function _IsEquivalent(const OtherObject: CORBAObject): Boolean; function _IsLocal: Boolean; function _IsPersistent: Boolean; function _IsRemote: Boolean; function _NonExistent: Boolean; function _ObjectName: string; procedure _PrepareReply(out Output: OutputStream); function _RepositoryId: string; procedure _SetBindOptions(const Options: BindOptions); property _BindOptions: BindOptions read _GetBindOptions write _SetBindOptions; end; TCORBAObject = class(TInterfacedObject, CORBAObject, ProxyUser, ISkeletonObject) protected FProxy: ORBPAS45.ObjectProxy; function Proxy: IUnknown; constructor Create(const Proxy: ORBPAS45.ObjectProxy); overload; constructor Create(const Obj: CORBAObject); overload; constructor CreateSkeleton(const InstanceName, InterfaceName, RepositoryId: string); procedure GetSkeleton(out Skeleton: ISkeleton); stdcall; procedure GetImplementation(out Impl: IUnknown); stdcall; function Execute(Operation: PChar; const Strm: MarshalInBufferProxy; Cookie: Pointer): CorbaBoolean; stdcall; function _is_a(LogicalTypeId: PChar): ByteBool; stdcall; procedure GetReplyBuffer(Cookie : Pointer; out Outbuf: OutputStream); procedure GetExceptionReplyBuffer(Cookie : Pointer; out Outbuf: OutputStream); public function _GetInterface: PCorbaInterfaceDef; function _IsA(const LogicalTypeId: string): Boolean; function _NonExistent: Boolean; function _IsEquivalent(const OtherObject: CORBAObject): Boolean; function _Hash(Maximum: Cardinal): Cardinal; function _IsLocal: Boolean; function _IsRemote: Boolean; function _IsBound: Boolean; function _IsPersistent: Boolean; function _Clone: CORBAObject; procedure _CreateRequest(const Operation: string; ResponseExpected: Boolean; out Output: OutputStream); procedure _Invoke(const Output: OutputStream; out Input: InputStream); procedure _SetBindOptions(const Options: BindOptions); function _GetBindOptions: BindOptions; function _RepositoryId: string; function _ObjectName: string; function _InterfaceName: string; procedure _PrepareReply(out Output: OutputStream); destructor Destroy; override; property _BindOptions: BindOptions read _GetBindOptions write _SetBindOptions; end; InputStream = interface procedure ReadBoolean(out Value: Boolean); procedure ReadChar(out Value: Char); procedure ReadWChar(out Value: WideChar); procedure ReadOctet(out Value: Byte); procedure ReadShort(out Value: SmallInt); procedure ReadUShort(out Value: Word); procedure ReadLong(out Value: Integer); procedure ReadULong(out Value: Cardinal); procedure ReadLongLong(out Value: Int64); procedure ReadULongLong(out Value: Int64); procedure ReadFloat(out Value: Single); procedure ReadDouble(out Value: Double); procedure ReadLongDouble(out Value: Extended); procedure ReadString(out Value: string); procedure ReadWString(out Value: WideString); procedure ReadBooleanArray(out Value: array of Boolean); procedure ReadCharArray(out Value: array of Char); procedure ReadWCharArray(out Value: array of WideChar); procedure ReadOctetArray(out Value: array of Byte); procedure ReadShortArray(out Value: array of SmallInt); procedure ReadUShortArray(out Value: array of Word); procedure ReadLongArray(out Value: array of Integer); procedure ReadULongArray(out Value: array of Cardinal); procedure ReadLongLongArray(out Value: array of Int64); procedure ReadULongLongArray(out Value: array of Int64); procedure ReadFloatArray(out Value: array of Single); procedure ReadDoubleArray(out Value: array of Double); procedure ReadLongDoubleArray(out Value: array of Extended); procedure ReadObject(out Value: CORBAObject); procedure ReadTypeCode(out Value: TypeCode); procedure ReadAny(out Value: Any); procedure ReadPrincipal(out Value : Principal); //dummy method end; OutputStream = interface function CreateInputStream: InputStream; procedure WriteBoolean(Value: Boolean); procedure WriteChar(Value: Char); procedure WriteWChar(Value: WideChar); procedure WriteOctet(Value: Byte); procedure WriteShort(Value: SmallInt); procedure WriteUShort(Value: Word); procedure WriteLong(Value: Integer); procedure WriteULong(Value: Cardinal); procedure WriteLongLong(Value: Int64); procedure WriteULongLong(Value: Int64); procedure WriteFloat(Value: Single); procedure WriteDouble(Value: Double); procedure WriteLongDouble(Value: Extended); procedure WriteString(const Value: string); procedure WriteWString(const Value: WideString); procedure WriteBooleanArray(const Value: array of Boolean); procedure WriteCharArray(const Value: array of Char); procedure WriteWCharArray(const Value: array of WideChar); procedure WriteOctetArray(const Value: array of Byte); procedure WriteShortArray(const Value: array of SmallInt); procedure WriteUShortArray(const Value: array of Word); procedure WriteLongArray(const Value: array of Integer); procedure WriteULongArray(const Value: array of Cardinal); procedure WriteLongLongArray(const Value: array of Int64); procedure WriteULongLongArray(const Value: array of Int64); procedure WriteFloatArray(const Value: array of Single); procedure WriteDoubleArray(const Value: array of Double); procedure WriteLongDoubleArray(const Value: array of Extended); procedure WriteObject(const Value: CORBAObject); procedure WriteTypeCode(const Value: TypeCode); procedure WriteAny(const Value: Any); procedure WritePrincipal(const Value : Principal); //dummy method end; Identifier = string; TIdentifierHelper = class class procedure Insert(var A: Any; const Value: Identifier); class function Extract(const A: Any): Identifier; class function TypeCode: TypeCode; class function RepositoryId: string; class function Read(const Input: InputStream): Identifier; class procedure Write(const Output: OutputStream; const Value: Identifier); end; RepositoryId = string; ScopedName = string; DefinitionKind = (dk_none, dk_all, dk_Attribute, dk_Constant, dk_Exception, dk_Interface, dk_Module, dk_Operation, dk_Typedef, dk_Alias, dk_Struct, dk_Union, dk_Enum, dk_Primitive, dk_String, dk_Sequence, dk_Array, dk_Repository, dk_Wstring); TDefinitionKindHelper = class class procedure Insert(var A: Any; const Value: DefinitionKind); class function Extract(const A: Any): DefinitionKind; class function TypeCode: TypeCode; class function RepositoryId: string; class function Read(const Input: InputStream): DefinitionKind; class procedure Write(const Output: OutputStream; const Value: DefinitionKind); end; IRObject = interface ['{E190D1E3-A996-11D2-AB01-00C04FB16F42}'] function _get_def_kind: DefinitionKind; function _get_comment: string; procedure _set_comment(const Value: string); function _get_file_name: string; procedure _set_file_name(const Value: string); procedure destroy; property def_kind: DefinitionKind read _get_def_kind; property comment: string read _get_comment write _set_comment; property file_name: string read _get_file_name write _set_file_name; end; TIRObjectHelper = class class procedure Insert(var A: Any; const Value: IRObject); class function Extract(var A: Any): IRObject; class function TypeCode: TypeCode; class function RepositoryId: string; class function Read(const Input: InputStream): IRObject; class procedure Write(const Output: OutputStream; const Value: IRObject); class function Narrow(const Obj: CORBAObject; IsA: Boolean = False): IRObject; class function Bind(const InstanceName: string = ''; HostName: string = ''): IRObject; end; TIRObjectStub = class(TCORBAObject, IRObject) public function _get_def_kind: DefinitionKind; virtual; function _get_comment: string; virtual; procedure _set_comment(const Value: string); virtual; function _get_file_name: string; virtual; procedure _set_file_name(const Value: string); virtual; procedure destroy; virtual; property def_kind: DefinitionKind read _get_def_kind; property comment: string read _get_comment write _set_comment; property file_name: string read _get_file_name write _set_file_name; end; IDLType = interface(IRObject) ['{E190D1E4-A996-11D2-AB01-00C04FB16F42}'] function _get_type: TypeCode; property _type: TypeCode read _get_type; end; TIDLTypeHelper = class class procedure Insert(var A: Any; const Value: IDLType); class function Extract(var A: Any): IDLType; class function TypeCode: TypeCode; class function RepositoryId: string; class function Read(const Input: InputStream): IDLType; class procedure Write(const Output: OutputStream; const Value: IDLType); class function Narrow(const Obj: CORBAObject; IsA: Boolean = False): IDLType; class function Bind(const InstanceName: string = ''; HostName: string = ''): IDLType; end; TIDLTypeStub = class(TIRObjectStub, IDLType) public function _get_type: TypeCode; virtual; property _type: TypeCode read _get_type; end; TBOA = class private BOA: IBOA; public class procedure Initialize(const CommandLine: TCommandLine = nil); destructor Destroy; override; procedure ObjIsReady(const Obj: _Object); procedure ImplIsReady; procedure Deactivate(const Obj: _Object); function GetPrincipalLength(const Proxy: PCorbaObject): CorbaULong; stdcall; procedure GetPrincipal(const Proxy: PCorbaObject; out ByteBuf); procedure SetScope(const Val : RegistrationScope); stdcall; function GetScope : RegistrationScope; stdcall; procedure ExitImplReady; stdcall; end; TPOA = class private POA: IPOA; public class procedure Initialize; destructor Destroy; override; procedure ActivateObject(const ObjectID : string; const Obj: _Object); end; TORB = class(TInterfacedObject, ProxyUser) private FProxy: ORBProxy; function Proxy: IUnknown; function MakeComplexAny(TypeCode: ITypeCode; const Elements: array of Any): Any; public class procedure Init(const CommandLine: TCommandLine); overload; class procedure Init; overload; destructor Destroy; override; { binding methods } function Bind(const RepositoryID: string; const ObjectName: string = ''; const HostName: string = ''): CORBAObject; overload; function Bind(const RepositoryID: string; const Options: BindOptions; const ObjectName: string = ''; const HostName: string = ''): CORBAObject; overload; function ObjectToString(const Obj: CORBAObject): string; function StringToObject(const ObjectString: string): CORBAObject; function ResolveInitialReferences(const ObjectName : String) : CORBAObject; { utility methods } procedure Shutdown; function CreateOutputStream: OutputStream; { TypeCode methods } function CreateTC(Kind: integer): TypeCode; function CreateStructTC(const RepositoryID, TypeName: string; const Members: StructMemberSeq): TypeCode; function CreateUnionTC(const RepositoryID, TypeName: string; const DiscriminatorType: TypeCode; const Members: UnionMemberSeq): TypeCode; function CreateEnumTC(const RepositoryID, TypeName: string; const Members: array of string): TypeCode; function CreateAliasTC(const RepositoryId, TypeName: string; const OrginalType: TypeCode): TypeCode; function CreateExceptionTC(const RepositoryId, TypeName: string; const Members: StructMemberSeq): TypeCode; function CreateInterfaceTC(const RepositoryId, TypeName: string): TypeCode; function CreateStringTC(Length: Integer): TypeCode; function CreateWStringTC(Length: Integer): TypeCode; function CreateSequenceTC(Length: Integer; const ElementType: TypeCode): TypeCode; function CreateRecursiveSequenceTC(Length, Offset: Integer): TypeCode; function CreateArrayTC(Length: Integer; const ElementType: TypeCode): TypeCode; { Dynamic invocation methods } function MakeArray(Kind: TCKind; const Elements: array of Any): Any; overload; function MakeArray(TypeCode: ITypeCode; const Elements: array of Any): Any; overload; function MakeSequence(Kind: TCKind; const Elements: array of Any): Any; overload; function MakeSequence(TypeCode: ITypeCode; const Elements: array of Any): Any; overload; function MakeStructure(TypeCode: ITypeCode; const Elements: array of Any): Any; function MakeAlias(const RepositoryID, TypeName: string; Value, Test: Any): Any; function MakeTypeCode(Kind: TCKind): ITypeCode; function MakeSequenceTypeCode(Bound: CorbaULong; const TC: ITypeCode): ITypeCode; function MakeStructureTypeCode(const RepositoryID, Name: string; Members: TStructMembers): ITypeCode; function MakeAliasTypeCode(const RepositoryID, Name: string; const TC: ITypeCode): ITypeCode; function MakeObjectRefTypeCode(const RepositoryID, Name: string): ITypeCode; function MakeObjectRef(tc : ITypeCode; const Obj: CorbaObject) : Any; procedure GetAny(Value : Any; out Input: InputStream); function GetObjectRef(var A : Any) : CORBAObject; procedure PutAny(var A : Any; const tc : ITypeCode; const Output : OutputStream); end; TCorbaListManager = class private FSync: TMultiReadExclusiveWriteSynchronizer; protected procedure BeginRead; procedure BeginWrite; procedure EndRead; procedure EndWrite; public constructor Create; destructor Destroy; override; end; TInterfaceIDEntry = record RepositoryID: string; IID: TGUID; end; TInterfaceIDManager = class(TCorbaListManager) private FList: array of TInterfaceIDEntry; FUsed: Integer; public procedure RegisterInterface(const IID: TGUID; const RepositoryID: string); function FindIID(const RepositoryID: string; out IID: TGUID): Boolean; function FindRepositoryID(const IID: TGUID; out RepositoryID: string): Boolean; procedure GetInterfaceList(var stList : TStringList); end; //This class is depreciated by Corba 2.2 Principal = class public procedure name; end; { CORBA helper routines } procedure CorbaInitialize; function BOA: TBOA; function ORB: TORB; function POA: TPOA; function RegisterUserException(const Name, RepositoryID: String; Factory: TUserExceptionFactoryProc): PExceptionDescription; forward; procedure UnRegisterUserException(Description: PExceptionDescription); forward; { Global variables } var InterfaceIDManager: TInterfaceIDManager; implementation uses Windows, CorbCnst; type TInputStream = class(TInterfacedObject, InputStream, ProxyUser) private FProxy : ORBPAS45.MarshalInBufferProxy; function Proxy: IUnknown; public procedure ReadBoolean(out Value: Boolean); procedure ReadChar(out Value: Char); procedure ReadWChar(out Value: WideChar); procedure ReadOctet(out Value: Byte); procedure ReadShort(out Value: SmallInt); procedure ReadUShort(out Value: Word); procedure ReadLong(out Value: Integer); procedure ReadULong(out Value: Cardinal); procedure ReadLongLong(out Value: Int64); procedure ReadULongLong(out Value: Int64); procedure ReadFloat(out Value: Single); procedure ReadDouble(out Value: Double); procedure ReadLongDouble(out Value: Extended); procedure ReadString(out Value: string); procedure ReadWString(out Value: WideString); procedure ReadBooleanArray(out Value: array of Boolean); procedure ReadCharArray(out Value: array of Char); procedure ReadWCharArray(out Value: array of WideChar); procedure ReadOctetArray(out Value: array of Byte); procedure ReadShortArray(out Value: array of SmallInt); procedure ReadUShortArray(out Value: array of Word); procedure ReadLongArray(out Value: array of Integer); procedure ReadULongArray(out Value: array of Cardinal); procedure ReadLongLongArray(out Value: array of Int64); procedure ReadULongLongArray(out Value: array of Int64); procedure ReadFloatArray(out Value: array of Single); procedure ReadDoubleArray(out Value: array of Double); procedure ReadLongDoubleArray(out Value: array of Extended); procedure ReadObject(out Value: CORBAObject); procedure ReadTypeCode(out Value: TypeCode); procedure ReadAny(out Value: Any); procedure ReadPrincipal(out Value : Principal); constructor Create(Proxy: ORBPAS45.MarshalInBufferProxy); destructor Destroy; override; end; TOutputStream = class(TInterfacedObject, OutputStream, ProxyUser) private FProxy : ORBPAS45.MarshalOutBufferProxy; function Proxy: IUnknown; public function CreateInputStream: InputStream; procedure WriteBoolean(Value: Boolean); procedure WriteChar(Value: Char); procedure WriteWChar(Value: WideChar); procedure WriteOctet(Value: Byte); procedure WriteShort(Value: SmallInt); procedure WriteUShort(Value: Word); procedure WriteLong(Value: Integer); procedure WriteULong(Value: Cardinal); procedure WriteLongLong(Value: Int64); procedure WriteULongLong(Value: Int64); procedure WriteFloat(Value: Single); procedure WriteDouble(Value: Double); procedure WriteLongDouble(Value: Extended); procedure WriteString(const Value: string); procedure WriteWString(const Value: WideString); procedure WriteBooleanArray(const Value: array of Boolean); procedure WriteCharArray(const Value: array of Char); procedure WriteWCharArray(const Value: array of WideChar); procedure WriteOctetArray(const Value: array of Byte); procedure WriteShortArray(const Value: array of SmallInt); procedure WriteUShortArray(const Value: array of Word); procedure WriteLongArray(const Value: array of Integer); procedure WriteULongArray(const Value: array of Cardinal); procedure WriteLongLongArray(const Value: array of Int64); procedure WriteULongLongArray(const Value: array of Int64); procedure WriteFloatArray(const Value: array of Single); procedure WriteDoubleArray(const Value: array of Double); procedure WriteLongDoubleArray(const Value: array of Extended); procedure WriteObject(const Value: CORBAObject); procedure WriteTypeCode(const Value: TypeCode); procedure WriteAny(const Value: Any); procedure WritePrincipal(const Value : Principal); constructor Create(Proxy: ORBPAS45.MarshalOutBufferProxy); destructor Destroy; override; end; var BOAVar: TBOA; POAVar: TPOA; ORBVar: TORB; procedure CorbaHookDispatch; forward; procedure CorbaHookExceptions; forward; procedure PBindOptionsToBindOptions(Source: ORBPAS45.PBindOptions; var Dest: BindOptions); begin Dest.DeferBind := Source.defer_bind; Dest.EnableRebind := Source.enable_rebind; Dest.MaxBindTries := Source.max_bind_tries; Dest.SendTimeOut := Source.send_timeout; Dest.ReceiveTimeOut := Source.receive_timeout; Dest.ConnectionTimeOut := Source.connection_timeout; end; procedure BindOptionsToPBindOptions(const Source: BindOptions; var Dest: ORBPAS45.BindOptions); begin Dest.defer_bind := Source.DeferBind; Dest.enable_rebind := Source.EnableRebind; Dest.max_bind_tries := Source.MaxBindTries; Dest.send_timeout := Source.SendTimeOut; Dest.receive_timeout := Source.ReceiveTimeOut; Dest.connection_timeout := Source.ConnectionTimeOut; end; { TCORBAObject } constructor TCORBAObject.Create(const Proxy: ORBPAS45.ObjectProxy); begin FProxy := Proxy; FProxy.set_proxy_user(Self); end; constructor TCORBAObject.Create(const Obj: CORBAObject); begin with Obj as ProxyUser do Create(Proxy as ORBPAS45.ObjectProxy); end; constructor TCORBAObject.CreateSkeleton(const InstanceName, InterfaceName, RepositoryId: string); var Proxy : ORBPAS45.ObjectProxy; begin ORBPAS45.CreateSkeletonProxy(PChar(Pointer(InterfaceName)), Self, PChar(Pointer(InstanceName)), PChar(Pointer(RepositoryID)), Proxy); Create(Proxy); end; destructor TCORBAObject.Destroy; begin try FProxy := nil; except // Ignore exceptions when disconnecting end; inherited Destroy; end; function TCORBAObject.Proxy: IUnknown; begin Result := FProxy; end; function TCORBAObject._Clone: CORBAObject; begin Result := Self; end; procedure TCORBAObject._CreateRequest(const Operation: string; ResponseExpected: Boolean; out Output: OutputStream); var Proxy: ORBPAS45.MarshalOutBufferProxy; begin FProxy.create_request(PChar(Pointer(Operation)), ResponseExpected, Proxy); Output := TOutputStream.Create(Proxy); end; {ISkeletonObject} function TCORBAObject.Execute(Operation: PChar; const Strm: MarshalInBufferProxy; Cookie: Pointer): CorbaBoolean; type TUnmarshalProc = procedure (const Input: InputStream; Cookie: Pointer) of object; var M: TUnmarshalProc; inBuf : TInputStream; begin Result := False; try TMethod(M).Code := Self.MethodAddress('_' + Operation); if TMethod(M).Code = nil then Exit; TMethod(M).Data := Self; inBuf := TInputStream.Create(Strm); try M(inBuf, Cookie); finally inBuf.free; end; except Exit; end; Result := True; end; procedure TCORBAObject.GetSkeleton(out Skeleton: ISkeleton); begin Skeleton := FProxy as ISkeleton; end; procedure TCORBAObject.GetImplementation(out Impl: _Object); begin Impl := nil; end; function TCORBAObject._is_a(LogicalTypeId: PChar): ByteBool; begin Result := _ISA(LogicalTypeId); end; procedure TCORBAObject.GetReplyBuffer(Cookie : Pointer; out Outbuf: OutputStream); var Proxy: ORBPAS45.MarshalOutBufferProxy; begin (FProxy as ObjectProxy).GetReplyBuffer(Cookie, Proxy); Outbuf := TOutputStream.Create(Proxy); end; procedure TCORBAObject.GetExceptionReplyBuffer(Cookie : Pointer; out Outbuf: OutputStream); var Proxy: ORBPAS45.MarshalOutBufferProxy; begin (FProxy as ObjectProxy).GetExceptionReplyBuffer(Cookie, Proxy); Outbuf := TOutputStream.Create(Proxy); end; function TCORBAObject._GetBindOptions: BindOptions; begin PBindOptionsToBindOptions(FProxy.get_bind_options, Result); end; function TCORBAObject._GetInterface: PCorbaInterfaceDef; begin Result := FProxy.get_interface; end; procedure TCORBAObject._Invoke(const Output: OutputStream; out Input: InputStream); var Proxy: ORBPAS45.MarshalInBufferProxy; begin FProxy.invoke((Output as ProxyUser).Proxy as ORBPAS45.MarshalOutBufferProxy, Proxy); Input := TInputStream.Create(Proxy); end; function TCORBAObject._IsA(const LogicalTypeId: string): Boolean; var IID: TGUID; Obj: _Object; begin Result := False; if InterfaceIDManager.FindIID(LogicalTypeId, IID) then Result := inherited QueryInterface(IID, Obj) = 0; if not Result and _IsRemote then Result := FProxy.is_a(PChar(Pointer(LogicalTypeId))); end; function TCORBAObject._IsBound: Boolean; begin Result := FProxy.is_bound; end; function TCORBAObject._IsEquivalent(const OtherObject: CORBAObject): Boolean; begin Result := FProxy.is_equivalent((OtherObject as ProxyUser).Proxy as ORBPAS45.ObjectProxy); end; function TCORBAObject._IsLocal: Boolean; begin Result := FProxy.is_local; end; function TCORBAObject._IsPersistent: Boolean; begin Result := FProxy.is_persistent; end; function TCORBAObject._IsRemote: Boolean; begin Result := not FProxy.is_local; end; function TCORBAObject._Hash(Maximum: Cardinal): Cardinal; begin Result := FProxy.hash(Maximum); end; function TCORBAObject._NonExistent: Boolean; begin Result := FProxy.non_existent; end; function TCORBAObject._ObjectName: string; begin Result := FProxy.object_name; end; function TCORBAObject._InterfaceName: string; begin Result := FProxy.interface_name; end; procedure TCORBAObject._PrepareReply(out Output: OutputStream); var Proxy: ORBPAS45.MarshalOutBufferProxy; begin FProxy.prepare_reply(Proxy); Output := TOutputStream.Create(Proxy); end; function TCORBAObject._RepositoryId: string; begin Result := FProxy.repository_id; end; procedure TCORBAObject._SetBindOptions(const Options: BindOptions); var Temp: ORBPAS45.BindOptions; begin BindOptionsToPBindOptions(Options, Temp); FProxy.set_bind_options(@Temp); end; { TInputStream } constructor TInputStream.Create(Proxy: ORBPAS45.MarshalInBufferProxy); begin FProxy := Proxy; end; destructor TInputStream.Destroy; begin inherited Destroy; FProxy := nil; end; function TInputStream.Proxy: IUnknown; begin Result := FProxy; end; procedure TInputStream.ReadBoolean(out Value: Boolean); var Temp: Byte; begin FProxy.get_unsigned_char(Temp); Value := Temp <> $00; end; procedure TInputStream.ReadChar(out Value: Char); begin FProxy.get_char(Value); end; procedure TInputStream.ReadWChar(out Value: WideChar); begin FProxy.get_wchar(Value); end; procedure TInputStream.ReadOctet(out Value: Byte); begin FProxy.get_unsigned_char(Value); end; procedure TInputStream.ReadShort(out Value: SmallInt); begin FProxy.get_short(Value); end; procedure TInputStream.ReadUShort(out Value: Word); begin FProxy.get_unsigned_short(Value); end; procedure TInputStream.ReadLong(out Value: Integer); begin FProxy.get_long(Value); end; procedure TInputStream.ReadULong(out Value: Cardinal); begin FProxy.get_unsigned_long(Value); end; procedure TInputStream.ReadLongLong(out Value: Int64); begin FProxy.get_long_long(Value); end; procedure TInputStream.ReadULongLong(out Value: Int64); begin FProxy.get_unsigned_long_long(Value); end; procedure TInputStream.ReadFloat(out Value: Single); begin FProxy.get_float(Value); end; procedure TInputStream.ReadDouble(out Value: Double); begin FProxy.get_double(Value); end; procedure TInputStream.ReadLongDouble(out Value: Extended); begin FProxy.get_long_double(Value); end; procedure TInputStream.ReadString(out Value: string); var L: Cardinal; temp : Char; begin FProxy.get_unsigned_long(L); SetLength(Value, L-1); if L = 1 then FProxy.get_char(temp) else FProxy.get_char_ptr(PChar(Pointer(Value)), L); end; procedure TInputStream.ReadWString(out Value: WideString); var L: Cardinal; temp : wChar; begin FProxy.get_unsigned_long(L); SetLength(Value, L-1); if L = 1 then FProxy.get_wchar(temp) else FProxy.get_wchar_ptr(PWideChar(Pointer(Value)), L); end; procedure TInputStream.ReadBooleanArray(out Value: array of Boolean); var I: Integer; Temp: array of Byte; begin SetLength(Temp, Length(Value)); FProxy.get_unsigned_char_array(Temp); for I := Low(Temp) to High(Temp) do Value[I] := Temp[I] <> $00; end; procedure TInputStream.ReadCharArray(out Value: array of Char); begin FProxy.get_char_ptr(Value, Length(Value)); end; procedure TInputStream.ReadWCharArray(out Value: array of WideChar); begin FProxy.get_wchar_ptr(Value, Length(Value)); end; procedure TInputStream.ReadOctetArray(out Value: array of Byte); begin FProxy.get_unsigned_char_array(Value); end; procedure TInputStream.ReadShortArray(out Value: array of SmallInt); begin FProxy.get_short_array(Value); end; procedure TInputStream.ReadUShortArray(out Value: array of Word); begin FProxy.get_unsigned_short_array(Value); end; procedure TInputStream.ReadLongArray(out Value: array of Integer); begin FProxy.get_long_array(Value); end; procedure TInputStream.ReadULongArray(out Value: array of Cardinal); begin FProxy.get_unsigned_long_array(Value); end; procedure TInputStream.ReadLongLongArray(out Value: array of Int64); begin FProxy.get_long_long_array(Value); end; procedure TInputStream.ReadULongLongArray(out Value: array of Int64); begin FProxy.get_unsigned_long_long_array(Value); end; procedure TInputStream.ReadFloatArray(out Value: array of Single); begin FProxy.get_float_array(Value); end; procedure TInputStream.ReadDoubleArray(out Value: array of Double); begin FProxy.get_double_array(Value); end; procedure TInputStream.ReadLongDoubleArray(out Value: array of Extended); begin FProxy.get_long_double_array(Value); end; procedure TInputStream.ReadObject(out Value: CORBAObject); var Proxy, tempProxy: ORBPAS45.ObjectProxy; begin FProxy.get_object(Proxy); if (Proxy <> nil) then begin if Proxy.QueryInterface(CORBAObject, Value) = 0 then Exit else if Proxy.QueryInterface(ObjectProxy, tempProxy) = 0 then Value := TCorbaObject.Create(tempProxy); end else Value := nil; end; procedure TInputStream.ReadTypeCode(out Value: TypeCode); begin FProxy.get_typecode(Value); end; procedure TInputStream.ReadAny(out Value: Any); var pTempCorbaAny : PCorbaAny; temp : Any; begin FProxy.Get_Any(pTempCorbaAny); if AnyToVariant(pTempCorbaAny, @temp) then Value := temp; end; procedure TInputStream.ReadPrincipal(out Value : Principal); begin Value := nil; end; { TOutputStream } constructor TOutputStream.Create(Proxy: ORBPAS45.MarshalOutBufferProxy); begin FProxy := Proxy; end; destructor TOutputStream.Destroy; begin inherited Destroy; FProxy := nil end; function TOutputStream.Proxy: _Object; begin Result := FProxy; end; function TOutputStream.CreateInputStream: InputStream; var inBuf : MarshalInBufferProxy; begin FProxy.CreateInputStream(Pointer(inBuf)); result := TInputStream.Create(inbuf); end; procedure TOutputStream.WriteBoolean(Value: Boolean); begin if Value then FProxy.put_unsigned_char($01) else FProxy.put_unsigned_char($00) end; procedure TOutputStream.WriteChar(Value: Char); begin FProxy.put_char(Value); end; procedure TOutputStream.WriteWChar(Value: WideChar); begin FProxy.put_wchar(Value); end; procedure TOutputStream.WriteOctet(Value: Byte); begin FProxy.put_unsigned_char(Value); end; procedure TOutputStream.WriteShort(Value: SmallInt); begin FProxy.put_short(Value); end; procedure TOutputStream.WriteUShort(Value: Word); begin FProxy.put_unsigned_short(Value); end; procedure TOutputStream.WriteLong(Value: Integer); begin FProxy.put_long(Value); end; procedure TOutputStream.WriteULong(Value: Cardinal); begin FProxy.put_unsigned_long(Value); end; procedure TOutputStream.WriteLongLong(Value: Int64); begin FProxy.put_long_long(Value); end; procedure TOutputStream.WriteULongLong(Value: Int64); begin FProxy.put_unsigned_long_long(Value); end; procedure TOutputStream.WriteFloat(Value: Single); begin FProxy.put_float(Value); end; procedure TOutputStream.WriteDouble(Value: Double); begin FProxy.put_double(Value); end; procedure TOutputStream.WriteLongDouble(Value: Extended); begin FProxy.put_long_double(Value); end; procedure TOutputStream.WriteString(const Value: string); var L: Cardinal; begin L := Length(Value) + 1; FProxy.put_unsigned_long(L); if L = 1 then FProxy.put_char_ptr('', L) else FProxy.put_char_ptr(PChar(Pointer(Value)), L); end; procedure TOutputStream.WriteWString(const Value: WideString); var L: Cardinal; begin L := Length(Value) + 1; FProxy.put_unsigned_long(L); if L = 1 then FProxy.put_wchar_ptr('', L) else FProxy.put_wchar_ptr(PWideChar(Pointer(Value)), L); end; procedure TOutputStream.WriteBooleanArray(const Value: array of Boolean); begin if Length(Value) < 1 then Exit; // need impl // FProxy.put_unsigned_char_array(Value); end; procedure TOutputStream.WriteCharArray(const Value: array of Char); begin if Length(Value) < 1 then Exit; FProxy.put_char_array(Value); end; procedure TOutputStream.WriteWCharArray(const Value: array of WideChar); begin if Length(Value) < 1 then Exit; FProxy.put_wchar_array(Value); end; procedure TOutputStream.WriteOctetArray(const Value: array of Byte); begin if Length(Value) < 1 then Exit; FProxy.put_unsigned_char_array(Value); end; procedure TOutputStream.WriteShortArray(const Value: array of SmallInt); begin if Length(Value) < 1 then Exit; FProxy.put_short_array(Value); end; procedure TOutputStream.WriteUShortArray(const Value: array of Word); begin if Length(Value) < 1 then Exit; FProxy.put_unsigned_short_array(Value); end; procedure TOutputStream.WriteLongArray(const Value: array of Integer); begin if Length(Value) < 1 then Exit; FProxy.put_long_array(Value); end; procedure TOutputStream.WriteULongArray(const Value: array of Cardinal); begin if Length(Value) < 1 then Exit; FProxy.put_unsigned_long_array(Value); end; procedure TOutputStream.WriteLongLongArray(const Value: array of Int64); begin if Length(Value) < 1 then Exit; FProxy.put_long_long_array(Value); end; procedure TOutputStream.WriteULongLongArray(const Value: array of Int64); begin if Length(Value) < 1 then Exit; FProxy.put_unsigned_long_long_array(Value); end; procedure TOutputStream.WriteFloatArray(const Value: array of Single); begin if Length(Value) < 1 then Exit; FProxy.put_float_array(Value); end; procedure TOutputStream.WriteDoubleArray(const Value: array of Double); begin if Length(Value) < 1 then Exit; FProxy.put_double_array(Value); end; procedure TOutputStream.WriteLongDoubleArray(const Value: array of Extended); begin if Length(Value) < 1 then Exit; FProxy.put_long_double_array(Value); end; procedure TOutputStream.WriteObject(const Value: CORBAObject); begin if Value = nil then begin FProxy.put_object(nil); Exit; end; FProxy.put_object((Value as ProxyUser).Proxy as ORBPAS45.ObjectProxy); end; procedure TOutputStream.WriteTypeCode(const Value: TypeCode); begin FProxy.put_typecode(Value); end; procedure TOutputStream.WriteAny(const Value: Any); var Temp: PCorbaAny; begin Temp := VariantToAny(@Value); try FProxy.Put_Any(Temp); finally CorbaReleaseAny(Temp) end; end; procedure TOutputStream.WritePrincipal(const Value : Principal); begin //dummy method Principal is depreciated in Corba 2.1 spec end; { TIdentifierHelper } class procedure TIdentifierHelper.Insert(var A: Any; const Value: Identifier); begin A := Value; end; class function TIdentifierHelper.Extract(const A: Any): Identifier; begin Result := Identifier(A) end; class function TIdentifierHelper.TypeCode: TypeCode; begin Result := ORB.CreateAliasTC(RepositoryId, 'Identifier', ORB.CreateTC( Integer(tk_string))); end; class function TIdentifierHelper.RepositoryId: string; begin Result := 'IDL:omg.org.CORBA/Identifier:1.0'; end; class function TIdentifierHelper.Read(const Input: InputStream): Identifier; begin Input.ReadString(Result); end; class procedure TIdentifierHelper.Write(const Output: OutputStream; const Value: Identifier); begin OutPut.WriteString(Value); end; { TDefinitionKindHelper } class procedure TDefinitionKindHelper.Insert(var A: Any; const Value: DefinitionKind); begin A := Value; end; class function TDefinitionKindHelper.Extract(const A: Any): DefinitionKind; begin if TypeCode.Equal(TAnyHelper.TypeCode(A)) then Result := DefinitionKind(A) else raise BAD_TYPECODE.Create; end; class function TDefinitionKindHelper.TypeCode: TypeCode; begin Result := ORB.CreateEnumTC(RepositoryId, 'DefinitionKind', ['dk_none', 'dk_all', 'dk_Attribute', 'dk_Constant', 'dk_Exception', 'dk_Interface', 'dk_Module', 'dk_Operation', 'dk_Typedef', 'dk_Alias', 'dk_Struct', 'dk_Union', 'dk_Enum', 'dk_Primitive', 'dk_String', 'dk_Sequence', 'dk_Array', 'dk_Repository', 'dk_Wstring']); end; class function TDefinitionKindHelper.RepositoryId: string; begin Result := 'IDL:omg.org.CORBA/DefinitionKind:1.0'; end; class function TDefinitionKindHelper.Read(const Input: InputStream): DefinitionKind; var Temp: Cardinal; begin Input.ReadULong(Temp); Result := DefinitionKind(Temp); end; class procedure TDefinitionKindHelper.Write(const Output: OutputStream; const Value: DefinitionKind); begin OutPut.WriteULong(Cardinal(Value)); end; { TIRObjectHelper } class procedure TIRObjectHelper.Insert(var A: Any; const Value: IRObject); begin A := Orb.MakeObjectRef(TIRObjectHelper.TypeCode, Value as CorbaObject); end; class function TIRObjectHelper.Extract(var A: Any): IRObject; var _obj : CorbaObject; begin _obj := Orb.GetObjectRef(A); result := TIRObjectHelper.Narrow(_obj, True); end; class function TIRObjectHelper.TypeCode: TypeCode; begin Result := ORB.CreateInterfaceTC(RepositoryId, 'IRObject'); end; class function TIRObjectHelper.RepositoryId: string; begin Result := 'IDL:omg.org.CORBA/IRObject:1.0'; end; class function TIRObjectHelper.Read(const Input: InputStream): IRObject; var Obj: CORBAObject; begin Input.ReadObject(Obj); Result := Narrow(Obj, True) end; class procedure TIRObjectHelper.Write(const Output: OutputStream; const Value: IRObject); begin OutPut.WriteObject(Value as CORBAObject); end; class function TIRObjectHelper.Narrow(const Obj: CORBAObject; IsA: Boolean): IRObject; begin Result := nil; if (Obj = nil) or (Obj.QueryInterface(IRObject, Result) = 0) then Exit; if IsA and Obj._IsA(RepositoryId) then Result := TIRObjectStub.Create(Obj); end; class function TIRObjectHelper.Bind(const InstanceName: string; HostName: string): IRObject; begin Result := Narrow(ORB.Bind(RepositoryId, InstanceName, HostName), True); end; { TIRObjectStub } function TIRObjectStub._get_def_kind: DefinitionKind; var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('_get_def_kind', True, Output); inherited _Invoke(Output, Input); Result := TDefinitionKindHelper.Read(Input); end; function TIRObjectStub._get_comment: string; var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('_get_comment', True, Output); inherited _Invoke(Output, Input); Input.ReadString(Result); end; procedure TIRObjectStub._set_comment(const Value: string); var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('_set_comment', True, Output); Output.WriteString(Value); inherited _Invoke(Output, Input); end; function TIRObjectStub._get_file_name: string; var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('_get_file_name', True, Output); inherited _Invoke(Output, Input); Input.ReadString(Result); end; procedure TIRObjectStub._set_file_name(const Value: string); var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('_set_file_name', True, Output); Output.WriteString(Value); inherited _Invoke(Output, Input); end; procedure TIRObjectStub.destroy; var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('destroy', True, Output); inherited _Invoke(Output, Input); end; { TIDLTypeHelper } class procedure TIDLTypeHelper.Insert(var A: Any; const Value: IDLType); begin A := Orb.MakeObjectRef(TIDLTypeHelper.TypeCode, Value as CorbaObject); end; class function TIDLTypeHelper.Extract(var A: Any): IDLType; var _obj : CorbaObject; begin _obj := Orb.GetObjectRef(A); result := TIDLTypeHelper.Narrow(_obj, True); end; class function TIDLTypeHelper.TypeCode: TypeCode; begin Result := ORB.CreateInterfaceTC(RepositoryId, 'IDLType'); end; class function TIDLTypeHelper.RepositoryId: string; begin Result := 'IDL:omg.org.CORBA/IDLType:1.0'; end; class function TIDLTypeHelper.Read(const Input: InputStream): IDLType; var Obj: CORBAObject; begin Input.ReadObject(Obj); Result := Narrow(Obj, True) end; class procedure TIDLTypeHelper.Write(const Output: OutputStream; const Value: IDLType); begin OutPut.WriteObject(Value as CORBAObject); end; class function TIDLTypeHelper.Narrow(const Obj: CORBAObject; IsA: Boolean): IDLType; begin Result := nil; if (Obj = nil) or (Obj.QueryInterface(IDLType, Result) = 0) then Exit; if IsA and Obj._IsA(RepositoryId) then Result := TIDLTypeStub.Create(Obj); end; class function TIDLTypeHelper.Bind(const InstanceName: string; HostName: string): IDLType; begin Result := Narrow(ORB.Bind(RepositoryId, InstanceName, HostName), True); end; { TIDLTypeStub } function TIDLTypeStub._get_type: TypeCode; var Output: OutputStream; Input: InputStream; begin inherited _CreateRequest('_get_type', True, Output); inherited _Invoke(Output, Input); Input.ReadTypeCode(Result); end; { SystemException } constructor SystemException.Create(Minor: Integer; Completed: CompletionStatus); begin FMinor := Minor; FCompleted := Completed; inherited Create(ClassName); end; { UserException } constructor UserException.Create; begin inherited Create(ClassName); FProxy := ORBPAS45.CreateUserException(_Copy, Throw) end; procedure UserException._Copy(const InBuf: ORBPAS45.MarshalInBufferProxy); begin Copy(TInputStream.Create(InBuf)); end; procedure UserException.Throw; begin raise Self; end; { TPOA } class procedure TPOA.Initialize; begin if POAVar = nil then begin POAVar := TPOA.Create; ORBVar.FProxy.poa_init(POAVar.POA); end; end; destructor TPOA.Destroy; begin if POA <> nil then POA := nil; inherited; end; procedure TPOA.ActivateObject(const ObjectID : string; const Obj: _Object); begin // This activates the root POA with an object name and Impl Pascal object POA.ActivateObject(PChar(Pointer(ObjectID)), ((Obj as ProxyUser).Proxy as ORBPAS45.ObjectProxy).CorbaObject); end; { TBOA } class procedure TBOA.Initialize(const CommandLine: TCommandLine); begin if BOAVar = nil then begin BOAVar := TBOA.Create; ORBVar.FProxy.boa_init(Length(CommandLine), CommandLine, BOAVar.BOA); end; end; destructor TBOA.Destroy; begin if BOA <> nil then BOA := nil; inherited Destroy; end; procedure TBOA.Deactivate(const Obj: _Object); begin BOA.ObjIsReady( ((Obj as ProxyUser).Proxy as ObjectProxy).CorbaObject); end; procedure TBOA.ImplIsReady; begin BOA.ImplIsReady; end; procedure TBOA.ObjIsReady(const Obj : _Object); begin BOA.ObjIsReady( ((Obj as ProxyUser).Proxy as ORBPAS45.ObjectProxy).CorbaObject); end; function TBOA.GetPrincipalLength(const Proxy: PCorbaObject): CorbaULong; begin result := BOA.GetPrincipalLength(Proxy); end; procedure TBOA.GetPrincipal(const Proxy: PCorbaObject; out ByteBuf); begin BOA.GetPrincipal(Proxy, ByteBuf); end; procedure TBOA.SetScope(const Val : RegistrationScope); begin BOA.SetScope(Val); end; function TBOA.GetScope : RegistrationScope; begin result := BOA.GetScope; end; procedure TBOA.ExitImplReady; begin BOA.ExitImplReady; end; { TORB } class procedure TORB.Init(const CommandLine: TCommandLine); begin ORBVar := TORB.Create(); ORBVar.FProxy := InitORB(CommandLine); end; class procedure TORB.Init; var CommandLine: TCommandLine; I: Integer; begin if ORBVar = nil then begin SetLength(CommandLine, ParamCount + 1); for I := 0 to ParamCount do CommandLine[I] := ParamStr(I); init(CommandLine); if BOAVar = nil then TBOA.Initialize(CommandLine); if POAVar = nil then TPOA.Initialize; end; end; function TORB.Proxy: IUnknown; begin Result := FProxy; end; destructor TORB.Destroy; begin if FProxy <> nil then FProxy := nil; inherited; end; function TORB.Bind(const RepositoryId, ObjectName, HostName: string): CORBAObject; var Proxy: ORBPAS45.ObjectProxy; begin FProxy.bind(PChar(Pointer(RepositoryId)), PChar(Pointer(ObjectName)), PChar(Pointer(HostName)), nil, Proxy); Result := TCorbaObject.Create(Proxy); end; function TORB.Bind(const RepositoryID: string; const Options: BindOptions; const ObjectName: string = ''; const HostName: string = ''): CORBAObject; var Proxy: ORBPAS45.ObjectProxy; Opt: ORBPAS45.BindOptions; begin BindOptionsToPBindOptions(Options, Opt); FProxy.bind(PChar(Pointer(RepositoryId)), PChar(Pointer(ObjectName)), PChar(Pointer(HostName)), @Opt, Proxy); Result := TCorbaObject.Create(Proxy); end; function TORB.ObjectToString(const Obj: CORBAObject): string; var P: PChar; begin P := FProxy.object_to_string((Obj as ProxyUser).Proxy as ORBPAS45.ObjectProxy); Result := P; end; function TORB.StringToObject(const ObjectString: string): CORBAObject; var Proxy: ORBPAS45.ObjectProxy; begin FProxy.string_to_object(PChar(Pointer(ObjectString)), Proxy); Result := TCorbaObject.Create(Proxy); end; procedure TORB.Shutdown; begin FProxy.Shutdown; end; function TORB.ResolveInitialReferences(const ObjectName : String) : CORBAObject; var Proxy : ORBPAS45.ObjectProxy; begin FProxy.resolve_initial_references(PChar(Pointer(ObjectName)), Proxy); result := TCorbaObject.Create(Proxy); end; function TORB.CreateOutputStream: OutputStream; var Proxy: ORBPAS45.MarshalOutBufferProxy; begin FProxy.create_marshaloutbuffer(Proxy); Result := TOutputStream.Create(Proxy); end; procedure TOrb.PutAny(var A : Any; const tc : ITypeCode; const Output : OutputStream); var CorbaAny : PCorbaAny; temp : Any; begin CorbaAny := nil; FProxy.Put_Any(CorbaAny, tc, (Output as ProxyUser).Proxy as ORBPAS45.MarshalOutBufferProxy); if AnyToVariant(CorbaAny, @temp) then A := temp end; { ORB TypeCode methods } function TORB.CreateTC(Kind: integer): TypeCode; begin FProxy.createTC(Kind, Result); end; function TORB.CreateStructTC(const RepositoryID, TypeName: string; const Members: StructMemberSeq): TypeCode; begin FProxy.CreateStructTC(PChar(Pointer(RepositoryID)), PChar(Pointer(TypeName)), Members, Length(Members), Result); end; function TORB.CreateUnionTC(const RepositoryID, TypeName: string; const DiscriminatorType: TypeCode; const Members: UnionMemberSeq): TypeCode; begin FProxy.create_union_tc(PChar(Pointer(RepositoryID)), PChar(Pointer(TypeName)), DiscriminatorType, Members, Length(Members), Result); end; function TORB.CreateEnumTC(const RepositoryID, TypeName: string; const Members: array of string): TypeCode; begin FProxy.create_enum_tc(PChar(Pointer(RepositoryID)), PChar(Pointer(TypeName)), Members, Result); end; function TORB.CreateAliasTC(const RepositoryId, TypeName: string; const OrginalType: TypeCode): TypeCode; begin FProxy.CreateAliasTC(PChar(Pointer(RepositoryId)), PChar(Pointer(TypeName)), OrginalType, Result); end; function TORB.CreateExceptionTC(const RepositoryId, TypeName: string; const Members: StructMemberSeq): TypeCode; begin // result := FProxy.create_exception_tc(PChar(Pointer(RepositoryID)), PChar(Pointer(TypeName)), // (Output as ProxyUser).Proxy as ORBPAS45.MarshalOutBufferProxy, Result); end; function TORB.CreateInterfaceTC(const RepositoryID, TypeName: string): TypeCode; begin FProxy.create_interface_tc(PChar(Pointer(RepositoryID)), PChar(Pointer(TypeName)), Result); end; function TORB.CreateStringTC(Length: Integer): TypeCode; begin FProxy.create_string_tc(Length, Result); end; function TORB.CreateWStringTC(Length: Integer): TypeCode; begin FProxy.create_wstring_tc(Length, Result); end; function TORB.CreateSequenceTC(Length: Integer; const ElementType: TypeCode): TypeCode; begin FProxy.CreateSequenceTC(Length, ElementType, Result); end; function TORB.CreateRecursiveSequenceTC(Length, Offset: Integer): TypeCode; begin FProxy.create_recursive_sequence_tc(Length, Offset, Result); end; function TORB.CreateArrayTC(Length: Integer; const ElementType: TypeCode): TypeCode; begin FProxy.CreateArrayTC(Length, ElementType, Result); end; procedure TOrb.GetAny(Value : Any; out Input : InputStream); var pTempCorbaAny : PCorbaAny; Proxy: ORBPAS45.MarshalInBufferProxy; begin pTempCorbaAny := VariantToAny(@Value); FProxy.Get_Any(pTempCorbaAny, Proxy); Input := TInputStream.Create(Proxy); end; { Dynamic invocation helper methods } (* function TORB.FindTypeCode(const RepositoryID: string): ITypeCode; begin FProxy.FindRepositoryTC(PChar(RepositoryID), Result); end; *) function TORB.MakeArray(Kind: TCKind; const Elements: array of Any): Any; var TC: ITypeCode; begin FProxy.CreateTC(Integer(Kind), TC); Result := MakeArray(TC, Elements); end; function TORB.MakeArray(TypeCode: ITypeCode; const Elements: array of Any): Any; begin Result := MakeComplexAny(TypeCode, Elements); end; function TORB.MakeSequence(Kind: TCKind; const Elements: array of Any): Any; var TC: ITypeCode; begin FProxy.CreateTC(Integer(Kind), TC); Result := MakeSequence(TC, Elements); end; function TORB.MakeSequence(TypeCode: ITypeCode; const Elements: array of Any): Any; begin Result := MakeComplexAny(TypeCode, Elements); end; function TORB.MakeStructure(TypeCode: ITypeCode; const Elements: array of Any): Any; begin Result := MakeComplexAny(TypeCode, Elements); end; function TORB.MakeAlias(const RepositoryID, TypeName: string; Value, Test: Any): Any; var Temp: Variant; TC, TC2: ITypeCode; begin TVarData(Temp).VAny := CorbaDuplicateAny(VariantToAny(@Value)); TVarData(Temp).VType := varAny; CorbaAnyType(TVarData(Temp).VAny, TC); FProxy.CreateAliasTC(PChar(Pointer(RepositoryID)), PChar(Pointer(TypeName)), TC, TC2); // TVarData(Result).VAny := FProxy.MakeAny(TC2, [Temp]); TVarData(Result).VType := varAny; end; function TORB.MakeTypeCode(Kind: TCKind): ITypeCode; begin FProxy.CreateTC(Integer(Kind), Result); end; function TORB.MakeSequenceTypeCode(Bound: CorbaULong; const TC: ITypeCode): ITypeCode; begin FProxy.CreateSequenceTC(Bound, TC, Result); end; function TORB.MakeStructureTypeCode(const RepositoryID, Name: string; Members: TStructMembers): ITypeCode; begin FProxy.CreateStructTC(PChar(Pointer(RepositoryID)), PChar(Pointer(Name)), Members, Length(Members), Result); end; function TORB.MakeAliasTypeCode(const RepositoryID, Name: string; const TC: ITypeCode): ITypeCode; begin FProxy.CreateAliasTC(PChar(Pointer(RepositoryID)), PChar(Pointer(Name)), TC, Result); end; function TORB.MakeObjectRefTypeCode(const RepositoryID, Name: string): ITypeCode; begin FProxy.CreateObjRefTC(PChar(Pointer(RepositoryID)), PChar(Pointer(Name)), Result); end; function TORB.MakeComplexAny(TypeCode: ITypeCode; const Elements: array of Any): Any; var pTempCorbaAny : PCorbaAny; temp : Any; begin // pTempCorbaAny := FProxy.MakeAny(TypeCode, Elements); try if AnyToVariant( pTempCorbaAny, @temp ) then result := temp; finally CorbaReleaseAny(pTempCorbaAny) end; end; function TORB.MakeObjectRef(tc : ITypeCode; const Obj: CorbaObject) : Any; var pTempCorbaAny : PCorbaAny; temp : Any; begin pTempCorbaAny := FProxy.MakeAnyObjRef(tc, (Obj as ProxyUser).Proxy as ORBPAS45.ObjectProxy); if AnyToVariant( pTempCorbaAny, @temp ) then result := temp else raise BAD_OPERATION.Create; end; function TORB.GetObjectRef(var A : Any) : CORBAObject; var Proxy: ORBPAS45.ObjectProxy; begin DelphiVariantToObject(@A, Proxy); result := TCorbaObject.Create(Proxy); end; function ORB: TORB; begin if not Assigned(ORBVar) then CorbaInitialize; Result := ORBVar; end; function BOA: TBOA; begin if not Assigned(BOAVar) then CorbaInitialize; Result := BOAVar; end; function POA : TPOA; begin if not Assigned(POAVar) then CorbaInitialize; result := POAVar; end; { TCorbaListManager } constructor TCorbaListManager.Create; begin FSync := TMultiReadExclusiveWriteSynchronizer.Create; end; destructor TCorbaListManager.Destroy; begin FSync.Free; end; procedure TCorbaListManager.BeginRead; begin FSync.BeginRead; end; procedure TCorbaListManager.BeginWrite; begin FSync.BeginWrite; end; procedure TCorbaListManager.EndRead; begin FSync.EndRead; end; procedure TCorbaListManager.EndWrite; begin FSync.EndWrite; end; { TInterfaceIDManager } procedure TInterfaceIDManager.RegisterInterface(const IID: TGUID; const RepositoryID: string); var L: Integer; begin BeginWrite; try L := Length(FList); if FUsed = L then begin if L = 0 then L := 8 else L := L * 2; SetLength(FList, L); end; FList[FUsed].IID := IID; FList[FUsed].RepositoryID := RepositoryID; Inc(FUsed); finally EndWrite; end; end; function TInterfaceIDManager.FindIID(const RepositoryID: string; out IID: TGUID): Boolean; var I: Integer; begin BeginRead; try for I := 0 to FUsed - 1 do if FList[I].RepositoryID = RepositoryID then begin IID := FList[I].IID; Result := True; Exit; end; finally EndRead; end; Result := False; end; function TInterfaceIDManager.FindRepositoryID(const IID: TGUID; out RepositoryID: string): Boolean; var I: Integer; begin BeginRead; try for I := 0 to FUsed - 1 do if CompareMem(@FList[I].IID, @IID, SizeOf(TGUID)) then begin RepositoryID := FList[I].RepositoryID; Result := True; Exit; end; finally EndRead; end; Result := False; end; procedure TInterfaceIDManager.GetInterfaceList(var stList : TStringList); var I: Integer; begin BeginRead; try for I := 0 to FUsed - 1 do stList.Add(FList[I].RepositoryID); finally EndRead; end; end; //depreciated by Corba 2.2 procedure Principal.name; begin raise NO_IMPLEMENT.Create; end; { TAnyHelper } class function TAnyHelper.TypeCode(const A: Any): TypeCode; begin case TVarData(A).VType of varEmpty : Result := ORB.CreateTC(Integer(tk_void)); varNull : Result := ORB.CreateTC(Integer(tk_null)); varSmallInt : Result := ORB.CreateTC(Integer(tk_short)); varInteger : Result := ORB.CreateTC(Integer(tk_long)); varSingle : Result := ORB.CreateTC(Integer(tk_float)); varDouble : Result := ORB.CreateTC(Integer(tk_double)); varBoolean : Result := ORB.CreateTC(Integer(tk_boolean)); varByte : Result := ORB.CreateTC(Integer(tk_octet)); varAny : Result := ORB.CreateTC(Integer(tk_any)); varUnknown : Result := ORB.CreateTC(Integer(tk_objref)); else raise BAD_TYPECODE.Create; end; end; { CORBA Dispatch } var OldVarDispProc: TVarDispProc; procedure ClearAnyImpl(var V: Variant); var P: Pointer; begin if (TVarData(V).VType = varAny) then begin TVarData(V).VType := varEmpty; P := TVarData(V).VAny; if P <> nil then CorbaReleaseAny(P); end; end; procedure ChangeAnyImpl(var V: Variant); var Tmp: Variant; begin if TVarData(V).VType = varAny then begin if not AnyToVariant(PCorbaAny(TVarData(V).VAny), @Tmp) then raise ECorbaDispatch.Create(sInvalidTypeCast); V := Tmp; end; end; procedure RefAnyImpl(var V: Variant); begin CorbaDuplicateAny(TVarData(V).VAny); end; { Corba exception mapper } type TExceptClassProc = function (P: PExceptionRecord): ExceptClass; TExceptObjectProc = function (P: PExceptionRecord): Exception; var OldExceptClassProc: TExceptClassProc; OldExceptObjectProc: TExceptObjectProc; function IsSystemException(P: PExceptionRecord; out SystemExceptionClass: ExceptClass): Boolean; const cCPPException = $EEFFACE; SystemExceptionClasses: array[0..25] of ExceptClass = ( BAD_CONTEXT, BAD_INV_ORDER, BAD_OPERATION, BAD_PARAM, BAD_TYPECODE, COMM_FAILURE, DATA_CONVERSION, FREE_MEM, IMP_LIMIT, INITIALIZE, INTERNAL, INTF_REPOS, INV_FLAG, INV_IDENT, INV_OBJREF, MARSHAL, NO_IMPLEMENT, NO_MEMORY, NO_PERMISSION, NO_RESOURCES, NO_RESPONSE, OBJ_ADAPTER, OBJECT_NOT_EXIST, PERSIST_STORE, TRANSIENT, UNKNOWN); var I: Integer; Name: PChar; begin Result := False; Name := PChar(P.ExceptionInformation[0]); if (P.ExceptionCode <> cCPPException) or (Name = nil) or (StrLComp('CORBA_', Name, 6) <> 0) then Exit; Inc(Name, 6); for I := Low(SystemExceptionClasses) to High(SystemExceptionClasses) do if CompareStr(SystemExceptionClasses[I].ClassName, Name) = 0 then begin Result := True; SystemExceptionClass := SystemExceptionClasses[I]; end; end; function CreateSystemException(P: PExceptionRecord; out E: Exception): Boolean; type SystemExceptionClass = class of SystemException; XD = packed record A: array[0..5] of LongInt; B1: Word; B2: Word; C: array[0..9] of LongInt; D1: Char; D2: Char; D: Integer; Minor: Integer; // Minor Status: Byte; // Complete end; XDP = ^XD; var EC: ExceptClass; begin Result := IsSystemException(P, EC); if Result then E := SystemExceptionClass(EC).Create( XDP(P.ExceptionInformation[2]).Minor, CompletionStatus(XDP(P.ExceptionInformation[2]).Status)); end; function CorbaGetExceptClass(P: PExceptionRecord): ExceptClass; begin if not IsSystemException(P, Result) then Result := OldExceptClassProc(P); end; function CorbaGetExceptObject(P: PExceptionRecord): Exception; begin if not CreateSystemException(P, Result) then Result := OldExceptObjectProc(P) end; procedure CorbaHookExceptions; begin OldExceptClassProc := ExceptClsProc; OldExceptObjectProc := ExceptObjProc; ExceptClsProc := @CorbaGetExceptClass; ExceptObjProc := @CorbaGetExceptObject; end; procedure CorbaUnhookExceptions; begin if ExceptClsProc = @CorbaGetExceptClass then begin ExceptClsProc := @OldExceptClassProc; if ExceptObjProc = @CorbaGetExceptObject then ExceptObjProc := @OldExceptObjectProc; end; end; procedure CorbaHookDispatch; begin ClearAnyProc := @ClearAnyImpl; ChangeAnyProc := @ChangeAnyImpl; RefAnyProc := @RefAnyImpl; OldVarDispProc := VarDispProc; // VarDispProc := @CorbaDispProc; end; procedure CorbaUnhookDispatch; begin if @ClearAnyProc = @ClearAnyImpl then begin ClearAnyProc := nil; ChangeAnyProc := nil; RefAnyProc := nil; end; // if @VarDispProc = @CorbaDispProc then // VarDispProc := OldVarDispProc; end; var Initialized: Boolean = False; procedure CorbaInitialize; begin if not Initialized then begin Initialized := True; TORB.init; CorbaHookDispatch; CorbaHookExceptions; end; end; function RegisterUserException(const Name, RepositoryID: String; Factory: TUserExceptionFactoryProc): PExceptionDescription; begin CorbaInitialize; //makes sure orb is ready when exceptions are registered result := ORBPAS45.RegisterUserException( PChar(Pointer (Name)), PChar(Pointer (RepositoryID)), Factory); end; procedure UnRegisterUserException(Description: PExceptionDescription); begin ORBPAS45.UnRegisterUserException(Description); end; initialization IsMultiThread := True; // Make memory manager thread safe InterfaceIDManager := TInterfaceIDManager.Create; finalization InterfaceIDManager.Free; BOAVar.Free; POAVar.Free; ORBVar.Free; CorbaUnhookDispatch; CorbaUnhookExceptions; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 1024,0,0} { by Behdad Esfahbod Algorithmic Problems Book September '1999 Problem 23 O(N2) Dijkstra Alg. O(N3) BellmanFord Alg. O(N3) FloydWarshal Alg. } program ShortestPathInWeightedGraph; const MaxN = 178; var N, V : Integer; G : array [1 .. MaxN, 1 .. MaxN] of Integer; A : array [1 .. MaxN] of Integer; M : array [1 .. MaxN] of Boolean; I, J, K : Integer; NegEdge, NegCycle : Boolean; TT : Longint; Time : Longint absolute $40:$6C; F : Text; procedure ReadInput; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N); for I := 1 to N do begin for J := 1 to N do begin Read(F, G[I, J]); if G[I, J] < 0 then NegEdge := True; end; Readln(F); end; Close(F); Write('Enter V : '); Readln(V); end; procedure Dijkstra; begin TT := Time; for I := 1 to N do A[I] := 10000; A[V] := 0; for K := 1 to N do begin J := 10001; for I := 1 to N do if (not M[I]) and (A[I] < J) then begin J := A[I]; K := I; end; M[K] := True; for I := 1 to N do if A[I] > A[K] + G[K, I] then A[I] := A[K] + G[K, I]; end; Writeln('Dijkstra''s Time : ', (Time - TT) / 18.2 : 0 : 2); Assign(F, 'ssspd.out'); Rewrite(F); if NegEdge then Writeln(F, 'Graph has Negative Edge(s), Dijkstra Algorithm dosn''t work.') else for I := 1 to N do Writeln(F, A[I]); Close(F); end; procedure BellManFord; begin TT := Time; for I := 1 to N do A[I] := 10000; A[V] := 0; for K := 1 to N do begin NegCycle := False; for I := 1 to N do for J := 1 to N do if A[J] > A[I] + G[I, J] then begin A[J] := A[I] + G[I, J]; NegCycle := True; end; end; Writeln('BellmanFord''s Time : ', (Time - TT) / 18.2 : 0 : 2); Assign(F, 'ssspb.out'); Rewrite(F); if NegCycle then Writeln(F, 'Graph has Negative Cycle(s), BellmanFord Algorithm dosn''t work.') else for I := 1 to N do Writeln(F, A[I]); Close(F); end; procedure FloydWarshal; begin TT := Time; for I := 1 to N do G[I, I] := 0; for K := 1 to N do for I := 1 to N do for J := 1 to N do if G[I, J] > G[I, K] + G[K, J] then G[I, J] := G[I, K] + G[K, J]; Writeln('FloydWarshal''s Time : ', (Time - TT) / 18.2 : 0 : 2); Assign(F, 'apsp.out'); Rewrite(F); if NegCycle then Writeln(F, 'Graph has Negative Cycle(s), FloydWarshal Algorithm dosn''t work.') else for I := 1 to N do begin for J := 1 to N do Write(F, G[I, J] : 2, ' '); Writeln(F); end; Close(F); end; begin ReadInput; Dijkstra; BellmanFord; FloydWarshal; end.
{**********************************************} { TChartObject (or derived) Editor Dialog } { Copyright (c) 1999-2004 by David Berneda } {**********************************************} unit TeeCustomShapeEditor; {$I TeeDefs.inc} interface uses {$IFDEF CLR} Classes, Borland.VCL.Controls, Borland.VCL.Forms, Borland.VCL.ComCtrls, Borland.VCL.StdCtrls, Borland.VCL.ExtCtrls, {$ELSE} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, {$ENDIF} {$ENDIF} TeeProcs, TeeEdiGrad, TeeEdiFont, TeCanvas, TeePenDlg, TeeShadowEditor; type TFormTeeShape = class(TForm) PC1: TPageControl; TabFormat: TTabSheet; BBackColor: TButtonColor; Button4: TButtonPen; Button6: TButton; CBRound: TCheckBox; CBTransparent: TCheckBox; TabGradient: TTabSheet; TabText: TTabSheet; CBBevel: TComboFlat; TabShadow: TTabSheet; Label2: TLabel; Label3: TLabel; EBevWidth: TEdit; UDBevW: TUpDown; Label4: TLabel; EShadowTransp: TEdit; UDShadowTransp: TUpDown; procedure BColorClick(Sender: TObject); procedure CBRoundClick(Sender: TObject); procedure BBrushClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CBTransparentClick(Sender: TObject); procedure CBBevelChange(Sender: TObject); procedure EBevWidthChange(Sender: TObject); procedure EShadowTranspChange(Sender: TObject); procedure CBVisibleChecked(Sender: TObject); private { Private declarations } CreatingForm : Boolean; FFontEditor : TTeeFontEditor; FGradientEditor : TTeeGradientEditor; FShadowEditor : TTeeShadowEditor; Procedure EnableBevel; public { Public declarations } TheShape : TTeeCustomShape; Constructor Create(AOwner:TComponent); override; class Function CreateForm(AOwner:TComponent; AShape:TTeeCustomShape; AParent:TWinControl=nil):TFormTeeShape; procedure RefreshControls(AShape:TTeeCustomShape); end; Function InsertTeeObjectForm(APageControl:TPageControl; AShape:TTeeCustomShape):TFormTeeShape; Procedure EditTeeCustomShape(AOwner:TComponent; AShape:TTeeCustomShape); implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeConst, TeeBrushDlg; class Function TFormTeeShape.CreateForm( AOwner:TComponent; AShape:TTeeCustomShape; AParent:TWinControl=nil):TFormTeeShape; begin result:=TFormTeeShape.Create(AOwner); result.TheShape:=AShape; if Assigned(AParent) then with result do begin BorderStyle:=TeeFormBorderStyle; Parent:=AParent; TeeTranslateControl(result); Align:=alClient; {$IFDEF CLX} TeeFixParentedForm(result); {$ENDIF} Show; end; end; Function InsertTeeObjectForm(APageControl:TPageControl; AShape:TTeeCustomShape):TFormTeeShape; var tmp : TTabSheet; begin result:=TFormTeeShape.CreateForm(APageControl.Owner,AShape); with result do begin BorderStyle:=TeeFormBorderStyle; Parent:=APageControl; Align:=alClient; While PC1.PageCount>0 do begin tmp:=PC1.Pages[0]; tmp.PageControl:=APageControl; {$IFDEF CLX} tmp.Show; {$ENDIF} end; APageControl.ActivePage:=APageControl.Pages[0]; TeeTranslateControl(result); end; end; Procedure EditTeeCustomShape(AOwner:TComponent; AShape:TTeeCustomShape); var tmp : TFormTeeShape; tmpPanel : TPanel; begin tmp:=TFormTeeShape.CreateForm(AOwner,AShape); with tmp do try BorderStyle:=TeeBorderStyle; Height:=Height+30; tmpPanel:=TPanel.Create(tmp); with tmpPanel do begin Height:=34; BevelOuter:=bvNone; Align:=alBottom; Parent:=tmp; end; with TButton.Create(tmp) do begin Left:=tmp.Width-98; Top:=4; Caption:='OK'; ModalResult:=mrOk; Parent:=tmpPanel; end; ShowModal; finally Free; end; end; // Constructor, for CLX compatib. Constructor TFormTeeShape.Create(AOwner:TComponent); begin CreatingForm:=True; inherited; end; procedure TFormTeeShape.BColorClick(Sender: TObject); begin CBTransparent.Checked:=False; end; procedure TFormTeeShape.CBRoundClick(Sender: TObject); begin if CBRound.Checked then TheShape.ShapeStyle:=fosRoundRectangle else TheShape.ShapeStyle:=fosRectangle end; procedure TFormTeeShape.BBrushClick(Sender: TObject); begin EditChartBrush(Self,TheShape.Brush); end; type TShapeAccess=class(TTeeCustomShape); procedure TFormTeeShape.RefreshControls(AShape:TTeeCustomShape); begin CreatingForm:=True; TheShape:=AShape; With {$IFNDEF CLR}TShapeAccess{$ENDIF}(TheShape) do begin CBRound.Checked :=ShapeStyle=fosRoundRectangle; CBTransparent.Checked :=Transparent; CBBevel.ItemIndex :=Ord(Bevel); UDBevW.Position :=BevelWidth; UDShadowTransp.Position:={$IFDEF CLR}TShapeAccess(TheShape).{$ENDIF}Transparency; FGradientEditor.RefreshGradient(Gradient); FFontEditor.RefreshControls(Font); FShadowEditor.RefreshControls(Shadow); Button4.LinkPen(Frame); end; BBackColor.LinkProperty(TheShape,'Color'); EnableBevel; CreatingForm:=False; end; Procedure TFormTeeShape.EnableBevel; begin EnableControls(TheShape.Bevel<>bvNone,[EBevWidth,UDBevW]); end; procedure TFormTeeShape.FormShow(Sender: TObject); begin PC1.ActivePage:=TabFormat; if Assigned(TheShape) then RefreshControls(TheShape); TeeTranslateControl(Self); end; procedure TFormTeeShape.FormCreate(Sender: TObject); begin CreatingForm:=True; FGradientEditor:=TTeeGradientEditor.CreateCustom(Self,nil); AddFormTo(FGradientEditor,TabGradient); FFontEditor:=InsertTeeFontEditor(TabText); FShadowEditor:=InsertTeeShadowEditor(TabShadow); end; procedure TFormTeeShape.CBTransparentClick(Sender: TObject); begin TheShape.Transparent:=CBTransparent.Checked; end; procedure TFormTeeShape.CBBevelChange(Sender: TObject); begin TheShape.Bevel:=TPanelBevel(CBBevel.ItemIndex); EnableBevel; end; procedure TFormTeeShape.EBevWidthChange(Sender: TObject); begin if not CreatingForm then TheShape.BevelWidth:=UDBevW.Position end; procedure TFormTeeShape.EShadowTranspChange(Sender: TObject); begin if not CreatingForm then TShapeAccess(TheShape).Transparency:=UDShadowTransp.Position; end; procedure TFormTeeShape.CBVisibleChecked(Sender: TObject); begin TheShape.Visible:=(Sender as TCheckBox).Checked; end; end.
unit ANovoEstagio; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, ExtCtrls, DBCtrls, Localizacao, Mask, Tabela, DBKeyViolation, Buttons, BotaoCadastro, Componentes1, PainelGradiente, DB, DBClient, CBancoDados; type TFNovoEstagio = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BotaoGravar1: TBotaoGravar; BotaoCancelar1: TBotaoCancelar; BFechar: TBitBtn; Label1: TLabel; Label2: TLabel; Label3: TLabel; SpeedButton1: TSpeedButton; Label4: TLabel; Label17: TLabel; BPlano: TSpeedButton; LPlano: TLabel; Label6: TLabel; ECodigo: TDBKeyViolation; DBEditColor1: TDBEditColor; ETipoEstagio: TDBEditLocaliza; EPlanoContas: TDBEditLocaliza; DBCheckBox1: TDBCheckBox; DBCheckBox2: TDBCheckBox; DBEditColor2: TDBEditColor; DBRadioGroup1: TDBRadioGroup; Label5: TLabel; DBEditColor3: TDBEditColor; EstagioProducao: TRBSQL; EstagioProducaoCODEST: TFMTBCDField; EstagioProducaoNOMEST: TWideStringField; EstagioProducaoCODTIP: TFMTBCDField; EstagioProducaoINDFIN: TWideStringField; EstagioProducaoCODPLA: TWideStringField; EstagioProducaoCODEMP: TFMTBCDField; EstagioProducaoINDOBS: TWideStringField; EstagioProducaoMAXDIA: TFMTBCDField; EstagioProducaoTIPEST: TWideStringField; EstagioProducaoDATALT: TSQLTimeStampField; DataEstagioProducao: TDataSource; ValidaGravacao1: TValidaGravacao; Localiza: TConsultaPadrao; EstagioProducaoVALHOR: TFMTBCDField; DBCheckBox3: TDBCheckBox; EstagioProducaoINDEMAIL: TWideStringField; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EstagioProducaoAfterInsert(DataSet: TDataSet); procedure EstagioProducaoAfterEdit(DataSet: TDataSet); procedure EstagioProducaoAfterScroll(DataSet: TDataSet); procedure ECodigoChange(Sender: TObject); procedure ETipoEstagioCadastrar(Sender: TObject); procedure EPlanoContasRetorno(Retorno1, Retorno2: string); procedure EstagioProducaoAfterPost(DataSet: TDataSet); procedure BFecharClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FNovoEstagio: TFNovoEstagio; implementation uses APrincipal, AEstagioProducao, ATipoEstagioProducao, unSistema, FunObjeto; {$R *.DFM} { **************************************************************************** } procedure TFNovoEstagio.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } EstagioProducao.Open; InicializaVerdadeiroeFalsoCheckBox(PanelColor1,'S','N'); end; { *************************************************************************** } procedure TFNovoEstagio.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFNovoEstagio.ECodigoChange(Sender: TObject); begin if (EstagioProducao.State in [dsedit,dsinsert]) then ValidaGravacao1.Execute; end; {******************************************************************************} procedure TFNovoEstagio.EPlanoContasRetorno(Retorno1, Retorno2: string); begin if Retorno1 <> '' then EstagioProducaoCODEMP.AsString := Retorno1 else EstagioProducaoCODEMP.Clear; end; {******************************************************************************} procedure TFNovoEstagio.EstagioProducaoAfterEdit(DataSet: TDataSet); begin ECodigo.ReadOnly := true; end; {******************************************************************************} procedure TFNovoEstagio.EstagioProducaoAfterInsert(DataSet: TDataSet); begin ECodigo.ReadOnly := false; ECodigo.ProximoCodigo; EstagioProducaoINDFIN.AsString := 'N'; EstagioProducaoINDOBS.AsString := 'N'; EstagioProducaoTIPEST.AsString := 'P'; end; procedure TFNovoEstagio.EstagioProducaoAfterPost(DataSet: TDataSet); begin Sistema.MarcaTabelaParaImportar('ESTAGIOPRODUCAO'); end; {******************************************************************************} procedure TFNovoEstagio.EstagioProducaoAfterScroll(DataSet: TDataSet); begin ETipoEstagio.Atualiza; EPlanoContas.Atualiza; end; {******************************************************************************} procedure TFNovoEstagio.ETipoEstagioCadastrar(Sender: TObject); begin FTipoEstagioProducao := TFTipoEstagioProducao.criarSDI(Application,'',FPrincipal.verificaPermisao('FTipoEstagioProducao')); FTipoEstagioProducao.BotaoCadastrar1.Click; FTipoEstagioProducao.Showmodal; FTipoEstagioProducao.free; Localiza.AtualizaConsulta; end; {******************************************************************************} procedure TFNovoEstagio.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } EstagioProducao.Close; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFNovoEstagio]); end.
{*************************************************************** * * Project : TCPStreamServer * Unit Name: ServerMain * Purpose : Indy TCP Stream Server Demo * Version : 1.0 * Date : October 6, 2000 * Author : Don Siders <sidersd@att.net> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit ServerMain; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} windows, messages, SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPServer, IdThreadMgr, IdThreadMgrPool; { ** NOTES ** OnExecute sends a HELLO message to the client and waits for a command. OnExecute handles the client command OUTLINE by writing hard-coded data using WriteStream. OnExecute disconnects prior to exiting. Displays a connection count for the number of running threads. Displays a request count for the number of connections requested. } type TForm1 = class(TForm) TCPServer: TIdTCPServer; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Edit2: TEdit; procedure FormCreate(Sender: TObject); procedure TCPServerExecute(AThread: TIdPeerThread); private FConnectionCount: Integer; FRequestCount: Integer; public procedure IncrConnectionCount; procedure DecrConnectionCount; end; var Form1: TForm1; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} procedure TForm1.FormCreate(Sender: TObject); begin TCPServer.Active := True; end; procedure TForm1.TCPServerExecute(AThread: TIdPeerThread); var SRequest: string; SOutline: string; AStream: TStringStream; const EOL: string = #13#10; begin with AThread.Connection do begin AThread.Synchronize(IncrConnectionCount); WriteLn('Hello from Indy TCP Stream Server.'); try SRequest := UpperCase(ReadLn); if SRequest = 'OUTLINE' then begin SOutline := 'Level 1' + EOL + ' Level 1.1' + EOL + ' Level 1.2' + EOL + 'Level 2' + EOL + ' Level 2.1' + EOL + ' Level 2.2' + EOL + 'Level 3' + EOL + ' Level 3.1' + EOL + ' Level 3.2' + EOL + 'Level 4' + EOL + ' Level 4.1' + EOL + ' Level 4.2' + EOL + 'Level 5' + EOL + ' Level 5.1' + EOL + ' Level 5.2' + EOL + 'Level 6' + EOL + ' Level 6.1' + EOL + ' Level 6.2' + EOL + 'Level 7' + EOL + ' Level 7.1' + EOL + ' Level 7.2' + EOL + 'Level 8' + EOL + ' Level 8.1' + EOL + ' Level 8.2' + EOL + 'Level 9' + EOL + ' Level 9.1' + EOL + ' Level 9.2'; AStream := TStringStream.Create(SOutline); OpenWriteBuffer; WriteStream(AStream); CloseWriteBuffer; AStream.Free; end; finally Disconnect; AThread.Synchronize(DecrConnectionCount); end; end; end; procedure TForm1.IncrConnectionCount; begin Inc(FConnectionCount); Inc(FRequestCount); Edit1.Text := IntToStr(FConnectionCount); Edit2.Text := IntToStr(FRequestCount); Edit1.Invalidate; Edit2.Invalidate; end; procedure TForm1.DecrConnectionCount; begin Dec(FConnectionCount); Edit1.Text := IntToStr(FConnectionCount); Edit1.Invalidate; end; end.