text
stringlengths
14
6.51M
unit LifeEngine; interface uses System.Types, System.SysUtils, System.Classes; type TLifeBoard = array of array of Byte; TNeighborCount = 0..8; TNeighborCounts = set of TNeighborCount; ELifeEngine = class(Exception); TLifeEngine = class private type TLifeThread = class(TThread) FLifeEngine: TLifeEngine; FOriginalBoard, FNewBoard: TLifeBoard; FGensPerSecond: Double; FElapsed: Int64; FParallel: LongBool; FSurvival, FBirth: TNeighborCounts; FUpdating: Boolean; procedure SetParallel(Value: LongBool); protected procedure UpdateGeneration; procedure ProcessCells(Sender: TObject; AIndex: Integer); procedure Execute; override; public constructor Create(ALifeEngine: TLifeEngine); property Parallel: LongBool read FParallel write SetParallel; end; private FLifeBoard: TLifeBoard; FSurvival, FBirth: TNeighborCounts; FDescription: string; FLifeThread: TLifeThread; FParallel: Boolean; FBoardSize: TSize; FGensPerSecond, FMaxGensPerSecond: Double; FGraphCount: Int64; FGenerationCount: Int64; FUpdateRate: Integer; FOnUpdate: TNotifyEvent; function GetRunning: Boolean; function GetParallel: Boolean; procedure SetParallel(Value: Boolean); procedure DoUpdate; procedure SetUpdateRate(const Value: Integer); public constructor Create(const ABoardSize: TSize); destructor Destroy; override; procedure Clear; procedure LoadPattern(const AFileName: string); overload; procedure LoadPattern(AStream: TStream); overload; procedure Start; procedure Stop; property Description: string read FDescription; property LifeBoard: TLifeBoard read FLifeBoard; property Parallel: Boolean read GetParallel write SetParallel; property Running: Boolean read GetRunning; property GensPerSecond: Double read FGensPerSecond; property GenerationCount: Int64 read FGenerationCount; property MaxGensPerSecond: Double read FMaxGensPerSecond; property UpdateRate: Integer read FUpdateRate write SetUpdateRate; property OnUpdate: TNotifyEvent read FOnUpdate write FOnUpdate; end; implementation uses System.Math, System.Diagnostics, System.Threading; { TLifeEngine } procedure TLifeEngine.Clear; var NewBoard: TLifeBoard; begin if Running then raise ELifeEngine.Create('Cannot clear life board while running'); SetLength(NewBoard, FBoardSize.cx, FBoardSize.cy); FLifeBoard := NewBoard; FGenerationCount := 0; end; constructor TLifeEngine.Create(const ABoardSize: TSize); begin inherited Create; FBoardSize := ABoardSize; FSurvival := [2,3]; FBirth := [3]; FUpdateRate := 60; Clear; end; destructor TLifeEngine.Destroy; begin inherited; end; procedure TLifeEngine.DoUpdate; begin if Assigned(FOnUpdate) then FOnUpdate(Self); end; function TLifeEngine.GetParallel: Boolean; begin if FLifeThread <> nil then Result := FLifeThread.Parallel else Result := FParallel; end; function TLifeEngine.GetRunning: Boolean; begin Result := FLifeThread <> nil; end; procedure TLifeEngine.LoadPattern(const AFileName: string); var Stream: TStream; begin Stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadPattern(Stream); finally Stream.Free; end; end; procedure TLifeEngine.LoadPattern(AStream: TStream); var X, Y: Integer; Pattern, Data, Description: TStringList; Size: TSize; Offset, Origin: TPoint; Line: string; CurLine: Integer; function ProcessPattern(APattern, AData, ADescription: TStrings; var ASize: TSize; var AOffset: TPoint; var LineNum: Integer; var ASurvival, ABirth: TNeighborCounts): Boolean; var I: Integer; Line: string; InPattern: Boolean; function GetNumber(const ALine: string; var Index: Integer): Integer; var Start: Integer; begin while (Index <= Length(ALine)) and ((ALine[Index] < '0') or (ALine[Index] > '9')) and (ALine[Index] <> '-') and (ALine[Index] <> '+') do Inc(Index); Start := Index; while (Index <= Length(ALine)) and (((ALine[Index] >= '0') and (ALine[Index] <= '9')) or (ALine[Index] = '-') or (ALine[Index] = '+')) do Inc(Index); Result := StrToIntDef(Copy(ALine, Start, Index - Start), 0); end; begin FillChar(ASize, SizeOf(ASize), 0); FillChar(AOffset, SizeOf(AOffset), 0); InPattern := False; while LineNum < APattern.Count do begin Line := APattern[LineNum]; if (LineNum = 0) and not SameText(Line, '#Life 1.05') then raise Exception.Create('Invalid .lif or .life format.') else if (Length(Line) > 0) and (Line[1] <> '#') then begin if not InPattern then AData.Clear; InPattern := True; Inc(ASize.cy); ASize.cx := Max(ASize.cx, Length(Line)); AData.Add(Line); end else if (Length(Line) > 1) and (Line[1] = '#') then begin if InPattern then Break; if UpCase(Line[2]) = 'P' then begin I := 3; AOffset.X := GetNumber(Line, I); AOffset.Y := GetNumber(Line, I); end else if UpCase(Line[2]) = 'N' then begin ASurvival := [2,3]; ABirth := [3]; end else if UpCase(Line[2]) = 'R' then begin ASurvival := []; ABirth := []; I := 3; while (Line[I] < '0') or (Line[I] > '8') do Inc(I); while (Line[I] >= '0') and (Line[I] <= '8') do begin Include(ASurvival, TNeighborCount(StrToInt(Line[I]))); Inc(I); end; if Line[I] = '/' then while (Line[I] >= '0') and (Line[I] <= '8') do begin Include(ABirth, TNeighborCount(StrToInt(Line[I]))); Inc(I); end; end else if (UpCase(Line[2]) = 'D') or (UpCase(Line[2]) = 'C') then ADescription.Add(Copy(Line, 3, MaxInt)); end; Inc(LineNum); end; Result := LineNum < APattern.Count; if not Running then DoUpdate; end; begin Pattern := TStringList.Create; try Data := TStringList.Create; try Description := TStringList.Create; try Pattern.LoadFromStream(AStream); Pattern.Add('#E'); CurLine := 0; while ProcessPattern(Pattern, Data, Description, Size, Offset, CurLine, FSurvival, FBirth) do begin if (Size.cx > Length(FLifeBoard)) or (Size.cy > Length(FLifeBoard[0])) then raise Exception.CreateFmt('Pattern too large for current board size. Pattern Size (%d, %d)', [Size.cx, Size.cy]); Origin := Point(Length(FLifeBoard) div 2 + Offset.X, Length(FLifeBoard[0]) div 2 + Offset.Y); for Y := 0 to Data.Count - 1 do begin Line := Data[Y]; for X := 1 to Length(Line) do if Line[X] = '*' then FLifeBoard[Origin.X + (X - 1), Origin.Y + Y] := 1 else FLifeBoard[Origin.X + (X - 1), Origin.Y + Y] := 0; end; end; FDescription := Description.Text; finally Description.Free; end; finally Data.Free; end; finally Pattern.Free; end; end; procedure TLifeEngine.SetParallel(Value: Boolean); begin if FLifeThread <> nil then FLifeThread.Parallel := Value; FParallel := Value; end; procedure TLifeEngine.SetUpdateRate(const Value: Integer); begin AtomicExchange(FUpdateRate, Value); end; procedure TLifeEngine.Start; begin if not Running then begin FLifeThread := TLifeThread.Create(Self); FLifeThread.Start; end else raise ELifeEngine.Create('Life Engine is already running'); end; procedure TLifeEngine.Stop; begin if Running then FreeAndNil(FLifeThread) else raise ELifeEngine.Create('Life Engine is not running'); end; { TLifeEngine.TLifeThread } constructor TLifeEngine.TLifeThread.Create(ALifeEngine: TLifeEngine); begin inherited Create(True); FLifeEngine := ALifeEngine; FSurvival := ALifeEngine.FSurvival; FBirth := ALifeEngine.FBirth; FParallel := ALifeEngine.Parallel; end; procedure TLifeEngine.TLifeThread.Execute; var Update, Timer: TStopwatch; I: Integer; begin NameThreadForDebugging('Life Thread'); Update := TStopwatch.StartNew; while not Terminated do begin Timer := TStopwatch.StartNew; if Length(FNewBoard) > 0 then begin FOriginalBoard := FNewBoard; FNewBoard := nil; end else FOriginalBoard := FLifeEngine.FLifeBoard; SetLength(FNewBoard, Length(FOriginalBoard), Length(FOriginalBoard[0])); if FParallel then begin TParallel.For(Low(FOriginalBoard), High(FOriginalBoard), procedure (Value: Integer) begin ProcessCells(nil, Value); end); end else for I := Low(FOriginalBoard) to High(FOriginalBoard) do ProcessCells(nil, I); FGensPerSecond := {FFrequency / (EndTicks - StartTicks)} Timer.Frequency / Timer.ElapsedTicks; if Update.ElapsedTicks >= Update.Frequency div FLifeEngine.UpdateRate then begin FUpdating := True; Synchronize(UpdateGeneration); Assert(not FUpdating); Update := TStopwatch.StartNew; end; Inc(FLifeEngine.FGenerationCount); //Sleep(100); FElapsed := Timer.ElapsedTicks; end; end; procedure TLifeEngine.TLifeThread.ProcessCells(Sender: TObject; AIndex: Integer); type TNeighbor = (nbAboveLeft, nbAbove, nbAboveRight, nbLeft, nbRight, nbBelowLeft, nbBelow, nbBelowRight); const NeighborDelta: array[TNeighbor] of TPoint = ( (X: -1; Y: -1), (X: 0; Y: -1), (X: 1; Y: -1), (X: -1; Y: 0), (X: 1; Y: 0), (X: -1; Y: 1), (X: 0; Y: 1), (X: 1; Y: 1)); function NeighborIsOccupied(ANeighbor: TNeighbor; Column, Row: Integer): Boolean; var Delta: TPoint; function WrapCoord(Index: Integer; ALow, AHigh: Integer): Integer; inline; begin Result := Index; if Result < ALow then Result := AHigh else if Result > AHigh then Result := ALow; end; begin Delta := NeighborDelta[ANeighbor]; Result := FOriginalBoard[WrapCoord(Column + Delta.X, Low(FOriginalBoard), High(FOriginalBoard)), WrapCoord(Row + Delta.Y, Low(FOriginalBoard[0]), High(FOriginalBoard[0]))] <> 0; end; function CountNeighbors(Column, Row: Integer): TNeighborCount; var N: TNeighbor; begin Result := 0; for N := Low(TNeighbor) to High(TNeighbor) do if NeighborIsOccupied(N, Column, Row) then Inc(Result); end; var I: Integer; NeighborCount: TNeighborCount; begin for I := Low(FOriginalBoard[AIndex]) to High(FOriginalBoard[AIndex]) do begin NeighborCount := CountNeighbors(AIndex, I); if (FOriginalBoard[AIndex, I] <> 0) and (NeighborCount in FSurvival) then FNewBoard[AIndex, I] := FOriginalBoard[AIndex, I] // lives to next gen if occupied else if (FOriginalBoard[AIndex, I] = 0) and (NeighborCount in FBirth) then FNewBoard[AIndex, I] := 1 // comes to life else FNewBoard[AIndex, I] := 0; // always dies end; end; procedure TLifeEngine.TLifeThread.SetParallel(Value: LongBool); begin AtomicExchange(Integer(FParallel), Integer(Value)); end; procedure TLifeEngine.TLifeThread.UpdateGeneration; begin FLifeEngine.FLifeBoard := FNewBoard; FOriginalBoard := nil; FNewBoard := nil; FLifeEngine.FGensPerSecond := FGensPerSecond; FLifeEngine.FGraphCount := FLifeEngine.FGraphCount + FElapsed; if FLifeEngine.FGraphCount > TStopwatch.Frequency * 2 then begin FLifeEngine.FMaxGensPerSecond := 0.0; FLifeEngine.FGraphCount := 0; end; FLifeEngine.FMaxGensPerSecond := Max(FLifeEngine.FMaxGensPerSecond, FLifeEngine.FGensPerSecond); FLifeEngine.DoUpdate; FUpdating := False; end; end.
{---------------------------------------------------------------- Nome: UntProcMsgIRC Descrição: Processa os tipos de menssagens do IRCUtils executando os comandos correspondentes ----------------------------------------------------------------} unit UntProcMsgIRC; interface uses SysUtils, Classes, IRCUtils, StrUtils, Windows, Dialogs, SrvAnalisesUtils, UntPrincipal, UntDepurador, UntProcMsgIRCSrv, UntDiversos, UntwIRCStatus; procedure ProcMsgIRC(TextoReceb: string); implementation procedure ProcMsgIRC; var Saida: TStringList; {Saida da função IrcAnalisar(Depende do tipo resultado)} TipoMsg: TIRCTipoMsg; {Variável que guarda o tipo da Saida} LinhaIRC: TSplitArray; {Variável que conterá todas as linhas separadas de TextoReceb(#10)} ContLinhaIRC: integer; {Contador usado para navegar entra as linhaa da array LinhaIRC} TipoSrvMsg: TIRCSrvMsg; {Variável que guarda o tipo de menssagem do servidor (Caso TipoMsg = imServMsg)} SaidaSrv: TStringList; {Saída da função AnalisarMsgSrv (Depende do tipo resultado)} begin SetLength(LinhaIRC, 0); LinhaIRC:=Split(TextoReceb, #10); for ContLinhaIRC:=0 to High(LinhaIRC) do begin Chomp(LinhaIRC[ContLinhaIRC]); TipoMsg:=IrcAnalisar(LinhaIRC[ContLinhaIRC], Saida); case TipoMsg of {Menssagem privada para cliente} imPrivMsg: begin FrmPrincipal.ProcMsg(Saida.Strings[0], Format(CompNick,[Saida.Strings[0]]) + Saida.Strings[3]) end; {Menssagem para canal} imChaMsg: begin FrmPrincipal.ProcChaMsg(Saida.Strings[2], Format(CompNick,[Saida.Strings[0]]) + Saida.Strings[3]) end; {Um usuário entrou em um canal} imJoin: begin FrmPrincipal.AdNick(Saida.Strings[0], Saida.Strings[2], false); end; {Um usuário deixou um canal} imPart: begin FrmPrincipal.RmNick(Saida.Strings[0], Saida.Strings[2]); end; {Notice para cliente} imPrivNotice: begin FrmPrincipal.ProcMsg(Saida.Strings[0], Format(CompNotice, [Saida.Strings[2], Saida.Strings[3]])); end; {Notice para um canal} imChaNotice: begin FrmPrincipal.ProcChaMsg(Saida.Strings[2], Format(CompNotice, [Saida.Strings[2], Saida.Strings[3]])); end; {Alguém mudou de nick} imMudNick: begin FrmPrincipal.AtlNick(Saida.Strings[0], Saida.Strings[2]); end; {Mudança de atributos de nick/canal} imMode: begin //soon... end; {Alguém esta oferecendo DCC CHAT} imDccChat: begin MessageBox(0, PChar(Saida.Strings[0] + ' está oferecendo CHAT'), 'Chat', MB_OK + MB_TASKMODAL + MB_ICONINFORMATION) end; {Alguém estaoferecendo DCC SEND} imDccSend: begin MessageBox(0, PChar(Saida.Strings[0] + ' está oferecendo SEND - ' + Saida.Strings[2]), 'Send', MB_OK + MB_TASKMODAL + MB_ICONINFORMATION) end; {Menssagens do servidor} imServMsg: begin TipoSrvMsg:=AnalisarMsgSrv(Saida.Strings[1], Saida.Strings[2], SaidaSrv); ProcMsgIRCSrv(TipoSrvMsg, SaidaSrv); end; {Notice do servidor} imSrvNotice: begin wIRCStatus.AdLinha(Saida.Strings[0]); end; {Erro no servidor} imSrvError: begin wIRCStatus.AdLinha(Saida.Strings[0]); end; end; end; end; end.
// // Generated by JavaToPas v1.5 20171018 - 171043 //////////////////////////////////////////////////////////////////////////////// unit javax.xml.datatype.Duration; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, javax.xml.namespace.QName, javax.xml.datatype.DatatypeConstants_Field, java.math.BigDecimal; type JDuration = interface; JDurationClass = interface(JObjectClass) ['{AB70CF6D-087F-442C-88CF-69E6F69BD567}'] function add(JDurationparam0 : JDuration) : JDuration; cdecl; // (Ljavax/xml/datatype/Duration;)Ljavax/xml/datatype/Duration; A: $401 function compare(JDurationparam0 : JDuration) : Integer; cdecl; // (Ljavax/xml/datatype/Duration;)I A: $401 function equals(duration : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getDays : Integer; cdecl; // ()I A: $1 function getField(JDatatypeConstants_Fieldparam0 : JDatatypeConstants_Field) : JNumber; cdecl;// (Ljavax/xml/datatype/DatatypeConstants$Field;)Ljava/lang/Number; A: $401 function getHours : Integer; cdecl; // ()I A: $1 function getMinutes : Integer; cdecl; // ()I A: $1 function getMonths : Integer; cdecl; // ()I A: $1 function getSeconds : Integer; cdecl; // ()I A: $1 function getSign : Integer; cdecl; // ()I A: $401 function getTimeInMillis(startInstant : JCalendar) : Int64; cdecl; overload;// (Ljava/util/Calendar;)J A: $1 function getTimeInMillis(startInstant : JDate) : Int64; cdecl; overload; // (Ljava/util/Date;)J A: $1 function getXMLSchemaType : JQName; cdecl; // ()Ljavax/xml/namespace/QName; A: $1 function getYears : Integer; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $401 function init : JDuration; cdecl; // ()V A: $1 function isLongerThan(duration : JDuration) : boolean; cdecl; // (Ljavax/xml/datatype/Duration;)Z A: $1 function isSet(JDatatypeConstants_Fieldparam0 : JDatatypeConstants_Field) : boolean; cdecl;// (Ljavax/xml/datatype/DatatypeConstants$Field;)Z A: $401 function isShorterThan(duration : JDuration) : boolean; cdecl; // (Ljavax/xml/datatype/Duration;)Z A: $1 function multiply(JBigDecimalparam0 : JBigDecimal) : JDuration; cdecl; overload;// (Ljava/math/BigDecimal;)Ljavax/xml/datatype/Duration; A: $401 function multiply(factor : Integer) : JDuration; cdecl; overload; // (I)Ljavax/xml/datatype/Duration; A: $1 function negate : JDuration; cdecl; // ()Ljavax/xml/datatype/Duration; A: $401 function normalizeWith(JCalendarparam0 : JCalendar) : JDuration; cdecl; // (Ljava/util/Calendar;)Ljavax/xml/datatype/Duration; A: $401 function subtract(rhs : JDuration) : JDuration; cdecl; // (Ljavax/xml/datatype/Duration;)Ljavax/xml/datatype/Duration; A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure addTo(JCalendarparam0 : JCalendar) ; cdecl; overload; // (Ljava/util/Calendar;)V A: $401 procedure addTo(date : JDate) ; cdecl; overload; // (Ljava/util/Date;)V A: $1 end; [JavaSignature('javax/xml/datatype/Duration')] JDuration = interface(JObject) ['{35B905C5-30D3-4BFD-8C3E-F3CAC51857EE}'] function add(JDurationparam0 : JDuration) : JDuration; cdecl; // (Ljavax/xml/datatype/Duration;)Ljavax/xml/datatype/Duration; A: $401 function compare(JDurationparam0 : JDuration) : Integer; cdecl; // (Ljavax/xml/datatype/Duration;)I A: $401 function equals(duration : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getDays : Integer; cdecl; // ()I A: $1 function getField(JDatatypeConstants_Fieldparam0 : JDatatypeConstants_Field) : JNumber; cdecl;// (Ljavax/xml/datatype/DatatypeConstants$Field;)Ljava/lang/Number; A: $401 function getHours : Integer; cdecl; // ()I A: $1 function getMinutes : Integer; cdecl; // ()I A: $1 function getMonths : Integer; cdecl; // ()I A: $1 function getSeconds : Integer; cdecl; // ()I A: $1 function getSign : Integer; cdecl; // ()I A: $401 function getTimeInMillis(startInstant : JCalendar) : Int64; cdecl; overload;// (Ljava/util/Calendar;)J A: $1 function getTimeInMillis(startInstant : JDate) : Int64; cdecl; overload; // (Ljava/util/Date;)J A: $1 function getXMLSchemaType : JQName; cdecl; // ()Ljavax/xml/namespace/QName; A: $1 function getYears : Integer; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $401 function isLongerThan(duration : JDuration) : boolean; cdecl; // (Ljavax/xml/datatype/Duration;)Z A: $1 function isSet(JDatatypeConstants_Fieldparam0 : JDatatypeConstants_Field) : boolean; cdecl;// (Ljavax/xml/datatype/DatatypeConstants$Field;)Z A: $401 function isShorterThan(duration : JDuration) : boolean; cdecl; // (Ljavax/xml/datatype/Duration;)Z A: $1 function multiply(JBigDecimalparam0 : JBigDecimal) : JDuration; cdecl; overload;// (Ljava/math/BigDecimal;)Ljavax/xml/datatype/Duration; A: $401 function multiply(factor : Integer) : JDuration; cdecl; overload; // (I)Ljavax/xml/datatype/Duration; A: $1 function negate : JDuration; cdecl; // ()Ljavax/xml/datatype/Duration; A: $401 function normalizeWith(JCalendarparam0 : JCalendar) : JDuration; cdecl; // (Ljava/util/Calendar;)Ljavax/xml/datatype/Duration; A: $401 function subtract(rhs : JDuration) : JDuration; cdecl; // (Ljavax/xml/datatype/Duration;)Ljavax/xml/datatype/Duration; A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure addTo(JCalendarparam0 : JCalendar) ; cdecl; overload; // (Ljava/util/Calendar;)V A: $401 procedure addTo(date : JDate) ; cdecl; overload; // (Ljava/util/Date;)V A: $1 end; TJDuration = class(TJavaGenericImport<JDurationClass, JDuration>) end; implementation end.
unit MyCat.Generics.Bytes; interface uses System.SysUtils; {$I DGLCfg.inc_h} const _NULL_Value: TBytes = []; type _ValueType = TBytes; function _HashValue(const Key: _ValueType): Cardinal; {$IFDEF _DGL_Inline} inline; {$ENDIF}// Hash函数 //{$DEFINE _DGL_Compare} // 比较函数 //function _IsEqual(const a, b: _ValueType): boolean; {$IFDEF _DGL_Inline} inline; //{$ENDIF} // result:=(a=b); //function _IsLess(const a, b: _ValueType): boolean; {$IFDEF _DGL_Inline} inline; //{$ENDIF} // result:=(a<b); 默认排序准则 {$I DGL.inc_h} type TBytesAlgorithms = _TAlgorithms; IBytesIterator = _IIterator; IBytesContainer = _IContainer; IBytesSerialContainer = _ISerialContainer; IBytesVector = _IVector; IBytesList = _IList; IBytesDeque = _IDeque; IBytesStack = _IStack; IBytesQueue = _IQueue; IBytesPriorityQueue = _IPriorityQueue; TBytesVector = _TVector; TBytesDeque = _TDeque; TBytesList = _TList; IBytesVectorIterator = _IVectorIterator; // 速度比_IIterator稍快一点:) IBytesDequeIterator = _IDequeIterator; // 速度比_IIterator稍快一点:) IBytesListIterator = _IListIterator; // 速度比_IIterator稍快一点:) TBytesStack = _TStack; TBytesQueue = _TQueue; TBytesPriorityQueue = _TPriorityQueue; // IBytesMapIterator = _IMapIterator; IBytesMap = _IMap; IBytesMultiMap = _IMultiMap; TBytesSet = _TSet; TBytesMultiSet = _TMultiSet; TBytesMap = _TMap; TBytesMultiMap = _TMultiMap; TBytesHashSet = _THashSet; TBytesHashMultiSet = _THashMultiSet; TBytesHashMap = _THashMap; TBytesHashMultiMap = _THashMultiMap; implementation uses HashFunctions; function _HashValue(const Key: _ValueType): Cardinal; overload; begin Result := HashValue_Data(@Key[0], Length(Key)); end; function memcmp(buf1, buf2: pbyte; count: integer): integer; begin if count = 0 then result := 0 else begin dec(count); while (count > 0) and (buf1^ = buf2^) do begin inc(buf1); inc(buf2); dec(count); end; result := buf1^ - buf2^; end; end; //function _IsEqual(const a, b: _ValueType): boolean; // result:=(a=b); //begin // // Result := isequal_(@a[0],@b[0],); // // IsEqual_StrCaseInsensitive(a, b); //end; // // // //function _IsLess(const a, b: _ValueType): boolean; // result:=(a<b); 默认排序准则 //begin // Result := a < b; //end; {$I DGL.inc_pas} end.
unit ibSHDMLHistory; interface uses SysUtils, Classes, SHDesignIntf, SHOptionsIntf, pSHSqlTxtRtns, pSHQStrings, ibSHMessages, ibSHConsts, ibSHDesignIntf, ibSHTool, ibSHComponent, ibSHValues; type TibSHDMLHistory = class(TibBTTool, IibSHDMLHistory, IibSHBranch, IfbSHBranch) private FItems: TStringList; FStatistic: TStringList; FStatementCRC: TList; FActive: Boolean; FMaxCount: Integer; FSelect: Boolean; FInsert: Boolean; FUpdate: Boolean; FDelete: Boolean; FExecute: Boolean; FCrash: Boolean; protected FSQLParser: TSQLParser; procedure SetOwnerIID(Value: TGUID); override; { IibSHDMLHistory } function GetActive: Boolean; procedure SetActive(const Value: Boolean); function GetHistoryFileName: string; function GetMaxCount: Integer; procedure SetMaxCount(const Value: Integer); function GetSelect: Boolean; procedure SetSelect(const Value: Boolean); function GetInsert: Boolean; procedure SetInsert(const Value: Boolean); function GetUpdate: Boolean; procedure SetUpdate(const Value: Boolean); function GetDelete: Boolean; procedure SetDelete(const Value: Boolean); function GetExecute: Boolean; procedure SetExecute(const Value: Boolean); function GetCrash: Boolean; procedure SetCrash(const Value: Boolean); function Count: Integer; procedure Clear; function Statement(Index: Integer): string; function Item(Index: Integer): string; function Statistics(Index: Integer): string; function AddStatement(AStatement: string; AStatistics: IibSHStatistics): Integer; procedure DeleteStatement(AStatementNo: Integer); procedure LoadFromFile; procedure SaveToFile; function SQLTextDigest(AText: string): Int64; procedure AddSQLTextDigest(ADigest: Int64); procedure ClearDigestList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Active: Boolean read GetActive write SetActive; property MaxCount: Integer read GetMaxCount write SetMaxCount; property Select: Boolean read GetSelect write SetSelect; property Insert: Boolean read GetInsert write SetInsert; property Update: Boolean read GetUpdate write SetUpdate; property Delete: Boolean read GetDelete write SetDelete; property Execute: Boolean read GetExecute write SetExecute; property Crash: Boolean read GetCrash write SetCrash; end; TibSHDMLHistoryFactory = class(TibBTComponentFactory) function SupportComponent(const AClassIID: TGUID): Boolean; override; function CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; override; end; procedure Register; implementation uses ibSHDMLHistoryActions, ibSHDMLHistoryEditors; procedure Register; begin SHRegisterImage(GUIDToString(IibSHDMLHistory), 'DMLHistory.bmp'); SHRegisterImage(TibSHDMLHistoryPaletteAction.ClassName, 'DMLHistory.bmp'); SHRegisterImage(TibSHDMLHistoryFormAction.ClassName, 'Form_DMLText.bmp'); SHRegisterImage(TibSHDMLHistoryToolbarAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHDMLHistoryToolbarAction_Pause.ClassName, 'Button_Stop.bmp'); SHRegisterImage(TibSHDMLHistoryToolbarAction_Region.ClassName, 'Button_Tree.bmp'); SHRegisterImage(TibSHDMLHistoryToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp'); // SHRegisterImage(TibSHDMLHistoryToolbarAction_Save.ClassName, 'Button_Save.bmp'); SHRegisterImage(SCallDMLStatements, 'Form_DMLText.bmp'); SHRegisterComponents([ TibSHDMLHistory, TibSHDMLHistoryFactory]); SHRegisterActions([ // Palette TibSHDMLHistoryPaletteAction, // Forms TibSHDMLHistoryFormAction, // Toolbar TibSHDMLHistoryToolbarAction_Run, TibSHDMLHistoryToolbarAction_Pause, TibSHDMLHistoryToolbarAction_Region, // Editors TibSHDMLHistoryEditorAction_SendToSQLEditor, TibSHDMLHistoryEditorAction_ShowDMLHistory]); end; { TibSHDMLHistory } constructor TibSHDMLHistory.Create(AOwner: TComponent); begin inherited Create(AOwner); FItems := TStringList.Create; FStatistic := TStringList.Create; FStatementCRC := TList.Create; FActive := True; FSQLParser := TSQLParser.Create; end; destructor TibSHDMLHistory.Destroy; var vDatabaseAliasOptionsInt: IibSHDatabaseAliasOptionsInt; begin if Supports(BTCLDatabase, IibSHDatabaseAliasOptionsInt, vDatabaseAliasOptionsInt) then begin vDatabaseAliasOptionsInt.DMLHistoryActive := Active; vDatabaseAliasOptionsInt.DMLHistoryMaxCount := MaxCount; vDatabaseAliasOptionsInt.DMLHistorySelect := Select; vDatabaseAliasOptionsInt.DMLHistoryInsert := Insert; vDatabaseAliasOptionsInt.DMLHistoryUpdate := Update; vDatabaseAliasOptionsInt.DMLHistoryDelete := Delete; vDatabaseAliasOptionsInt.DMLHistoryExecute := Execute; vDatabaseAliasOptionsInt.DMLHistoryCrash := Crash; end; // SaveToFile; FSQLParser.Free; FStatistic.Free; FItems.Free; ClearDigestList; FStatementCRC.Free; inherited Destroy; end; procedure TibSHDMLHistory.SetOwnerIID(Value: TGUID); var vDatabaseAliasOptionsInt: IibSHDatabaseAliasOptionsInt; begin if not IsEqualGUID(OwnerIID, Value) then begin inherited SetOwnerIID(Value); if Supports(BTCLDatabase, IibSHDatabaseAliasOptionsInt, vDatabaseAliasOptionsInt) then begin Active := vDatabaseAliasOptionsInt.DMLHistoryActive; MaxCount := vDatabaseAliasOptionsInt.DMLHistoryMaxCount; Select := vDatabaseAliasOptionsInt.DMLHistorySelect; Insert := vDatabaseAliasOptionsInt.DMLHistoryInsert; Update := vDatabaseAliasOptionsInt.DMLHistoryUpdate; Delete := vDatabaseAliasOptionsInt.DMLHistoryDelete; Execute := vDatabaseAliasOptionsInt.DMLHistoryExecute; Crash := vDatabaseAliasOptionsInt.DMLHistoryCrash; end else begin Active := True; MaxCount := 0; Select := True; Insert := True; Update := True; Delete := True; Execute := True; Crash := True; end; LoadFromFile; end; end; function TibSHDMLHistory.GetActive: Boolean; begin Result := FActive; end; procedure TibSHDMLHistory.SetActive(const Value: Boolean); begin FActive := Value; end; function TibSHDMLHistory.GetHistoryFileName: string; var vDir: string; vOldDir: string; vOldFile: string; begin Result := EmptyStr; if Assigned(BTCLDatabase) then begin vDir := BTCLDatabase.DataRootDirectory; if SysUtils.DirectoryExists(vDir) then Result := vDir + DMLHistoryFile; vDir := ExtractFilePath(Result); if not SysUtils.DirectoryExists(vDir) then begin ForceDirectories(vDir); //Перенос старых данных vOldFile := BTCLDatabase.DataRootDirectory + SQLHistoryFile; vOldDir := ExtractFilePath(vOldFile); if SysUtils.DirectoryExists(vOldDir) and FileExists(vOldFile) then begin RenameFile(vOldFile, Result); RemoveDir(vOldDir); end; end; end; end; function TibSHDMLHistory.GetMaxCount: Integer; begin Result := FMaxCount; end; procedure TibSHDMLHistory.SetMaxCount(const Value: Integer); begin FMaxCount := Value; end; function TibSHDMLHistory.GetSelect: Boolean; begin Result := FSelect; end; procedure TibSHDMLHistory.SetSelect(const Value: Boolean); begin FSelect := Value; end; function TibSHDMLHistory.GetInsert: Boolean; begin Result := FInsert; end; procedure TibSHDMLHistory.SetInsert(const Value: Boolean); begin FInsert := Value; end; function TibSHDMLHistory.GetUpdate: Boolean; begin Result := FUpdate; end; procedure TibSHDMLHistory.SetUpdate(const Value: Boolean); begin FUpdate := Value; end; function TibSHDMLHistory.GetDelete: Boolean; begin Result := FDelete; end; procedure TibSHDMLHistory.SetDelete(const Value: Boolean); begin FDelete := Value; end; function TibSHDMLHistory.GetExecute: Boolean; begin Result := FExecute; end; procedure TibSHDMLHistory.SetExecute(const Value: Boolean); begin FExecute := Value; end; function TibSHDMLHistory.GetCrash: Boolean; begin Result := FCrash; end; procedure TibSHDMLHistory.SetCrash(const Value: Boolean); begin FCrash := Value; end; function TibSHDMLHistory.Count: Integer; begin Result := FItems.Count; end; procedure TibSHDMLHistory.Clear; var I: Integer; vDMLHistoryForm: IibSHDMLHistoryForm; begin FItems.Clear; FStatistic.Clear; ClearDigestList; FStatementCRC.Clear; SaveToFile; for I := 0 to Pred(ComponentForms.Count) do if Supports(ComponentForms[I], IibSHDMLHistoryForm, vDMLHistoryForm) then begin vDMLHistoryForm.FillEditor; end; end; function TibSHDMLHistory.Statement(Index: Integer): string; //var // vStatement: TStringList; // I: Integer; begin Result := EmptyStr; if (Index >= 0) and (Index < Count) then begin Result := FItems[Index]; System.Delete(Result, 1, Pos(#13#10,Result) + 1); end; { Result := EmptyStr; if (Index >= 0) and (Index < Count) then begin vStatement := TStringList.Create; try vStatement.Text := FItems[Index]; if vStatement.Count > 1 then begin vStatement.Delete(0); I := 0; while (I < vStatement.Count) and (Pos(sHistoryStatisticsHeader, vStatement[I]) = 0) do Inc(I); while (I < vStatement.Count) do vStatement.Delete(I); Result := vStatement.Text; end; finally vStatement.Free; end; end; } end; function TibSHDMLHistory.Item(Index: Integer): string; //var // vStatement: TStringList; // I: Integer; begin Result := EmptyStr; if (Index >= 0) and (Index < Count) then Result := FItems[Index]; { Result := EmptyStr; if (Index >= 0) and (Index < Count) then begin vStatement := TStringList.Create; try vStatement.Text := FItems[Index]; if vStatement.Count > 1 then begin I := 1; while (I < vStatement.Count) and (Pos(sHistoryStatisticsHeader, vStatement[I]) = 0) do Inc(I); while (I < vStatement.Count) do vStatement.Delete(I); Result := vStatement.Text; end; finally vStatement.Free; end; end; } end; function TibSHDMLHistory.Statistics(Index: Integer): string; //var // vStatement: TStringList; // I: Integer; begin Result := EmptyStr; if (Index >= 0) and (Index < Count) then begin Result := FStatistic[Index]; System.Delete(Result, 1, Pos(#13#10,Result) + 1); end; { Result := EmptyStr; if (Index >= 0) and (Index < Count) then begin vStatement := TStringList.Create; try vStatement.Text := FItems[Index]; if vStatement.Count > 1 then begin I := 0; while (I < vStatement.Count) and (Pos(sHistoryStatisticsHeader, vStatement[I]) = 0) do vStatement.Delete(0); vStatement.Delete(0); Result := vStatement.Text; end; finally vStatement.Free; end; end; } end; function TibSHDMLHistory.AddStatement(AStatement: string; AStatistics: IibSHStatistics): Integer; var vItem: string; vFileName: string; vStatistic: string; vDMLHistoryForm: IibSHDMLHistoryForm; vDigest: Int64; vExistingIndex: Integer; I: Integer; function TrimLeftEpmtyStr(AString: string): string; var vStrList: TStringList; begin vStrList := TStringList.Create; Result := AString; try vStrList.Text := AString; while (vStrList.Count > 0) and (Length(vStrList[0]) = 0) do vStrList.Delete(0); Result := TrimRight(vStrList.Text); finally vStrList.Free; end; end; begin Result := -1; if Active then begin FSQLParser.SQLText := AStatement; if ((FSQLParser.SQLKind = skSelect) and (not Select)) or ((FSQLParser.SQLKind = skInsert) and (not Insert)) or ((FSQLParser.SQLKind = skUpdate) and (not Update)) or ((FSQLParser.SQLKind = skDelete) and (not Delete)) or ((FSQLParser.SQLKind = skExecuteProc) and (not Execute)) then Exit; //!!! vDigest := SQLTextDigest(AStatement); vExistingIndex := -1; for I := Pred(FStatementCRC.Count) downto 0 do begin if vDigest = PInt64(FStatementCRC[I])^ then begin vExistingIndex := I; Break; end; end; vItem := Format(sHistorySQLHeader + sHistorySQLHeaderSuf, [DateTimeToStr(Now)]) + sLineBreak + TrimLeftEpmtyStr(AStatement) + sLineBreak + sLineBreak; vStatistic := EmptyStr; if Assigned(AStatistics) then begin vStatistic := sHistoryStatisticsHeader + sLineBreak; if Assigned(AStatistics.DRVTimeStatistics) then begin vStatistic := vStatistic + Format(SHistoryExecute + '=%d' + sLineBreak, [AStatistics.DRVTimeStatistics.ExecuteTime]); vStatistic := vStatistic + Format(SHistoryPrepare + '=%d' + sLineBreak, [AStatistics.DRVTimeStatistics.PrepareTime]); vStatistic := vStatistic + Format(SHistoryFetch + '=%d' + sLineBreak, [AStatistics.DRVTimeStatistics.FetchTime]); end; vStatistic := vStatistic + Format(SHistoryIndexedReads + '=%d' + sLineBreak, [AStatistics.DRVStatistics.IdxReads]); vStatistic := vStatistic + Format(SHistoryNonIndexedReads + '=%d' + sLineBreak, [AStatistics.DRVStatistics.SeqReads]); vStatistic := vStatistic + Format(SHistoryInserts + '=%d' + sLineBreak, [AStatistics.DRVStatistics.Inserts]); vStatistic := vStatistic + Format(SHistoryUpdates + '=%d' + sLineBreak, [AStatistics.DRVStatistics.Updates]); vStatistic := vStatistic + Format(SHistoryDeletes + '=%d' + sLineBreak, [AStatistics.DRVStatistics.Deletes]); end; if vExistingIndex > -1 then begin FStatistic.Delete(vExistingIndex); FItems.Delete(vExistingIndex); Dispose(PInt64(FStatementCRC[vExistingIndex])); FStatementCRC.Delete(vExistingIndex); end; AddSQLTextDigest(vDigest); FStatistic.Add(vStatistic); Result := FItems.Add(vItem); vItem := FItems[Result] + FStatistic[Result] + sLineBreak + Format(SHistorySQLTextDigest + '=%d', [PInt64(FStatementCRC[Result])^]) + sLineBreak; vFileName := GetHistoryFileName; AddToTextFile(vFileName, vItem); if GetComponentFormIntf(IibSHDMLHistoryForm, vDMLHistoryForm) then vDMLHistoryForm.ChangeNotification(vExistingIndex, opInsert); end; end; procedure TibSHDMLHistory.DeleteStatement(AStatementNo: Integer); var vDMLHistoryForm: IibSHDMLHistoryForm; begin if (AStatementNo >= 0) and (AStatementNo < FItems.Count) then begin FStatistic.Delete(AStatementNo); FItems.Delete(AStatementNo); Dispose(PInt64(FStatementCRC[AStatementNo])); FStatementCRC.Delete(AStatementNo); if GetComponentFormIntf(IibSHDMLHistoryForm, vDMLHistoryForm) then vDMLHistoryForm.ChangeNotification(AStatementNo, opRemove); end; end; procedure TibSHDMLHistory.LoadFromFile; var vFileName: string; vTextFile: TextFile; vItem: TStringList; vStatistic: TStringList; S: string; vCurrent: Integer; vStatisticIndex: Integer; vDigestIndex: Integer; procedure SetItem; var I: Integer; vCurrentDiget: Int64; begin if vItem.Count > 0 then begin if vDigestIndex > -1 then begin vCurrentDiget := StrToInt64Def(vItem.ValueFromIndex[vDigestIndex], 0); AddSQLTextDigest(vCurrentDiget); vItem.Delete(vDigestIndex); end else begin vCurrentDiget := SQLTextDigest(Statement(Pred(FItems.Count))); AddSQLTextDigest(vCurrentDiget); end; if vStatisticIndex > -1 then for I := vStatisticIndex to Pred(vItem.Count) do vStatistic.Add(vItem[I]); while Pred(vItem.Count) >= vStatisticIndex do vItem.Delete(Pred(vItem.Count)); FItems.Add(vItem.Text); FStatistic.Add(vStatistic.Text); if vCurrentDiget <> 0 then for I := Pred(Pred(FStatementCRC.Count)) downto 0 do //Pred(Pred - Пропускаем только что вставленный! begin if vCurrentDiget = PInt64(FStatementCRC[I])^ then begin FItems.Delete(I); FStatistic.Delete(I); Dispose(PInt64(FStatementCRC[I])); FStatementCRC.Delete(I); Break; end; end; end; end; begin vFileName := GetHistoryFileName; if FileExists(vFileName) then begin FItems.Clear; vItem := TStringList.Create; vStatistic := TStringList.Create; try AssignFile(vTextFile, vFileName); try Reset(vTextFile); vStatisticIndex := -1; vDigestIndex := -1; while not Eof(vTextFile) do begin Readln(vTextFile, S); if Pos(sHistorySQLHeader, S) > 0 then begin if vItem.Count = 0 then vItem.Add(S) else begin SetItem; // FItems.Add(vItem.Text); vItem.Clear; vStatistic.Clear; vStatisticIndex := -1; vDigestIndex := -1; vItem.Add(S) end; end else begin vCurrent := vItem.Add(S); if Pos(sHistoryStatisticsHeader, S) > 0 then vStatisticIndex := vCurrent else if Pos(SHistorySQLTextDigest, S) > 0 then vDigestIndex := vCurrent; end; end; SetItem; finally CloseFile(vTextFile); end; finally vItem.Free; vStatistic.Free; end; //Обеспечиваем чистку "лишних" сиквелов - сжатие файла необходимо, т.к. //автозапись каждого сиквела не удаляет предыдущие выполения SaveToFile; end; end; procedure TibSHDMLHistory.SaveToFile; var vStartSavingFrom: Integer; I: Integer; vFileName: string; vTextFile: TextFile; begin if Count > 0 then begin vFileName := GetHistoryFileName; if Length(vFileName) > 0 then begin AssignFile(vTextFile, vFileName); try Rewrite(vTextFile); if (MaxCount = 0) or (Count < MaxCount) then vStartSavingFrom := 0 else vStartSavingFrom := Count - MaxCount; for I := vStartSavingFrom to Pred(Count) do Writeln(vTextFile, FItems[I] + FStatistic[I] + sLineBreak + Format(SHistorySQLTextDigest + '=%d', [PInt64(FStatementCRC[I])^]) ); finally CloseFile(vTextFile); end; end; end else begin vFileName := GetHistoryFileName; if (Length(vFileName) > 0) and FileExists(vFileName) then RenameFile(vFileName, vFileName + '.bak'); // DeleteFile(vFileName); end; end; function TibSHDMLHistory.SQLTextDigest(AText: string): Int64; type PInt64 = ^Int64; var NormSQL: string; Digest: TSHA1Digest; begin NormalizeSQLText(AText, '@', NormSQL); Q_SHA1(Trim(NormSQL), Digest); Result := PInt64(@Digest)^; end; procedure TibSHDMLHistory.AddSQLTextDigest(ADigest: Int64); var vDigest: PInt64; begin New(vDigest); vDigest^ := ADigest; FStatementCRC.Add(vDigest); end; procedure TibSHDMLHistory.ClearDigestList; var I: Integer; begin for I := 0 to Pred(FStatementCRC.Count) do Dispose(PInt64(FStatementCRC[I])); end; { TibSHDMLHistoryFactory } function TibSHDMLHistoryFactory.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHDMLHistory); end; function TibSHDMLHistoryFactory.CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; var BTCLDatabase: IibSHDatabase; vSHSystemOptions: ISHSystemOptions; begin Result := nil; if IsEqualGUID(AOwnerIID, IUnknown) then begin Supports(Designer.CurrentDatabase, IibSHDatabase, BTCLDatabase); if not Assigned(BTCLDatabase) and IsEqualGUID(AOwnerIID, IUnknown) and (Length(ACaption) = 0) then Designer.AbortWithMsg(Format('%s', [SDatabaseIsNotInterBase])); Result := Designer.FindComponent(Designer.CurrentDatabase.InstanceIID, AClassIID); if not Assigned(Result) then begin Result := Designer.GetComponent(AClassIID).Create(nil); Result.OwnerIID := Designer.CurrentDatabase.InstanceIID; Result.Caption := Designer.GetComponent(AClassIID).GetHintClassFnc; if Assigned(BTCLDatabase) and Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSHSystemOptions) and not vSHSystemOptions.UseWorkspaces then Result.Caption := Format('%s for %s', [Result.Caption, BTCLDatabase.Alias]); end; Designer.ChangeNotification(Result, SCallDMLStatements, opInsert) end else begin if Supports(Designer.FindComponent(AOwnerIID), IibSHDatabase, BTCLDatabase) then begin Result := Designer.FindComponent(AOwnerIID, AClassIID); if not Assigned(Result) then begin Result := Designer.GetComponent(AClassIID).Create(nil); Result.OwnerIID := AOwnerIID; Result.Caption := Designer.GetComponent(AClassIID).GetHintClassFnc; if Assigned(BTCLDatabase) and Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSHSystemOptions) and not vSHSystemOptions.UseWorkspaces then Result.Caption := Format('%s for %s', [Result.Caption, BTCLDatabase.Alias]); end; Designer.ChangeNotification(Result, SCallDMLStatements, opInsert); end else Designer.AbortWithMsg(Format('%s', [SDatabaseIsNotInterBase])); end; end; initialization Register; end.
unit CadastroBase.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Base.View, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxControls, cxContainer, cxEdit, cxLabel, Tipos.Controller.Interf, dxGDIPlusClasses, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver; type TFCadastroView = class(TFBaseView) BtSalvar: TcxButton; LbOperacao: TcxLabel; procedure BtSalvarClick(Sender: TObject); private { Private declarations } protected procedure exibirTituloOperacao(AValue: TTipoOperacao); public { Public declarations } end; var FCadastroView: TFCadastroView; implementation {$R *.dfm} { TFCadastroView } procedure TFCadastroView.exibirTituloOperacao(AValue: TTipoOperacao); begin case AValue of toIncluir: begin LbOperacao.Caption := '(Incluindo)'; end; toAlterar: begin LbOperacao.Caption := '(Alterando)'; end; toConsultar: begin LbOperacao.Caption := '(Consultando)'; BtSalvar.Visible := False; end; toExcluir: begin LbOperacao.Caption := '(Excluindo)'; LbOperacao.Style.TextColor := $003F42C3; LbOperacao.StyleDisabled.TextColor := $003F42C3; end; toDuplicar: begin LbOperacao.Caption := '(Duplicando)'; end; end; end; procedure TFCadastroView.BtSalvarClick(Sender: TObject); begin inherited; Close; end; end.
unit Simple.Navigator; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Objects, FMX.Navigator, FMX.MultiView, FMX.Effects, 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, FMX.Ani, Storage.Chronos; type TSimpleNavigator = class(TForm) MultiView: TMultiView; Button1: TButton; Navigator: TNavigator; Chronos: TChronos; procedure Button1Click(Sender: TObject); procedure NavigatorSettingsClick(Sender: TObject); procedure NavigatorGetFrameMainClass(out AFrameClass: TFrameClass); public constructor Create(AOwner: TComponent); override; end; var SimpleNavigator: TSimpleNavigator; implementation {$R *.fmx} uses Simple.Master; procedure TSimpleNavigator.Button1Click(Sender: TObject); begin Close; end; constructor TSimpleNavigator.Create(AOwner: TComponent); begin inherited; Chronos.SetItem('navigator', Navigator); end; procedure TSimpleNavigator.NavigatorGetFrameMainClass( out AFrameClass: TFrameClass); begin AFrameClass := TSimpleMaster; end; procedure TSimpleNavigator.NavigatorSettingsClick(Sender: TObject); begin ShowMessage('Test'); end; end.
namespace CallingWin32DLL; interface uses System.Windows.Forms, System.Drawing, System.Runtime.InteropServices; // this namespace contains the DllImport attribute needed for importing Win32 DLLs. type MainForm = partial class(System.Windows.Forms.Form) private method btnSoundRenamed_Click(sender: System.Object; e: System.EventArgs); method btnSoundStandard_Click(sender: System.Object; e: System.EventArgs); protected method Dispose(aDisposing: Boolean); override; public constructor; end; Win32Methods = class public [DllImport('kernel32.dll')] //this attribute indentifies the DLL that is used for identifying the origing of the method after the attribute. class method Beep(Tone, Length: UInt32): Boolean; external; [DllImport('kernel32.dll', EntryPoint := 'Beep')] //same as previous attribute but here the method name is different from the one in the DLL. class method BeepFromKernel(Tone, Length: UInt32): Boolean; external; //same method as 'Beep' but renamed to 'BeepFromKernel' end; implementation {$REGION Construction and Disposition} constructor MainForm; begin InitializeComponent(); end; method MainForm.Dispose(aDisposing: boolean); begin if aDisposing then begin if assigned(components) then components.Dispose(); end; inherited Dispose(aDisposing); end; {$ENDREGION} method MainForm.btnSoundStandard_Click(sender: System.Object; e: System.EventArgs); begin //call the standard imported Beep method imported from kernel32.dll Win32Methods.Beep(tbFrequency.Value, 1000); // this method will make a sound through the PC-Speaker of your PC. end; method MainForm.btnSoundRenamed_Click(sender: System.Object; e: System.EventArgs); begin //call the renamed imported Beep method imported from kernel32.dll Win32Methods.BeepFromKernel(tbFrequency.Value, 1000); end; end.
unit uMGeo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList, Vcl.ExtCtrls, Vcl.Buttons, Vcl.StdCtrls, Vcl.Imaging.pngimage; type TforMediaGeo = class(TForm) edValor: TEdit; edMGeo: TEdit; labValor: TLabel; labMediaGeo: TLabel; lbValor: TListBox; labValoresAdd: TLabel; acGeo: TActionList; speedCalcular: TSpeedButton; speedLimpar: TSpeedButton; speedFechar: TSpeedButton; ptexto: TPanel; lbtexto: TLabel; actCalcular: TAction; actLimpa: TAction; actFechar: TAction; SpeedButton4: TSpeedButton; actAdicionar: TAction; imgFundo: TImage; imgFormulas: TImage; procedure actAdicionarExecute(Sender: TObject); procedure actFecharExecute(Sender: TObject); procedure actLimpaExecute(Sender: TObject); procedure actCalcularExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var forMediaGeo: TforMediaGeo; geo: array of real; cont: integer; implementation {$R *.dfm} procedure TforMediaGeo.actAdicionarExecute(Sender: TObject); begin if edvalor.Text = '' then begin application.MessageBox('Adicione um valor','Atenção',mb_iconexclamation+mb_ok); exit; end; setlength(geo,cont+1); geo[cont]:= strtofloat(edValor.Text); edValor.Clear; lbValor.items.add(floattostr(geo[cont])); cont:= cont+1; end; procedure TforMediaGeo.actCalcularExecute(Sender: TObject); var mgeo, pvalor: real; contf:integer; begin if cont<1 then begin application.MessageBox('Não tem valor para ser calculado','Atenção',mb_iconexclamation+mb_ok); exit; end; pvalor:=1; for contf := Low(geo) to High(geo) do begin pvalor:= pvalor*geo[contf]; end; mgeo:= exp(1/(cont)*ln(pvalor)); edMGeo.text:= formatFloat('#0.00',mgeo); end; procedure TforMediaGeo.actFecharExecute(Sender: TObject); begin Close; end; procedure TforMediaGeo.actLimpaExecute(Sender: TObject); begin edValor.Clear; edMGeo.Clear; lbValor.clear; cont:= 0; end; procedure TforMediaGeo.FormCreate(Sender: TObject); begin lbtexto.Caption:= 'A média geométrica é'+#13+ 'uma proporção contínua'+#13+ 'de um conjunto de n'+#13+ 'número a1, a2, a3, ... ,'+#13+ 'an e a raiz de ordem n'+#13+ 'do produto desses números.'+#13+ 'De notação:'; end; end.
// // Generated by JavaToPas v1.5 20171018 - 170747 //////////////////////////////////////////////////////////////////////////////// unit javax.xml.transform.Transformer; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, javax.xml.transform.Source, javax.xml.transform.Result, javax.xml.transform.URIResolver, java.util.Properties, javax.xml.transform.ErrorListener; type JTransformer = interface; JTransformerClass = interface(JObjectClass) ['{515D364D-FD7A-4585-98B2-14CDC5C79F89}'] function getErrorListener : JErrorListener; cdecl; // ()Ljavax/xml/transform/ErrorListener; A: $401 function getOutputProperties : JProperties; cdecl; // ()Ljava/util/Properties; A: $401 function getOutputProperty(JStringparam0 : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $401 function getParameter(JStringparam0 : JString) : JObject; cdecl; // (Ljava/lang/String;)Ljava/lang/Object; A: $401 function getURIResolver : JURIResolver; cdecl; // ()Ljavax/xml/transform/URIResolver; A: $401 procedure clearParameters ; cdecl; // ()V A: $401 procedure reset ; cdecl; // ()V A: $1 procedure setErrorListener(JErrorListenerparam0 : JErrorListener) ; cdecl; // (Ljavax/xml/transform/ErrorListener;)V A: $401 procedure setOutputProperties(JPropertiesparam0 : JProperties) ; cdecl; // (Ljava/util/Properties;)V A: $401 procedure setOutputProperty(JStringparam0 : JString; JStringparam1 : JString) ; cdecl;// (Ljava/lang/String;Ljava/lang/String;)V A: $401 procedure setParameter(JStringparam0 : JString; JObjectparam1 : JObject) ; cdecl;// (Ljava/lang/String;Ljava/lang/Object;)V A: $401 procedure setURIResolver(JURIResolverparam0 : JURIResolver) ; cdecl; // (Ljavax/xml/transform/URIResolver;)V A: $401 procedure transform(JSourceparam0 : JSource; JResultparam1 : JResult) ; cdecl;// (Ljavax/xml/transform/Source;Ljavax/xml/transform/Result;)V A: $401 end; [JavaSignature('javax/xml/transform/Transformer')] JTransformer = interface(JObject) ['{4633CECA-63D7-485C-8A7F-542F76950809}'] function getErrorListener : JErrorListener; cdecl; // ()Ljavax/xml/transform/ErrorListener; A: $401 function getOutputProperties : JProperties; cdecl; // ()Ljava/util/Properties; A: $401 function getOutputProperty(JStringparam0 : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $401 function getParameter(JStringparam0 : JString) : JObject; cdecl; // (Ljava/lang/String;)Ljava/lang/Object; A: $401 function getURIResolver : JURIResolver; cdecl; // ()Ljavax/xml/transform/URIResolver; A: $401 procedure clearParameters ; cdecl; // ()V A: $401 procedure reset ; cdecl; // ()V A: $1 procedure setErrorListener(JErrorListenerparam0 : JErrorListener) ; cdecl; // (Ljavax/xml/transform/ErrorListener;)V A: $401 procedure setOutputProperties(JPropertiesparam0 : JProperties) ; cdecl; // (Ljava/util/Properties;)V A: $401 procedure setOutputProperty(JStringparam0 : JString; JStringparam1 : JString) ; cdecl;// (Ljava/lang/String;Ljava/lang/String;)V A: $401 procedure setParameter(JStringparam0 : JString; JObjectparam1 : JObject) ; cdecl;// (Ljava/lang/String;Ljava/lang/Object;)V A: $401 procedure setURIResolver(JURIResolverparam0 : JURIResolver) ; cdecl; // (Ljavax/xml/transform/URIResolver;)V A: $401 procedure transform(JSourceparam0 : JSource; JResultparam1 : JResult) ; cdecl;// (Ljavax/xml/transform/Source;Ljavax/xml/transform/Result;)V A: $401 end; TJTransformer = class(TJavaGenericImport<JTransformerClass, JTransformer>) end; implementation end.
{ @abstract(Provides Old Format 1.5 highlighters import) @authors(Vitalik [just_vitalik@yahoo.com]) @created(2005) @lastmod(2006-06-30) } {$IFNDEF QSynUniFormatNativeXml15} unit SynUniFormatNativeXml15; {$ENDIF} {$I SynUniHighlighter.inc} interface uses {$IFDEF SYN_CLX} QClasses, QGraphics, QSynUniFormat, QSynUniClasses, QSynUniRules, QSynUniHighlighter {$ELSE} Classes, Graphics, {$IFDEF SYN_COMPILER_6_UP} Variants, {$ENDIF} SynUniFormat, SynUniFormatNativeXml, SynUniClasses, SynUniRules, SynUniHighlighter, {$ENDIF} SysUtils, Dialogs, {XMLIntf; } // DW SimpleXML; type TSynUniFormatNativeXml15 = class(TSynUniFormatNativeXml) class function ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override; class function ImportFromStream(AObject: TObject; AStream: TStream): Boolean; override; class function ImportFromFile(AObject: TObject; AFileName: string): Boolean; override; end; implementation {$IFNDEF SYN_COMPILER_7_UP} function StrToBoolDef(const S: string; const Default: Boolean): Boolean; begin if (S = 'True') or (S = '1') or (S = '-1') then Result := True else if (S = 'False') or (S = '0') then Result := False else Result := Default; end; {$ENDIF} //------------------------------------------------------------------------------ class function TSynUniFormatNativeXml15.ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; var Schemes: TStringList; SchemeIndex: integer; //---------------------------------- procedure LoadInfo(ANode: IXMLNode); var i: integer; begin with ANode, SynUniSyn.Info do begin with EnsureChild('General'), General do begin Name := EnsureChild('Name').Text; Extensions := EnsureChild('FileTypeName').Text; EnsureChild('Layout').Text; end; with EnsureChild('Author'), Author do begin Name := EnsureChild('Name').Text; Email := EnsureChild('Email').Text; Web := EnsureChild('Web').Text; Copyright := EnsureChild('Copyright').Text; Company := EnsureChild('Company').Text; Remark := EnsureChild('Remark').Text; end; with EnsureChild('Version'), General do begin Version := StrToInt(EnsureChild('Version').Text); Revision := StrToInt(EnsureChild('Revision').Text); EnsureChild('Date').Text; EnsureChild('Type').Text; end; with EnsureChild('Sample'), General do for i := 0 to ChildNodes.Count-1 do Sample := Sample + ChildNodes[i].Text + #13#10; with EnsureChild('History'), General do for i := 0 to ChildNodes.Count-1 do History := History + ChildNodes[i].Text + #13#10; end; end; //-------------------------------------------------------------- procedure LoadSchemes({Schemes: TSynUniSchemes; }ANode: IXMLNode); begin //TODO: Add implementation here end; //--------------------------------------------------------------- procedure LoadAttri(Attributes: TSynAttributes; ANode: IXMLNode); begin with Attributes, ANode do begin if EnsureChild('Fore').Text <> '' then Foreground := StringToColor(EnsureChild('Fore').Text); if EnsureChild('Back').Text <> '' then Background := StringToColor(EnsureChild('Back').Text); Style := StrToFontStyle(EnsureChild('Style').Text); ParentForeground := StrToBoolDef(EnsureChild('ParentForeground').Text, False); ParentBackground := StrToBoolDef(EnsureChild('ParentBackground').Text, False); end; end; //------------------------------------------------------------ procedure LoadKeyList(AKeyList: TSynKeyList; ANode: IXMLNode); var i: integer; begin with AKeyList, ANode do begin Name := VarToStr(GetVarAttr('Name','')); LoadAttri(AKeyList.Attributes, ChildNodes[SchemeIndex]); for i := 0 to ChildNodes.Count-1 do if ChildNodes[i].NodeName = 'W' then KeyList.Add(ChildNodes[i].Text); end; end; //------------------------------------------------ procedure LoadSet(ASet: TSynSet; ANode: IXMLNode); begin with ASet, ANode do begin Name := VarToStr(GetVarAttr('Name','')); LoadAttri(ASet.Attributes, ChildNodes[SchemeIndex]); CharSet := StrToSet(EnsureChild('S').Text); end; end; //------------------------------------------------------ procedure LoadRange(ARange: TSynRange; ANode: IXMLNode); var i: integer; NewRange: TSynRange; NewKeyList: TSynKeyList; NewSet: TSynSet; procedure LoadToken(AToken: TSynMultiToken; ANode: IXMLNode; Kind: string); begin with AToken, ANode do begin FinishOnEol := StrToBoolDef(EnsureChild(Kind+'FinishOnEol').Text, False); StartLine := StrToStartLine(EnsureChild(Kind+'StartLine').Text); StartType := StrToStartType(EnsureChild(Kind+'PartOfTerm').Text); BreakType := StrToBreakType(EnsureChild(Kind+'PartOfTerm').Text); end; end; var b: Boolean; begin with ARange, ANode do begin Name := VarToStr(GetVarAttr('Name','')); //TODO: Сделать считывание Num как создание SynSet (если Num <> Def) LoadAttri(ARange.Attributes, EnSureChild('Def')); LoadAttri(ARange.Attributes, ChildNodes[SchemeIndex]); OpenToken.Clear(); CloseToken.Clear(); AddCoupleTokens(EnsureChild('OpenSymbol').Text, EnsureChild('CloseSymbol').Text); Delimiters := StrToSet(EnsureChild('DelimiterChars').Text); CaseSensitive := StrToBoolDef(EnsureChild('CaseSensitive').Text, False); CloseOnTerm := StrToBoolDef(EnsureChild('CloseOnTerm').Text, False); // ShowMessage(ChildNodes['CloseOnEol'].Text); // b := StrToBoolDef(ChildNodes['CloseOnEol'].Text, False); // ShowMessage(BoolToStr(b)); // ShowMessage(BoolToStr(StrToBoolDef(ChildNodes['CloseOnEol'].Text, False))); CloseOnEol := StrToBoolDef(EnsureChild('CloseOnEol').Text, False); // ShowMessage(BoolToStr(CloseOnEol)); AllowPreviousClose := StrToBoolDef(EnsureChild('AllowPredClose').Text, False); LoadToken(OpenToken, ANode, 'OpenSymbol'); LoadToken(CloseToken, ANode, 'CloseSymbol'); for i := 0 to ChildNodes.Count-1 do if ChildNodes[i].NodeName = 'Range' then begin NewRange := TSynRange.Create; LoadRange(NewRange, ChildNodes[i]); AddRange(NewRange); end else if ChildNodes[i].NodeName = 'KW' then begin NewKeyList := TSynKeyList.Create(); LoadKeyList(NewKeyList, ChildNodes[i]); AddKeyList(NewKeyList); end else if ChildNodes[i].NodeName = 'Set' then begin NewSet := TSynSet.Create(); LoadSet(NewSet, ChildNodes[i]); AddSet(NewSet); end; end; end; begin with ANode, SynUniSyn do begin Clear(); LoadInfo(EnsureChild('Info')); if EnsureChild('SchemeIndex').Text <> '' then begin // DW SchemeIndex := StrToInt(EnsureChild('SchemeIndex').Text); LoadSchemes(EnsureChild('Schemes')); end; LoadRange(MainRules, EnsureChild('Range')); FormatVersion := '1.5'; end; Result := True; end; //------------------------------------------------------------------------------ class function TSynUniFormatNativeXml15.ImportFromStream(AObject: TObject; AStream: TStream): Boolean; var Buffer: TStringlist; Stream: TMemoryStream; begin VerifyStream(AStream); Buffer := TStringList.Create(); Buffer.LoadFromStream(AStream); Buffer.Text := Stringreplace(Buffer.Text, '&qt;', '&quot;',[rfreplaceall, rfignorecase]); Buffer.Insert(0, '<?xml version="1.0" encoding="windows-1251"?>'); Stream := TMemoryStream.Create(); Buffer.SaveToStream(Stream); FreeAndNil(Buffer); Result := inherited ImportFromStream(AObject, Stream); FreeAndNil(Stream); end; //------------------------------------------------------------------------------ class function TSynUniFormatNativeXml15.ImportFromFile(AObject: TObject; AFileName: string): Boolean; begin Result := inherited ImportFromFile(AObject, AFileName); end; end.
unit UnitServicos; interface uses Windows, winsvc; function ServiceStatus(sService: string; Change:bool; StartStop: bool): string; function ServiceList: string; function InstallService(ServiceName, DisplayName: pchar; FileName: string): bool; function UninstallService(sService: string): bool; function ServiceStringCode(nID : integer): string; implementation uses UnitDiversos, UnitServerUtils, UnitListarProcessos; function GetServiceDescription(ServiceName: String): String; begin result := lerreg(HKEY_LOCAL_MACHINE, pchar('System\CurrentControlSet\Services\' + ServiceName), 'Description', ''); end; function ServiceStringCode(nID: integer): string; begin result := '0'; case nID of SERVICE_STOPPED: Result := inttostr(SERVICE_STOPPED); SERVICE_RUNNING: Result := inttostr(SERVICE_RUNNING); SERVICE_PAUSED: Result := inttostr(SERVICE_PAUSED); SERVICE_START_PENDING: Result := inttostr(SERVICE_START_PENDING); SERVICE_STOP_PENDING: Result := inttostr(SERVICE_STOP_PENDING); SERVICE_CONTINUE_PENDING: Result := inttostr(SERVICE_CONTINUE_PENDING); SERVICE_PAUSE_PENDING: Result := inttostr(SERVICE_PAUSE_PENDING); end; end; function ServiceStatus(sService: string; Change: bool; StartStop: bool): string; var schm, schs: SC_Handle; ss: TServiceStatus; psTemp: PChar; s_s: dword; begin Result := ''; ss.dwCurrentState := 0; psTemp := nil; schm := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if (schm > 0) then begin if StartStop = true then s_s := SERVICE_START else s_s := SERVICE_STOP; schs:= OpenService(schm, pchar(sService), s_s or SERVICE_QUERY_STATUS); if (schs > 0) then begin if change = true then if StartStop = true then StartService(schs, 0, psTemp) else ControlService(schs, SERVICE_CONTROL_STOP, ss); QueryServiceStatus(schs, ss); CloseServiceHandle(schs); end; CloseServiceHandle(schm); end; Result := ServiceStringCode(ss.dwCurrentState); end; function UninstallService(sService: string): bool; var schm, schs : SC_Handle; begin result := false; schm := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if (schm > 0) then begin schs := OpenService(schm, pchar(sService), $10000); if (schs > 0) then begin if DeleteService(schs) then result := true; CloseServiceHandle(schs); end; CloseServiceHandle(schm); end; end; function ServiceList: string; var j, i: integer; schm: SC_Handle; nBytesNeeded, nServices, nResumeHandle: DWord; ServiceStatusRecs: array[0..511] of TEnumServiceStatus; begin Result := ''; //SC_MANAGER_ALL_ACCESS schm := OpenSCManager(nil, Nil, SC_MANAGER_CONNECT or SC_MANAGER_ENUMERATE_SERVICE); if (schm = 0) then Exit; nResumeHandle := 0; while True do begin EnumServicesStatus(schm, SERVICE_TYPE_ALL, SERVICE_STATE_ALL, ServiceStatusRecs[0], sizeof(ServiceStatusRecs), nBytesNeeded, nServices, nResumeHandle); for j:=0 to nServices-1 do begin if ServiceStatusRecs[j].lpServiceName = '' then Result := result + ' «' else Result := result + ServiceStatusRecs[j].lpServiceName + '«'; // Nome verdadeiro if ServiceStatusRecs[j].lpDisplayName = '' then result := result + ' «' else Result := result + ServiceStatusRecs[j].lpDisplayName + '«'; // Nome do servišo (o que aparece no msconfig) Result := result + GetServiceDescription(ServiceStatusRecs[j].lpServiceName) + ' «'; // Nome do servišo (o que aparece no msconfig) result := result + ServiceStatus(ServiceStatusRecs[j].lpServiceName, false, false) + ' «'; end; if (nBytesNeeded = 0) then Break; end; if (schm > 0) then CloseServiceHandle(schm); end; function InstallService(ServiceName, DisplayName: pchar; FileName: string): bool; var SCManager: SC_HANDLE; Service: SC_HANDLE; Args: pchar; begin result := false; SetTokenPrivileges; SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if SCManager = 0 then Exit; try Service := CreateService(SCManager, ServiceName, ServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS or SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, pchar(FileName), nil, nil, nil, nil, nil); write2reg(HKEY_LOCAL_MACHINE, pchar('System\CurrentControlSet\Services\' + ServiceName), 'Description', pchar(DisplayName)); Args := nil; CloseServiceHandle(Service); CloseServiceHandle(SCManager); except exit; end; result := true; end; end.
unit FFPlay; interface {$IFDEF DEF_OUTPUT_WIN} const LIBNAME = '..\Bin\FFPlayLib.dll'; {$ELSE} const LIBNAME = 'libFFPlay.so'; {$ENDIF} const FFP_AUDIO_U8 = $0008; const FFP_AUDIO_S8 = $8008; const FFP_AUDIO_U16LSB = $0010; const FFP_AUDIO_S16LSB = $8010; const FFP_AUDIO_U16MSB = $1010; const FFP_AUDIO_S16MSB = $9010; const FFP_AUDIO_U16 = FFP_AUDIO_U16LSB; const FFP_AUDIO_S16 = FFP_AUDIO_S16LSB; type TFFP_UITYPE = ( FFP_CLI = 0, FFP_GUI = 1 ); type TFFP_BOOL = ( FFP_FALSE = 0, FFP_TRUE = 1); type TFFP_INFO = ( FFP_INFO_NONE = 0, FFP_INFO_ERROR = 1, FFP_INFO_WARNING = 2, FFP_INFO_STREAM_ERROR = 3, FFP_INFO_DEBUG = 4); type TFFP_PLAY_STATUS = ( FFP_STOP = 0, FFP_PLAY = 1, FFP_PAUSED = 2, FFP_RESUMED = 3, FFP_EOF = 4); type TFFP_CHAR = AnsiChar; type PFFP_CHAR = ^TFFP_CHAR; type TFFP_AUD_PARAMS = record Freq : Integer; Channels : Byte; Format : Word; SampsInBuff : Word; BuffSizeinByte : Cardinal; end; type PFFP_AUD_PARAMS = ^TFFP_AUD_PARAMS; type TFFP_VID_PARAMS = record Width : Integer; Height : Integer; BytesPerPixel : Integer; end; type PFFP_VID_PARAMS = ^TFFP_VID_PARAMS; type TFFP_YUV_DATA = record width : Integer; height : Integer; pixels : pointer; end; type PFFP_YUV_DATA = ^TFFP_YUV_DATA; type TFFP_RGB_DATA = record width : Integer; height : Integer; bpp : Integer; pixels : pointer; end; type PFFP_RGB_DATA = ^TFFP_RGB_DATA; type TFFP_EVENTEXIT = procedure( sender : pointer ; exitCode : Integer ) ; cdecl ; type TFFP_EVENTINFO = procedure( sender : pointer ; infoCode : Integer ; msg : PFFP_CHAR ) ; cdecl ; type TFFP_EVENTAUDIO = procedure( sender : pointer ; buff : PByte ; BuffLenInByte : Integer ) ; cdecl ; type TFFP_EVENTVIDEO = procedure( sender : pointer ; rgbData : PFFP_RGB_DATA) ; cdecl ; type TFFP_EVENTVIDEORESIZE = procedure( sender : pointer ; w , h : Integer ) ; cdecl; type TFFP_EVENTPLAYSTATUS = procedure( sender : pointer ; status : TFFP_PLAY_STATUS ) ; cdecl; type TFFP_EVENTS = record sender : Pointer; screenID : Cardinal; duration_in_us : Int64; current_in_s : double; uiType : TFFP_UITYPE; eventInfo : TFFP_EVENTINFO; eventExit : TFFP_EVENTEXIT; eventAudio : TFFP_EVENTAUDIO; eventVideo : TFFP_EVENTVIDEO; eventResize : TFFP_EVENTVIDEORESIZE; eventStatus : TFFP_EVENTPLAYSTATUS; playStatus : TFFP_PLAY_STATUS; end; type PFFP_EVENTS = ^TFFP_EVENTS; procedure multimedia_exit() ; cdecl ; external LIBNAME; function multimedia_get_filename() : PFFP_CHAR ; cdecl ; external LIBNAME; procedure multimedia_parse_options( argc : Integer ; argv : PFFP_CHAR ) ; cdecl ;external LIBNAME; procedure multimedia_set_filename( filename : PFFP_CHAR ) ; cdecl ; external LIBNAME; procedure multimedia_stream_stop() ; cdecl ; external LIBNAME; procedure multimedia_stream_start() ; cdecl ; external LIBNAME; function multimedia_get_audioformat() : PFFP_AUD_PARAMS ; cdecl ; external LIBNAME; function multimedia_get_videoformat() : PFFP_VID_PARAMS ; cdecl ; external LIBNAME; function multimedia_get_duration_in_mSec() : Int64 ; cdecl ; external LIBNAME; procedure multimedia_pause_resume() ; cdecl ; external LIBNAME; function multimedia_event_loop_alive() : Integer ; cdecl ; external LIBNAME; procedure multimedia_resize_screen(w,h : Integer) ; cdecl ; external LIBNAME; procedure multimedia_clear_screen( screenID, width, height : Integer ) ; cdecl ; external LIBNAME; procedure multimedia_reset_pointer(); cdecl ; external LIBNAME; procedure multimedia_yuv420p_to_rgb24( YuvData : PFFP_YUV_DATA ; RGBBuff : pointer) ; cdecl ; external LIBNAME; procedure multimedia_yuv420p_to_rgb32( YuvData : PFFP_YUV_DATA ; RGBBuff : pointer) ; cdecl ; external LIBNAME; procedure multimedia_rgb_swap(RgbData: PFFP_RGB_DATA ;shiftR,shiftG,shitB : Integer);cdecl ; external LIBNAME; function multimedia_test_xwin_draw_start(XWinID, width, height : Integer) : Integer ; cdecl ; external LIBNAME; procedure multimedia_test_xwin_draw_stop(); cdecl ; external LIBNAME; function multimedia_setup_gui_player( events : PFFP_EVENTS ):Integer; cdecl ; external LIBNAME; implementation initialization finalization end.
{ Delphi Thread Unit by Aphex http://iamaphex.cjb.net unremote@knology.net } unit ThreadUnit; {$D-,L-,O+,Q-,R-,Y-,S-} interface uses Windows; type TThread = class; TThreadProcedure = procedure(Thread: TThread); TSynchronizeProcedure = procedure; TThread = class private FThreadHandle: longword; FThreadID: longword; FExitCode: longword; FTerminated: boolean; FExecute: TThreadProcedure; FData: pointer; protected public constructor Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal); destructor Destroy; override; procedure Synchronize(Synchronize: TSynchronizeProcedure); procedure Lock; procedure Unlock; property Terminated: boolean read FTerminated write FTerminated; property ThreadHandle: longword read FThreadHandle; property ThreadID: longword read FThreadID; property ExitCode: longword read FExitCode; property Data: pointer read FData write FData; end; implementation var ThreadLock: TRTLCriticalSection; procedure ThreadWrapper(Thread: TThread); var ExitCode: dword; begin Thread.FTerminated := False; try Thread.FExecute(Thread); finally GetExitCodeThread(Thread.FThreadHandle, ExitCode); Thread.FExitCode := ExitCode; Thread.FTerminated := True; ExitThread(ExitCode); end; end; constructor TThread.Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal); begin inherited Create; FExitCode := 0; FExecute := ThreadProcedure; FThreadHandle := BeginThread(nil, 0, @ThreadWrapper, Pointer(Self), CreationFlags, FThreadID); end; destructor TThread.Destroy; begin inherited; CloseHandle(FThreadHandle); end; procedure TThread.Synchronize(Synchronize: TSynchronizeProcedure); begin EnterCriticalSection(ThreadLock); try Synchronize; finally LeaveCriticalSection(ThreadLock); end; end; procedure TThread.Lock; begin EnterCriticalSection(ThreadLock); end; procedure TThread.Unlock; begin LeaveCriticalSection(ThreadLock); end; initialization InitializeCriticalSection(ThreadLock); finalization DeleteCriticalSection(ThreadLock); end.
unit LAB; interface Uses Files, SysUtils, Classes; Type TResType=array[0..3] of char; TLABDirectory=class(TContainerFile) Procedure Refresh;override; Function GetContainerCreator(name:String):TContainerCreator;override; end; TLABHeader=packed record Magic:array[0..3] of char; {'LABN'} Version:Longint; {65536} NFiles:Longint; NamePoolSize:Longint; end; TLABEntry=packed record Nameoffset:longint; // from the beginning of the name pool offset:Longint; //absolute from the beginning of the file size:longint; ResType:TResType; end; TLABCreator=class(TContainerCreator) pes:TList; centry:integer; lh:TLABHeader; Procedure PrepareHeader(newfiles:TStringList);override; Procedure AddFile(F:TFile);override; Function ValidateName(name:String):String;override; Destructor Destroy;override; Private Function GetResType(const Name:String):TResType; end; implementation uses FileOperations; Type TLABFileInfo=class(TFileInfo) resType:TResType; end; Procedure TLABDirectory.Refresh; var f:TFile; Lh:TLabHeader; Le:TLabEntry; PNpool:pchar; Fi:TLABFileInfo; i:integer; s:string; begin ClearIndex; f:=OpenFileRead(name,0); Try F.FRead(lh,sizeof(lh)); if (lh.magic<>'LABN') then raise Exception.Create(Name+' is not a LAB file'); F.Fseek(lh.NFiles*sizeof(le)+sizeof(lh)); GetMem(PNPool,lh.NamePoolSize); F.Fread(PNPool^,lh.NamePoolSize); F.Fseek(sizeof(lh)); for i:=0 to lh.nFiles-1 do begin F.FRead(le,sizeof(le)); fi:=TLABFileInfo.Create; fi.offs:=le.offset; fi.size:=le.size; fi.resType:=le.ResType; Files.AddObject((PNPool+le.NameOffset),fi); end; Finally F.FClose; FreeMem(PnPool); end; end; Function TLABDirectory.GetContainerCreator(name:String):TContainerCreator; begin Result:=TLABCreator.Create(Name); end; Procedure TLABCreator.PrepareHeader(newfiles:TStringList); var i:integer; buf:Array[0..255] of char; len:Integer; ple:^TLabEntry; aName:String; begin pes:=TList.Create; Lh.magic:='LABN'; lh.Version:=65536; lh.NFiles:=newfiles.count; lh.NamePoolSize:=0; cf.Fseek(sizeof(lh)+lh.NFiles*sizeof(TLABEntry)); for i:=0 to newfiles.count-1 do begin aName:=ExtractName(newfiles[i]); StrPCopy(buf,aName); len:=Length(aName); cf.FWrite(buf,len+1); new(ple); with ple^ do begin NameOffset:=lh.NamePoolSize; size:=0; offset:=0; resType:=GetResType(aName); end; inc(lh.NamePoolSize,len+1); pes.Add(ple); end; Centry:=0; end; Function TLabCreator.GetResType(const Name:String):TResType; var ext:String; begin ext:=UpperCase(ExtractExt(Name)); if ext='.PCX' then Result:='MTXT' else if ext='.ITM' then Result:='METI' else if ext='.ATX' then Result:='FXTA' else if ext='.NWX' then Result:='FXAW' else if ext='.WAV' then Result:='DVAW' else if ext='.PHY' then Result:='SYHP' else if ext='.RCS' then Result:='BPCR' else if ext='.MSC' then Result:='BCSM' else if ext='.LAF' then Result:='TNFN' else if ext='.LVT' then Result:='FTVL' else if ext='.OBT' then Result:='FTBO' else if ext='.INF' then Result:='FFNI' else Result:=#0#0#0#0; end; Procedure TLABCreator.AddFile(F:TFile); begin with TLABEntry(pes[centry]^) do begin offset:=cf.Fpos; size:=f.Fsize; end; CopyFileData(f,cf,f.Fsize); inc(centry); end; Function TLABCreator.ValidateName(name:String):String; begin Result:=name; end; Destructor TLABCreator.Destroy; var i:integer; begin cf.Fseek(0); cf.FWrite(lh,sizeof(lh)); for i:=0 to pes.count-1 do begin cf.FWrite(TLABEntry(pes[i]^),sizeof(TLABEntry)); Dispose(pes[i]); end; Inherited Destroy; end; end.
unit fpcGenerics; interface type TInt = TInt; generic TGList<T> = class function GetCurrent: T; end; TIntList = specialize TGList<TInt>; implementation generic function Add<T>(aLeft, aRight: T): T; begin Result := aLeft + aRight; end; function TGList.GetCurrent: T; begin Result := specialize Add(1, 2); end; end.
unit uContatoController; interface uses MVCFramework, MVCFramework.Commons, MVCFramework.Serializer.Commons; type [MVCPath('/api/v1')] TContatoController = class(TMVCController) public [MVCPath('/echostring/($Value)')] [MVCHTTPMethod([httpGET])] procedure GetEchoString(const Value: string); protected procedure OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); override; procedure OnAfterAction(Context: TWebContext; const AActionName: string); override; end; implementation uses System.SysUtils, MVCFramework.Logger, System.StrUtils; procedure TContatoController.OnAfterAction(Context: TWebContext; const AActionName: string); begin { Executed after each action } inherited; end; procedure TContatoController.OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); begin { Executed before each action if handled is true (or an exception is raised) the actual action will not be called } inherited; end; procedure TContatoController.GetEchoString(const Value: string); var lStringBuilder: TStringBuilder; begin lStringBuilder := TStringBuilder.Create; try lStringBuilder.Append('{"Result":"'); lStringBuilder.Append(Value); lStringBuilder.Append('"}'); Render(lStringBuilder.ToString); finally lStringBuilder.Free; end; end; end.
unit filelist_atd; interface uses Dos, Crt, Tabul_Atd, onefile_atd, DOSWIN; type onefilearray = array [1..maxint] of onefile; files_pointer = ^onefilearray; type filelist = object public constructor init (Coordinates : Coords; thistabula : tabula); procedure getfilelist; {получить список файлов} procedure ClearDisplay; {очистить колонки} procedure DoDisplay (i : word); {вывести список файлов} procedure filelist_driver; {управляющая подпрограмма} private first, second : Coords; {координаты первого и второго стобцов} numfiles : word; files : files_pointer; procedure addfileinfo (var i : word; S : SearchRec); {добавить информацию о файле в массив} procedure ClearColumn (X : Coords); {очистить колонку} procedure DisplayColumn (X : Coords; var i : word); {вывести колонку} procedure Restore_Native (X, Y : byte; i : word); {вернуть файлу на экране родной цвет} procedure Draw_Cursor (X, Y : byte; i : word; Color : byte); converter : doswinconverter; end; implementation constructor filelist.init (Coordinates : Coords; thistabula : tabula); begin thistabula.Get_Cursor_Position_Coordinates (Coordinates, first, second); numfiles := 0; {кол-во файлов} window (1, 1, 80, 25); end; procedure filelist.addfileinfo (var i : word; S : SearchRec); {добавить информацию о файле в массив} begin inc (i); {увеличиваем счетчик массива} files^[i].GetFromSearch (S); {копируем информацию из SearchRec в элемент массива} files^[i].SetFileInformation; {устанавливаем информацию файла (см. onefile_atd)} end; procedure filelist.getfilelist; var S : SearchRec; i : word; begin Findfirst ('*.*', Anyfile, S); {ищем первый файл} if DoSError = 0 then {если не ошибка и } if S.Name <> '.' then {Имя файла - не точка} inc (numfiles); {увеличиваем кол-во файлов} while DosError = 0 do begin {найдем кол-во файлов} FindNext (s); if DoSError = 0 then inc (numfiles) end; GetMem (files, Sizeof (onefile) * numfiles); {выделим память} i := 0; {счетчик массива} Findfirst ('*.*', Anyfile, S); {первую точку пропускаем} if DoSError = 0 then {если не ошибка и } if S.Name <> '.' then begin {Имя файла - не точка} converter.decode_string (S.Name); Self.addfileinfo (i, S); {добавляем файл} end; while DoSError = 0 do begin FindNext (s); if DoSError = 0 then begin converter.decode_string (S.Name); Self.addfileinfo (i, S); {добавляем инфу о файле} end end end; procedure filelist.DisplayColumn (X : Coords; var i : word); var i2 : byte; begin i2 := X.LeftY; while (i <= numfiles) and (i2 <= X.RightY) do begin Gotoxy (X.LeftX, i2); textcolor (files^[i].GetFileColor); {получаем цвет файла} files^[i].SetCoordinates (X.LeftX, i2); {устанавливаем координаты} Write (files^[i].GetFileName); {выводим имя} inc (i); inc (i2) end; end; procedure filelist.DoDisplay (i : word); begin ClearDisplay; {очищаем экран} DisplayColumn (First, i); {отобразить первую колонку} if i <= numfiles then {если элемент массива меньше кол-ва файлов то} DisplayColumn (Second, i); {отобразить вторую колонку} Gotoxy (1, 1); end; procedure filelist.ClearColumn (X : Coords); {очистить колонку} var i2 : byte; begin for i2 := X.LeftY to X.RightY do begin gotoxy (X.LeftX, i2); write (' ' : 12); end; end; procedure filelist.ClearDisplay; var i2 : byte; begin ClearColumn (First); {очищаем первую колонку} ClearColumn (Second); {очищаем вторую колонку} end; procedure filelist.Restore_Native (X, Y : byte; i : word); {вернуть родной цвет после курсора} begin GotoXy (X, Y); {переходим куда нам надо} textcolor (files^[i].GetFileColoR); {востанавливаем родной цвет} Write (files^[i].GetFileName); {рисуем} end; procedure filelist.Draw_Cursor (X, Y : byte; i : word; Color : byte); begin GotoXY (X, Y); {переходим к нужному месту} if Color = 0 then {если цвет = 0} textcolor (files^[i].GetFileColor + Blink) {то будет мерцание} else begin {иначе} textbackground (color); {вводимый цвет - фоновый} textcolor (files^[i].GetFileColor) {а цвет текста - стандартный} end; Write (files^[i].GetFileName); {написать} textbackground (black); {вернуть черный цвет} end; procedure filelist.filelist_Driver; var i : word; {счетчик массива} i2 : byte; {счетчик столбца - "движение" } ch : char; CurrentX : byte; const Cursor_Color = 5; begin i := 1; {счетчик равен единице} DoDisplay (i); i2 := first.LeftY; {начало курсора - в начале левого столбца} CurrentX := first.LeftX; {соответственно х в данный момент - левый} Draw_Cursor (CurrentX, i2, i, Cursor_Color); repeat ch := readkey; {жмем клавишу} if ch = #0 then {если считанный символ = 0, то} ch := readkey; {считываем расширенный код} {если это - стрелка вниз} if ch = #80 then begin {если это стрелка вниз то} if i <> numfiles then begin {если номер массива равен длине массива, то пока ничего не делать} Restore_Native (CurrentX, i2, i); {восстанавливаем стандарт} if (i2 = first.RightY) and (CurrentX = first.LeftX) then begin {если это конец столбца, то} i2 := second.LeftY; {левый Y - игрек правого столбца} CurrentX := Second.LeftX; {"настоящий" Х - Второй Х} inc (i) {увеличиваем элемент массива на 1} end else if i2 = Second.RightY then begin {иначе, если это конец правого столбца} inc (i); {увеличиваем элемент массива на 1} DoDisplay (i); {выводим таблицу, начиная с элемента массива} i2 := first.LeftY; {даем новые координаты i2 (Левый верхний игрек)} CurrentX := first.LeftX {настоящий Х - первый.ЛевыйХ} end else begin {иначе} inc (i); {увеличиваем элемент массива на 1} inc (i2); {и положение курсора} end; Draw_Cursor (CurrentX, i2, i, Cursor_color); end end else if ch = #72 then begin if i <> 1 then begin Restore_Native (CurrentX, i2, i); {восстанавливаем стандарт} if (i2 = Second.LeftY) and (CurrentX = Second.LeftX) then begin i2 := First.RightY; CurrentX := First.LeftX; dec (i); end else if i2 = First.LeftY then begin Dodisplay (i - 36); dec (i); i2 := Second.RightY; CurrentX := Second.LeftX; end else begin dec (i); dec (i2) end; Draw_Cursor (CurrentX, i2, i, Cursor_Color); end end else if ch = #77 then begin if i + 18 <= numfiles then begin Restore_Native (CurrentX, i2, i); if CurrentX = First.LeftX then begin inc (i, 18); CurrentX := Second.LeftX; end else if CurrentX = Second.LeftX then begin Dodisplay (i + (Second.RightY - i2 + 1)); inc (i, 18); CurrentX := First.LeftX end; Draw_Cursor (CurrentX, i2, i, Cursor_Color); end end else if ch = #75 then begin if i - 18 >= 1 then begin Restore_Native (CurrentX, i2, i); if CurrentX = Second.LeftX then begin dec (i, 18); CurrentX := First.LeftX end else if CurrentX = First.LeftX then begin Dodisplay (i - 36 - (i2 - First.LeftX)); dec (i, 18); CurrentX := Second.LeftX end; Draw_Cursor (CurrentX, i2, i, Cursor_Color); end end; until ch = #27; end; end.
unit Server.Resources; interface uses System.Generics.Collections , WiRL.Core.Attributes , WiRL.Core.MessageBody.Default , WiRL.Core.Registry , WiRL.Core.Validators , WiRL.http.Accept.MediaType , WiRL.http.Request , WiRL.http.Response , WiRL.Schemas.Swagger , Common.Entities.Player , Common.Entities.Card , Common.Entities.Round , Common.Entities.Bet , Common.Entities.GameSituation , Server.Entities.Game , Server.WIRL.Response ; type [Path('/v1')] TApiV1Resource = class private [Context] Request: TWiRLRequest; [Context] Response: TWiRLResponse; public [GET] [Produces(TMediaType.TEXT_PLAIN + TMediaType.WITH_CHARSET_UTF8)] function Info: string; [GET, Path('/gameinfo')] [Produces(TMediaType.APPLICATION_JSON)] function GetGameSituation: TGameSituation<TPlayer>; [GET, Path('/players')] [Produces(TMediaType.APPLICATION_JSON)] function GetPlayers: TPlayers<TPlayer>; [POST, Path('/players'),Produces(TMediaType.APPLICATION_JSON)] function RegisterPlayer([BodyParam]APlayer:TPlayers<TPlayer>):TBaseRESTResponse; [DELETE, Path('/players/{AName}'),Produces(TMediaType.APPLICATION_JSON)] function DeletePlayer([PathParam]APlayerName:String):TBaseRESTResponse; [GET, Path('/cards')] [Produces(TMediaType.APPLICATION_JSON)] function GetAllCards: TCards; [POST, Path('/games')] [Produces(TMediaType.APPLICATION_JSON)] function NewGame: TExtendedRESTResponse; (* [GET, Path('/games/{AGameID}')] [Produces(TMediaType.APPLICATION_JSON)] function GetGame([PathParam]AGameID:String): TGame; *) [GET, Path('/games/{AGameID}/cards/{AName}')] [Produces(TMediaType.APPLICATION_JSON)] function GetPlayerCards([PathParam] AGameID:String;[PathParam] AName:String): TCards; [GET, Path('/bets')] [Produces(TMediaType.APPLICATION_JSON)] function GetBets: TBets; [Path('/bets')] [POST, Consumes(TMediaType.APPLICATION_JSON), Produces(TMediaType.APPLICATION_JSON)] function NewBet([BodyParam]ABet: TBet): TBaseRESTResponse; [Path('/king/{ACard}')] [PUT, Produces(TMediaType.APPLICATION_JSON)] function SetKing([PathParam] ACard:Integer):TBaseRESTResponse; [Path('/changecards')] [PUT, Consumes(TMediaType.APPLICATION_JSON), Produces(TMediaType.APPLICATION_JSON)] function ChangeCards([BodyParam]ACards: TCards):TBaseRESTResponse; [GET, Path('/round')] [Produces(TMediaType.APPLICATION_JSON)] function GetRound: TGameRound; [POST, Path('/round')] [Produces(TMediaType.APPLICATION_JSON)] function NewRound: TBaseRESTResponse; [POST, Path('/giveup')] [Produces(TMediaType.APPLICATION_JSON)] function GiveUp: TBaseRESTResponse; [POST, Path('/gameinfo/{AMessage}')] procedure NewGameInfo([PathParam]AMessage:String); [PUT, Path('/round/{AName}/{ACard}')] [Produces(TMediaType.APPLICATION_JSON)] function Turn([PathParam] AName:String; [PathParam] ACard:Integer): TBaseRESTResponse; end; implementation uses System.SysUtils , System.JSON , REST.JSon , WiRL.http.Core , WiRL.http.Accept.Language , Server.Controller , Server.Register ; { THelloWorldResource } {======================================================================================================================} function TApiV1Resource.Info: string; {======================================================================================================================} var lang: TAcceptLanguage; begin lang := TAcceptLanguage.Create('it'); try if Request.AcceptableLanguages.Contains(lang) then Result := 'WiRL Server Template - API v.1 (fai una get di /swagger per la documentazione OpenAPI)' else Result := 'WiRL Server Template - API v.1 (get /swagger for the OpenAPI documentation)'; finally lang.Free; end; end; function TApiV1Resource.NewBet(ABet: TBet): TBaseRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.NewBet(ABet); end; function TApiV1Resource.NewGame:TExtendedRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.NewGame; end; procedure TApiV1Resource.NewGameInfo(AMessage: String); begin GetContainer.Resolve<IApiV1Controller>.NewGameInfo(AMessage); end; function TApiV1Resource.NewRound: TBaseRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.NewRound; end; function TApiV1Resource.RegisterPlayer([BodyParam]APlayer:TPlayers<TPlayer>): TBaseRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.RegisterPlayer(APlayer); end; function TApiV1Resource.SetKing(ACard: Integer): TBaseRESTResponse; begin if (ACard<Ord(Low(TCardKey))) or (ACard>Ord(High(TCardKey))) then raise Exception.Create('Wrong CardValue'); Result := GetContainer.Resolve<IApiV1Controller>.SetKing(TCardKey(ACard)); end; function TApiV1Resource.Turn(AName:String; ACard:Integer): TBaseRESTResponse; begin if (ACard<Ord(Low(TCardKey))) or (ACard>Ord(High(TCardKey))) then raise Exception.Create('Wrong CardValue'); Result := GetContainer.Resolve<IApiV1Controller>.Turn(AName, TCardKey(ACard)); end; function TApiV1Resource.ChangeCards(ACards: TCards): TBaseRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.ChangeCards(ACards); end; function TApiV1Resource.DeletePlayer([PathParam]APlayerName:String): TBaseRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.DeletePlayer(APlayerName); end; function TApiV1Resource.GetAllCards: TCards; begin Result := GetContainer.Resolve<IApiV1Controller>.GetAllCards; if Assigned(Result) then Result:=Result.Clone; end; function TApiV1Resource.GetBets: TBets; begin Result := GetContainer.Resolve<IApiV1Controller>.GetBets; if Assigned(Result) then Result:=Result.Clone; end; function TApiV1Resource.GetGameSituation: TGameSituation<TPlayer>; begin Result:=GetContainer.Resolve<IApiV1Controller>.GetGameSituation; end; function TApiV1Resource.GetPlayerCards(AGameID: String; AName: String): TCards; begin Result:=GetContainer.Resolve<IApiV1Controller>.GetPlayerCards(AGameID,AName); if Assigned(Result) then Result:=Result.Clone; end; function TApiV1Resource.GetPlayers: TPlayers<TPlayer>; begin Result := GetContainer.Resolve<IApiV1Controller>.GetPlayers; if Assigned(Result) then Result:=Result.Clone<TPlayer>; end; function TApiV1Resource.GetRound: TGameRound; begin Result := GetContainer.Resolve<IApiV1Controller>.GetRound; if Assigned(Result) then Result:=Result.Clone; end; function TApiV1Resource.GiveUp: TBaseRESTResponse; begin Result := GetContainer.Resolve<IApiV1Controller>.GiveUp; end; initialization TWiRLResourceRegistry.Instance.RegisterResource<TApiV1Resource>; end.
unit Chapter04._05_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils; // 454. 4Sum II // https://leetcode.com/problems/4sum-ii/description/ // 时间复杂度: O(n^2) // 空间复杂度: O(n^2) type TSolution = class(TObject) public function FourSumCount(a, b, c, d: TArr_int): integer; end; procedure Main; implementation procedure Main; var ret: integer; a, b, c, d: TArr_int; begin a := [1, 2]; b := [-2, -1]; c := [-1, 2]; d := [0, 2]; with TSolution.Create do begin ret := FourSumCount(a, b, c, d); Free; end; WriteLn(ret); end; { TSolution } function TSolution.FourSumCount(a, b, c, d: TArr_int): integer; var map: TMap_int_int; i, j, sum, ret: integer; begin map := TMap_int_int.Create; for i := 0 to High(c) do begin for j := 0 to High(d) do begin sum := c[i] + d[j]; if map.ContainsKey(sum) then map[sum] := map[sum] + 1 else map.Add(sum, 1); end; end; ret := 0; for i := 0 to High(a) do begin for j := 0 to High(b) do begin if map.ContainsKey(0 - a[i] - b[j]) then ret += map.GetItem(0 - a[i] - b[j]); end; end; Result := ret; end; end.
unit uSubStoreQty; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentSub, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, ADODB, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, siComp, siLangRT, Provider, DBClient; type TSubStoreQty = class(TParentSub) grdQty: TcxGrid; grdQtyDB: TcxGridDBTableView; grdQtyDBName: TcxGridDBColumn; grdQtyDBQtyOnPreSale: TcxGridDBColumn; grdQtyDBQtyOnHand: TcxGridDBColumn; grdQtyDBQtyOnOrder: TcxGridDBColumn; grdQtyDBQtyOnRepair: TcxGridDBColumn; grdQtyDBQtyOnPrePurchase: TcxGridDBColumn; grdQtyLevel: TcxGridLevel; spQty: TADOStoredProc; spQtyName: TStringField; spQtyStoreID: TIntegerField; spQtyCurrentCost: TFloatField; dsQty: TDataSource; grdQtyDBQtyFloating: TcxGridDBColumn; spQtyFloatPercent: TIntegerField; spQtyHasInStore: TStringField; grdQtyDBHasInStore: TcxGridDBColumn; spQtyQtyOnPreSale: TFloatField; spQtyQtyOnHand: TFloatField; spQtyQtyOnOrder: TFloatField; spQtyQtyOnRepair: TFloatField; spQtyQtyOnPrePurchase: TFloatField; spQtyQtyOnOrderPositive: TFloatField; spQtyQtyFloating: TFloatField; spQtyMinQty: TFloatField; spQtyMaxQty: TFloatField; grdQtyDBMinQty: TcxGridDBColumn; grdQtyDBMaxQty: TcxGridDBColumn; grdQtyDBIDStore: TcxGridDBColumn; procedure dsQtyDataChange(Sender: TObject; Field: TField); procedure spQtyAfterOpen(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure spQtyCalcFields(DataSet: TDataSet); private { Private declarations } fIDModel : Integer; fQtyOnHold : Double; fQtyOnHand : Double; fQtyOnRepair : Double; fQtyOnOrder : Double; fQtyInRec : Double; fShowMinMax : Boolean; procedure RefreshQty; protected sYes, sNo : String; procedure AfterSetParam; override; public { Public declarations } procedure DataSetRefresh; procedure DataSetOpen; override; procedure DataSetClose; override; procedure DisplayQty; function GetCurrentKey: integer; override; property QtyOnHold : Double read fQtyOnHold; property QtyOnHand : Double read fQtyOnHand; property QtyOnRepair : Double read fQtyOnRepair; property QtyOnOrder : Double read fQtyOnOrder; property QtyInRec : Double read fQtyInRec; end; implementation uses uDM, uParamFunctions, cxStyleSheetEditor, cxLookAndFeels, uPassword, uSystemConst, uDMGlobal, cxGridDBDataDefinitions; {$R *.dfm} procedure TSubStoreQty.AfterSetParam; begin fIDModel := StrToIntDef(ParseParam(FParam, 'IDModel'),0); fShowMinMax := (ParseParam(FParam, 'ShowMinMax')='Y'); DataSetRefresh; DisplayQty; end; procedure TSubStoreQty.RefreshQty; begin fQtyOnHold := spQtyQtyOnPreSale.AsFloat; fQtyOnHand := spQtyQtyOnHand.AsFloat; fQtyOnRepair := spQtyQtyOnRepair.AsFloat; fQtyOnOrder := spQtyQtyOnOrder.AsFloat; fQtyInRec := spQtyQtyOnPrePurchase.AsFloat; end; procedure TSubStoreQty.DataSetRefresh; begin DataSetClose; DataSetOpen; end; procedure TSubStoreQty.DataSetOpen; begin with spQty do if not Active then begin Parameters.ParambyName('@ModelID').Value := fIDModel; Open; end; end; procedure TSubStoreQty.DataSetClose; begin with spQty do if Active then Close; end; procedure TSubStoreQty.dsQtyDataChange(Sender: TObject; Field: TField); begin inherited; RefreshQty; end; procedure TSubStoreQty.spQtyAfterOpen(DataSet: TDataSet); begin inherited; RefreshQty; end; procedure TSubStoreQty.FormCreate(Sender: TObject); begin inherited; Case DM.fGrid.Kind of 0 : grdQty.LookAndFeel.Kind := lfStandard; 1 : grdQty.LookAndFeel.Kind := lfFlat; 2 : grdQty.LookAndFeel.Kind := lfUltraFlat; end; if (DM.fPredefinedStyle.Count > DM.fGrid.Layout) and (DM.fGrid.Layout<>-1) then TcxGridDBTableView(grdQty.ActiveView).Styles.StyleSheet := TcxGridTableViewStyleSheet(DM.fPredefinedStyle.Objects[DM.fGrid.Layout]); Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sYes := 'Yes'; sNo := 'No'; end; LANG_PORTUGUESE : begin sYes := 'Sim'; sNo := 'Não'; end; LANG_SPANISH : begin sYes := 'Sí'; sNo := 'No'; end; end; end; procedure TSubStoreQty.FormDestroy(Sender: TObject); begin DataSetClose; inherited; end; procedure TSubStoreQty.spQtyCalcFields(DataSet: TDataSet); begin inherited; if spQtyQtyOnOrder.AsFloat < 0 then spQtyQtyOnOrderPositive.AsFloat := 0 else spQtyQtyOnOrderPositive.AsFloat := spQtyQtyOnOrder.AsFloat; if spQtyQtyOnHand.AsFloat > 0 then spQtyHasInStore.AsString := sYes else spQtyHasInStore.AsString := sNo; //Calcular a quantidade Flutuante do Modelo if (not grdQtyDBQtyFloating.Visible) or (spQtyFloatPercent.AsFloat = 0) then begin spQtyQtyFloating.AsFloat := (spQtyQtyOnHand.AsFloat - spQtyQtyOnPreSale.AsFloat); Exit; end; if DM.fSystem.SrvParam[PARAM_USE_FRACTIONARY_QTY] then spQtyQtyFloating.AsFloat := (spQtyQtyOnHand.AsFloat - spQtyQtyOnPreSale.AsFloat) + ((spQtyQtyOnPreSale.AsFloat * spQtyFloatPercent.AsFloat)) / 100 else spQtyQtyFloating.AsFloat := Trunc((spQtyQtyOnHand.AsFloat - spQtyQtyOnPreSale.AsFloat) + ((spQtyQtyOnPreSale.AsFloat * spQtyFloatPercent.AsFloat)) / 100); end; procedure TSubStoreQty.DisplayQty; begin grdQtyDBQtyOnHand.Visible := Password.HasFuncRight(45); grdQtyDBQtyFloating.Visible := Password.HasFuncRight(46); grdQtyDBQtyOnPreSale.Visible := Password.HasFuncRight(47); grdQtyDBHasInStore.Visible := Password.HasFuncRight(56); grdQtyDBMinQty.Visible := fShowMinMax; grdQtyDBMaxQty.Visible := fShowMinMax; end; function TSubStoreQty.GetCurrentKey: integer; begin Result := spQty.FieldByName('StoreID').AsInteger; end; initialization RegisterClass(TSubStoreQty); end.
unit UBalanceSetupProp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, cxRadioGroup, cxTextEdit, cxControls, cxContainer, cxEdit, cxLabel, cxLookAndFeelPainters, cxButtons, ActnList, cxCheckBox, cxMaskEdit, DB, FIBDataSet, pFIBDataSet, cxDBEdit, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid, FIBQuery, pFIBQuery; type TfrmBalanceSetupProp = class(TForm) LBalanceSetupName: TcxLabel; LLineCode: TcxLabel; TextEdit_BalanceSetupName: TcxTextEdit; LFormula: TcxLabel; Panel1: TPanel; Panel2: TPanel; Button_OK: TcxButton; Button_Cancel: TcxButton; CheckBox_root: TcxCheckBox; Button_plusSch: TcxButton; Button_minusSch: TcxButton; DataSource: TDataSource; pFIBDataSet: TpFIBDataSet; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; cxGrid1DBTableView1DBColumn1: TcxGridDBColumn; cxGrid1DBTableView1DBColumn2: TcxGridDBColumn; pFIBDataSet_Sch: TpFIBDataSet; DataSource_Sch: TDataSource; cxStyleRepository2: TcxStyleRepository; cxStyle2: TcxStyle; Button_DelSch: TcxButton; cxGrid1DBTableView1DBColumn3: TcxGridDBColumn; cxGrid1DBTableView1DBColumn4: TcxGridDBColumn; cxStyle1: TcxStyle; TextEdit_Formula: TcxMaskEdit; pFIBQuery: TpFIBQuery; MaskEdit_LineCode: TcxMaskEdit; ActionList1: TActionList; act_OK: TAction; act_Cancel: TAction; act_delSch: TAction; act_PlusSch: TAction; act_MinusSch: TAction; LOrderCode: TcxLabel; MaskEdit_OrderCode: TcxMaskEdit; RadioGroup_FormulaType: TcxRadioGroup; CheckBox_no_summ: TcxCheckBox; procedure act_OKExecute(Sender: TObject); procedure act_plusSchExecute(Sender: TObject); procedure act_delSchExecute(Sender: TObject); procedure act_minusSchExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure act_CancelExecute(Sender: TObject); procedure CheckBox_rootPropertiesChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure RadioGroup_FormulaTypePropertiesChange(Sender: TObject); private { Private declarations } public ID_BALANCE_SETUP, ID_BALANCE: int64; n1,n2:string; FormulaBySch, FormulaByCode: string; constructor Create(AOwner: TComponent; ID_BALANCE_SETUP, ID_BALANCE: int64);overload; end; implementation uses Math, UBalance, UDbKrSch, GlobalSPR, getBalance, Resources_unitb; {$R *.dfm} constructor TfrmBalanceSetupProp.Create(AOwner: TComponent; ID_BALANCE_SETUP, ID_BALANCE: int64); begin Inherited Create(AOwner); self.ID_BALANCE_SETUP:=ID_BALANCE_SETUP; self.ID_BALANCE:=ID_BALANCE; FormulaBySch :=''; FormulaByCode:=''; Button_OK.Caption := getBalance.btn_Ok; Button_Cancel.Caption := getBalance.btn_Cancel; LBalanceSetupName.Caption := getBalance.column_Name; LLineCode.Caption := getBalance.column_Code; LOrderCode.Caption := getBalance.column_Order; CheckBox_root.Properties.Caption := getBalance.checkbox_root; CheckBox_no_summ.Properties.Caption := getBalance.checkbox_nosumm; RadioGroup_FormulaType.ItemIndex := -1; RadioGroup_FormulaType.Properties.Items[0].Caption :=getBalance.rdbtn_frmlbysch; RadioGroup_FormulaType.Properties.Items[1].Caption :=getBalance.rdbtn_frmlbycode; RadioGroup_FormulaType.Properties.Items[2].Caption :=getBalance.rdbtn_frmlbysum; end; procedure TfrmBalanceSetupProp.FormShow(Sender: TObject); var flag_sum: variant; begin pFIBDataSet.Close; pFIBDataSet.SelectSQL.Text:='select NO_SUMM from PUB_SP_BALANCE_SETUP WHERE ID_BALANCE_SETUP=:ID_BALANCE_SETUP'; pFIBDataSet.ParamByName('ID_BALANCE_SETUP').AsInt64:=ID_BALANCE_SETUP; pFIBDataSet.Open; flag_sum:=pFIBDataSet.FBN('NO_SUMM').Value; if (flag_sum=null) or (flag_sum=0) then CheckBox_no_summ.Checked:=false else CheckBox_no_summ.Checked:=true; pFIBDataSet.Close; pFIBDataSet.SelectSQL.Text:='select FORMULA from PUB_SP_BALANCE_SETUP_CHNG_FRML(:ID_BALANCE_SETUP,NULL,NULL,NULL)'; pFIBDataSet.ParamByName('ID_BALANCE_SETUP').AsInt64:=ID_BALANCE_SETUP; pFIBDataSet.Open; TextEdit_Formula.Text:=pFIBDataSet.FBN('FORMULA').AsString; pFIBDataSet_Sch.Close; pFIBDataSet_Sch.SelectSQL.Text:= 'select bsf.ID_FORMULA, (case when bsf.sch_sign=-1 then ''-'' when bsf.sch_sign=1 then ''+'' end) as sch_sign,'+ ' ms.sch_number||'' (''||bsf.DB_OR_KR||'')'' as sch_number, ms.sch_title, bsf.DB_OR_KR '+ ' from PUB_SP_BALANCE_SETUP_FORMULA bsf join PUB_SP_MAIN_SCH ms on bsf.id_sch=ms.id_sch '+ ' where ''now'' between ms.date_beg and ms.date_end '+ ' and bsf.ID_BALANCE_SETUP='+inttostr(ID_BALANCE_SETUP); pFIBDataSet_Sch.Open; end; procedure TfrmBalanceSetupProp.act_OKExecute(Sender: TObject); var f1: boolean; i: Integer; begin f1:=false; n1:=''; n2:=''; if Length(TextEdit_BalanceSetupName.Text)=0 then begin showmessage('Заповніть дані. Введіть назву.'); TextEdit_BalanceSetupName.SetFocus; exit; end; if RadioGroup_FormulaType.ItemIndex = 1 then begin pFIBQuery.Close; pFIBQuery.Transaction.StartTransaction; pFIBQuery.SQL.Text:='delete from PUB_SP_BALANCE_SETUP_FORMULA bsf where bsf.ID_BALANCE_SETUP='+inttostr(ID_BALANCE_SETUP); pFIBQuery.Prepare; pFIBQuery.ExecQuery; pFIBQuery.Transaction.Commit; if (TextEdit_Formula.Text<>'') then begin for i:=1 to Length(TextEdit_Formula.Text) do begin if (TextEdit_Formula.Text[i]='+') or (TextEdit_Formula.Text[i]='-') then f1:=true else if f1 then n2:=n2+TextEdit_Formula.Text[i] else n1:=n1+TextEdit_Formula.Text[i]; end; if (Length(n1)=0) or (Length(n2)=0) or (n1=MaskEdit_LineCode.Text) or (n2=MaskEdit_LineCode.Text) or (n1=n2) then begin showmessage('Введіть коректні дані.'); TextEdit_Formula.SetFocus; exit; end; pFIBDataSet.Close; pFIBDataSet.SelectSQL.Text:='select * from PUB_SP_BALANCE_SETUP bs where bs.LINE_CODE='+n1+' and bs.ID_BALANCE='+inttostr(ID_BALANCE); pFIBDataSet.Open; if pFIBDataSet.RecordCount=0 then begin showmessage('Не існує балансової строки з кодом '+n1); TextEdit_Formula.SetFocus; exit; end; if pFIBDataSet.FBN('FORMULA_TYPE').AsString='1' then begin showmessage('Не можна ссилатися на балансову строку '+n1+#13+'Вона має тип "сума балансових рахунків".'); TextEdit_Formula.SetFocus; exit; end; if pFIBDataSet.RecordCount>1 then begin showmessage('Існує кілька записів з кодом '+n1); exit; end; n1:=pFIBDataSet.FBN('ID_BALANCE_SETUP').AsString; pFIBDataSet.Close; pFIBDataSet.SelectSQL.Text:='select * from PUB_SP_BALANCE_SETUP bs where bs.LINE_CODE='+n2+' and bs.ID_BALANCE='+inttostr(ID_BALANCE); pFIBDataSet.Open; if pFIBDataSet.RecordCount=0 then begin showmessage('Не існує балансової строки з кодом '+n2); TextEdit_Formula.SetFocus; exit; end; if pFIBDataSet.FBN('FORMULA_TYPE').AsString='1' then begin showmessage('Не можна ссилатися на балансову строку '+n2); TextEdit_Formula.SetFocus; exit; end; if pFIBDataSet.RecordCount>1 then begin showmessage('Існує кілька записів з кодом '+n2); exit; end; n2:=pFIBDataSet.FBN('ID_BALANCE_SETUP').AsString; end; end; if MaskEdit_LineCode.Text<>'' then begin pFIBDataSet.Close; pFIBDataSet.SelectSQL.Text:='select * from PUB_SP_BALANCE_SETUP bs where bs.LINE_CODE='+MaskEdit_LineCode.Text+' and bs.ID_BALANCE='+inttostr(ID_BALANCE)+' and bs.ID_BALANCE_SETUP<>'+inttostr(ID_BALANCE_SETUP); pFIBDataSet.Open; if pFIBDataSet.RecordCount>0 then begin ShowMessage('Код '+MaskEdit_LineCode.Text+' вже існує. Введіть інший.'); MaskEdit_LineCode.SetFocus; exit; end; end; ModalResult:=mrOk; end; procedure TfrmBalanceSetupProp.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult<>mrOk then begin pFIBQuery.Close; pFIBQuery.Transaction.StartTransaction; pFIBQuery.SQL.Text:='select bs.FORMULA_TYPE from PUB_SP_BALANCE_SETUP bs where bs.ID_BALANCE_SETUP=:ID_BALANCE_SETUP'; pFIBQuery.ParamByName('ID_BALANCE_SETUP').AsInt64:=ID_BALANCE_SETUP; pFIBQuery.ExecQuery; if pFIBQuery.FieldByName('FORMULA_TYPE').AsString='1' then begin try pFIBQuery.Transaction.Commit; pFIBQuery.Close; pFIBQuery.Transaction.StartTransaction; pFIBQuery.SQL.Text:='DELETE FROM PUB_SP_BALANCE_SETUP_FORMULA bsf WHERE bsf.id_balance_setup=:id_balance_setup'; pFIBQuery.ParamByName('ID_BALANCE_SETUP').AsInt64:=ID_BALANCE_SETUP; pFIBQuery.ExecQuery; pFIBQuery.Transaction.Commit; Except on E:Exception do begin pFIBQuery.Transaction.Rollback; ShowMessage(E.Message); end; end; end else pFIBQuery.Transaction.Commit; ModalResult:=mrCancel; end; end; procedure TfrmBalanceSetupProp.act_delSchExecute(Sender: TObject); begin if pFIBDataSet_Sch.IsEmpty then exit; if MessageBox(self.Handle,'?','Warning',MB_YESNO or MB_ICONWARNING)=mryes then begin try pFIBQuery.Close; pFIBQuery.Transaction.StartTransaction; pFIBQuery.ExecProcedure('PUB_SP_BALANCE_SETUP_FRML_DEL',[pFIBDataSet_Sch.FBN('ID_FORMULA').AsInteger]); pFIBQuery.Transaction.Commit; except on E:Exception do begin pFIBQuery.Transaction.Rollback; ShowMessage(E.Message); end; end; end; pFIBDataSet_Sch.CloseOpen(true); end; procedure TfrmBalanceSetupProp.act_plusSchExecute(Sender: TObject); var RES: Variant; i: Integer; d: int64; T: TfrmDbKr; begin if not pFIBDataSet_Sch.IsEmpty then d:=pFIBDataSet_Sch.FBN('ID_FORMULA').AsInteger; RES:=GlobalSpr.GetSch( self, TfrmBalance(self.Owner).DB.Handle, fsNormal, DATE, DEFAULT_ROOT_ID,0,0); T:=TfrmDbKr.Create(self); if TfrmBalance(self.Owner).PageControl.ActivePageIndex=0 then T.RadioButton_Db.Checked:=true else T.RadioButton_Kr.Checked:=true; if (VarArrayDimCount(RES)>0) and (T.ShowModal=mrOk) then begin for i:=0 to VarArrayHighBound(RES,1) do begin try pFIBQuery.Close; pFIBQuery.Transaction.StartTransaction; pFIBQuery.SQL.Text:='execute procedure PUB_SP_BALANCE_SETUP_CHNG_FRML(:ID_BALANCE_SETUP,:ID_SCH,:SCH_SIGN,:DB_KR)'; pFIBQuery.ParamByName('ID_BALANCE_SETUP').AsInt64:=ID_BALANCE_SETUP; pFIBQuery.ParamByName('ID_SCH').AsInt64:=RES[i][0]; pFIBQuery.ParamByName('SCH_SIGN').AsInteger:=1; if T.RadioButton_Db.Checked then pFIBQuery.ParamByName('DB_KR').AsString:='дб'; if T.RadioButton_Kr.Checked then pFIBQuery.ParamByName('DB_KR').AsString:='кр'; pFIBQuery.Prepare; pFIBQuery.ExecProc; d:=pFIBQuery.FldByName['OUT_FORMULA'].AsInteger; TextEdit_Formula.Text:=pFIBQuery.FldByName['FORMULA'].AsString; pFIBQuery.Transaction.Commit; except on E:Exception do begin pFIBQuery.Transaction.Rollback; ShowMessage(E.Message); end; end; end; pFIBDataSet_Sch.CloseOpen(true); if not pFIBDataSet_Sch.IsEmpty then pFIBDataSet_Sch.Locate('ID_FORMULA',d,[]); end; end; procedure TfrmBalanceSetupProp.act_minusSchExecute(Sender: TObject); var RES: Variant; i: Integer; d: int64; T: TfrmDbKr; begin if not pFIBDataSet_Sch.IsEmpty then d:=pFIBDataSet_Sch.FBN('ID_FORMULA').AsInteger; RES:=GlobalSpr.GetSch( self, TfrmBalance(self.Owner).DB.Handle, fsNormal, DATE, DEFAULT_ROOT_ID,0,0); T:=TfrmDbKr.Create(self); if TfrmBalance(self.Owner).PageControl.ActivePageIndex=0 then T.RadioButton_Db.Checked:=true else T.RadioButton_Kr.Checked:=true; if (VarArrayDimCount(RES)>0) and (T.ShowModal=mrOk) then begin for i:=0 to VarArrayHighBound(RES,1) do begin try pFIBQuery.Close; pFIBQuery.Transaction.StartTransaction; pFIBQuery.SQL.Text:='execute procedure PUB_SP_BALANCE_SETUP_CHNG_FRML(:ID_BALANCE_SETUP,:ID_SCH,:SCH_SIGN,:DB_KR)'; pFIBQuery.ParamByName('ID_BALANCE_SETUP').AsInt64:=ID_BALANCE_SETUP; pFIBQuery.ParamByName('ID_SCH').AsInt64:=RES[i][0]; pFIBQuery.ParamByName('SCH_SIGN').AsInteger:=-1; if T.RadioButton_Db.Checked then pFIBQuery.ParamByName('DB_KR').AsString:='дб'; if T.RadioButton_Kr.Checked then pFIBQuery.ParamByName('DB_KR').AsString:='кр'; pFIBQuery.Prepare; pFIBQuery.ExecProc; d:=pFIBQuery.FldByName['OUT_FORMULA'].AsInteger; TextEdit_Formula.Text:=pFIBQuery.FldByName['FORMULA'].AsString; pFIBQuery.Transaction.Commit; except on E:Exception do begin pFIBQuery.Transaction.Rollback; ShowMessage(E.Message); end; end; end; pFIBDataSet_Sch.CloseOpen(True); if not pFIBDataSet_Sch.IsEmpty then pFIBDataSet_Sch.Locate('ID_FORMULA',d,[]); end; end; procedure TfrmBalanceSetupProp.act_CancelExecute(Sender: TObject); begin close; end; procedure TfrmBalanceSetupProp.CheckBox_rootPropertiesChange(Sender: TObject); begin RadioGroup_FormulaType.Enabled :=not CheckBox_root.Checked; end; procedure TfrmBalanceSetupProp.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ((key=ord('+')) and (ssCtrl in Shift)) then showmessage('+'); if ((key=ord('-')) and (ssCtrl in Shift)) then showmessage('-'); end; procedure TfrmBalanceSetupProp.RadioGroup_FormulaTypePropertiesChange( Sender: TObject); begin if RadioGroup_FormulaType.ItemIndex = 1 then begin Button_plusSch.Enabled:=false; Button_minusSch.Enabled:=false; Button_DelSch.Enabled:=false; TextEdit_Formula.Style.Color:=cxStyle2.Color; TextEdit_Formula.Properties.ReadOnly:=false; TextEdit_Formula.TabStop:=true; FormulaBySch:=TextEdit_Formula.Text; TextEdit_Formula.Properties.EditMask:='\d\d?\d?\d?-\d\d?\d?\d?'; TextEdit_Formula.Text:=FormulaByCode; cxGrid1.Enabled:=false; cxGrid1DBTableView1.Styles.Content:=cxStyle1; cxGrid1DBTableView1.Styles.Background:=cxStyle1; end; if RadioGroup_FormulaType.ItemIndex = 0 then begin Button_plusSch.Enabled:=true; Button_minusSch.Enabled:=true; Button_DelSch.Enabled:=true; TextEdit_Formula.Style.Color:=cxStyle1.Color; TextEdit_Formula.Properties.ReadOnly:=true; TextEdit_Formula.TabStop:=false; FormulaByCode:=TextEdit_Formula.Text; TextEdit_Formula.Properties.EditMask:=''; TextEdit_Formula.Text:=FormulaBySch; cxGrid1.Enabled:=true; cxGrid1DBTableView1.Styles.Content:=cxStyle2; cxGrid1DBTableView1.Styles.Background:=cxStyle2; end; if RadioGroup_FormulaType.ItemIndex = 2 then begin Button_plusSch.Enabled:=false; Button_minusSch.Enabled:=false; Button_DelSch.Enabled:=false; TextEdit_Formula.Style.Color:=cxStyle2.Color; TextEdit_Formula.Properties.ReadOnly:=true; TextEdit_Formula.TabStop:=true; FormulaBySch:=TextEdit_Formula.Text; TextEdit_Formula.Properties.EditMask:='\d\d?\d?\d?-\d\d?\d?\d?'; TextEdit_Formula.Text:=FormulaByCode; cxGrid1.Enabled:=false; cxGrid1DBTableView1.Styles.Content:=cxStyle1; cxGrid1DBTableView1.Styles.Background:=cxStyle1; end; end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2021 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Client.CustomResource; {$I ..\Core\WiRL.inc} interface uses System.SysUtils, System.Classes, System.Rtti, System.Contnrs, System.Types, System.TypInfo, System.Generics.Collections, Data.DB, WiRL.Core.Context, WiRL.Client.Application, WiRL.Data.Utils, WiRL.http.Core, WiRL.http.Headers, WiRL.http.Client.Interfaces, WiRL.http.Client; type TBeforeRequestEvent = procedure (Sender: TObject; const AHttpMethod: string; ARequestStream: TStream; out AResponse: IWiRLResponse) of object; TAfterRequestEvent = procedure (Sender: TObject; const AHttpMethod: string; ARequestStream: TStream; AResponse: IWiRLResponse) of object; TRequestErrorEvent = procedure (Sender: TObject; const AHttpMethod: string; ARequestStream: TStream; AResponse: IWiRLResponse) of object; {$IF DEFINED(HAS_NEW_ANDROID_PID)} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator32 or pidiOSDevice32 or pidAndroidArm32)] {$ELSEIF DEFINED(HAS_NEW_PIDS)} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator32 or pidiOSDevice32 or pidAndroid32Arm)] {$ELSE} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] {$ENDIF} TWiRLClientCustomResource = class(TComponent) private FContext: TWiRLContextHttp; FResource: string; FApplication: TWiRLClientApplication; FPathParams: TStrings; FQueryParams: TStrings; FHeaders: IWiRLHeaders; FBeforeRequest: TBeforeRequestEvent; FAfterRequest: TAfterRequestEvent; FOnRequestError: TRequestErrorEvent; FFilters: TStringDynArray; procedure SetPathParams(const Value: TStrings); procedure SetQueryParams(const Value: TStrings); procedure ContextInjection(AInstance: TObject); function MergeHeaders(const AHttpMethod: string): IWiRLHeaders; function StreamToObject<T>(AHeaders: IWiRLHeaders; AStream: TStream): T; overload; procedure StreamToObject(AObject: TObject; AHeaders: IWiRLHeaders; AStream: TStream); overload; procedure ObjectToStream<T>(AHeaders: IWiRLHeaders; AObject: T; AStream: TStream); overload; function SameObject<T>(AGeneric: T; AObject: TObject): Boolean; procedure SetApplication(const Value: TWiRLClientApplication); function ValueToString(const AValue: TValue): string; procedure StreamToEntity<T>(AEntity: T; AHeaders: IWiRLHeaders; AStream: TStream); procedure StreamToArray(AArray: TValue; AHeaders: IWiRLHeaders; AStream: TStream); protected function GetClient: TWiRLClient; virtual; function GetPath: string; virtual; function GetURL: string; virtual; function GetApplication: TWiRLClientApplication; virtual; function GetAccept: string; function GetContentType: string; procedure DoBeforeRequest(const AHttpMethod: string; ARequestStream: TStream; out AResponse: IWiRLResponse); virtual; procedure DoAfterRequest(const AHttpMethod: string; ARequestStream: TStream; AResponse: IWiRLResponse); virtual; procedure DoRequestError(const AHttpMethod: string; ARequestStream: TStream; AResponse: IWiRLResponse); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; // Handles the parent/child relationship for the designer procedure SetParentComponent(AParent: TComponent); override; procedure InitHttpRequest; virtual; function InternalHttpRequest(const AHttpMethod: string; ARequestStream, AResponseStream: TStream): IWiRLResponse; virtual; procedure DefineProperties(Filer: TFiler); override; procedure LoadHeadersProperty(Reader: TReader); procedure StoreHeadersProperty(Writer: TWriter); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetFilters(const AFilters: TStringDynArray); function HasFilter(AAttribute: TCustomAttribute): Boolean; // Handles the parent/child relationship for the designer function GetParentComponent: TComponent; override; function HasParent: Boolean; override; // http verbs function Get<T>: T; overload; procedure Get(AResponseEntity: TObject); overload; procedure Get<T>(AResponseEntity: T); overload; function Post<T, V>(const ARequestEntity: T): V; overload; procedure Post<T>(const ARequestEntity: T; AResponseEntity: TObject); overload; function Put<T, V>(const ARequestEntity: T): V; overload; procedure Put<T>(const ARequestEntity: T; AResponseEntity: TObject); overload; function Delete<T>: T; overload; procedure Delete(AResponseEntity: TObject); overload; function Patch<T, V>(const ARequestEntity: T): V; overload; procedure Patch<T>(const ARequestEntity: T; AResponseEntity: TObject); overload; function GenericHttpRequest<T, V>(const AHttpMethod: string; const ARequestEntity: T): V; overload; procedure GenericHttpRequest<T, V>(const AHttpMethod: string; const ARequestEntity: T; AResponseEntity: V); overload; public procedure QueryParam(const AName: string; const AValue: TValue); procedure PathParam(const AName: string; const AValue: TValue); property Accept: string read GetAccept; property ContentType: string read GetContentType; property Application: TWiRLClientApplication read GetApplication write SetApplication; property Client: TWiRLClient read GetClient; property Resource: string read FResource write FResource; property Path: string read GetPath; property PathParams: TStrings read FPathParams write SetPathParams; property QueryParams: TStrings read FQueryParams write SetQueryParams; property URL: string read GetURL; property Headers: IWiRLHeaders read FHeaders write FHeaders; property AfterRequest: TAfterRequestEvent read FAfterRequest write FAfterRequest; property BeforeRequest: TBeforeRequestEvent read FBeforeRequest write FBeforeRequest; property OnRequestError: TRequestErrorEvent read FOnRequestError write FOnRequestError; end; TWiRLResourceHeaders = class(TWiRLHeaders) private FCustomResource: TWiRLClientCustomResource; protected procedure SetValue(const AName: string; const AValue: string); override; public constructor Create(ACustomResource: TWiRLClientCustomResource); end; implementation uses WiRL.Configuration.Core, WiRL.Configuration.Neon, WiRL.Configuration.Converter, WiRL.http.Accept.MediaType, WiRL.Core.Classes, WiRL.Core.Injection, WiRL.Core.Converter, WiRL.Core.MessageBodyReader, WiRL.Core.MessageBodyWriter, WiRL.Client.Utils, WiRL.http.URL, WiRL.Rtti.Utils, WiRL.Core.Utils; type THttpMethodImplementation = reference to function ( AResource: TWiRLClientCustomResource; ARequestStream, AResponseStream: TStream; ACustomHeaders: IWiRLHeaders): IWiRLResponse; THttpMethodImplementations = array [TWiRLHttpMethod] of THttpMethodImplementation; var HttpMethodImplementations: THttpMethodImplementations; procedure RegisterHttpMethodImplementations; begin HttpMethodImplementations[TWiRLHttpMethod.GET] := function (AResource: TWiRLClientCustomResource; ARequestStream, AResponseStream: TStream; ACustomHeaders: IWiRLHeaders): IWiRLResponse begin Result := AResource.Client.Get(AResource.URL, AResponseStream, ACustomHeaders); end; HttpMethodImplementations[TWiRLHttpMethod.POST] := function (AResource: TWiRLClientCustomResource; ARequestStream, AResponseStream: TStream; ACustomHeaders: IWiRLHeaders): IWiRLResponse begin Result := AResource.Client.Post(AResource.URL, ARequestStream, AResponseStream, ACustomHeaders); end; HttpMethodImplementations[TWiRLHttpMethod.PUT] := function (AResource: TWiRLClientCustomResource; ARequestStream, AResponseStream: TStream; ACustomHeaders: IWiRLHeaders): IWiRLResponse begin Result := AResource.Client.Put(AResource.URL, ARequestStream, AResponseStream, ACustomHeaders); end; HttpMethodImplementations[TWiRLHttpMethod.DELETE] := function (AResource: TWiRLClientCustomResource; ARequestStream, AResponseStream: TStream; ACustomHeaders: IWiRLHeaders): IWiRLResponse begin Result := AResource.Client.Delete(AResource.URL, AResponseStream, ACustomHeaders); end; HttpMethodImplementations[TWiRLHttpMethod.PATCH] := function (AResource: TWiRLClientCustomResource; ARequestStream, AResponseStream: TStream; ACustomHeaders: IWiRLHeaders): IWiRLResponse begin Result := AResource.Client.Patch(AResource.URL, ARequestStream, AResponseStream, ACustomHeaders); end; end; { TWiRLClientCustomResource } procedure TWiRLClientCustomResource.ContextInjection(AInstance: TObject); begin TWiRLContextInjectionRegistry.Instance. ContextInjection(AInstance, FContext); end; constructor TWiRLClientCustomResource.Create(AOwner: TComponent); begin inherited; FResource := 'main'; // if TWiRLComponentHelper.IsDesigning(Self) then // Application := TWiRLComponentHelper.FindDefault<TWiRLClientApplication>(Self); FPathParams := TStringList.Create; FQueryParams := TStringList.Create; FContext := TWiRLContextHttp.Create; FHeaders := TWiRLResourceHeaders.Create(Self); end; function TWiRLClientCustomResource.GetClient: TWiRLClient; begin Result := nil; if Assigned(FApplication) then Result := FApplication.Client; end; function TWiRLClientCustomResource.GetContentType: string; begin Result := Headers.ContentType; if (Result = '') and Assigned(Application) then Result := Application.DefaultMediaType; end; function TWiRLClientCustomResource.GetParentComponent: TComponent; begin Result := Application; end; function TWiRLClientCustomResource.GetPath: string; var LEngine: string; LApplication: string; begin LEngine := ''; if Assigned(Client) then LEngine := Client.WiRLEngineURL; LApplication := ''; if Assigned(Application) then LApplication := Application.AppName; Result := TWiRLURL.CombinePath([LEngine, LApplication, Resource]); end; function TWiRLClientCustomResource.GetURL: string; var LIndex: Integer; begin Result := Path; for LIndex := 0 to FPathParams.Count - 1 do begin Result := StringReplace(Result, '{' + FPathParams.Names[LIndex] + '}', TWiRLURL.URLEncode(FPathParams.ValueFromIndex[LIndex]), [rfReplaceAll, rfIgnoreCase]); end; // Result := TWiRLURL.CombinePath([ // Path, // TWiRLURL.CombinePath(TWiRLURL.URLEncode(FPathParamsValues.ToStringArray)) // ]); if FQueryParams.Count > 0 then Result := Result + '?' + SmartConcat(TWiRLURL.URLEncode(FQueryParams.ToStringArray), '&'); end; function TWiRLClientCustomResource.HasFilter( AAttribute: TCustomAttribute): Boolean; var LFilterName: string; LAttributeName: string; begin Result := False; LAttributeName := AAttribute.ClassName; for LFilterName in FFilters do begin if SameText(LFilterName, LAttributeName) or SameText(LFilterName + 'Attribute', LAttributeName) then Exit(True); end; end; function TWiRLClientCustomResource.HasParent: Boolean; begin Result := Assigned(FApplication); end; procedure TWiRLClientCustomResource.InitHttpRequest; var LPair: TPair<TWiRLConfigurationClass, TWiRLConfiguration>; begin // Fill the context FContext.AddContainerOnce(FApplication, False); for LPair in FApplication.Configs do FContext.AddContainerOnce(LPair.Value, False); end; function TWiRLClientCustomResource.InternalHttpRequest( const AHttpMethod: string; ARequestStream, AResponseStream: TStream): IWiRLResponse; var LHttpMethodImplementation: THttpMethodImplementation; begin LHttpMethodImplementation := HttpMethodImplementations[TWiRLHttpMethod.ConvertFromString(AHttpMethod)]; if not Assigned(LHttpMethodImplementation) then raise EWiRLClientException.CreateFmt('Implementation not found for method [%s]', [AHttpMethod]); try Result := LHttpMethodImplementation(Self, ARequestStream, AResponseStream, MergeHeaders(AHttpMethod)); except on E: EWiRLClientProtocolException do begin raise EWiRLClientResourceException.Create(E.Response); end; end; end; procedure TWiRLClientCustomResource.LoadHeadersProperty(Reader: TReader); var LRowHeader: string; LHeaderPair: TArray<string>; begin Reader.ReadListBegin; while not Reader.EndOfList do begin LRowHeader := Reader.ReadString; LHeaderPair := LRowHeader.Split(['=']); if Length(LHeaderPair) > 1 then begin FHeaders.AddHeader(TWiRLHeader.Create(LHeaderPair[0], LHeaderPair[1])); end; end; Reader.ReadListEnd; end; function TWiRLClientCustomResource.MergeHeaders(const AHttpMethod: string): IWiRLHeaders; function HasRequestBody(const AHttpMethod: string): Boolean; begin if (AHttpMethod = 'POST') or (AHttpMethod = 'PUT') then Result := True else Result := False; end; var LHeader: TWiRLHeader; begin Result := TWiRLHeaders.Create; if Accept <> '' then Result.Accept := Accept; if HasRequestBody(AHttpMethod) and (ContentType <> '') then Result.ContentType := ContentType; for LHeader in FHeaders do begin Result.Values[LHeader.Name] := LHeader.Value; end; end; procedure TWiRLClientCustomResource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = FApplication then FApplication := nil; end; end; procedure TWiRLClientCustomResource.StoreHeadersProperty(Writer: TWriter); var LHeader: TWiRLHeader; begin Writer.WriteListBegin; for LHeader in FHeaders do begin Writer.WriteString(LHeader.Name + '=' + LHeader.Value); end; Writer.WriteListEnd; end; procedure TWiRLClientCustomResource.StreamToObject(AObject: TObject; AHeaders: IWiRLHeaders; AStream: TStream); var LType: TRttiType; LMediaType: TMediaType; LReader: IMessageBodyReader; begin LType := TRttiHelper.Context.GetType(AObject.ClassInfo); LMediaType := TMediaType.Create(AHeaders.Values[TWiRLHeader.CONTENT_TYPE]); try LReader := Application.ReaderRegistry.FindReader(LType, LMediaType); if not Assigned(LReader) then raise EWiRLClientException.CreateFmt('Reader not found for [%s] content type: [%s]', [LType.Name, LMediaType.MediaType]); ContextInjection(LReader as TObject); LReader.ReadFrom(AObject, LType, LMediaType, AHeaders, AStream); finally LMediaType.Free; end; end; procedure TWiRLClientCustomResource.StreamToArray(AArray: TValue; AHeaders: IWiRLHeaders; AStream: TStream); var LList: TDataSetList; LIndex: Integer; LItem: TValue; begin LList := TDataSetList.Create(False); try for LIndex := 0 to AArray.GetArrayLength - 1 do begin LItem := AArray.GetArrayElement(LIndex); if not LItem.IsObject then raise EWiRLClientException.Create('Array of primitive type not supported'); if not (LItem.AsObject is TDataSet) then raise EWiRLClientException.Create('Error Message'); LList.Add(TDataSet(LItem.AsObject)); end; StreamToObject(LList, AHeaders, AStream); finally LList.Free; end; end; procedure TWiRLClientCustomResource.StreamToEntity<T>(AEntity: T; AHeaders: IWiRLHeaders; AStream: TStream); var LValue: TValue; begin LValue := TValue.From<T>(AEntity); if LValue.IsObject then StreamToObject(LValue.AsObject, AHeaders, AStream) else if LValue.IsArray then StreamToArray(LValue, AHeaders, AStream) else raise EWiRLClientException.Create('Not supported'); end; function TWiRLClientCustomResource.StreamToObject<T>(AHeaders: IWiRLHeaders; AStream: TStream): T; var LType: TRttiType; LMediaType: TMediaType; LReader: IMessageBodyReader; LValue: TValue; begin LType := TRttiHelper.Context.GetType(TypeInfo(T)); LMediaType := TMediaType.Create(AHeaders.ContentType); try LReader := Application.ReaderRegistry.FindReader(LType, LMediaType); if not Assigned(LReader) then raise EWiRLClientException.CreateFmt('Reader not found for [%s] content type: [%s]', [LType.Name, LMediaType.MediaType]); ContextInjection(LReader as TObject); LValue := LReader.ReadFrom(LType, LMediaType, AHeaders, AStream); Result := LValue.AsType<T>; finally LMediaType.Free; end; end; procedure TWiRLClientCustomResource.ObjectToStream<T>(AHeaders: IWiRLHeaders; AObject: T; AStream: TStream); var LType: TRttiType; LMediaType: TMediaType; LWriter: IMessageBodyWriter; LValue: TValue; begin LType := TRttiHelper.Context.GetType(TypeInfo(T)); LMediaType := TMediaType.Create(ContentType); try LValue := TValue.From<T>(AObject); LWriter := Application.WriterRegistry.FindWriter(LType, LMediaType); if not Assigned(LWriter) then raise EWiRLClientException.CreateFmt('Writer not found for [%s] content type: [%s]', [LType.Name, LMediaType.MediaType]); ContextInjection(LWriter as TObject); LWriter.WriteTo(LValue, nil, LMediaType, AHeaders, AStream); AStream.Position := soFromBeginning; finally LMediaType.Free; end; end; procedure TWiRLClientCustomResource.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('CustomHeaders', LoadHeadersProperty, StoreHeadersProperty, FHeaders.Count > 0); end; procedure TWiRLClientCustomResource.Delete(AResponseEntity: TObject); begin GenericHttpRequest<string, TObject>('DELETE', '', AResponseEntity); end; function TWiRLClientCustomResource.Delete<T>: T; begin Result := GenericHttpRequest<string, T>('DELETE', ''); end; function TWiRLClientCustomResource.GenericHttpRequest<T, V>( const AHttpMethod: string; const ARequestEntity: T): V; var LRequestStream, LResponseStream: TMemoryStream; LResponse: IWiRLResponse; begin if not Assigned(Client) then Exit; Result := default(V); LResponse := nil; InitHttpRequest; LRequestStream := TMemoryStream.Create; try LResponseStream := TGCMemoryStream.Create; try ObjectToStream<T>(MergeHeaders(AHttpMethod), ARequestEntity, LRequestStream); DoBeforeRequest(AHttpMethod, LRequestStream, LResponse); try if Assigned(LResponse) then begin if LResponse.StatusCode >= 400 then raise EWiRLClientProtocolException.Create(LResponse); end else LResponse := InternalHttpRequest(AHttpMethod, LRequestStream, LResponseStream); except on E: EWiRLClientProtocolException do begin DoRequestError(AHttpMethod, LRequestStream, E.Response); raise; end; end; DoAfterRequest(AHttpMethod, LRequestStream, LResponse); if Assigned(LResponse.ContentStream) then Result := StreamToObject<V>(LResponse.Headers, LResponse.ContentStream) else Result := StreamToObject<V>(LResponse.Headers, LResponseStream); finally if not SameObject<V>(Result, LResponseStream) then LResponseStream.Free; end; finally LRequestStream.Free; end; end; procedure TWiRLClientCustomResource.GenericHttpRequest<T, V>( const AHttpMethod: string; const ARequestEntity: T; AResponseEntity: V); var LRequestStream, LResponseStream: TMemoryStream; LResponse: IWiRLResponse; begin if not Assigned(Client) then Exit; InitHttpRequest; LRequestStream := TMemoryStream.Create; try LResponseStream := TGCMemoryStream.Create; try ObjectToStream<T>(MergeHeaders(AHttpMethod), ARequestEntity, LRequestStream); DoBeforeRequest(AHttpMethod, LRequestStream, LResponse); try if Assigned(LResponse) then begin if LResponse.StatusCode >= 400 then raise EWiRLClientProtocolException.Create(LResponse); end else LResponse := InternalHttpRequest(AHttpMethod, LRequestStream, LResponseStream); except on E: EWiRLClientProtocolException do begin DoRequestError(AHttpMethod, LRequestStream, E.Response); raise; end; end; DoAfterRequest(AHttpMethod, LRequestStream, LResponse); if Assigned(LResponse.ContentStream) then StreamToEntity<V>(AResponseEntity, LResponse.Headers, LResponse.ContentStream) else StreamToEntity<V>(AResponseEntity, LResponse.Headers, LResponseStream); finally LResponseStream.Free; end; finally LRequestStream.Free; end; end; procedure TWiRLClientCustomResource.Get(AResponseEntity: TObject); begin GenericHttpRequest<string, TObject>('GET', '', AResponseEntity); end; procedure TWiRLClientCustomResource.Get<T>(AResponseEntity: T); begin GenericHttpRequest<string, T>('GET', '', AResponseEntity); end; function TWiRLClientCustomResource.Get<T>: T; begin Result := GenericHttpRequest<string, T>('GET', ''); end; function TWiRLClientCustomResource.Patch<T, V>(const ARequestEntity: T): V; begin Result := GenericHttpRequest<T, V>('PATCH', ARequestEntity); end; procedure TWiRLClientCustomResource.Patch<T>(const ARequestEntity: T; AResponseEntity: TObject); begin GenericHttpRequest<T, TObject>('PATCH', ARequestEntity, AResponseEntity); end; function TWiRLClientCustomResource.ValueToString(const AValue: TValue): string; var LConfig: TWiRLFormatSettingConfig; begin LConfig := FApplication.GetConfigByClassRef(TWiRLFormatSettingConfig) as TWiRLFormatSettingConfig; Result := TWiRLConvert.From(AValue, AValue.TypeInfo, LConfig.GetFormatSettingFor(AValue.TypeInfo)); end; procedure TWiRLClientCustomResource.PathParam(const AName: string; const AValue: TValue); begin PathParams.Values[AName] := ValueToString(AValue); end; function TWiRLClientCustomResource.Post<T, V>(const ARequestEntity: T): V; begin Result := GenericHttpRequest<T, V>('POST', ARequestEntity); end; procedure TWiRLClientCustomResource.Post<T>(const ARequestEntity: T; AResponseEntity: TObject); begin GenericHttpRequest<T, TObject>('POST', ARequestEntity, AResponseEntity); end; function TWiRLClientCustomResource.Put<T, V>(const ARequestEntity: T): V; begin Result := GenericHttpRequest<T, V>('PUT', ARequestEntity); end; procedure TWiRLClientCustomResource.Put<T>(const ARequestEntity: T; AResponseEntity: TObject); begin GenericHttpRequest<T, TObject>('PUT', ARequestEntity, AResponseEntity); end; procedure TWiRLClientCustomResource.QueryParam(const AName: string; const AValue: TValue); begin QueryParams.Values[AName] := ValueToString(AValue); end; destructor TWiRLClientCustomResource.Destroy; begin if Assigned(FApplication) then FApplication.Resources.Extract(Self); FPathParams.Free; FQueryParams.Free; FContext.Free; inherited; end; procedure TWiRLClientCustomResource.DoAfterRequest(const AHttpMethod: string; ARequestStream: TStream; AResponse: IWiRLResponse); var LRequestPosition: Integer; LResponsePosition: Integer; begin // Call filters LRequestPosition := 0; LResponsePosition := 0; if Assigned(ARequestStream) then LRequestPosition := ARequestStream.Position; if Assigned(AResponse.ContentStream) then LResponsePosition := AResponse.ContentStream.Position; FApplication.ApplyResponseFilter(Self, AHttpMethod, ARequestStream, AResponse); if Assigned(ARequestStream) then ARequestStream.Position := LRequestPosition; if Assigned(AResponse.ContentStream) then AResponse.ContentStream.Position := LResponsePosition; // Manager event handlers if Assigned(FAfterRequest) then begin FAfterRequest(Self, AHttpMethod, ARequestStream, AResponse); if Assigned(ARequestStream) then ARequestStream.Position := LRequestPosition; if Assigned(AResponse.ContentStream) then AResponse.ContentStream.Position := LResponsePosition; end; end; procedure TWiRLClientCustomResource.DoBeforeRequest(const AHttpMethod: string; ARequestStream: TStream; out AResponse: IWiRLResponse); var LPosition: Integer; begin // Call filters LPosition := 0; if Assigned(ARequestStream) then LPosition := ARequestStream.Position; FApplication.ApplyRequestFilter(Self, AHttpMethod, ARequestStream, AResponse); if Assigned(ARequestStream) then ARequestStream.Position := LPosition; // Manage event handlers if Assigned(FBeforeRequest) then begin FBeforeRequest(Self, AHttpMethod, ARequestStream, AResponse); if Assigned(ARequestStream) then ARequestStream.Position := LPosition; end; end; procedure TWiRLClientCustomResource.DoRequestError(const AHttpMethod: string; ARequestStream: TStream; AResponse: IWiRLResponse); var LRequestPosition: Integer; LResponsePosition: Integer; begin LRequestPosition := 0; LResponsePosition := 0; if Assigned(FAfterRequest) then begin if Assigned(ARequestStream) then LRequestPosition := ARequestStream.Position; if Assigned(AResponse.ContentStream) then LResponsePosition := AResponse.ContentStream.Position; FOnRequestError(Self, AHttpMethod, ARequestStream, AResponse); if Assigned(ARequestStream) then ARequestStream.Position := LRequestPosition; if Assigned(AResponse.ContentStream) then AResponse.ContentStream.Position := LResponsePosition; end; end; function TWiRLClientCustomResource.GetAccept: string; begin Result := FHeaders.Accept; if (Result = '') and Assigned(Application) then Result := Application.DefaultMediaType; end; function TWiRLClientCustomResource.GetApplication: TWiRLClientApplication; begin Result := FApplication; end; function TWiRLClientCustomResource.SameObject<T>(AGeneric: T; AObject: TObject): Boolean; var LValue: TValue; begin Result := False; if not Assigned(AObject) then Exit; LValue := TValue.From<T>(AGeneric); if LValue.IsEmpty then Exit; if LValue.IsObject and (LValue.AsObject = AObject) then Result := True; end; procedure TWiRLClientCustomResource.SetApplication( const Value: TWiRLClientApplication); begin if FApplication <> Value then begin if Assigned(FApplication) then FApplication.Resources.Remove(Self); FApplication := Value; if Assigned(FApplication) and (FApplication.Resources.IndexOf(Self) < 0) then FApplication.Resources.Add(Self); end; end; procedure TWiRLClientCustomResource.SetFilters(const AFilters: TStringDynArray); begin FFilters := AFilters; end; procedure TWiRLClientCustomResource.SetParentComponent(AParent: TComponent); begin inherited; if AParent is TWiRLClientApplication then Application := AParent as TWiRLClientApplication; end; procedure TWiRLClientCustomResource.SetPathParams(const Value: TStrings); begin FPathParams.Assign(Value); end; procedure TWiRLClientCustomResource.SetQueryParams(const Value: TStrings); begin FQueryParams.Assign(Value); end; { TWiRLResourceHeaders } constructor TWiRLResourceHeaders.Create( ACustomResource: TWiRLClientCustomResource); begin inherited Create; FCustomResource := ACustomResource; end; procedure TWiRLResourceHeaders.SetValue(const AName, AValue: string); begin if Assigned(FCustomResource.Application) then begin if SameText(AName, TWiRLHeader.ACCEPT) and SameText(AValue, FCustomResource.Application.DefaultMediaType) then Exit; if SameText(AName, TWiRLHeader.CONTENT_TYPE) and SameText(AValue, FCustomResource.Application.DefaultMediaType) then Exit; end; inherited SetValue(AName, AValue); end; initialization RegisterHttpMethodImplementations; end.
// // Generated by JavaToPas v1.5 20180804 - 082450 //////////////////////////////////////////////////////////////////////////////// unit android.telecom.Connection_RttModifyStatus; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JConnection_RttModifyStatus = interface; JConnection_RttModifyStatusClass = interface(JObjectClass) ['{5421FE3B-D335-489A-80F6-E94C2F378518}'] function _GetSESSION_MODIFY_REQUEST_FAIL : Integer; cdecl; // A: $19 function _GetSESSION_MODIFY_REQUEST_INVALID : Integer; cdecl; // A: $19 function _GetSESSION_MODIFY_REQUEST_REJECTED_BY_REMOTE : Integer; cdecl; // A: $19 function _GetSESSION_MODIFY_REQUEST_SUCCESS : Integer; cdecl; // A: $19 function _GetSESSION_MODIFY_REQUEST_TIMED_OUT : Integer; cdecl; // A: $19 property SESSION_MODIFY_REQUEST_FAIL : Integer read _GetSESSION_MODIFY_REQUEST_FAIL;// I A: $19 property SESSION_MODIFY_REQUEST_INVALID : Integer read _GetSESSION_MODIFY_REQUEST_INVALID;// I A: $19 property SESSION_MODIFY_REQUEST_REJECTED_BY_REMOTE : Integer read _GetSESSION_MODIFY_REQUEST_REJECTED_BY_REMOTE;// I A: $19 property SESSION_MODIFY_REQUEST_SUCCESS : Integer read _GetSESSION_MODIFY_REQUEST_SUCCESS;// I A: $19 property SESSION_MODIFY_REQUEST_TIMED_OUT : Integer read _GetSESSION_MODIFY_REQUEST_TIMED_OUT;// I A: $19 end; [JavaSignature('android/telecom/Connection_RttModifyStatus')] JConnection_RttModifyStatus = interface(JObject) ['{8F847F9D-0082-4CD8-BA15-6FB419922FA5}'] end; TJConnection_RttModifyStatus = class(TJavaGenericImport<JConnection_RttModifyStatusClass, JConnection_RttModifyStatus>) end; const TJConnection_RttModifyStatusSESSION_MODIFY_REQUEST_FAIL = 2; TJConnection_RttModifyStatusSESSION_MODIFY_REQUEST_INVALID = 3; TJConnection_RttModifyStatusSESSION_MODIFY_REQUEST_REJECTED_BY_REMOTE = 5; TJConnection_RttModifyStatusSESSION_MODIFY_REQUEST_SUCCESS = 1; TJConnection_RttModifyStatusSESSION_MODIFY_REQUEST_TIMED_OUT = 4; implementation end.
unit UDTableFields; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32, Grids; type TCrpeTableFieldsDlg = class(TForm) btnOk: TButton; sgFields: TStringGrid; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure UpdateFields; procedure sgFieldsClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } Cr : TCrpe; FieldIndex : smallint; end; var CrpeTableFieldsDlg: TCrpeTableFieldsDlg; bTableFields : boolean; implementation {$R *.DFM} uses TypInfo, UCrpeUtl, UDTables, UCrpeClasses; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpeTableFieldsDlg.FormCreate(Sender: TObject); begin bTableFields := True; LoadFormPos(Self); btnOk.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpeTableFieldsDlg.FormShow(Sender: TObject); begin sgFields.RowCount := 2; {Grid Titles} sgFields.ColWidths[0] := 45; sgFields.ColWidths[1] := 150; sgFields.ColWidths[2] := 90; sgFields.ColWidths[3] := 45; sgFields.Cells[0,0] := 'Number'; sgFields.Cells[1,0] := 'Name'; sgFields.Cells[2,0] := 'FieldType'; sgFields.Cells[3,0] := 'NBytes'; UpdateFields; end; {------------------------------------------------------------------------------} { UpdateFields procedure } {------------------------------------------------------------------------------} procedure TCrpeTableFieldsDlg.UpdateFields; var i : smallint; OnOff : boolean; begin if Cr.Tables.Item.Fields.ItemIndex > -1 then FieldIndex := Cr.Tables.Item.Fields.ItemIndex else FieldIndex := 0; {Enable/Disable controls} OnOff := (Cr.Tables.Item.Fields.Count > 0); for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TStringGrid then begin TStringGrid(Components[i]).Color := ColorState(OnOff); TStringGrid(Components[i]).Enabled := OnOff; end; end; end; {Update list box} if OnOff = True then begin {Field} for i := 0 to (Cr.Tables.Item.Fields.Count - 1) do begin sgFields.Cells[0,i+1] := IntToStr(i); sgFields.Cells[1,i+1] := Cr.Tables.Item.Fields[i].FieldName; sgFields.Cells[2,i+1] := GetEnumName(TypeInfo(TCrFieldValueType),Ord(Cr.Tables.Item.Fields[i].FieldType)); sgFields.Cells[3,i+1] := IntToStr(Cr.Tables.Item.Fields[i].FieldLength); if i <> (Cr.Tables.Item.Fields.Count - 1) then sgFields.RowCount := sgFields.RowCount + 1; end; sgFields.Row := FieldIndex + 1; sgFieldsClick(Self); end; end; {------------------------------------------------------------------------------} { sgFieldsClick procedure } {------------------------------------------------------------------------------} procedure TCrpeTableFieldsDlg.sgFieldsClick(Sender: TObject); begin FieldIndex := sgFields.Row - 1; Cr.Tables.Item.Fields[FieldIndex]; // editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType), // Ord(Cr.Tables.Item.Fields.Item.FieldType)); end; {------------------------------------------------------------------------------} { btnOkClick procedure } {------------------------------------------------------------------------------} procedure TCrpeTableFieldsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose procedure } {------------------------------------------------------------------------------} procedure TCrpeTableFieldsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bTableFields := False; Release; end; end.
unit Dmitry.Controls.PathEditor; interface uses Generics.Collections, System.Types, System.SysUtils, System.Classes, System.SysConst, System.StrUtils, System.SyncObjs, System.Math, System.Win.ComObj, Winapi.Windows, Winapi.Messages, Winapi.ShellApi, Winapi.CommCtrl, Winapi.ActiveX, Vcl.Controls, Vcl.Graphics, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.Menus, Vcl.Forms, Vcl.ImgList, Vcl.ActnPopup, Vcl.ActnMenus, Dmitry.Memory, Dmitry.Graphics.LayeredBitmap, Dmitry.Utils.ShellIcons, Dmitry.PathProviders; const PATH_EMPTY = '{21D84E1B-A7AB-4318-8A99-E603D9E1108F}'; PATH_LOADING = '{B1F847E1-DF22-40BD-9527-020EE0E9B22A}'; PATH_RELOAD = '{8A0FE330-1F30-4DBC-B439-A6EDD611FCDC}'; PATH_STOP = '{24794A3D-2983-4D7F-A85A-62D1C776C296}'; PATH_EX = '{07000F3F-50C9-4238-A31B-A7DAC4D4A4B0}'; type TGOM = class(TObject) private FList: TList; FSync: TCriticalSection; public constructor Create; destructor Destroy; override; procedure AddObj(Obj: TObject); procedure RemoveObj(Obj: TObject); function IsObj(Obj: TObject): Boolean; end; TPathEvent = procedure(Sender: TObject; Item: TPathItem) of object; TPathListEvent = procedure(Sender: TObject; PathItems: TPathItemCollection) of object; TDirectoryListingThread = class; TPathEditor = class; TThreadNotifyEvent = procedure(Sender: TThread); TGetSystemIconEvent = procedure(Sender: TPathEditor; IconType: string; var Image: TPathImage) of object; TGetItemIconEvent = procedure(Sender: TPathEditor; Item: TPathItem) of object; TIconExtractThread = class(TThread) private FPath: TPathItem; FOwner: TPathEditor; FImageParam: TPathImage; procedure UpdateIcon; procedure GetIcon; protected procedure Execute; override; public constructor Create(Owner: TPathEditor; Path: TPathItem); destructor Destroy; override; end; TDirectoryListingThread = class(TThread) private FPath: TPathItem; FNextPath: TPathItem; FOwner: TPathEditor; FItems: TPathItemCollection; FPathParam: TPathItem; FOnlyFS: Boolean; procedure FillItems; protected procedure Execute; override; public constructor Create(Owner: TPathEditor; Path, NextPath: TPathItem; OnlyFS: Boolean); destructor Destroy; override; end; TPathEditor = class(TWinControl) private { Private declarations } FCanvas: TCanvas; FPnContainer: TPanel; FEditor: TEdit; FImage: TImage; FIsEditorVisible: Boolean; FCurrentPath: string; FPmListMenu: TPopupActionBar; FBitmap: TBitmap; FOnChange: TNotifyEvent; FOnUserChange: TNotifyEvent; FBuilding: Boolean; FParts: TPathItemCollection; FTempParts: TPathItemCollection; FOnUpdateItem: TPathEvent; FClean: Boolean; FOnFillLevel: TPathListEvent; FOnParsePath: TPathListEvent; FTrash: TList<TControl>; FImages: TImageList; FCurrentState: string; FLoadingText: string; FCurrentPathEx: TPathItem; FGetSystemIcon: TGetSystemIconEvent; FGetItemIconEvent: TGetItemIconEvent; FCanBreakLoading: Boolean; FOnBreakLoading: TNotifyEvent; FTrashSender: TObject; FOnImageContextPopup: TContextPopupEvent; FOnPathPartContextPopup: TNotifyEvent; FOnContextPopup: TContextPopupEvent; FListPaths: TList<TPathItem>; FOnlyFileSystem: Boolean; FHideExtendedButton: Boolean; FShowBorder: Boolean; procedure SetPath(const Value: string); procedure SetBitmap(const Value: TBitmap); function GetCurrentPathEx: TPathItem; procedure SetCurrentPathEx(const Value: TPathItem); procedure SetCanBreakLoading(const Value: Boolean); procedure ImageContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure SetHideExtendedButton(const Value: Boolean); procedure SetShowBorder(const Value: Boolean); protected { Protected declarations } procedure WMSize(var Message : TSize); message WM_SIZE; procedure Erased(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure InitControls; procedure BuildPathParts(Sender: TObject; Item: TPathItem); procedure OnPathClick(Sender: TObject); procedure OnPathListClick(Sender: TObject); procedure EditorKeyPress(Sender: TObject; var Key: Char); procedure ClearParts; procedure PnContainerClick(Sender: TObject); procedure PnContainerExit(Sender: TObject); procedure FillPathParts(PathEx: TPathItem; PathList: TPathItemCollection); procedure SetThreadItems(PathList: TPathItemCollection; Path, NextPath: TPathItem); function LoadItemIcon(PathType: string): TPathImage; procedure LoadIcon(PathEx: TPathItem); procedure OnActionClick(Sender: TObject); procedure UpdateActionIcon; procedure UpdateIcon(Icon: TPathImage; Path: TPathItem); procedure UpdateBorderStyle; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Edit; procedure SetPathEx(Sender: TObject; Path: TPathItem; Force: Boolean); overload; procedure SetPathEx(PathType: TPathItemClass; Path: string); overload; published { Published declarations } property DoubleBuffered; property ParentDoubleBuffered; property Align; property Anchors; property Path: string read FCurrentPath write SetPath; property PathEx: TPathItem read FCurrentPathEx; property SeparatorImage: TBitmap read FBitmap write SetBitmap; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnUserChange: TNotifyEvent read FOnUserChange write FOnUserChange; property OnUpdateItem: TPathEvent read FOnUpdateItem write FOnUpdateItem; property OnFillLevel: TPathListEvent read FOnFillLevel write FOnFillLevel; property OnParsePath: TPathListEvent read FOnParsePath write FOnParsePath; property LoadingText: string read FLoadingText write FLoadingText; property GetSystemIcon: TGetSystemIconEvent read FGetSystemIcon write FGetSystemIcon; property CurrentPathEx: TPathItem read GetCurrentPathEx write SetCurrentPathEx; property CanBreakLoading: Boolean read FCanBreakLoading write SetCanBreakLoading; property OnBreakLoading: TNotifyEvent read FOnBreakLoading write FOnBreakLoading; property OnImageContextPopup: TContextPopupEvent read FOnImageContextPopup write FOnImageContextPopup; property OnPathPartContextPopup: TNotifyEvent read FOnPathPartContextPopup write FOnPathPartContextPopup; property OnContextPopup: TContextPopupEvent read FOnContextPopup write FOnContextPopup; property GetItemIconEvent: TGetItemIconEvent read FGetItemIconEvent write FGetItemIconEvent; property OnlyFileSystem: Boolean read FOnlyFileSystem write FOnlyFileSystem; property HideExtendedButton: Boolean read FHideExtendedButton write SetHideExtendedButton; property ShowBorder: Boolean read FShowBorder write SetShowBorder; end; var PERegisterThreadEvent: TThreadNotifyEvent = nil; PEUnRegisterThreadEvent: TThreadNotifyEvent = nil; procedure Register; implementation var FGOM: TGOM = nil; function GOM: TGOM; begin if FGOM = nil then FGOM := TGOM.Create; Result := FGOM; end; procedure Register; begin RegisterComponents('Dm', [TPathEditor]); end; procedure BeginScreenUpdate(Hwnd: THandle); begin SendMessage(Hwnd, WM_SETREDRAW, 0, 0); end; procedure EndScreenUpdate(Hwnd: THandle; Erase: Boolean); begin SendMessage(Hwnd, WM_SETREDRAW, 1, 0); RedrawWindow(Hwnd, nil, 0, { DW_FRAME + } RDW_INVALIDATE + RDW_ALLCHILDREN + RDW_NOINTERNALPAINT); if (Erase) then InvalidateRect(Hwnd, nil, True); end; {$ENDREGION} { TPathEditor } procedure TPathEditor.FillPathParts(PathEx: TPathItem; PathList: TPathItemCollection); var PathPart: TPathItem; begin if PathEx = nil then Exit; try PathPart := PathEx; while (PathPart <> nil) do begin PathList.Insert(0, PathPart.Copy); PathPart := PathPart.Parent; end; finally if Assigned(OnParsePath) then OnParsePath(Self, PathList); end; end; function TPathEditor.GetCurrentPathEx: TPathItem; begin Result := FCurrentPathEx; end; constructor TPathEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); GOM.AddObj(Self); FTrash := TList<TControl>.Create; FListPaths := TList<TPathItem>.Create; FIsEditorVisible := False; FOnlyFileSystem := False; FClean := True; FOnChange := nil; FOnUpdateItem := nil; FOnUserChange := nil; FOnFillLevel := nil; FOnParsePath := nil; FCurrentPathEx := nil; FGetSystemIcon := nil; FOnBreakLoading := nil; FOnImageContextPopup := nil; FOnPathPartContextPopup := nil; FOnContextPopup := nil; FTrashSender := nil; FLoadingText := 'Loading...'; FCurrentState := ''; FBuilding := False; FParts := TPathItemCollection.Create; FTempParts := TPathItemCollection.Create; ControlStyle := ControlStyle - [csDoubleClicks]; Height := 25; FBitmap := TBitmap.Create; FCanvas := TControlCanvas.Create; TControlCanvas(FCanvas).Control := Self; InitControls; end; destructor TPathEditor.Destroy; begin GOM.RemoveObj(Self); ClearParts; FreeList(FTrash); F(FListPaths); F(FCanvas); F(FBitmap); FParts.FreeItems; F(FParts); FTempParts.FreeItems; F(FTempParts); F(FCurrentPathEx); inherited; end; procedure TPathEditor.ImageContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); begin if Assigned(FOnImageContextPopup) then FOnImageContextPopup(Self, MousePos, Handled); end; procedure TPathEditor.InitControls; var Image: TPathImage; begin Color := clWhite; FPnContainer := TPanel.Create(Self); FPnContainer.Parent := Self; FPnContainer.DoubleBuffered := True; FPnContainer.ParentBackground := False; FPnContainer.Align := alClient; FPnContainer.Color := clWindow; FPnContainer.OnClick := PnContainerClick; FPnContainer.OnExit := PnContainerExit; FPnContainer.BevelOuter := bvNone; FPnContainer.BorderStyle := bsNone; UpdateBorderStyle; FPnContainer.OnContextPopup := ContextPopup; FImage := TImage.Create(FPnContainer); FImage.Parent := FPnContainer; FImage.Left := 2; FImage.Top := Height div 2 - 16 div 2; FImage.Width := 16; FImage.Height := 16; FImage.Center := True; FImage.OnContextPopup := ImageContextPopup; Image := LoadItemIcon(PATH_EMPTY); try if Image <> nil then FImage.Picture.Graphic := Image.Graphic; finally F(Image); end; FEditor := TEdit.Create(FPnContainer); FEditor.Parent := FPnContainer; FEditor.Align := alClient; FEditor.Visible := False; FEditor.OnExit := PnContainerExit; FEditor.OnKeyPress := EditorKeyPress; FImages := TImageList.Create(Self); FImages.ColorDepth := cd32Bit; FPmListMenu := TPopupActionBar.Create(Self); FPmListMenu.Images := FImages; end; procedure TPathEditor.LoadIcon(PathEx: TPathItem); begin if Assigned(GetItemIconEvent) then GetItemIconEvent(Self, PathEx); end; function TPathEditor.LoadItemIcon(PathType: string): TPathImage; begin Result := nil; if Assigned(FGetSystemIcon) then FGetSystemIcon(Self, PathType, Result); end; function CleanCaptionName(const S: string): string; var I: Integer; begin Result := S; for I := Length(Result) downto 1 do if Result[I] = '&' then Insert('&', Result, I); end; procedure TPathEditor.BuildPathParts(Sender: TObject; Item: TPathItem); var I, P, MaxWidth: Integer; PathPart: TPathItem; ButtonPath, ButtonList, ButtonListReload: TSpeedButton; StartItem, ItemHeight: Integer; begin if FBuilding then Exit; MaxWidth := Width - 20; if Item <> nil then Item := Item.Copy; try if (FTrashSender <> Sender) and (Sender <> nil) then begin FTrashSender := Sender; for I := FTrash.Count - 1 downto 0 do if FTrash[I] <> Sender then begin TControl(FTrash[I]).Free; FTrash.Delete(I); end; end; BeginScreenUpdate(Handle); FPnContainer.DisableAlign; try FClean := False; FBuilding := True; try ClearParts; FillPathParts(Item, FParts); if FParts.Count = 0 then Exit; P := 22; StartItem := FParts.Count - 1; for I := FParts.Count - 1 downto 0 do begin PathPart := FParts[I]; P := P + FCanvas.TextWidth(PathPart.DisplayName) + 15 - 2; P := P + 16; P := P + 1; if P <= MaxWidth then StartItem := I else Break; end; ItemHeight := FPnContainer.Height - 1; if FShowBorder then Dec(ItemHeight, 3); P := 22; for I := StartItem to FParts.Count - 1 do begin PathPart := FParts[I]; ButtonPath := TSpeedButton.Create(FPnContainer); ButtonPath.Parent := FPnContainer; ButtonPath.Font := FCanvas.Font; ButtonList := TSpeedButton.Create(FPnContainer); ButtonList.Parent := FPnContainer; ButtonList.Font := FCanvas.Font; ButtonPath.Top := 0; ButtonPath.Left := P; ButtonPath.Width := Min(FCanvas.TextWidth(PathPart.DisplayName) + 15, MaxWidth - 16); ButtonPath.Height := ItemHeight; ButtonPath.Caption := CleanCaptionName(PathPart.DisplayName); ButtonPath.Flat := True; ButtonPath.Tag := NativeInt(PathPart); ButtonPath.OnClick := OnPathClick; P := P + ButtonPath.Width - 2; ButtonList.Top := 0; ButtonList.Left := P; ButtonList.Width := 16; ButtonList.Height := ItemHeight; ButtonList.Tag := NativeInt(PathPart); ButtonList.Glyph := FBitmap; ButtonList.Flat := True; ButtonList.OnClick := OnPathListClick; FListPaths.Add(PathPart); P := P + ButtonList.Width; P := P + 1; end; if not HideExtendedButton then begin ButtonListReload := TSpeedButton.Create(FPnContainer); ButtonListReload.Parent := FPnContainer; ButtonListReload.Top := 0; ButtonListReload.Width := 20; ButtonListReload.Left := Width - ButtonListReload.Width - 2; ButtonListReload.Height := ItemHeight; ButtonListReload.OnClick := OnActionClick; ButtonListReload.Flat := True; ButtonListReload.Tag := 1; end; UpdateActionIcon; finally FBuilding := False; end; finally FPnContainer.EnableAlign; EndScreenUpdate(Handle, True); end; finally F(Item); end; end; procedure TPathEditor.ClearParts; var I: Integer; begin FListPaths.Clear; for I := FPnContainer.ControlCount - 1 downto 0 do if (FPnContainer.Controls[I] <> FEditor) and (FPnContainer.Controls[I] <> FImage) then begin FTrash.Add(FPnContainer.Controls[I]); FPnContainer.RemoveControl(FPnContainer.Controls[I]); end; FParts.FreeItems; FClean := True; end; procedure TPathEditor.ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); begin if Assigned(FOnContextPopup) then FOnContextPopup(Sender, MousePos, Handled); end; procedure TPathEditor.Edit; begin //Clear items and display path editor FIsEditorVisible := True; FEditor.Text := FCurrentPath; FEditor.Show; FEditor.SetFocus; ClearParts; end; procedure TPathEditor.EditorKeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = VK_RETURN then begin Key := #0; PnContainerExit(FEditor); if Assigned(FOnUserChange) then FOnUserChange(Self); end; end; procedure TPathEditor.Erased(var Message: TWMEraseBkgnd); begin Message.Result := 1; end; procedure TPathEditor.OnActionClick(Sender: TObject); begin if FCanBreakLoading and Assigned(FOnBreakLoading) then begin FOnBreakLoading(Self); Exit; end else if not FCanBreakLoading then begin if Assigned(FOnUserChange) then FOnUserChange(Self); end; end; procedure TPathEditor.OnPathClick(Sender: TObject); var PathPart: TPathItem; begin PathPart := TPathItem(TControl(Sender).Tag); SetPathEx(Sender, PathPart, False); if Assigned(FOnUserChange) then FOnUserChange(Self); end; procedure TPathEditor.OnPathListClick(Sender: TObject); var MI: TMenuItem; ListButton: TSpeedButton; P: TPoint; Path: string; Image: TPathImage; I, Index: Integer; PathPart, PP, NextPath: TPathItem; begin ListButton := TSpeedButton(Sender); PathPart := TPathItem(ListButton.Tag); PP := PathPart.Copy; FCurrentState := PP.Path; try Path := PP.Path; FPmListMenu.Items.Clear; FTempParts.FreeItems; FImages.Clear; MI := TMenuItem.Create(FPmListMenu); MI.Caption := FLoadingText; MI.Tag := 0; Image := LoadItemIcon(PATH_LOADING); try if Image <> nil then begin Image.AddToImageList(FImages); MI.ImageIndex := 0; end; finally F(Image); end; FPmListMenu.Items.Add(MI); NextPath := nil; Index := -1; for I := 0 to FListPaths.Count - 1 do if FListPaths[I].Path = PP.Path then Index := I; if (Index > -1) and (Index < FListPaths.Count - 1) then NextPath := FListPaths[Index + 1]; TDirectoryListingThread.Create(Self, PP, NextPath, FOnlyFileSystem); P := Point(ListButton.Left, ListButton.BoundsRect.Bottom); P := FPnContainer.ClientToScreen(P); FPmListMenu.Popup(P.X, P.Y); finally F(PP); end; end; procedure TPathEditor.PnContainerClick(Sender: TObject); begin Edit; end; procedure TPathEditor.PnContainerExit(Sender: TObject); begin FIsEditorVisible := False; FEditor.Hide; if Sender = Self then Exit; if PathProviderManager.Supports(FEditor.Text) then Path := FEditor.Text else Path := FCurrentPath; end; procedure TPathEditor.SetBitmap(const Value: TBitmap); begin FBitmap.Assign(Value); end; procedure TPathEditor.SetCanBreakLoading(const Value: Boolean); begin FCanBreakLoading := Value; UpdateActionIcon; end; procedure TPathEditor.SetCurrentPathEx(const Value: TPathItem); var P: TPathItem; begin P := FCurrentPathEx; FCurrentPathEx := Value.Copy; F(P); end; procedure TPathEditor.SetHideExtendedButton(const Value: Boolean); begin FHideExtendedButton := Value; end; procedure TPathEditor.SetPathEx(Sender: TObject; Path: TPathItem; Force: Boolean); var Image: TPathImage; ExtractIcon: Boolean; P: TPathItem; begin if not Force and (Path.EqualsTo(FCurrentPathEx)) then Exit; if FIsEditorVisible then PnContainerExit(Self); CurrentPathEx := Path; FCurrentPath := CurrentPathEx.Path; BuildPathParts(Sender, CurrentPathEx); P := CurrentPathEx.Copy; try ExtractIcon := not P.IsInternalIcon; if not ExtractIcon then begin P.LoadImage(PATH_LOAD_NORMAL, 16); if P.Image <> nil then Image := P.Image.Copy; end else Image := LoadItemIcon(PATH_EMPTY); try if Image <> nil then FImage.Picture.Graphic := Image.Graphic; finally F(Image); end; if ExtractIcon then begin FCurrentState := P.Path; TIconExtractThread.Create(Self, P); end; finally F(P); end; if Assigned(FOnChange) then FOnChange(Self); end; procedure TPathEditor.SetPath(const Value: string); var PP: TPathItem; begin if (FCurrentPath = Value) and not FClean then Exit; FCurrentPath := Value; PP := PathProviderManager.CreatePathItem(Value); try if PP <> nil then SetPathEx(nil, PP, True); finally F(PP); end; end; procedure TPathEditor.SetPathEx(PathType: TPathItemClass; Path: string); var PP: TPathItem; begin PP := PathType.CreateFromPath(Path, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0); try SetPathEx(Self, PP, False); finally F(PP); end; end; procedure TPathEditor.SetShowBorder(const Value: Boolean); begin FShowBorder := Value; UpdateBorderStyle; end; type TXPStylePopupMenuEx = class(TCustomActionPopupMenu); procedure TPathEditor.SetThreadItems(PathList: TPathItemCollection; Path, NextPath: TPathItem); var I: Integer; MI: TMenuItem; PP: TPathItem; CurrentPath: string; begin CurrentPath := ''; if (NextPath <> nil) then CurrentPath := ExcludeTrailingPathDelimiter(NextPath.Path); if FCurrentState = Path.Path then begin FImages.Clear; for I := 0 to PathList.Count - 1 do begin PP := PathList[I]; FTempParts.Add(PP); MI := TMenuItem.Create(FPmListMenu); MI.Caption := CleanCaptionName(PP.DisplayName); MI.Tag := NativeInt(PP); MI.OnClick := OnPathClick; MI.Default := AnsiLowerCase(ExcludeTrailingPathDelimiter(PP.Path)) = AnsiLowerCase(CurrentPath); if PP.Image <> nil then begin PP.Image.AddToImageList(FImages); MI.ImageIndex := FImages.Count - 1; end; FPmListMenu.Items.Add(MI); end; PathList.Clear; if FPmListMenu.PopupMenu <> nil then begin if FPmListMenu.Items.Count = 1 then //close popup menu FPmListMenu.PopupMenu.CloseMenu else begin FPmListMenu.PopupMenu.DisableAlign; try FPmListMenu.Items.Delete(0); FPmListMenu.PopupMenu.LoadMenu(FPmListMenu.PopupMenu.ActionClient.Items, FPmListMenu.Items); finally FPmListMenu.PopupMenu.EnableAlign; end; TXPStylePopupMenuEx(FPmListMenu.PopupMenu).PositionPopup(nil, nil); FPmListMenu.PopupMenu.ActionClient.Items.Delete(0); end; end; if Assigned(OnFillLevel) then OnFillLevel(Self, FTempParts); end else PathList.Clear; end; procedure TPathEditor.UpdateActionIcon; var Image: TPathImage; LB: TLayeredBitmap; I: Integer; begin if FCanBreakLoading then Image := LoadItemIcon(PATH_STOP) else Image := LoadItemIcon(PATH_RELOAD); try if Image <> nil then begin LB := TLayeredBitmap.Create; try if Image.HIcon <> 0 then LB.LoadFromHIcon(Image.HIcon, 16, 16, Color) else if Image.Icon <> nil then LB.LoadFromHIcon(Image.Icon.Handle, 16, 16, Color) else if Image.Bitmap <> nil then LB.LoadFromBitmap(Image.Bitmap); for I := 0 to FPnContainer.ControlCount - 1 do if FPnContainer.Controls[I].Tag = 1 then TSpeedButton(FPnContainer.Controls[I]).Glyph := LB; finally F(LB); end; end; finally F(Image); end; end; procedure TPathEditor.UpdateBorderStyle; begin if FShowBorder then FPnContainer.BevelKind := bkFlat else FPnContainer.BevelKind := bkNone; end; procedure TPathEditor.UpdateIcon(Icon: TPathImage; Path: TPathItem); begin if FCurrentState = Path.Path then begin if Icon <> nil then FImage.Picture.Graphic := Icon.Graphic; end; end; procedure TPathEditor.WMSize(var Message: TSize); begin inherited; if (Width <> Message.cx) and Visible then BuildPathParts(Self, CurrentPathEx); end; { TIconExtractThread } constructor TIconExtractThread.Create(Owner: TPathEditor; Path: TPathItem); begin inherited Create(False); FOwner := Owner; FPath := Path.Copy; if Assigned(PERegisterThreadEvent) then PERegisterThreadEvent(Self); end; destructor TIconExtractThread.Destroy; begin F(FPath); if Assigned(PEUnRegisterThreadEvent) then PEUnRegisterThreadEvent(Self); inherited; end; procedure TIconExtractThread.Execute; begin FreeOnTerminate := True; CoInitializeEx(nil, COINIT_MULTITHREADED); try try FPath.LoadImage(PATH_LOAD_NORMAL, 16); if FPath.Image = nil then Synchronize(GetIcon); FImageParam := FPath.Image; finally Synchronize(UpdateIcon); end; finally CoUninitialize; end; end; procedure TIconExtractThread.GetIcon; begin if GOM.IsObj(FOwner) then FOwner.LoadIcon(FPath); end; procedure TIconExtractThread.UpdateIcon; begin if GOM.IsObj(FOwner) then FOwner.UpdateIcon(FImageParam, FPath); end; { TDirectoryListingThread } constructor TDirectoryListingThread.Create(Owner: TPathEditor; Path, NextPath: TPathItem; OnlyFS: Boolean); begin inherited Create(False); FPath := Path.Copy; FNextPath := nil; FOnlyFS := OnlyFS; if NextPath <> nil then FNextPath := NextPath.Copy; FOwner := Owner; FItems := TPathItemCollection.Create; FPathParam := nil; if Assigned(PERegisterThreadEvent) then PERegisterThreadEvent(Self); end; destructor TDirectoryListingThread.Destroy; begin F(FPath); F(FNextPath); F(FItems); if Assigned(PEUnRegisterThreadEvent) then PEUnRegisterThreadEvent(Self); inherited; end; procedure TDirectoryListingThread.Execute; var Item: TPathItem; Options: Integer; begin FreeOnTerminate := True; CoInitialize(nil); try try Item := PathProviderManager.CreatePathItem(FPath.Path); try Options := PATH_LOAD_DIRECTORIES_ONLY or PATH_LOAD_FOR_IMAGE_LIST; if FOnlyFS then Options := Options or PATH_LOAD_ONLY_FILE_SYSTEM; if Item <> nil then Item.Provider.FillChildList(Self, Item, FItems, Options, 16, MaxInt, nil); finally F(Item); end; finally Synchronize(FillItems); end; finally CoUninitialize; end; end; procedure TDirectoryListingThread.FillItems; begin if GOM.IsObj(FOwner) then begin FOwner.SetThreadItems(FItems, FPath, FNextPath); FItems.FreeItems; end; end; { TGOM } procedure TGOM.AddObj(Obj: TObject); begin FSync.Enter; try FList.Add(Obj); finally FSync.Leave; end; end; constructor TGOM.Create; begin FList := TList.Create; FSync := TCriticalSection.Create; end; destructor TGOM.Destroy; begin F(FList); F(FSync); inherited; end; function TGOM.IsObj(Obj: TObject): Boolean; begin FSync.Enter; try Result := FList.IndexOf(Obj) > -1; finally FSync.Leave; end; end; procedure TGOM.RemoveObj(Obj: TObject); begin FSync.Enter; try FList.Remove(Obj); finally FSync.Leave; end; end; initialization finalization F(FGOM); end.
unit MainFormUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.Menus; type TMode = (off, on); TMainForm = class(TForm) EmotarImage: TImage; GenerateBtn: TButton; PopupMenu: TPopupMenu; HeadTypeBtn: TBitBtn; HairTypeBtn: TBitBtn; MouthTypeBtn: TBitBtn; EyesTypeBtn: TBitBtn; PupilsTypeBtn: TBitBtn; EyebrowsTypeBtn: TBitBtn; SignTypeBtn: TBitBtn; N11: TMenuItem; N21: TMenuItem; N31: TMenuItem; N41: TMenuItem; FormCaption: TLabel; Timer: TTimer; procedure ButtonClick(Sender: TObject); procedure GenerateBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); private const GMOnWidth = 200; GMOffWidth = 100; var GenerateMode: TMode; procedure GenerateEmotion; procedure ToogleGenerateMode; procedure SetGenerateMode(M: TMode); public CurrentEmotion: String; procedure DisplayEmotion(EmoCode: String); end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.ButtonClick(Sender: TObject); var B: TBitBtn; begin B := TBitBtn(Sender); with Mouse.CursorPos do PopupMenu.Popup(X, Y); end; procedure TMainForm.DisplayEmotion(EmoCode: String); begin // end; procedure TMainForm.FormShow(Sender: TObject); begin SetGenerateMode(off); CurrentEmotion := ''; end; procedure TMainForm.GenerateBtnClick(Sender: TObject); begin ToogleGenerateMode; end; procedure TMainForm.GenerateEmotion; begin // end; procedure TMainForm.SetGenerateMode(M: TMode); begin case M of off: Width := GMOffWidth; on: Width := GMOnWidth; end; GenerateMode := M; end; procedure TMainForm.ToogleGenerateMode; begin case GenerateMode of off: begin Width := GMOnWidth; GenerateMode := on; end; on: begin Width := GMOffWidth; GenerateMode := off; GenerateEmotion; end; end; end; end.
unit FuncionarioDAO; interface uses DBXCommon, SqlExpr, BaseDAO, Funcionario, Cargo; type TFuncionarioDAO = class(TBaseDAO) public function List: TDBXReader; function NextCodigo: string; function Insert(Funcionario: TFuncionario): Boolean; function Update(Funcionario: TFuncionario): Boolean; function Delete(Funcionario: TFuncionario): Boolean; function FindByCodigo(Codigo: string): TFuncionario; end; implementation uses uSCPrincipal, StringUtils; { TFuncionarioDAO } function TFuncionarioDAO.List: TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT F.CODIGO, F.NOME, F.CARGO_ID, C.DESCRICAO AS CARGO_DESCRICAO '+ 'FROM FUNCIONARIOS F '+ 'INNER JOIN CARGOS C ON C.ID = F.CARGO_ID'; Result := FComm.ExecuteQuery; end; function TFuncionarioDAO.NextCodigo: string; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'SELECT MAX(CODIGO) AS MAX_CODIGO FROM FUNCIONARIOS'; query.Open; // if query.FieldByName('MAX_CODIGO').IsNull then Result := StrZero(1, 6) else Result := StrZero(query.FieldByName('MAX_CODIGO').AsInteger + 1, 6); finally query.Free; end; end; function TFuncionarioDAO.Insert(Funcionario: TFuncionario): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'INSERT INTO FUNCIONARIOS (CODIGO, NOME, CARGO_ID) VALUES (:CODIGO, :NOME, :CARGO_ID)'; // query.ParamByName('CODIGO').AsString := Funcionario.Codigo; query.ParamByName('NOME').AsString := Funcionario.Nome; query.ParamByName('CARGO_ID').AsInteger := Funcionario.Cargo.Id; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TFuncionarioDAO.Update(Funcionario: TFuncionario): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'UPDATE FUNCIONARIOS SET NOME = :NOME, CARGO_ID = :CARGO_ID '+ 'WHERE CODIGO = :CODIGO'; // query.ParamByName('NOME').AsString := Funcionario.Nome; query.ParamByName('CODIGO').AsString := Funcionario.Codigo; query.ParamByName('CARGO_ID').AsInteger := Funcionario.Cargo.Id; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TFuncionarioDAO.Delete(Funcionario: TFuncionario): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'DELETE FROM FUNCIONARIOS WHERE CODIGO = :CODIGO'; // query.ParamByName('CODIGO').AsString := Funcionario.Codigo; // try query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TFuncionarioDAO.FindByCodigo(Codigo: string): TFuncionario; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; // query.SQL.Text := 'SELECT F.*, C.* '+ 'FROM FUNCIONARIOS F '+ 'INNER JOIN CARGOS C ON C.ID = F.CARGO_ID '+ 'WHERE CODIGO = ''' + Codigo + ''''; query.Open; // Result := TFuncionario.Create(query.FieldByName('CODIGO').AsString, query.FieldByName('NOME').AsString, TCargo.Create(query.FieldByName('CARGO_ID').AsInteger, query.FieldByName('DESCRICAO').AsString)); finally query.Free; end; end; end.
unit NewAcceptUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, RxMemDS, uCommonSp, uFormControl, Buttons, Grids, Spin, StdCtrls, SpComboBox, DBGrids, ExtCtrls, Mask, CheckEditUnit, ComCtrls, uFControl, uLabeledFControl, uSpravControl, uDateControl, uEnumControl, uCharControl, uIntControl, uBoolControl, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, ibase, uSelectForm, uFloatControl, uShtatUtils, ActnList, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, uActionControl, uLogicCheck, uSimpleCheck, fmAddSmetaUnit, qFTools, DBCtrls; type TNewAcceptForm = class(TForm) OkButton: TBitBtn; CancelButton: TBitBtn; FormControl: TqFFormControl; PageControl: TPageControl; MainSheet: TTabSheet; Fio: TqFSpravControl; DateBeg: TqFDateControl; DateEnd: TqFDateControl; MovingType: TqFSpravControl; Department: TqFSpravControl; PostSalary: TqFSpravControl; IsForever: TqFBoolControl; PayType: TqFEnumControl; LocalDatabase: TpFIBDatabase; GetIdMovingQuery: TpFIBDataSet; LocalReadTransaction: TpFIBTransaction; LocalWriteTransaction: TpFIBTransaction; GetIdMovingQueryID_MAN_MOVING: TFIBIntegerField; WorkModeSheet: TTabSheet; MovTypeQuery: TpFIBDataSet; MovTypeQueryID_MOVING_TYPE: TFIBIntegerField; MovTypeQueryNAME_MOVING_TYPE: TFIBStringField; KeyList: TActionList; OkAction: TAction; CancelAction: TAction; Spz: TqFSpravControl; WorkMode: TqFSpravControl; qFIntControl1: TqFIntControl; Label1: TLabel; PayForm: TqFSpravControl; WorkCond: TqFSpravControl; OkladSheet: TTabSheet; Panel3: TPanel; AddItemButton: TSpeedButton; ModifyItemButton: TSpeedButton; DeleteItemButton: TSpeedButton; ItemsGrid: TcxGrid; cxGridDBTableView5: TcxGridDBTableView; cxGridLevel5: TcxGridLevel; SmetViewQuery: TRxMemoryData; SmetSource: TDataSource; SmetViewQueryID_MAN_MOV_SMET: TIntegerField; SmetViewQueryID_MAN_MOVING: TIntegerField; SmetViewQueryKOD_SM: TIntegerField; SmetViewQueryKOD_SM_PPS: TIntegerField; SmetViewQueryDATE_BEG: TIntegerField; SmetViewQueryDATE_END: TIntegerField; SmetViewQueryKOEFF_PPS: TFloatField; SmetViewQueryKOL_STAVOK: TFloatField; SmetViewQueryOKLAD: TFloatField; SmetViewQueryOKLAD_PPS: TFloatField; SmetViewQueryOKLAD_BASE: TFloatField; cxGridDBTableView5DBColumn1: TcxGridDBColumn; cxGridDBTableView5DBColumn3: TcxGridDBColumn; cxGridDBTableView5DBColumn4: TcxGridDBColumn; cxGridDBTableView5DBColumn5: TcxGridDBColumn; cxGridDBTableView5DBColumn6: TcxGridDBColumn; AddSmeta: TAction; ModifySmeta: TAction; DeleteSmeta: TAction; ViewSmeta: TAction; qFSimpleCheck1: TqFSimpleCheck; GetSmTitle: TpFIBDataSet; SmetViewQuerySM_TITLE: TStringField; SmetViewQuerySM_PPS_TITLE: TStringField; GetSmTitleSM_TITLE: TFIBStringField; GetSmTitleSM_PPS_TITLE: TFIBStringField; WorkQuery: TpFIBDataSet; Type_Post: TqFSpravControl; SelectTypePost: TpFIBDataSet; SelectTypePostID_TYPE_POST: TFIBIntegerField; SelectTypePostNAME_TYPE_POST: TFIBStringField; qFLogicCheck1: TqFLogicCheck; GetDefaultsQuery: TpFIBDataSet; GetDefaultsQueryDEFAULT_WORK_MODE: TFIBIntegerField; GetDefaultsQueryDEFAULT_PAY_FORM: TFIBIntegerField; GetDefaultsQueryDEFAULT_WORK_COND: TFIBIntegerField; GetDefaultsQueryNAME: TFIBStringField; GetDefaultsQueryNAME_WORK_COND: TFIBStringField; GetDefaultsQueryNAME_PAY_FORM: TFIBStringField; Reason: TqFCharControl; SelectWorkType: TpFIBDataSet; SelectWorkTypeID_SOVMEST: TFIBIntegerField; SelectWorkTypeNAME_SOVMEST: TFIBStringField; SelectWorkTypeNO_ADD: TFIBStringField; SelectWorkTypeSHORT_NAME: TFIBStringField; SelectWorkTypeSHTAT: TFIBStringField; SelectWorkTypeTEMPFREE: TFIBStringField; SelectWorkTypeTEMPFOR: TFIBStringField; WorkType: TqFSpravControl; StyleRepository: TcxStyleRepository; stBackground: TcxStyle; stContent: TcxStyle; stContentEven: TcxStyle; stContentOdd: TcxStyle; stFilterBox: TcxStyle; stFooter: TcxStyle; stGroup: TcxStyle; stGroupByBox: TcxStyle; stHeader: TcxStyle; stInactive: TcxStyle; stIncSearch: TcxStyle; stIndicator: TcxStyle; stPreview: TcxStyle; stSelection: TcxStyle; stHotTrack: TcxStyle; qizzStyle: TcxGridTableViewStyleSheet; GetDefaultsQueryALLOW_EMPTY_SMETS_IN_ORDERS: TFIBStringField; ShtatrasQuery: TpFIBDataSet; ShtatrasQueryID_SR: TFIBIntegerField; ShtatrasQueryKOL_STAVOK: TFIBFloatField; ShtatrasQueryKOL_VACANT_STAVOK: TFIBFloatField; ShtatrasQueryKOEFF_PPS: TFIBFloatField; ShtatrasQueryWITHKOEF: TFIBStringField; ShtatrasQueryOKLAD: TFIBFloatField; ShtatrasQueryKOD_SM_PPS: TFIBIntegerField; ShtatrasQueryKOD_SM: TFIBIntegerField; ShtatrasQuerySM_TITLE: TFIBStringField; ShtatrasQuerySM_TITLE_PPS: TFIBStringField; ShtatrasQuerySM_NUMBER: TFIBIntegerField; ShtatrasQuerySM_NUMBER_PPS: TFIBIntegerField; ShtatrasQuerySR_NAME: TFIBStringField; IsMainPost: TqFBoolControl; CondDateBeg: TqFDateControl; CondDateEnd: TqFDateControl; IdAcceptCond: TqFSpravControl; Label2: TLabel; AcceptCondQuery: TpFIBDataSet; AcceptCondQueryID_ACCEPT_COND: TFIBIntegerField; AcceptCondQueryNAME_ACCEPT_COND: TFIBStringField; ShtatrasQueryID_WORK_COND: TFIBIntegerField; ShtatrasQueryNAME_WORK_COND: TFIBStringField; ShtatrasQueryID_WORK_MODE: TFIBIntegerField; ShtatrasQueryNAME_WORK_MODE: TFIBStringField; WorkReasonQuery: TpFIBDataSet; WorkReasonQueryID_WORK_REASON: TFIBIntegerField; WorkReasonQueryNAME_FULL: TFIBStringField; WorkReasonQueryNAME_SHORT: TFIBStringField; WorkReason: TqFSpravControl; SelectTypePostSHORT_NAME: TFIBStringField; BonusSheet: TTabSheet; BonusButtonsPanel: TPanel; AddBonusButton: TSpeedButton; ModifyBonusButton: TSpeedButton; DeleteBonusButton: TSpeedButton; BonusGrid: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridDBColumn2: TcxGridDBColumn; cxGridDBColumn3: TcxGridDBColumn; cxGridDBColumn4: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; AddBonus: TAction; ModifyBonus: TAction; DeleteBonus: TAction; SpeedButton1: TSpeedButton; Panel1: TPanel; Label3: TLabel; DBText1: TDBText; BonusQuery: TpFIBDataSet; BonusQueryID_MAN_MOVING: TFIBIntegerField; BonusQueryID_MAN_BONUS: TFIBIntegerField; BonusQueryIS_PERCENT: TFIBStringField; BonusQuerySUMMA: TFIBFloatField; BonusQueryDATE_BEG: TFIBDateField; BonusQueryDATE_END: TFIBDateField; BonusQueryID_RAISE: TFIBIntegerField; BonusQueryNOTE: TFIBStringField; BonusQueryREASON: TFIBStringField; BonusQueryRAISE_NAME: TFIBStringField; BonusQueryFIO: TFIBStringField; BonusQueryWORK_PLACE: TFIBStringField; BonusQueryID_PCARD: TFIBIntegerField; BonusQueryThe_Bonus: TStringField; cxGridDBTableView5DBColumn2: TcxGridDBColumn; ViewBonusButton: TSpeedButton; ViewBonus: TAction; BonusSource: TDataSource; WorkQueryID_MAN_MOV_SMET: TFIBIntegerField; WorkQueryID_MAN_MOVING: TFIBIntegerField; WorkQueryKOD_SM: TFIBIntegerField; WorkQueryKOD_SM_PPS: TFIBIntegerField; WorkQueryKOEFF_PPS: TFIBFloatField; WorkQueryOKLAD: TFIBFloatField; WorkQueryOKLAD_PPS: TFIBFloatField; WorkQueryKOL_STAVOK: TFIBFloatField; WorkQueryDATE_BEG: TFIBDateField; WorkQueryDATE_END: TFIBDateField; WorkQueryOKLAD_BASE: TFIBFloatField; WorkQuerySM_TITLE: TFIBStringField; WorkQuerySM_PPS_TITLE: TFIBStringField; ReformBonusButton: TSpeedButton; FormShtatBonus: TAction; ReformBonusQuery: TpFIBDataSet; GetDefaultsQueryDEFAULT_ID_MOVING_TYPE_ACCEPT: TFIBIntegerField; GetDefaultsQueryDEFAULT_ID_SOVMEST_ACCEPT: TFIBIntegerField; GetDefaultsQueryNAME_MOVING_TYPE: TFIBStringField; GetDefaultsQueryNAME_SOVMEST: TFIBStringField; GetDefaultsQueryDEFAULT_ID_WORK_REASON: TFIBIntegerField; GetDefaultsQueryNAME_FULL: TFIBStringField; AcceptCondYears: TqFFloatControl; AcceptHistoryButton: TButton; AcceptCondQueryNAME_ACCEPT_COND_PRINT: TFIBStringField; GetDefaultsQueryCHECK_SR_VACANT_ST: TFIBStringField; StagirovkaSrok: TqFIntControl; IspitSrok: TqFIntControl; IsHoliday: TqFBoolControl; IsHospital: TqFBoolControl; HolidayFio: TqFSpravControl; HospitalFio: TqFSpravControl; BonusQueryPERCENT: TFIBFloatField; Note: TqFCharControl; BonusQueryORDER_BONUS_STR: TFIBStringField; BonusQueryRAISE_FULL_NAME: TFIBStringField; BonusQuerySOVM_ID_DEPARTMENT: TFIBIntegerField; BonusQuerySOVM_ID_POST_SALARY: TFIBIntegerField; BonusQuerySOVM_NAME_DEPARTMENT: TFIBStringField; BonusQuerySOVM_NAME_POST_SALARY: TFIBStringField; BonusQuerySMETA_NAME: TFIBStringField; cxGridDBColumn5: TcxGridDBColumn; pFIBDS_CheckPermission: TpFIBDataSet; pFIBDS_CheckPermissionNUM_PROJECT: TFIBStringField; pFIBDS_CheckPermissionDATE_ORDER: TFIBDateField; pFIBDS_CheckPermissionOWNER_NAME: TFIBStringField; procedure GetMovingByOrder; procedure DepartmentOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure OkButtonClick(Sender: TObject); procedure FioOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure SpzOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure WorkCondOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure WorkModeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure PayFormOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure PostSalaryOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure MovingTypeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure OkActionExecute(Sender: TObject); procedure CancelActionExecute(Sender: TObject); procedure IsForeverChange(Sender: TObject); procedure FormControlNewRecordAfterPrepare(Sender: TObject); procedure FormControlModifyRecordAfterPrepare(Sender: TObject); procedure FormControlInfoRecordAfterPrepare(Sender: TObject); procedure DeleteSmetaExecute(Sender: TObject); procedure ShowChangeSmetaForm(FMode : TFormMode); procedure AddSmetaExecute(Sender: TObject); procedure ModifySmetaExecute(Sender: TObject); procedure ViewSmetaExecute(Sender: TObject); procedure WriteSmetaInfo(FMode : TFormMode); procedure FormControlAfterRecordAdded(Sender: TObject); procedure ReadSmet; procedure Type_PostOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure PostSalaryChange(Sender: TObject); procedure qFLogicCheck1Check(Sender: TObject; var Error: String); procedure WorkTypeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure GetDefaultsQueryAfterOpen(DataSet: TDataSet); procedure DateBegChange(Sender: TObject); procedure DepartmentChange(Sender: TObject); procedure IdAcceptCondOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure ShtatrasQueryAfterOpen(DataSet: TDataSet); procedure WorkReasonOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure ShowChangeBonusForm(FMode : TFormMode); procedure AddBonusExecute(Sender: TObject); procedure ModifyBonusExecute(Sender: TObject); procedure DeleteBonusExecute(Sender: TObject); procedure BonusQueryCalcFields(DataSet: TDataSet); procedure ViewBonusExecute(Sender: TObject); procedure FormShtatBonusExecute(Sender: TObject); procedure AcceptHistoryButtonClick(Sender: TObject); procedure DateEndChange(Sender: TObject); procedure HolidayFioOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure IsHolidayChange(Sender: TObject); procedure IsHospitalChange(Sender: TObject); private { Private declarations } public Id_Order_Type : Integer; Date_Order : TDate; Id_Order : Integer; Id_Man_Moving : Integer; dmShtatUtils : TdmShtatUtils; ALLOW_EMPTY_SMETS_IN_ORDERS : Boolean; Id_order_group : Integer; end; type TNewAcceptOrderSprav = class(TSprav) private IsConnected: Boolean; Form : TNewAcceptForm; procedure PrepareConnect; public constructor Create; destructor Destroy;override; procedure Show;override; procedure GetInfo;override; function Exists: boolean;override; end; function CreateSprav: TSprav;stdcall; exports CreateSprav; var NewAcceptForm : TNewAcceptForm; implementation {$R *.dfm} procedure TNewAcceptForm.GetMovingByOrder; begin GetIdMovingQuery.Close; GetIdMovingQuery.Params.ParamByName('ID_ORDER').AsInteger := Id_Order; GetIdMovingQuery.Open; if (GetIdMovingQuery.IsEmpty) or (VarIsNull(GetIdMovingQuery['ID_MAN_MOVING'])) then Id_Man_Moving := -1 else Id_Man_Moving := GetIdMovingQueryID_MAN_MOVING.Value; GetIdMovingQuery.Close; end; function CreateSprav: TSprav; begin Result := TNewAcceptOrderSprav.Create; end; constructor TNewAcceptOrderSprav.Create; begin inherited Create; // создание входных/выходных полей Input.FieldDefs.Add('Id_Order_Type', ftInteger); Input.FieldDefs.Add('Id_Order', ftInteger); Input.FieldDefs.Add('Date_Order', ftDate); Input.FieldDefs.Add('SpMode', ftInteger); Input.FieldDefs.Add('Num_Item', ftInteger); Input.FieldDefs.Add('Sub_Item', ftInteger); Input.FieldDefs.Add('Id_Order_Group', ftInteger); Input.FieldDefs.Add('Intro', ftString, 4096); Output.FieldDefs.Add('New_Id_Order', ftInteger); end; destructor TNewAcceptOrderSprav.Destroy; begin inherited Destroy; end; // подготовить соединение с базой procedure TNewAcceptOrderSprav.PrepareConnect; begin end; procedure TNewAcceptOrderSprav.Show; var hnd : Integer; y, m, d : Word; begin Form := TNewAcceptForm.Create(Application.MainForm); Form.LocalReadTransaction.Active := False; Form.LocalWriteTransaction.Active := False; if Form.LocalDatabase.Connected then Form.LocalDatabase.Close; hnd := Input['DBHANDLE']; Form.LocalDatabase.Handle := TISC_DB_HANDLE(hnd); Form.Id_Order := Input['Id_Order']; Form.Id_Order_Type := Input['Id_Order_Type']; Form.Date_Order := Input['Date_Order']; Form.PageControl.ActivePageIndex := 0; Form.dmShtatUtils := TdmShtatUtils.Create(Form, Integer(Form.LocalDatabase.Handle), Form.Date_Order); NewAcceptForm := Form; Form.GetMovingByOrder; if not Form.SmetViewQuery.Active then Form.SmetViewQuery.Active := True; case Input['SpMode'] of 1 : Form.FormControl.Mode := fmAdd; 2 : Form.FormControl.Mode := fmModify; 3 : Form.FormControl.Mode := fmInfo; end; Form.Id_order_group:=Input['ID_ORDER_GROUP']; Form.FormControl.Prepare(Form.LocalDatabase, Form.FormControl.Mode, IntToStr(Form.Id_Man_Moving), ''); Form.FormControl.InsertSQL.Text := StringReplace(Form.FormControl.InsertSQL.Text, ':ID_ORDER_TYPE', IntToStr(Form.Id_Order_Type), []); Form.FormControl.InsertSQL.Text := StringReplace(Form.FormControl.InsertSQL.Text, ':NUM_ITEM', IntToStr(Input['NUM_ITEM']), []); Form.FormControl.InsertSQL.Text := StringReplace(Form.FormControl.InsertSQL.Text, ':SUB_ITEM', IntToStr(Input['SUB_ITEM']), []); Form.FormControl.InsertSQL.Text := StringReplace(Form.FormControl.InsertSQL.Text, ':ID_ORDER_GROUP', IntToStr(Input['ID_ORDER_GROUP']), []); if not varIsNull(Input['INTRO']) then Form.FormControl.InsertSQL.Text := StringReplace(Form.FormControl.InsertSQL.Text, ':INTRO', QuotedStr(Input['INTRO']), []); Form.FormControl.UpdateSQL.Text := StringReplace(Form.FormControl.UpdateSQL.Text, ':ID_ORDER', IntToStr(Form.Id_Order), []); { if Form.FormControl.Mode = fmAdd then begin DecodeDate(Form.Date_Order, y, m, d); Form.DateBeg.Value := EncodeDate(y, 9, 1); Form.DateEnd.Value := EncodeDate(y + 1, 8, 31); end;} Form.ShowModal; if Form.Id_Order <> -1 then begin Output.Open; Output.Append; Output['New_Id_Order'] := Form.Id_Order; Output.Post; end; form.Free; end; function TNewAcceptOrderSprav.Exists: boolean; begin if not IsConnected then PrepareConnect; Result := True; end; procedure TNewAcceptOrderSprav.GetInfo; begin if not IsConnected then PrepareConnect; end; procedure TNewAcceptForm.DepartmentOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var sp: TSprav; begin // создать справочник sp := GetSprav('SpDepartment'); if sp <> nil then begin // заполнить входные параметры with sp.Input do begin Append; FieldValues['DBHandle'] := Integer(LocalDatabase.Handle); FieldValues['Actual_Date'] := Date_Order; Post; end; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if ( sp.Output <> nil ) and not sp.Output.IsEmpty then begin Value := sp.Output['Id_Department']; DisplayText := sp.Output['Name_Full']; ShtatrasQuery.CloseOpen(False); end; sp.Free; end; end; procedure TNewAcceptForm.OkButtonClick(Sender: TObject); var Mode : TFormMode; begin // ShowMessage(IntToStr(Id_order_group)); pFIBDS_CheckPermission.ParamByName('id_pcard').AsInteger:=FIO.Value; pFIBDS_CheckPermission.ParamByName('id_order').AsInteger:=Id_order_group; pFIBDS_CheckPermission.Open; if (not pFIBDS_CheckPermission.IsEmpty) then begin qFInformDialog('Не можливо створити наказ на цю людину тому, що є інші не виконані накази пов''язані з нею!'); qSelect(pFIBDS_CheckPermission,'Перелік наказів'); pFIBDS_CheckPermission.Close; ModalResult:=0; Exit; end; pFIBDS_CheckPermission.Close; if IsForever.Value then DateEnd.Value := EncodeDate(2150, 12, 31); Mode := FormControl.Mode; FormControl.Ok; WriteSmetaInfo(Mode); if Mode <> FormControl.Mode then begin ReformBonusQuery.Close; ReformBonusQuery.Transaction.StartTransaction; ReformBonusQuery.QInsert.ParamByName('Id_Man_Moving').AsInteger := Id_Man_Moving; ReformBonusQuery.QInsert.ExecQuery; ReformBonusQuery.Transaction.Commit; BonusQuery.Close; BonusQuery.ParamByName('ID_ORDER').AsInteger := Id_Order; BonusQuery.Open; PageControl.ActivePageIndex := 3; qFInformDialog('Наказ занесено до бази, перевірте автоматично створені "Доплати та надбавки"!'); end; end; procedure TNewAcceptForm.FioOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var sp: TSprav; begin // создать справочник sp := GetSprav('asup\PCardsList'); if sp <> nil then begin // заполнить входные параметры with sp.Input do begin Append; FieldValues['DBHandle'] := Integer(LocalDatabase.Handle); FieldValues['ActualDate'] := Date_Order; FieldValues['SecondDate'] := 0; FieldValues['ShowWorking'] := False; FieldValues['CanRemoveFilter'] := True; FieldValues['AdminMode'] := True; Post; end; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if ( sp.Output <> nil ) and not sp.Output.IsEmpty then begin Value := sp.Output['ID_PCARD']; DisplayText := sp.Output['FIO']; Reason.Value := 'Заява ' + sp.Output['FIO_SMALL']; end; sp.Free; end; end; procedure TNewAcceptForm.SpzOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin dmShtatUtils.GetSPZ(Value, DisplayText); end; procedure TNewAcceptForm.WorkCondOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin dmShtatUtils.GetWorkCond(Value, DisplayText); end; procedure TNewAcceptForm.WorkModeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin dmShtatUtils.GetWorkMode(Value, DisplayText); end; procedure TNewAcceptForm.PayFormOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin dmShtatUtils.GetPayForm(Value, DisplayText); end; procedure TNewAcceptForm.PostSalaryOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var NewValue, OldValue : Variant; NewDisplayText, OldDisplayText : String; begin if VarIsNull(Department.Value) then begin qFErrorDialog('Спочатку треба вибрати підрозділ!'); exit; end; OldValue := PostSalary.Value; OldDisplayText := PostSalary.DisplayText; dmShtatUtils.Actual_Date := DateBeg.Value; dmShtatUtils.GetSalaryFilter(NewValue, NewDisplayText, Department.Value); if (not (VarType(NewValue) = Unassigned)) and (not VarIsNull(PostSalary.Value)) and (qFConfirm('Зміна посадового окладу призведе до вилучення усіх заведених джерел фінансування, ви справді бажаєте змінити посадовий оклад?')) then begin SmetViewQuery.Close; SmetViewQuery.Open; end; Value := NewValue; DisplayText := NewDisplayText; Type_Post.Value := dmShtatUtils.SalarySelectFilterID_TYPE_POST.Value; Type_Post.DisplayText := dmShtatUtils.SalarySelectFilterNAME_TYPE_POST.Value; ShtatrasQuery.CloseOpen(False); end; procedure TNewAcceptForm.MovingTypeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var sp: TSprav; begin // создать справочник sp := GetSprav('Asup\SpMovingType'); if sp <> nil then begin // заполнить входные параметры with sp.Input do begin Append; FieldValues['DBHandle'] := Integer(LocalDatabase.Handle); FieldValues['IdType'] := 1; Post; end; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if ( sp.Output <> nil ) and not sp.Output.IsEmpty then begin Value := sp.Output['Id_Moving_Type']; DisplayText := sp.Output['Name_Moving_Type']; end; sp.Free; end; end; procedure TNewAcceptForm.OkActionExecute(Sender: TObject); begin OkButton.Click; end; procedure TNewAcceptForm.CancelActionExecute(Sender: TObject); begin CancelButton.Click; end; procedure TNewAcceptForm.IsForeverChange(Sender: TObject); var Year, Day, Month : Word; begin DecodeDate(Date, Year, Month, Day); if IsForever.Value then begin IsHoliday.Value := False; IsHospital.Value := False; IsHolidayChange(Sender); IsHospitalChange(Sender); DateEnd.Value := EncodeDate(2150, 12, 31); DateEnd.Visible := False; end else begin DateEnd.Value := EncodeDate(Year , 12, 31); DateEnd.Visible := True; end; end; procedure TNewAcceptForm.FormControlNewRecordAfterPrepare(Sender: TObject); begin //IsForever.Value := True; //IsForeverChange(DateEnd); GetDefaultsQuery.Close; GetDefaultsQuery.Open; WorkMode.Value := GetDefaultsQueryDEFAULT_WORK_MODE.Value; WorkMode.DisplayText := GetDefaultsQueryNAME.Value; WorkCond.Value := GetDefaultsQueryDEFAULT_WORK_COND.Value; WorkCond.DisplayText := GetDefaultsQueryNAME_WORK_COND.Value; PayForm.Value := GetDefaultsQueryDEFAULT_PAY_FORM.Value; PayForm.DisplayText := GetDefaultsQueryNAME_PAY_FORM.Value; MovingType.Value := GetDefaultsQueryDEFAULT_ID_MOVING_TYPE_ACCEPT.Value; MovingType.DisplayText := GetDefaultsQueryNAME_MOVING_TYPE.Value; WorkType.Value := GetDefaultsQueryDEFAULT_ID_SOVMEST_ACCEPT.Value; WorkType.DisplayText := GetDefaultsQueryNAME_SOVMEST.Value; WorkReason.Value := GetDefaultsQueryDEFAULT_ID_WORK_REASON.Value; WorkReason.DisplayText := GetDefaultsQueryNAME_FULL.Value; dmShtatUtils.SpzSelect.Close; dmShtatUtils.SpzSelect.Open; dmShtatUtils.SpzSelect.FetchAll; if (not dmShtatUtils.SpzSelect.IsEmpty) and (dmShtatUtils.SpzSelect.RecordCount = 1) then begin Spz.Value := dmShtatUtils.SpzSelectID_SPZ.Value; Spz.DisplayText := dmShtatUtils.SpzSelectNAME_SPZ.Value; end; GetDefaultsQuery.Close; ShtatrasQuery.Close; ShtatrasQuery.ParamByName('CUR_DATE').AsDate := DateBeg.Value; end; procedure TNewAcceptForm.FormControlModifyRecordAfterPrepare( Sender: TObject); begin if not VarIsNull(HospitalFio.Value) then begin IsHospital.Value := True; IsHospitalChange(IsHospital); end else if not VarIsNull(HolidayFio.Value) then begin IsHoliday.Value := True; IsHolidayChange(IsHoliday); end else if DateEnd.Value = EncodeDate(2150, 12, 31) then begin IsForever.Value := True; IsForeverChange(DateEnd); end; ReadSmet; GetDefaultsQuery.Open; GetDefaultsQuery.Close; ShtatrasQuery.Close; ShtatrasQuery.ParamByName('ID_POST_SALARY').AsInteger := PostSalary.Value; ShtatrasQuery.ParamByName('ID_DEPARTMENT').AsInteger := Department.Value; ShtatrasQuery.ParamByName('CUR_DATE').AsDate := DateBeg.Value; BonusQuery.Close; BonusQuery.Params.ParamByName('ID_ORDER').AsInteger := Id_Order; BonusQuery.Open; end; procedure TNewAcceptForm.FormControlInfoRecordAfterPrepare( Sender: TObject); begin if not VarIsNull(HospitalFio.Value) then begin IsHospital.Value := True; IsHospitalChange(IsHospital); end else if not VarIsNull(HolidayFio.Value) then begin IsHoliday.Value := True; IsHolidayChange(IsHoliday); end else if DateEnd.Value = EncodeDate(2150, 12, 31) then begin IsForever.Value := True; IsForeverChange(DateEnd); end; ReadSmet; AddItemButton.Enabled := False; ModifyItemButton.Enabled := False; DeleteItemButton.Enabled := False; AddBonusButton.Enabled := False; ModifyBonusButton.Enabled := False; DeleteBonusButton.Enabled := False; ReformBonusButton.Enabled := False; BonusQuery.Close; BonusQuery.Params.ParamByName('ID_ORDER').AsInteger := Id_Order; BonusQuery.Open; end; procedure TNewAcceptForm.ShowChangeSmetaForm(FMode : TFormMode); var Form : TfmAddSmeta; begin if VarIsNull(PostSalary.Value) then begin qFErrorDialog('Треба спочатку вибрати посадовий оклад!'); exit; end; if (FMode <> fmAdd) and (SmetViewQuery.IsEmpty) then begin qFErrorDialog('Немає записів!'); exit; end; Form := TfmAddSmeta.Create(Self); Form.FMode := FMode; Form.IdPostSalary := PostSalary.Value; Form.DateBeg.Value := DateBeg.Value; Form.DateEnd.Value := DateEnd.Value; Form.DateEnd.Visible := not (Form.DateEnd.Value = EncodeDate(2150, 12, 31)); Form.ForeverLabel.Visible := (Form.DateEnd.Value = EncodeDate(2150, 12, 31)); if (FMode = fmModify) or (FMode = fmInfo) then with Form do begin Smeta.Value := SmetViewQueryKOD_SM.Value; Smeta.DisplayText := SmetViewQuerySM_TITLE.Value; Kol_Stavok.value := SmetViewQueryKOL_STAVOK.Value; Koeff_Pps.Value := SmetViewQueryKOEFF_PPS.Value; Kod_Sm_Pps.DisplayText := SmetViewQuerySM_PPS_TITLE.Value; Kod_Sm_Pps.Value := SmetViewQueryKOD_SM_PPS.Value; if not VarIsNull(Form.Kod_Sm_Pps.Value) then GetSmTitle.ParamByName('KOD_SM_PPS').AsInteger := Form.Kod_Sm_Pps.Value else GetSmTitle.ParamByName('KOD_SM_PPS').AsVariant := null; // Пытаемся получить количество вакантных ставок ShtatrasQuery.open; if ShtatrasQuery.Locate('Kod_Sm;Kod_Sm_Pps', VarArrayOf([SmetViewQueryKOD_SM.Value, SmetViewQueryKOD_SM_PPS.Value]), []) then KolVacantStavok.Value := ShtatrasQueryKOL_VACANT_STAVOK.Value; ShtatrasQuery.Close; Base_Oklad.Value := SmetViewQueryOKLAD_BASE.Value; Oklad_Pps.Value := SmetViewQueryOKLAD_PPS.Value; Oklad.Value := SmetViewQueryOKLAD.Value; end; Form.Prepare; if (Form.ShowModal = mrOk) and (FMode <> fmInfo) then begin if FMode = fmAdd then SmetViewQuery.Append; if FMode = fmModify then SmetViewQuery.Edit; SmetViewQuery['ID_MAN_MOV_SMET'] := -1; SmetViewQuery['ID_MAN_MOVING'] := Id_Man_Moving; SmetViewQuery['KOD_SM'] := Form.Smeta.Value; SmetViewQuery['KOD_SM_PPS'] := Form.Kod_Sm_Pps.Value; SmetViewQuery['DATE_BEG'] := Form.DateBeg.Value; SmetViewQuery['DATE_END'] := Form.DateEnd.Value; SmetViewQuery['KOEFF_PPS'] := Form.Koeff_Pps.Value; SmetViewQuery['KOL_STAVOK'] := Form.Kol_Stavok.Value; SmetViewQuery['OKLAD'] := Form.Oklad.Value; SmetViewQuery['OKLAD_PPS'] := Form.Oklad_Pps.Value; SmetViewQuery['OKLAD_BASE'] := Form.Base_Oklad.Value; GetSmTitle.Close; GetSmTitle.ParamByName('KOD_SM').AsInteger := Form.Smeta.Value; if not VarIsNull(Form.Kod_Sm_Pps.Value) then GetSmTitle.ParamByName('KOD_SM_PPS').AsInteger := Form.Kod_Sm_Pps.Value else GetSmTitle.ParamByName('KOD_SM_PPS').AsVariant := null; GetSmTitle.Open; SmetViewQuery['SM_TITLE'] := GetSmTitleSM_TITLE.Value; SmetViewQuery['SM_PPS_TITLE'] := GetSmTitleSM_PPS_TITLE.Value; GetSmTitle.Close; SmetViewQuery.Post; end; Form.Free; end; procedure TNewAcceptForm.DeleteSmetaExecute(Sender: TObject); begin if SmetViewQuery.IsEmpty then begin qFErrorDialog('Немає записів!'); exit; end; if not qFConfirm('Ви справді бажаєте вилучити цей запис?') then exit; SmetViewQuery.Delete; end; procedure TNewAcceptForm.AddSmetaExecute(Sender: TObject); begin ShowChangeSmetaForm(fmAdd); end; procedure TNewAcceptForm.ModifySmetaExecute(Sender: TObject); begin ShowChangeSmetaForm(fmModify); end; procedure TNewAcceptForm.ViewSmetaExecute(Sender: TObject); begin ShowChangeSmetaForm(fmInfo); end; procedure TNewAcceptForm.WriteSmetaInfo(FMode : TFormMode); begin if (FMode = fmInfo) then exit; WorkQuery.Transaction.StartTransaction; try WorkQuery.Close; // Удаляем старые записи из БД if FMode <> fmAdd then begin WorkQuery.QDelete.Close; WorkQuery.QDelete.ParamByName('ID_ORDER').AsInteger := Id_Order; WorkQuery.QDelete.ExecQuery; end; // Пишем новые записи SmetViewQuery.First; while not SmetViewQuery.Eof do begin WorkQuery.QInsert.Close; WorkQuery.QInsert.ParamByName('ID_MAN_MOVING').AsInteger := Id_Man_Moving; WorkQuery.QInsert.ParamByName('KOD_SM').AsInteger := SmetViewQuery['KOD_SM']; if (VarType(SmetViewQuery['KOD_SM_PPS']) = Unassigned) or (not VarIsNull(SmetViewQuery['KOD_SM_PPS'])) then WorkQuery.QInsert.ParamByName('KOD_SM_PPS').AsInteger := SmetViewQuery['KOD_SM_PPS'] else WorkQuery.QInsert.ParamByName('KOD_SM_PPS').Value := null; if (VarType(SmetViewQuery['KOEFF_PPS']) = Unassigned) or (not VarIsNull(SmetViewQuery['KOEFF_PPS'])) then WorkQuery.QInsert.ParamByName('KOEFF_PPS').AsFloat := SmetViewQuery['KOEFF_PPS'] else WorkQuery.QInsert.ParamByName('KOEFF_PPS').Value := null; WorkQuery.QInsert.ParamByName('OKLAD').AsFloat := SmetViewQuery['OKLAD']; WorkQuery.QInsert.ParamByName('OKLAD_PPS').AsFloat := SmetViewQuery['OKLAD_PPS']; WorkQuery.QInsert.ParamByName('KOL_STAVOK').AsFloat := SmetViewQuery['KOL_STAVOK']; WorkQuery.QInsert.ParamByName('ID_ORDER').AsInteger := Id_Order; WorkQuery.QInsert.ParamByName('DATE_BEG').AsDate := SmetViewQuery['DATE_BEG']; WorkQuery.QInsert.ParamByName('DATE_END').AsDate := SmetViewQuery['DATE_END']; WorkQuery.QInsert.ParamByName('OKLAD_BASE').AsFloat := SmetViewQuery['OKLAD_BASE']; WorkQuery.QInsert.ExecQuery; SmetViewQuery.Next; end; except on E:Exception do begin qFErrorDialog('При занесенні даних про джерела фінансування виникла помилка: "' + E.Message + '"'); WorkQuery.Transaction.Rollback; exit; end; end; WorkQuery.Transaction.Commit; end; procedure TNewAcceptForm.FormControlAfterRecordAdded(Sender: TObject); begin Id_Order := FormControl.LastId; GetMovingByOrder; FormControl.Mode := fmModify; ModalResult := 0; end; procedure TNewAcceptForm.ReadSmet; begin WorkQuery.Close; WorkQuery.ParamByName('ID_ORDER').AsInteger := Id_Order; WorkQuery.Open; While not WorkQuery.Eof do begin SmetViewQuery.Append; WorkQuery.QInsert.ParamByName('ID_MAN_MOVING').AsInteger := Id_Man_Moving; SmetViewQuery['KOD_SM'] := WorkQueryKOD_SM.Value; SmetViewQuery['KOD_SM_PPS'] := WorkQueryKOD_SM_PPS.Value; SmetViewQuery['KOEFF_PPS'] := WorkQueryKOEFF_PPS.Value; SmetViewQuery['OKLAD'] := WorkQueryOKLAD.Value; SmetViewQuery['OKLAD_PPS'] := WorkQueryOKLAD_PPS.Value; SmetViewQuery['KOL_STAVOK'] := WorkQueryKOL_STAVOK.Value; SmetViewQuery['DATE_BEG'] := WorkQueryDATE_BEG.Value; SmetViewQuery['DATE_END'] := WorkQueryDATE_END.Value; SmetViewQuery['OKLAD_BASE'] := WorkQueryOKLAD_BASE.Value; SmetViewQuery['SM_TITLE'] := WorkQuerySM_TITLE.Value; SmetViewQuery['SM_PPS_TITLE'] := WorkQuerySM_PPS_TITLE.Value; SmetViewQuery['ID_MAN_MOV_SMET'] := WorkQueryID_MAN_MOV_SMET.Value; SmetViewQuery['ID_MAN_MOVING'] := WorkQueryID_MAN_MOVING.Value; SmetViewQuery.Post; WorkQuery.Next; end; WorkQuery.Close; end; procedure TNewAcceptForm.Type_PostOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin if VarIsNull(PostSalary.Value) then begin qFErrorDialog('Спочатку треба вибрати посадовий оклад!'); exit; end; if qSelect(SelectTypePost) then begin Value := SelectTypePost['Id_Type_Post']; DisplayText := SelectTypePost['Name_Type_Post']; end; end; procedure TNewAcceptForm.PostSalaryChange(Sender: TObject); begin if not VarIsNull(PostSalary.Value) then begin SelectTypePost.Close; SelectTypePost.ParamByName('Id_Post').Value := dmShtatUtils.GetSalaryIdPost(PostSalary.Value); SelectTypePost.Open; SelectTypePost.FetchAll; end; if not VarIsNull(PostSalary.Value) then begin ShtatrasQuery.Close; ShtatrasQuery.ParamByName('ID_POST_SALARY').AsInteger := PostSalary.Value; end; end; procedure TNewAcceptForm.qFLogicCheck1Check(Sender: TObject; var Error: String); begin if ALLOW_EMPTY_SMETS_IN_ORDERS then exit; if SmetViewQuery.IsEmpty then begin Error := 'Треба вказати хоча б одне джерело фінансування!'; OkladSheet.Show; end; end; procedure TNewAcceptForm.WorkTypeOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin if qSelect(SelectWorkType, 'Виберіть тип роботи') then begin Value := SelectWorkTypeID_SOVMEST.Value; DisplayText := SelectWorkTypeNAME_SOVMEST.Value; end; end; procedure TNewAcceptForm.GetDefaultsQueryAfterOpen(DataSet: TDataSet); begin if (not GetDefaultsQuery.Active) or (GetDefaultsQuery.IsEmpty) then exit; ALLOW_EMPTY_SMETS_IN_ORDERS := (GetDefaultsQueryALLOW_EMPTY_SMETS_IN_ORDERS.Value = 'T'); end; procedure TNewAcceptForm.DateBegChange(Sender: TObject); begin ShtatrasQuery.Close; ShtatrasQuery.ParamByName('CUR_DATE').AsDate := DateBeg.Value; if FormControl.Mode = fmAdd then CondDateBeg.Value := DateBeg.Value; end; procedure TNewAcceptForm.DepartmentChange(Sender: TObject); begin if not VarIsNull(Department.Value) then begin ShtatrasQuery.Close; ShtatrasQuery.ParamByName('ID_DEPARTMENT').AsInteger := Department.Value; end; PostSalary.Clear; end; procedure TNewAcceptForm.IdAcceptCondOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin if qSelect(AcceptCondQuery, 'Виберіть умови вступу до посади...') then begin Value := AcceptCondQueryID_ACCEPT_COND.Value; DisplayText := AcceptCondQueryNAME_ACCEPT_COND.Value; end; end; procedure TNewAcceptForm.ShtatrasQueryAfterOpen(DataSet: TDataSet); begin if (Dataset.IsEmpty) or (varIsNull(ShtatrasQueryID_WORK_COND.Value)) then exit; WorkCond.Value := ShtatrasQueryID_WORK_COND.Value; WorkCond.DisplayText := ShtatrasQueryNAME_WORK_COND.Value; WorkMode.Value := ShtatrasQueryID_WORK_MODE.Value; WorkMode.DisplayText := ShtatrasQueryNAME_WORK_MODE.Value; end; procedure TNewAcceptForm.WorkReasonOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); begin if qSelect(WorkReasonQuery, 'Виберіть підставу роботи...') then begin Value := WorkReasonQueryID_WORK_REASON.Value; DisplayText := WorkReasonQueryNAME_FULL.Value; end; end; procedure TNewAcceptForm.ShowChangeBonusForm(FMode : TFormMode); var Sp : TSprav; Mode : Integer; begin if FormControl.Mode = fmAdd then begin qFErrorDialog('Змінення надбавок можливо тільки після створення наказу!'); exit; end; Sp := GetSprav('Asup\BonusOrder'); Sp.Input.Open; Sp.Input.Append; Sp.Input['DBHANDLE'] := Integer(LocalDatabase.Handle); Mode := 1; case FMode of fmAdd : Mode := 1; fmModify : Mode := 2; fmInfo : Mode := 3; end; Sp.Input['SpMode'] := Mode; Sp.Input['Id_Order'] := Id_Order; Sp.Input['Id_Order_group'] := Id_Order_group; Sp.Input['Date_Order'] := Date_Order; Sp.Input['Date_Beg'] := DateBeg.Value; Sp.Input['Date_End'] := DateEnd.Value; Sp.Input['Id_Man_Moving'] := Id_Man_Moving; Sp.Input['SpType'] := 1; if FMode = fmAdd then Sp.Input['Id_Man_Bonus'] := -1 else Sp.Input['Id_Man_Bonus'] := BonusQueryID_MAN_BONUS.Value; Sp.Show; BonusQuery.Close; BonusQuery.Open; if Sp.Output.Active then BonusQuery.Locate('Id_Man_Bonus', Sp.Output['New_Id_Man_Bonus'], []); Sp.Free; end; procedure TNewAcceptForm.AddBonusExecute(Sender: TObject); begin ShowChangeBonusForm(fmAdd); end; procedure TNewAcceptForm.ModifyBonusExecute(Sender: TObject); begin ShowChangeBonusForm(fmModify); end; procedure TNewAcceptForm.DeleteBonusExecute(Sender: TObject); begin if BonusQuery.IsEmpty then begin qFErrorDialog('Немає записів!'); exit; end; if not qFConfirm('Ви справді бажаєте вилучити цей запис?') then exit; LocalWriteTransaction.StartTransaction; try BonusQuery.QDelete.Close; BonusQuery.QDelete.ParamByName('Id_Man_Bonus').AsInteger := BonusQueryID_MAN_BONUS.Value; BonusQuery.QDelete.ExecQuery; except on E:Exception do begin qFErrorDialog(E.Message); LocalWriteTransaction.Rollback; exit; end; end; LocalWriteTransaction.Commit; BonusQuery.CloseOpen(True); end; procedure TNewAcceptForm.BonusQueryCalcFields(DataSet: TDataSet); begin if BonusQueryIS_PERCENT.Value = 'T' then BonusQueryThe_Bonus.Value := BonusQueryPERCENT.AsString + ' %' else BonusQueryThe_Bonus.Value := BonusQuerySUMMA.AsString + ' грн.'; end; procedure TNewAcceptForm.ViewBonusExecute(Sender: TObject); begin ShowChangeBonusForm(fmInfo); end; procedure TNewAcceptForm.FormShtatBonusExecute(Sender: TObject); begin if FormControl.Mode = fmAdd then begin qFErrorDialog('Змінення надбавок можливо тільки після створення наказу!'); exit; end; if not qFConfirm('Ви справді бажаєте переформувати список надбавок? При цьому буде вилучено усі надбавки і буде знову забрано зі штатного розкладу.') then exit; ReformBonusQuery.Close; ReformBonusQuery.Transaction.StartTransaction; ReformBonusQuery.QInsert.ParamByName('Id_Man_Moving').AsInteger := Id_Man_Moving; ReformBonusQuery.QInsert.ExecQuery; ReformBonusQuery.Transaction.Commit; BonusQuery.CloseOpen(True); end; procedure TNewAcceptForm.AcceptHistoryButtonClick(Sender: TObject); var Value : Variant; DisplayText : String; begin dmShtatUtils.GetAcceptCondHistory(FIO.Value, Value, DisplayText); end; procedure TNewAcceptForm.DateEndChange(Sender: TObject); begin if FormControl.Mode = fmAdd then CondDateEnd.Value := DateEnd.Value; if (not SmetViewQuery.IsEmpty) then begin SmetViewQuery.First; SmetViewQuery.Edit; while (not SmetViewQuery.Eof) do begin SmetViewQuery['date_end']:=DateEnd.Value; SmetViewQuery.Next; end end; end; procedure TNewAcceptForm.HolidayFioOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var sp: TSprav; begin // создать справочник sp := GetSprav('asup\PCardsList'); if sp <> nil then begin // заполнить входные параметры with sp.Input do begin Append; FieldValues['DBHandle'] := Integer(LocalDatabase.Handle); FieldValues['ActualDate'] := Date_Order; FieldValues['SecondDate'] := 0; FieldValues['ShowWorking'] := False; FieldValues['CanRemoveFilter'] := True; FieldValues['AdminMode'] := True; Post; end; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if ( sp.Output <> nil ) and not sp.Output.IsEmpty then begin Value := sp.Output['ID_PCARD']; DisplayText := sp.Output['FIO']; end; sp.Free; end; end; procedure TNewAcceptForm.IsHolidayChange(Sender: TObject); begin if IsHoliday.Value then begin HolidayFio.Blocked := False; HolidayFio.Required := True; IsForever.Value := False; IsHospital.Value := False; end else begin HolidayFio.Blocked := True; HolidayFio.Required := False; HolidayFio.Value := null; HolidayFio.DisplayText := ''; end; end; procedure TNewAcceptForm.IsHospitalChange(Sender: TObject); var Year, Day, Month : Word; begin if IsHospital.Value then begin HospitalFio.Blocked := False; HospitalFio.Required := True; IsForever.Value := False; IsHoliday.Value := False; DateEnd.Value := EncodeDate(2150, 12, 31); DateEnd.Visible := False; end else begin HospitalFio.Blocked := True; HospitalFio.Required := False; HospitalFio.Value := null; HospitalFio.DisplayText := ''; DecodeDate(Date, Year, Month, Day); DateEnd.Value := EncodeDate(Year , 12, 31); DateEnd.Visible := True; end; end; end.
unit FormUnit9; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, REST.Backend.PushTypes, REST.Backend.KinveyPushDevice, System.JSON, System.PushNotification, FMX.StdCtrls, REST.Backend.KinveyProvider, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.PushDevice, FMX.Layouts, FMX.Memo, REST.OpenSSL; type TForm9 = class(TForm) PushEvents1: TPushEvents; KinveyProvider1: TKinveyProvider; ToolBar1: TToolBar; Button1: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure PushEvents1DeviceRegistered(Sender: TObject); procedure PushEvents1DeviceTokenReceived(Sender: TObject); procedure PushEvents1DeviceTokenRequestFailed(Sender: TObject; const AErrorMessage: string); procedure PushEvents1PushReceived(Sender: TObject; const AData: TPushData); procedure Button1Click(Sender: TObject); private procedure OnIdle(Sender: TObject; var ADone: Boolean); { Private declarations } public { Public declarations } end; var Form9: TForm9; implementation {$R *.fmx} procedure TForm9.Button1Click(Sender: TObject); begin PushEvents1.Active := not PushEvents1.Active; end; procedure TForm9.FormCreate(Sender: TObject); begin Application.OnIdle := OnIdle; end; procedure TForm9.OnIdle(Sender: TObject; var ADone: Boolean); begin if PushEvents1.Active then Button1.Text := 'Active' else Button1.Text := 'Inactive'; end; procedure TForm9.PushEvents1DeviceRegistered(Sender: TObject); begin Memo1.Lines.Add('PushEvents1DeviceRegistered'); end; procedure TForm9.PushEvents1DeviceTokenReceived(Sender: TObject); begin Memo1.Lines.Add('PushEvents1DeviceTokenReceived'); end; procedure TForm9.PushEvents1DeviceTokenRequestFailed(Sender: TObject; const AErrorMessage: string); begin Memo1.Lines.Add('PushEvents1DeviceTokenRequestFailed'); Memo1.Lines.Add('ErrorMessage: ' + AErrorMessage); end; procedure TForm9.PushEvents1PushReceived(Sender: TObject; const AData: TPushData); begin Memo1.Lines.Add('PushEvents1PushReceived'); Memo1.Lines.Add('JSON: ' + AData.Message); end; end.
{#####################################################################################} {## ##} {## Texture_3D_Unit ##} {## ##} {## A small sample class for 3D textures ##} {## ##} {## History ##} {## 13.12.2003 : Jürgen Abel : First version ##} {## ##} {#####################################################################################} Unit Texture_3D_Unit; interface uses Winapi.Messages, Winapi.OpenGL, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls, GLScene, GLObjects, GLWin32Viewer, GLTexture, GLContext, GLVectorGeometry, GLCadencer; Type TTexture_3D = Class (TObject) protected M_Data_Type : Longword; M_X_Size : Integer; M_Y_Size : Integer; M_Z_Size : Integer; M_Texel_Byte_Size : Integer; M_Data : String; function Data_Type_To_Texel_Byte_Size (F_Data_Type : Integer) : Integer; procedure Set_Data_Type (F_Value : Longword); procedure Set_X_Size (F_Value : Integer); procedure Set_Y_Size (F_Value : Integer); procedure Set_Z_Size (F_Value : Integer); procedure Set_Data (Const F_Value : String); public constructor Create; destructor Destroy; override; procedure Save_To_File (const F_FileName : String); procedure Load_From_File (const F_FileName : String); property Data_Type : Longword read M_Data_Type write Set_Data_Type; property X_Size : Integer read M_X_Size write Set_X_Size; property Y_Size : Integer read M_Y_Size write Set_Y_Size; property Z_Size : Integer read M_Z_Size write Set_Z_Size; property Texel_Byte_Size : Integer read M_Texel_Byte_Size; property Data : string read M_Data write Set_Data; end; { TTexture_3D } //============================================================ implementation //============================================================ {-------------------------------------------------------------------------------------} { Initializes dynamical data } {-------------------------------------------------------------------------------------} constructor TTexture_3D.Create; begin inherited Create; { Initialize variables } M_Data_Type := GL_RGBA; M_X_Size := 0; M_Y_Size := 0; M_Z_Size := 0; M_Texel_Byte_Size := Data_Type_To_Texel_Byte_Size (M_Data_Type); SetLength (M_Data, M_X_Size * M_Y_Size * M_Z_Size * M_Texel_Byte_Size); end; {-------------------------------------------------------------------------------------} { Release dynamic data } {-------------------------------------------------------------------------------------} destructor TTexture_3D.Destroy; begin { Free data } SetLength (M_Data, 0); Inherited Destroy; end; {-------------------------------------------------------------------------------------} { Calculates texel size in bytes } {-------------------------------------------------------------------------------------} function TTexture_3D.Data_Type_To_Texel_Byte_Size (F_Data_Type : Integer) : Integer; begin case F_Data_Type Of GL_COLOR_INDEX : Result := 1; GL_STENCIL_INDEX : Result := 1; GL_DEPTH_COMPONENT : Result := 1; GL_RED : Result := 1; GL_GREEN : Result := 1; GL_BLUE : Result := 1; GL_ALPHA : Result := 1; GL_RGB : Result := 3; GL_RGBA : Result := 4; GL_LUMINANCE : Result := 1; GL_LUMINANCE_ALPHA : Result := 2; else Result := 4; end; { Case } end; {-------------------------------------------------------------------------------------} { Sets data type } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Set_Data_Type (F_Value : Longword); begin M_Data_Type := F_Value; M_Texel_Byte_Size := Data_Type_To_Texel_Byte_Size (M_Data_Type); SetLength (M_Data, M_X_Size * M_Y_Size * M_Z_Size * M_Texel_Byte_Size); end; {-------------------------------------------------------------------------------------} { Sets X size } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Set_X_Size (F_Value : Integer); begin M_X_Size := F_Value; SetLength (M_Data, M_X_Size * M_Y_Size * M_Z_Size * M_Texel_Byte_Size); end; {-------------------------------------------------------------------------------------} { Sets Y size } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Set_Y_Size (F_Value : Integer); begin M_Y_Size := F_Value; SetLength (M_Data, M_X_Size * M_Y_Size * M_Z_Size * M_Texel_Byte_Size); end; {-------------------------------------------------------------------------------------} { Sets Z size } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Set_Z_Size (F_Value : Integer); begin M_Z_Size := F_Value; SetLength (M_Data, M_X_Size * M_Y_Size * M_Z_Size * M_Texel_Byte_Size); end; {-------------------------------------------------------------------------------------} { Sets data } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Set_Data (Const F_Value : String); begin SetLength (M_Data, Length (F_Value)); M_Data := F_Value; end; {-------------------------------------------------------------------------------------} { Save data to file } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Save_To_File (Const F_FileName : String); var File_Stream : TFileStream; begin File_Stream := TFileStream.Create (F_FileName, fmCreate or fmShareDenyWrite); try File_Stream.WriteBuffer (M_Data_Type, SizeOf (Longword)); File_Stream.WriteBuffer (M_X_Size, SizeOf (Integer)); File_Stream.WriteBuffer (M_Y_Size, SizeOf (Integer)); File_Stream.WriteBuffer (M_Z_Size, SizeOf (Integer)); File_Stream.WriteBuffer (PChar (M_Data)^, Length (M_Data)); finally File_Stream.Free; end; end; {-------------------------------------------------------------------------------------} { Load data from file } {-------------------------------------------------------------------------------------} procedure TTexture_3D.Load_From_File (Const F_FileName : String); var File_Stream : TFileStream; begin { TTexture_3D.Load_From_File } File_Stream := TFileStream.Create (F_FileName, fmOpenRead or fmShareDenyWrite); try File_Stream.ReadBuffer (M_Data_Type, SizeOf (Longword)); File_Stream.ReadBuffer (M_X_Size, SizeOf (Integer)); File_Stream.ReadBuffer (M_Y_Size, SizeOf (Integer)); File_Stream.ReadBuffer (M_Z_Size, SizeOf (Integer)); M_Texel_Byte_Size := Data_Type_To_Texel_Byte_Size (M_Data_Type); SetLength (M_Data, M_X_Size * M_Y_Size * M_Z_Size * M_Texel_Byte_Size); File_Stream.ReadBuffer (PChar (M_Data)^, Length (M_Data)); finally File_Stream.Free; end; end; end.
unit Adler_32; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DsgnIntf; type TZeroHundred = 0..100; TAboutProperty = class(TPropertyEditor) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; end; TAdler32 = class(TComponent) private { Private declarations } FAbout : TAboutProperty; FAdler32FileName : String; FWindowOnError : boolean; FOnProgress : TNotifyEvent; FProgress : integer; FProgressStep : TZeroHundred; protected { Protected declarations } procedure DoOnProgress; virtual; public { Public declarations } constructor Create( AOwner: TComponent); override; function CalcAdler32 : longint; function CalcAdler32_hex : string; property Progress : integer read FProgress write FProgress; published { Published declarations } property About: TAboutProperty read FAbout write FAbout; property Adler32FileName : String read FAdler32FileName write FAdler32FileName; Property WindowOnError : boolean read FWindowOnError write FWindowOnError; property ProgressStep : TZeroHundred read FProgressStep write FProgressStep; property OnProgress : TNotifyEvent read FOnProgress write FOnProgress; end; procedure Register; implementation uses adler, zutil, utils; constructor TAdler32.Create( AOwner: TComponent); begin inherited Create( AOwner); WindowOnError := True; FProgressStep := 0 end; procedure TAdler32.DoOnProgress; begin if Assigned (FOnProgress) then FOnProgress (self) end; function TAdler32.CalcAdler32 : longint; var adler : uLong; len : integer; buffer : array [0..BUFLEN-1] of Byte; infile : file; fsize, lensize : longword; begin adler := 0; if FileExists( FAdler32Filename) then begin AssignFile(infile, FAdler32FileName); Reset(infile, 1); adler := adler32(0, NIL, 0); FProgress := 0; fsize := FileSize(infile); lensize := 0; if FProgressStep > 0 then DoOnProgress; while true do begin blockread (infile, buffer, BUFLEN, len); if len=0 then break; adler := adler32(adler, @buffer, len); if FProgressStep > 0 then begin {$WARNINGS OFF} lensize := lensize + len; if ((lensize / fsize) * 100 >= FProgress + FProgressStep) or (lensize = fsize) then begin FProgress := Trunc((lensize / fsize) * 100); DoOnProgress end {$WARNINGS ON} end end; CloseFile(infile) end else if FWindowOnError then MessageDlg('File '+FAdler32FileName+' does not exist.', mtError, [mbAbort], 0); CalcAdler32 := adler end; function TAdler32.CalcAdler32_hex : string; var utils : TUtils; begin CalcAdler32_hex := utils.HexToStr(CalcAdler32) end; procedure TAboutProperty.Edit; var utils : TUtils; begin ShowMessage(utils.CreateAboutMsg('DelphiAdler32')) end; function TAboutProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paDialog, paReadOnly]; end; function TAboutProperty.GetValue: string; begin Result := 'DelphiAdler32'; end; procedure Register; begin RegisterComponents('Samples', [TAdler32]); RegisterPropertyEditor(TypeInfo(TAboutProperty), TAdler32, 'ABOUT', TAboutProperty); end; end.
{: A bare-bones sample for TGLHUDText.<p> To use a TGLHUDText, you must first place a TGLBitmapFont component and specify a font bitmap and it character ranges (ie. which tile represents which character). The component allows for a wide variety of fixed-width font bitmaps, and you can reuse many of the old bitmap fonts sets that were written for Atari, Amiga etc.<p> The TGLHUDText can then be placed in the hierarchy: just link it to the TGLBitmapFont, specify a text, alignment, layout, scale and position to whatever suits your need and that's all.<p> Clicking on the viewer will hide/show the teapot (when teapot is on, the framerate is much lower, f.i. on my GF3 / K7 1.2, the rating can reach 1050FPS with teapot off) } unit Unit1; {$MODE Delphi} interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLScene, GLHUDObjects, GLObjects, GLCadencer, ExtCtrls, GLBitmapFont, GLLCLViewer, GLTeapot, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; BitmapFont1: TGLBitmapFont; GLLightSource1: TGLLightSource; GLCamera1: TGLCamera; HUDText1: TGLHUDText; GLCadencer1: TGLCadencer; Timer1: TTimer; HUDText2: TGLHUDText; HUDText3: TGLHUDText; Teapot1: TGLTeapot; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GLSceneViewer1Click(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.lfm} uses GLUtils; procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); // Load the font bitmap BitmapFont1.Glyphs.LoadFromFile('darkgold_font.bmp'); // sorry, couldn't resist... HUDText1.Text := 'Hello World !'#13#10#13#10 + 'This is me, '#13#10 + 'the HUD Text.'#13#10#13#10 + 'Bitmap Fonts!'; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin // make things move a little HUDText2.Rotation := HUDText2.Rotation + 15 * deltaTime; HUDText3.Scale.X := 0.5 * sin(newTime) + 1; HUDText3.Scale.Y := 0.5 * cos(newTime) + 1; GLSceneViewer1.Invalidate; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.GLSceneViewer1Click(Sender: TObject); begin Teapot1.Visible := not Teapot1.Visible; end; end.
unit UDLogOnInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpeLogOnInfoDlg = class(TForm) pnlLogOnInfo1: TPanel; lblTable: TLabel; lblTableType: TLabel; lblDLLName: TLabel; lblServerType: TLabel; lbTables: TListBox; pnlLogOnInfo2: TPanel; lblServerName: TLabel; lblDatabaseName: TLabel; lblUserID: TLabel; lblPassword: TLabel; editServerName: TEdit; editDatabaseName: TEdit; editUserID: TEdit; editPassword: TEdit; editTableType: TEdit; editDLLName: TEdit; editServerType: TEdit; btnOk: TButton; btnClear: TButton; cbSQLTablesOnly: TCheckBox; btnTest: TButton; lblCount: TLabel; editCount: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure lbTablesClick(Sender: TObject); procedure editServerNameChange(Sender: TObject); procedure editUserIDChange(Sender: TObject); procedure editPasswordChange(Sender: TObject); procedure editDatabaseNameChange(Sender: TObject); procedure btnTestClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure UpdateLogOn; procedure cbSQLTablesOnlyClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure InitializeControls(OnOff: boolean); private { Private declarations } public { Public declarations } Cr : TCrpe; TableIndex : smallint; end; var CrpeLogOnInfoDlg: TCrpeLogOnInfoDlg; bLogOnInfo : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.FormCreate(Sender: TObject); begin bLogOnInfo := True; LoadFormPos(Self); btnOk.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.FormShow(Sender: TObject); begin UpdateLogOn; end; {------------------------------------------------------------------------------} { UpdateLogOn } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.UpdateLogOn; var OnOff : boolean; i : integer; begin TableIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then OnOff := False else begin cbSQLTablesOnly.Checked := Cr.LogOnInfo.SQLTablesOnly; OnOff := (Cr.LogOnInfo.Count > 0); {Get LogOnInfo Index} if OnOff then begin if Cr.LogOnInfo.ItemIndex > -1 then TableIndex := Cr.LogOnInfo.ItemIndex else TableIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff then begin {Fill Tables ListBox} for i := 0 to (Cr.LogOnInfo.Count - 1) do lbTables.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.LogOnInfo.Count); lbTables.ItemIndex := TableIndex; lbTablesClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin if not OnOff then TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbTablesClick } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.lbTablesClick(Sender: TObject); begin TableIndex := lbTables.ItemIndex; Cr.LogOnInfo[TableIndex]; {Fill in controls} editServerName.Text := Cr.LogOnInfo.Item.ServerName; editUserID.Text := Cr.LogOnInfo.Item.UserID; editPassword.Text := Cr.LogOnInfo.Item.Password; editDatabaseName.Text := Cr.LogOnInfo.Item.DatabaseName; cbSQLTablesOnly.Checked := Cr.LogOnInfo.SQLTablesOnly; case Ord(Cr.LogOnInfo.Item.TableType) of 0: editTableType.Text := 'ttUnknown'; 1: editTableType.Text := 'ttStandard'; 2: editTableType.Text := 'ttSQL'; end; editDLLName.Text := Cr.LogOnInfo.Item.DLLName; editServerType.Text := Cr.LogOnInfo.Item.ServerType; end; {------------------------------------------------------------------------------} { editServerNameChange } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.editServerNameChange(Sender: TObject); begin Cr.LogOnInfo.Item.ServerName := editServerName.Text; end; {------------------------------------------------------------------------------} { editUserIDChange } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.editUserIDChange(Sender: TObject); begin Cr.LogOnInfo.Item.UserID := editUserID.Text; end; {------------------------------------------------------------------------------} { editPasswordChange } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.editPasswordChange(Sender: TObject); begin Cr.LogOnInfo.Item.Password := editPassword.Text; end; {------------------------------------------------------------------------------} { editDatabaseNameChange } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.editDatabaseNameChange(Sender: TObject); begin Cr.LogOnInfo.Item.DatabaseName := editDatabaseName.Text; end; {------------------------------------------------------------------------------} { cbSQLTablesOnlyClick } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.cbSQLTablesOnlyClick(Sender: TObject); begin Cr.LogOnInfo.SQLTablesOnly := cbSQLTablesOnly.Checked; UpdateLogOn; end; {------------------------------------------------------------------------------} { btnTestClick } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.btnTestClick(Sender: TObject); begin if Cr.LogOnInfo.Item.Test then MessageDlg('LogOn Succeeded!', mtInformation, [mbOk], 0) else MessageDlg('LogOn Failed.' + Chr(10) + Cr.LastErrorString, mtError, [mbOk], 0); end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.btnClearClick(Sender: TObject); begin Cr.LogOnInfo.Clear; UpdateLogOn; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeLogOnInfoDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bLogOnInfo := False; Release; end; end.
unit UDPFAsDate; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Calendar, Buttons, ComCtrls, ExtCtrls, UCrpe32; type TCrpePFAsDateDlg = class(TForm) pnlPValueEdit: TPanel; pcPValueEdit: TPageControl; tsDate: TTabSheet; pnlAsDate: TPanel; lblMonthYear1: TLabel; sbYearMinus1: TSpeedButton; sbYearPlus1: TSpeedButton; sbMonthPlus1: TSpeedButton; sbMonthMinus1: TSpeedButton; lblYear1: TLabel; lblMonth1: TLabel; lblDay1: TLabel; Calendar2: TCalendar; editDay1: TEdit; editMonth1: TEdit; editYear1: TEdit; cbToday1: TCheckBox; tsBoolean: TTabSheet; pnlAsBoolean: TPanel; tsNumber: TTabSheet; pnlAsNumber: TPanel; lblDot1: TLabel; tsCurrency: TTabSheet; pnlAsCurrency: TPanel; lblDollar: TLabel; btnOk: TButton; btnCancel: TButton; tsDateTime: TTabSheet; tsTime: TTabSheet; pnlAsTime: TPanel; pnlDateTime: TPanel; sbTrue: TSpeedButton; sbFalse: TSpeedButton; lblHourMinSep2: TLabel; lblMinSecSep2: TLabel; lblHours: TLabel; lblMinutes: TLabel; lblSeconds: TLabel; lblMonthYear2: TLabel; sbYearMinus2: TSpeedButton; sbYearPlus2: TSpeedButton; sbMonthPlus2: TSpeedButton; sbMonthMinus2: TSpeedButton; lblYear2: TLabel; lblMonth2: TLabel; lblDay2: TLabel; Calendar1: TCalendar; editDay2: TEdit; editMonth2: TEdit; editYear2: TEdit; cbToday2: TCheckBox; lblHourMinSep: TLabel; lblMinSecSep: TLabel; lblHours2: TLabel; lblMinutes2: TLabel; lblSeconds2: TLabel; lblYearMonthSep: TLabel; lblMonthDaySep: TLabel; editHours2: TEdit; editMinutes2: TEdit; editSeconds2: TEdit; editHour: TEdit; editMinutes: TEdit; editSeconds: TEdit; editNumber: TEdit; editDecimal1: TEdit; editDecimal2: TEdit; Label2: TLabel; editNumber2: TEdit; editDecimal3: TEdit; editDecimal4: TEdit; procedure btnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbTodayClick(Sender: TObject); procedure CalendarChange(Sender: TObject); procedure editDayExit(Sender: TObject); procedure editMonthExit(Sender: TObject); procedure editYearExit(Sender: TObject); procedure editFieldKeyPress(Sender: TObject; var Key: Char); procedure editHours2Exit(Sender: TObject); procedure editMinutes2Exit(Sender: TObject); procedure editSeconds2Exit(Sender: TObject); procedure sbMonthMinusClick(Sender: TObject); procedure sbMonthPlusClick(Sender: TObject); procedure sbYearMinusClick(Sender: TObject); procedure sbYearPlusClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } Value : string; ValueType : TCrParamFieldType; end; var CrpePFAsDateDlg: TCrpePFAsDateDlg; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.FormShow(Sender: TObject); var nTmp : double; iTmp : integer; xDate : TDateTime; begin {Enable/Disable applicable pages} tsDate.TabVisible := (ValueType = pfDate); tsDate.Visible := (ValueType = pfDate); tsDateTime.TabVisible := (ValueType = pfDateTime); tsDateTime.Visible := (ValueType = pfDateTime); tsTime.TabVisible := (ValueType = pfTime); tsTime.Visible := (ValueType = pfTime); tsBoolean.TabVisible := (ValueType = pfBoolean); tsBoolean.Visible := (ValueType = pfBoolean); tsCurrency.TabVisible := (ValueType = pfCurrency); tsCurrency.Visible := (ValueType = pfCurrency); tsNumber.TabVisible := (ValueType = pfNumber); tsNumber.Visible := (ValueType = pfNumber); {Set Value on applicable page} case ValueType of pfNumber : begin pcPValueEdit.ActivePage := tsNumber; Caption := 'Number - CrStrToFloating'; nTmp := CrStrToFloating(Value); editNumber.Text := IntToStr(Trunc(nTmp)); iTmp := Trunc(nTmp * 100) - (Trunc(nTmp) * 100); if iTmp < 10 then begin editDecimal1.Text := '0'; editDecimal2.Text := IntToStr(iTmp); end else begin editDecimal1.Text := IntToStr(iTmp div 10); editDecimal2.Text := IntToStr(iTmp - ((iTmp div 10) * 10)); end; end; pfCurrency : begin pcPValueEdit.ActivePage := tsCurrency; Caption := 'Currency - CrStrToFloating'; nTmp := CrStrToFloating(Value); editNumber2.Text := IntToStr(Trunc(nTmp)); iTmp := Trunc(nTmp * 100) - (Trunc(nTmp) * 100); if iTmp < 10 then begin editDecimal3.Text := '0'; editDecimal4.Text := IntToStr(iTmp); end else begin editDecimal3.Text := IntToStr(iTmp div 10); editDecimal4.Text := IntToStr(iTmp - ((iTmp div 10) * 10)); end; end; pfBoolean : begin pcPValueEdit.ActivePage := tsBoolean; Caption := 'Boolean - CrStrToBoolean'; sbTrue.Down := (CrStrToBoolean(Value) = True) end; pfDate : begin pcPValueEdit.ActivePage := tsDate; Caption := 'Date - CrStrToDate'; CrStrToDate(Value, xDate); Calendar1.CalendarDate := xDate; CalendarChange(Calendar1); end; pfDateTime : begin pcPValueEdit.ActivePage := tsDateTime; Caption := 'DateTime - CrStrToDateTime'; CrStrToDateTime(Value, xDate); Calendar2.CalendarDate := xDate; editHours2.Text := FormatDateTime ('h', xDate); editMinutes2.Text := FormatDateTime('n', xDate); editSeconds2.Text := FormatDateTime('s', xDate); CalendarChange(Calendar2); end; pfTime : begin pcPValueEdit.ActivePage := tsTime; Caption := 'Time - CrStrToTime'; CrStrToTime(Value, xDate); editHour.Text := FormatDateTime('h', xDate); editMinutes.Text := FormatDateTime('n', xDate); editSeconds.Text := FormatDateTime('s', xDate); end; end; end; {------------------------------------------------------------------------------} { cbTodayClick procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.cbTodayClick(Sender: TObject); var cnt1 : integer; Present : TDateTime; Year, Month, Day : Word; cbToday : TCheckBox; Calendar : TCalendar; editYear, editMonth, editDay : TEdit; begin cbToday := TCheckBox(Sender); if cbToday.Name = 'cbToday1' then begin Calendar := Calendar1; editYear := editYear1; editMonth := editMonth1; editDay := editDay1; end else begin Calendar := Calendar2; editYear := editYear2; editMonth := editMonth2; editDay := editDay2; end; {Turn off CalendarChange event} Calendar.OnChange := nil; if not cbToday.Checked then begin {Set Calendar to a Month with 31 days, to prevent an error of changing to 31, while month is still on February, etc.} Calendar.Month := 1; end {Set Calendar to Todays Date} else begin {Get Todays Date from system} Present := Now; DecodeDate(Present, Year, Month, Day); Calendar.Month := 1; Calendar.Year := Year; Calendar.Day := Day; Calendar.Month := Month; end; {Update Edit Boxes} CalendarChange(Calendar); {Update EditBox colors} editYear.Color := ColorState(not cbToday.Checked); editMonth.Color := ColorState(not cbToday.Checked); editDay.Color := ColorState(not cbToday.Checked); {Enable/Disable Controls} for cnt1 := 0 to ComponentCount - 1 do begin if Components[cnt1] is TControl then begin if (TControl(Components[cnt1]).Parent = pnlAsDate) or (TControl(Components[cnt1]).Parent = pnlDateTime) then begin if TControl(Components[cnt1]).Tag = 2 then TControl(Components[cnt1]).Enabled := (not cbToday.Checked); end; end; end; {Turn on CalendarChange event} Calendar.OnChange := CalendarChange; end; {------------------------------------------------------------------------------} { CalendarChange procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.CalendarChange(Sender: TObject); const MonthArray: array[1..12] of string = ('January','February', 'March','April','May','June','July','August','September', 'October','November','December'); var lblMonthYear : TLabel; Calendar : TCalendar; editYear, editMonth, editDay : TEdit; begin if TCalendar(Sender).Name = 'Calendar1' then begin lblMonthYear := lblMonthYear1; Calendar := Calendar1; editYear := editYear1; editMonth := editMonth1; editDay := editDay1; end else begin lblMonthYear := lblMonthYear2; Calendar := Calendar2; editYear := editYear2; editMonth := editMonth2; editDay := editDay2; end; {Update Calendar Title} lblMonthYear.Caption := MonthArray[Calendar.Month] + ' ' + IntToStr(Calendar.Year); {Disable Edit events} editYear.OnExit := nil; editMonth.OnExit := nil; editDay.OnExit := nil; {Update Edit boxes} editYear.Text := IntToStr(Calendar.Year); editMonth.Text := IntToStr(Calendar.Month); editDay.Text := IntToStr(Calendar.Day); {Update VCL} {Enable Edit events} editYear.OnExit := editYearExit; editMonth.OnExit := editMonthExit; editDay.OnExit := editDayExit; end; {------------------------------------------------------------------------------} { editDayExit procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editDayExit(Sender: TObject); var editDay : TEdit; Calendar : TCalendar; begin editDay := TEdit(Sender); if editDay.Name = 'editDay1' then Calendar := Calendar1 else Calendar := Calendar2; try if (StrToInt(editDay.Text) < 1) or (StrToInt(editDay.Text) > 31) then begin ShowMessage('Day must be between 1 and 31.'); editDay.SetFocus; editDay.SelLength := Length(editDay.Text); end else Calendar.Day := StrToInt(editDay.Text); except ShowMessage('Day must be a number between 1 and 31.'); editDay.SetFocus; editDay.SelLength := Length(editDay.Text); end; end; {------------------------------------------------------------------------------} { editMonthExit procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editMonthExit(Sender: TObject); var editMonth : TEdit; Calendar : TCalendar; begin editMonth := TEdit(Sender); if editMonth.Name = 'editMonth1' then Calendar := Calendar1 else Calendar := Calendar2; try if (StrToInt(editMonth.Text) < 1) or (StrToInt(editMonth.Text) > 12) then begin ShowMessage('Month must be between 1 and 12.'); editMonth.SetFocus; editMonth.SelLength := Length(editMonth.Text); end else Calendar.Month := StrToInt(editMonth.Text); except ShowMessage('Month must be a number between 1 and 12.'); editMonth.SetFocus; editMonth.SelLength := Length(editMonth.Text); end; end; {------------------------------------------------------------------------------} { editYearExit procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editYearExit(Sender: TObject); var editYear : TEdit; Calendar : TCalendar; begin editYear := TEdit(Sender); if editYear.Name = 'editYear1' then Calendar := Calendar1 else Calendar := Calendar2; try if (StrToInt(editYear.Text) < 0) then begin ShowMessage('Year must be greater than or equal to 0.'); editYear.SetFocus; editYear.SelLength := Length(editYear.Text); end else Calendar.Year := StrToInt(editYear.Text); except ShowMessage('Year must be a number greater than or equal to 0.'); editYear.SetFocus; editYear.SelLength := Length(editYear.Text); end; end; {------------------------------------------------------------------------------} { editHours2Exit procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editHours2Exit(Sender: TObject); begin try if (StrToInt(editHours2.Text) < 0) or (StrToInt(editHours2.Text) > 23) then begin ShowMessage('Hours must be between 0 and 23.'); editHours2.SetFocus; editHours2.SelLength := Length(editHours2.Text); end; except ShowMessage('Hours must be a number between 0 and 23.'); editHours2.SetFocus; editHours2.SelLength := Length(editHours2.Text); end; end; {------------------------------------------------------------------------------} { editMinutes2Exit procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editMinutes2Exit(Sender: TObject); begin try if (StrToInt(editMinutes2.Text) < 0) or (StrToInt(editMinutes2.Text) > 59) then begin ShowMessage('Minutes must be between 0 and 59.'); editMinutes2.SetFocus; editMinutes2.SelLength := Length(editMinutes2.Text); end; except ShowMessage('Minutes must be a number between 0 and 59.'); editMinutes2.SetFocus; editMinutes2.SelLength := Length(editMinutes2.Text); end; end; {------------------------------------------------------------------------------} { editSeconds2Exit procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editSeconds2Exit(Sender: TObject); begin try if (StrToInt(editSeconds2.Text) < 0) or (StrToInt(editSeconds2.Text) > 59) then begin ShowMessage('Seconds must be between 0 and 59.'); editSeconds2.SetFocus; editSeconds2.SelLength := Length(editSeconds2.Text); end; except ShowMessage('Seconds must be a number between 0 and 59.'); editSeconds2.SetFocus; editSeconds2.SelLength := Length(editSeconds2.Text); end; end; {------------------------------------------------------------------------------} { editFieldKeyPress procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.editFieldKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; Perform(wm_NextDlgCtl,0,0); end; end; {------------------------------------------------------------------------------} { sbMonthMinusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.sbMonthMinusClick(Sender: TObject); var Calendar : TCalendar; begin if TSpeedButton(Sender).Name = 'sbMonthMinus1' then Calendar := Calendar1 else Calendar := Calendar2; if Calendar.Month > 1 then begin while True do begin {if the Day is 31, this might fail...} try Calendar.Month := Calendar.Month - 1; Break; {...so back up the day by one and try again} except Calendar.Day := Calendar.Day - 1; end; end; end else begin Calendar.Month := Calendar.Month + 11; Calendar.Year := Calendar.Year - 1; end; end; {------------------------------------------------------------------------------} { sbMonthPlusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.sbMonthPlusClick(Sender: TObject); var Calendar : TCalendar; begin if TSpeedButton(Sender).Name = 'sbMonthPlus1' then Calendar := Calendar1 else Calendar := Calendar2; if Calendar.Month < 12 then begin while True do begin {if the Day is 31, this might fail...} try Calendar.Month := Calendar.Month + 1; Break; {...so back up the day by one and try again} except Calendar.Day := Calendar.Day - 1; end; end; end else begin Calendar.Month := Calendar.Month - 11; Calendar.Year := Calendar.Year + 1; end; end; {------------------------------------------------------------------------------} { sbYearMinusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.sbYearMinusClick(Sender: TObject); var Calendar : TCalendar; begin if TSpeedButton(Sender).Name = 'sbYearMinus1' then Calendar := Calendar1 else Calendar := Calendar2; while True do begin {if the Day is 31, this might fail...} try Calendar.Year := Calendar.Year - 1; Break; {...so back up the day by one and try again} except Calendar.Day := Calendar.Day - 1; end; end; end; {------------------------------------------------------------------------------} { sbYearPlusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.sbYearPlusClick(Sender: TObject); var Calendar : TCalendar; begin if TSpeedButton(Sender).Name = 'sbYearPlus1' then Calendar := Calendar1 else Calendar := Calendar2; while True do begin {if the Day is 31, this might fail...} try Calendar.Year := Calendar.Year + 1; Break; {...so back up the day by one and try again} except Calendar.Day := Calendar.Day - 1; end; end; end; {------------------------------------------------------------------------------} { btnOKClick procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.btnOKClick(Sender: TObject); var iTmp : integer; begin SaveFormPos(Self); {Set Value} case ValueType of pfNumber : begin if IsNumeric(editNumber.Text) and IsNumeric(editDecimal1.Text) and IsNumeric(editDecimal2.Text) then begin iTmp := StrToInt(editDecimal1.Text) * 10 + StrToInt(editDecimal2.Text); iTmp := StrToInt(editNumber.Text) + (iTmp div 100); Value := IntToStr(iTmp); end; end; pfCurrency : begin if IsNumeric(editNumber2.Text) and IsNumeric(editDecimal3.Text) and IsNumeric(editDecimal4.Text) then begin iTmp := StrToInt(editDecimal3.Text) * 10 + StrToInt(editDecimal4.Text); Value := CrFloatingToStr(StrToInt(editNumber2.Text) + (iTmp / 100)); end; end; pfBoolean : Value := CrBooleanToStr(sbTrue.Down, False); pfDate : Value := CrDateToStr(Calendar1.CalendarDate); pfDateTime : begin if IsNumeric(editYear2.Text) and IsNumeric(editMonth2.Text) and IsNumeric(editDay2.Text) and IsNumeric(editHours2.Text) and IsNumeric(editMinutes2.Text) and IsNumeric(editSeconds2.Text) then begin Value := editYear2.Text + ',' + editMonth2.Text + ',' + editDay2.Text + ' ' + editHours2.Text + ':' + editMinutes2.Text + ':' + editSeconds2.Text; end; end; pfTime : begin if IsNumeric(editHours2.Text) and IsNumeric(editMinutes2.Text) and IsNumeric(editSeconds2.Text) then begin Value := editHours2.Text + ':' + editMinutes2.Text + ':' + editSeconds2.Text; end; end; end; end; {------------------------------------------------------------------------------} { FormClose procedure } {------------------------------------------------------------------------------} procedure TCrpePFAsDateDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
unit Pospolite.View.CSS.Basics; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, math, Pospolite.View.Basics, Pospolite.View.Drawing.Basics, dialogs; type // https://www.w3.org/TR/SVG/coords.html#NestedTransformations TPLCSSMatrixData = array[0..5] of TPLFloat; { TPLCSSMatrix } TPLCSSMatrix = packed record private FData: TPLCSSMatrixData; public constructor Create(const AData: TPLCSSMatrixData); constructor Create(const AData: array of TPLFloat); class function Identity: TPLCSSMatrix; static; inline; function Flip(const AVertical: TPLBool = true): TPLCSSMatrix; inline; function Scale(const AX, AY: TPLFloat): TPLCSSMatrix; function Translate(const AX, AY: TPLFloat): TPLCSSMatrix; inline; function Skew(const AX, AY: TPLFloat): TPLCSSMatrix; inline; function Rotate(const AAngle: TPLFloat): TPLCSSMatrix; procedure Transform(var APoint: TPLPointF); overload; procedure Transform(var APoints: TPLPointFArray); overload; class operator =(m1, m2: TPLCSSMatrix) r: TPLBool; inline; class operator *(m1, m2: TPLCSSMatrix) r: TPLCSSMatrix; class operator *(m: TPLCSSMatrix; x: TPLFloat) r: TPLCSSMatrix; class operator *(x: TPLFloat; m: TPLCSSMatrix) r: TPLCSSMatrix; inline; end; const // https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix PLCSSCommonPrefixes: array[0..4] of TPLString = ( '-webkit-', // Chrome, Safari, newer versions of Opera, almost all iOS browsers including Firefox for iOS; basically, any WebKit based browser '-moz-', // Firefox '-ms-', // Internet Explorer and Microsoft Edge '-o-', // old pre-WebKit versions of Opera '-pl-' // Pospolite View (for experimental features) ); procedure RemoveCSSComments(var ASource: TPLString); function WithoutCommonPrefix(const AName: TPLString): TPLString; implementation procedure RemoveCSSComments(var ASource: TPLString); var i: SizeInt = 1; pom: TPLString = ''; qt: TPLBool = false; begin if Length(ASource) = 0 then exit; while i <= Length(ASource) do begin if ASource[i] in ['"', ''''] then qt := not qt else if ASource[i] in [#10, #11, #13] then qt := false; if not qt and (Copy(ASource, i, 2) = '/*') then begin i += 2; while (i <= Length(ASource)) and (Copy(ASource, i, 2) <> '*/') do i += 1; if Copy(ASource, i, 2) = '*/' then i += 2; end; if (i <= Length(ASource)) and not (ASource[i] in [#0..#13]) then pom += ASource[i]; i += 1; end; ASource := pom; end; function WithoutCommonPrefix(const AName: TPLString): TPLString; var s: TPLString; begin Result := AName; for s in PLCSSCommonPrefixes do if Result.StartsWith(s, true) then begin Result := Result.SubStr(s.Length + 1); break; end; end; { TPLCSSMatrix } constructor TPLCSSMatrix.Create(const AData: TPLCSSMatrixData); var i: SizeInt; begin for i := 0 to 5 do FData[i] := AData[i]; end; constructor TPLCSSMatrix.Create(const AData: array of TPLFloat); var i: SizeInt; begin if Length(AData) <> 6 then begin for i := 0 to 5 do FData[i] := 0; exit; end; for i := 0 to 5 do FData[i] := AData[i]; end; class function TPLCSSMatrix.Identity: TPLCSSMatrix; begin Result := TPLCSSMatrix.Create([1, 0, 0, 1, 0, 0]); end; function TPLCSSMatrix.Flip(const AVertical: TPLBool): TPLCSSMatrix; begin Result := Self * TPLCSSMatrix.Create([IfThen(AVertical, 1, -1), 0, 0, IfThen(AVertical, -1, 1), 0, 0]); end; function TPLCSSMatrix.Scale(const AX, AY: TPLFloat): TPLCSSMatrix; var i: SizeInt; begin Result := Self; for i := 0 to 5 do Result.FData[i] *= IfThen(i mod 2 = 0, AX, AY); end; function TPLCSSMatrix.Translate(const AX, AY: TPLFloat): TPLCSSMatrix; begin Result := Self * TPLCSSMatrix.Create([1, 0, 0, 1, AX, AY]); end; function TPLCSSMatrix.Skew(const AX, AY: TPLFloat): TPLCSSMatrix; begin Result := Self * TPLCSSMatrix.Create([1, Tan(RadToDeg(AX)), Tan(RadToDeg(AY)), 1, 0, 0]); end; function TPLCSSMatrix.Rotate(const AAngle: TPLFloat): TPLCSSMatrix; var c, s: TPLFloat; begin SinCos(RadToDeg(AAngle), s, c); Result := Self * TPLCSSMatrix.Create([c, s, -s, c, 0, 0]); end; procedure TPLCSSMatrix.Transform(var APoint: TPLPointF); var x: TPLFloat; begin x := APoint.X; APoint.X := x * FData[0] + APoint.Y * FData[2] + FData[4]; APoint.Y := x * FData[1] + APoint.Y * FData[3] + FData[5]; end; procedure TPLCSSMatrix.Transform(var APoints: TPLPointFArray); var i: SizeInt; begin for i := Low(APoints) to High(APoints) do Transform(APoints[i]); end; class operator TPLCSSMatrix.=(m1, m2: TPLCSSMatrix)r: TPLBool; begin r := (m1.FData[0] = m2.FData[0]) and (m1.FData[1] = m2.FData[1]) and (m1.FData[2] = m2.FData[2]) and (m1.FData[3] = m2.FData[3]) and (m1.FData[4] = m2.FData[4]) and (m1.FData[5] = m2.FData[5]); end; class operator TPLCSSMatrix.*(m1, m2: TPLCSSMatrix)r: TPLCSSMatrix; var p0, p2, p4: TPLFloat; begin p0 := m1.FData[0] * m2.FData[0] + m1.FData[1] * m2.FData[2]; p2 := m1.FData[2] * m2.FData[0] + m1.FData[3] * m2.FData[2]; p4 := m1.FData[4] * m2.FData[0] + m1.FData[5] * m2.FData[2] + m2.FData[4]; m1.FData[1] := m1.FData[0] * m2.FData[1] + m1.FData[1] * m2.FData[3]; m1.FData[3] := m1.FData[2] * m2.FData[1] + m1.FData[3] * m2.FData[3]; m1.FData[5] := m1.FData[4] * m2.FData[1] + m1.FData[5] * m2.FData[3] + m2.FData[5]; m1.FData[0] := p0; m1.FData[2] := p2; m1.FData[4] := p4; r := m1; end; class operator TPLCSSMatrix.*(m: TPLCSSMatrix; x: TPLFloat)r: TPLCSSMatrix; var i: SizeInt; begin for i := 0 to 5 do m.FData[i] *= x; r := m; end; class operator TPLCSSMatrix.*(x: TPLFloat; m: TPLCSSMatrix)r: TPLCSSMatrix; begin r := m * x; end; end.
unit MyCat.BackEnd.Mysql.CrossSocket; interface uses Net.CrossSocket, MyCat.BackEnd; type TMySQLConnection = class(TCrossConnection, IBackEndConnection) function IsModifiedSQLExecuted: Boolean; function IsFromSlaveDB: Boolean; function GetSchema: string; procedure SetSchema(newSchema: string); function GetLastTime: Int64; function IsClosedOrQuit: Boolean; procedure SetAttachment(attachment: TObject); procedure Quit; procedure SetLastTime(currentTimeMillis: Int64); procedure Release; // function setResponseHandler(commandHandler: ResponseHandler): Boolean; procedure Commit(); procedure Query(sql: string); function GetAttachment: TObject; // procedure execute(node: RouteResultsetNode; source: ServerConnection; // autocommit: Boolean); procedure RecordSql(host: String; schema: String; statement: String); function SyncAndExcute: Boolean; procedure Rollback; function GetBorrowed: Boolean; procedure SetBorrowed(Borrowed: Boolean); function GetTxIsolation: Integer; function IsAutocommit: Boolean; function GetId: Int64; procedure DiscardClose(reason: string); property Borrowed: Boolean read GetBorrowed write SetBorrowed; property schema: string read GetSchema write SetSchema; end; implementation { TMySQLConnection } procedure TMySQLConnection.Commit; begin end; procedure TMySQLConnection.DiscardClose(reason: string); begin end; function TMySQLConnection.GetAttachment: TObject; begin end; function TMySQLConnection.GetBorrowed: Boolean; begin end; function TMySQLConnection.GetId: Int64; begin end; function TMySQLConnection.GetLastTime: Int64; begin end; function TMySQLConnection.GetSchema: string; begin end; function TMySQLConnection.GetTxIsolation: Integer; begin end; function TMySQLConnection.IsAutocommit: Boolean; begin end; function TMySQLConnection.IsClosedOrQuit: Boolean; begin end; function TMySQLConnection.IsFromSlaveDB: Boolean; begin end; function TMySQLConnection.IsModifiedSQLExecuted: Boolean; begin end; procedure TMySQLConnection.Query(sql: string); begin end; procedure TMySQLConnection.Quit; begin end; procedure TMySQLConnection.RecordSql(host, schema, statement: String); begin end; procedure TMySQLConnection.Release; begin end; procedure TMySQLConnection.Rollback; begin end; procedure TMySQLConnection.SetAttachment(attachment: TObject); begin end; procedure TMySQLConnection.SetBorrowed(Borrowed: Boolean); begin end; procedure TMySQLConnection.SetLastTime(currentTimeMillis: Int64); begin end; procedure TMySQLConnection.SetSchema(newSchema: string); begin end; function TMySQLConnection.SyncAndExcute: Boolean; begin end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: skybox.pas,v 1.7 2007/02/05 22:21:09 clootie Exp $ *----------------------------------------------------------------------------*) //----------------------------------------------------------------------------- // File: skybox.h, skybox.cpp // // Desc: Encapsulation of skybox geometry and textures // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- {$I DirectX.inc} unit skybox; interface uses Windows, Direct3D9, D3DX9, DXUTcore, DXUTmisc; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders type CSkybox = class protected m_pEnvironmentMap: IDirect3DCubeTexture9; m_pEnvironmentMapSH: IDirect3DCubeTexture9; m_pEffect: ID3DXEffect; m_pVB: IDirect3DVertexBuffer9; m_pVertexDecl: IDirect3DVertexDeclaration9; m_pd3dDevice: IDirect3DDevice9; m_fSize: Single; m_bDrawSH: Boolean; public constructor Create; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; fSize: Single; pEnvMap: IDirect3DCubeTexture9; strEffectFileName: PWideChar): HRESULT; overload; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; fSize: Single; strCubeMapFile, strEffectFileName: PWideChar): HRESULT; overload; {$IFNDEF FPC} function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; fSize: Single; strCubeMapFile, strEffectFileName: WideString): HRESULT; overload;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} {$ENDIF} procedure OnResetDevice(const pBackBufferSurfaceDesc: TD3DSurfaceDesc); procedure Render(const pmWorldViewProj: TD3DXMatrix; fAlpha, fScale: Single); procedure OnLostDevice; procedure OnDestroyDevice; procedure InitSH(pSHTex: IDirect3DCubeTexture9); // function GetSHMap: IDirect3DCubeTexture9; { return m_pEnvironmentMapSH; } // procedure SetDrawSH(bVal: Boolean); { m_bDrawSH = bVal; } // function GetEnvironmentMap: IDirect3DCubeTexture9; { return m_pEnvironmentMap; } property DrawSH: Boolean read m_bDrawSH write m_bDrawSH; property SHMap: IDirect3DCubeTexture9 read m_pEnvironmentMapSH; property EnvironmentMap: IDirect3DCubeTexture9 read m_pEnvironmentMap; end; implementation type PSkyboxVertex = ^TSkyboxVertex; TSkyboxVertex = packed record pos: TD3DXVector4; tex: TD3DXVector3; end; PSkyboxVertexArray = ^TSkyboxVertexArray; TSkyboxVertexArray = array[0..MaxInt div SizeOf(TSkyboxVertex)-1] of TSkyboxVertex; var g_aSkyboxDecl: array[0..1] of TD3DVertexElement9 = ( (Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT4; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0), {D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0) ); { CSkybox } //----------------------------------------------------------------------------- // Name: CSkybox // Desc: Constructor //----------------------------------------------------------------------------- constructor CSkybox.Create; begin m_pVB := nil; m_pd3dDevice := nil; m_pEffect := nil; m_pVertexDecl := nil; m_pEnvironmentMap := nil; m_pEnvironmentMapSH := nil; m_fSize := 1.0; m_bDrawSH := False; end; //----------------------------------------------------------------------------- function CSkybox.OnCreateDevice(const pd3dDevice: IDirect3DDevice9; fSize: Single; pEnvMap: IDirect3DCubeTexture9; strEffectFileName: PWideChar): HRESULT; var dwShaderFlags: DWORD; str: array[0..MAX_PATH-1] of WideChar; begin m_pd3dDevice := pd3dDevice; m_fSize := fSize; m_pEnvironmentMap := pEnvMap; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the shader debugger. // Debugging vertex shaders requires either REF or software vertex processing, and debugging // pixel shaders requires REF. The D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug // experience in the shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile against the next // higher available software target, which ensures that the unoptimized shaders do not exceed // the shader model limitations. Setting these flags will cause slower rendering since the shaders // will be unoptimized and forced into software. See the DirectX documentation for more information // about using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} // Read the D3DX effect file Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, strEffectFileName); if V_Failed(Result) then Exit; // If this fails, there should be debug output as to // they the .fx file failed to compile Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, m_pEffect, nil); if V_Failed(Result) then Exit; // Create vertex declaration Result:= pd3dDevice.CreateVertexDeclaration(@g_aSkyboxDecl, m_pVertexDecl); if V_Failed(Result) then Exit; Result:= S_OK; end; procedure CSkybox.InitSH(pSHTex: IDirect3DCubeTexture9); begin m_pEnvironmentMapSH := pSHTex; end; //----------------------------------------------------------------------------- function CSkybox.OnCreateDevice(const pd3dDevice: IDirect3DDevice9; fSize: Single; strCubeMapFile, strEffectFileName: PWideChar): HRESULT; var strPath: array[0..MAX_PATH-1] of WideChar; pEnvironmentMap: IDirect3DCubeTexture9; begin Result:= DXUTFindDXSDKMediaFile(strPath, MAX_PATH, strCubeMapFile); if V_Failed(Result) then Exit; Result:= D3DXCreateCubeTextureFromFileExW(pd3dDevice, strPath, 512, 1, 0, D3DFMT_A16B16G16R16F, D3DPOOL_MANAGED, D3DX_FILTER_LINEAR, D3DX_FILTER_LINEAR, 0, nil, nil, pEnvironmentMap); if V_Failed(Result) then Exit; Result:= OnCreateDevice(pd3dDevice, fSize, pEnvironmentMap, strEffectFileName); if V_Failed(Result) then Exit; Result:= S_OK; end; {$IFNDEF FPC} function CSkybox.OnCreateDevice(const pd3dDevice: IDirect3DDevice9; fSize: Single; strCubeMapFile, strEffectFileName: WideString): HRESULT; begin Result := OnCreateDevice(pd3dDevice, fSize, PWideChar(strCubeMapFile), PWideChar(strEffectFileName)); end; {$ENDIF} //----------------------------------------------------------------------------- procedure CSkybox.OnResetDevice( const pBackBufferSurfaceDesc: TD3DSurfaceDesc); var pVertex: PSkyboxVertexArray; fHighW, fHighH, fLowW, fLowH: Single; begin if Assigned(m_pEffect) then V(m_pEffect.OnResetDevice); V(m_pd3dDevice.CreateVertexBuffer(4 * SizeOf(TSkyboxVertex), D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, m_pVB, nil)); // Fill the vertex buffer V(m_pVB.Lock(0, 0, Pointer(pVertex), 0)); // Map texels to pixels fHighW := -1.0 - (1.0/pBackBufferSurfaceDesc.Width); fHighH := -1.0 - (1.0/pBackBufferSurfaceDesc.Height); fLowW := 1.0 + (1.0/pBackBufferSurfaceDesc.Width); fLowH := 1.0 + (1.0/pBackBufferSurfaceDesc.Height); pVertex[0].pos := D3DXVector4(fLowW, fLowH, 1.0, 1.0); pVertex[1].pos := D3DXVector4(fLowW, fHighH, 1.0, 1.0); pVertex[2].pos := D3DXVector4(fHighW, fLowH, 1.0, 1.0); pVertex[3].pos := D3DXVector4(fHighW, fHighH, 1.0, 1.0); m_pVB.Unlock; end; //----------------------------------------------------------------------------- // Name: Render // Desc: //----------------------------------------------------------------------------- procedure CSkybox.Render(const pmWorldViewProj: TD3DXMatrix; fAlpha, fScale: Single); var mInvWorldViewProj: TD3DXMatrix; uiPass: Integer; uiNumPasses: LongWord; begin D3DXMatrixInverse(mInvWorldViewProj, nil, pmWorldViewProj); V(m_pEffect.SetMatrix('g_mInvWorldViewProjection', mInvWorldViewProj)); if (fScale = 0.0) or (fAlpha = 0.0) then Exit; // do nothing if no intensity... // Draw the skybox V(m_pEffect.SetTechnique('Skybox')); V(m_pEffect.SetFloat('g_fAlpha', fAlpha)); V(m_pEffect.SetFloat('g_fScale', fAlpha*fScale)); if m_bDrawSH then V(m_pEffect.SetTexture('g_EnvironmentTexture', m_pEnvironmentMapSH)) else V(m_pEffect.SetTexture('g_EnvironmentTexture', m_pEnvironmentMap)); m_pd3dDevice.SetStreamSource(0, m_pVB, 0, SizeOf(TSkyboxVertex)); m_pd3dDevice.SetVertexDeclaration(m_pVertexDecl); V(m_pEffect._Begin(@uiNumPasses, 0)); for uiPass := 0 to uiNumPasses - 1 do begin V(m_pEffect.BeginPass(uiPass)); m_pd3dDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); V(m_pEffect.EndPass); end; V(m_pEffect._End); end; //----------------------------------------------------------------------------- procedure CSkybox.OnLostDevice; begin if Assigned(m_pEffect) then V(m_pEffect.OnLostDevice); m_pVB := nil; end; //----------------------------------------------------------------------------- procedure CSkybox.OnDestroyDevice; begin m_pEnvironmentMap := nil; m_pEnvironmentMapSH := nil; m_pEffect := nil; m_pVertexDecl := nil; m_pd3dDevice := nil; end; end.
Unit WebcamAPI; interface uses Windows, Messages, unitobjeto, classes; var MyWebCamObject: TMyObject; function ListarDispositivosWebCam(Delimitador: WideString): WideString; function InitCapture(WebcamID: integer): boolean; function GetWebcamImage(var ReplyStream: TMemoryStream): boolean; procedure DestroyCapture; implementation const WM_CAP_START = WM_USER; WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11; WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10; WM_CAP_SET_PREVIEW = WM_CAP_START + 50; WM_CAP_SET_OVERLAY = WM_CAP_START + 51; WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52; WM_CAP_GRAB_FRAME_NOSTOP = WM_CAP_START + 61; WM_CAP_SET_CALLBACK_FRAME = WM_CAP_START + 5; WM_CAP_SAVEDIB = WM_CAP_START + 25; WM_CAP_EDIT_COPY = WM_CAP_START + 30; WM_CAP_GRAB_FRAME = WM_CAP_START + 60; PICWIDTH = 640; PICHEIGHT = 480; SUBLINEHEIGHT = 18; EXTRAHEIGHT = 400; var FCapHandle: THandle; function IntToStr(i: Integer): WideString; begin Str(i, Result); end; function StrToInt(S: WideString): Integer; begin Val(S, Result, Result); end; function SaveBitmapToStream(Stream: TMemoryStream; HBM: HBitmap): Integer; const BMType = $4D42; type TBitmap = record bmType: Integer; bmWidth: Integer; bmHeight: Integer; bmWidthBytes: Integer; bmPlanes: Byte; bmBitsPixel: Byte; bmBits: Pointer; end; var BM: TBitmap; BFH: TBitmapFileHeader; BIP: PBitmapInfo; DC: HDC; HMem: THandle; Buf: Pointer; ColorSize, DataSize: Longint; BitCount: word; function AlignDouble(Size: Longint): Longint; begin Result := (Size + 31) div 32 * 4; end; begin Result := 0; if GetObject(HBM, SizeOf(TBitmap), @BM) = 0 then Exit; BitCount := 32; if (BitCount <> 24) then ColorSize := SizeOf(TRGBQuad) * (1 shl BitCount) else ColorSize := 0; DataSize := AlignDouble(bm.bmWidth * BitCount) * bm.bmHeight; GetMem(BIP, SizeOf(TBitmapInfoHeader) + ColorSize); if BIP <> nil then begin with BIP^.bmiHeader do begin biSize := SizeOf(TBitmapInfoHeader); biWidth := bm.bmWidth; biHeight := bm.bmHeight; biPlanes := 1; biBitCount := BitCount; biCompression := 0; biSizeImage := DataSize; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; end; with BFH do begin bfOffBits := SizeOf(BFH) + SizeOf(TBitmapInfo) + ColorSize; bfReserved1 := 0; bfReserved2 := 0; bfSize := longint(bfOffBits) + DataSize; bfType := BMType; end; HMem := GlobalAlloc(gmem_Fixed, DataSize); if HMem <> 0 then begin Buf := GlobalLock(HMem); DC := GetDC(0); if GetDIBits(DC, hbm, 0, bm.bmHeight, Buf, BIP^, dib_RGB_Colors) <> 0 then begin Stream.WriteBuffer(BFH, SizeOf(BFH)); Stream.WriteBuffer(PChar(BIP)^, SizeOf(TBitmapInfo) + ColorSize); Stream.WriteBuffer(Buf^, DataSize); Result := 1; end; ReleaseDC(0, DC); GlobalUnlock(HMem); GlobalFree(HMem); end; end; FreeMem(BIP, SizeOf(TBitmapInfoHeader) + ColorSize); DeleteObject(HBM); end; function capCreateCaptureWindow(lpszWindowName: pWideChar; dwStyle: DWORD; x, y, nWidth, nHeight: integer; hwndParent: HWND; nID: integer): HWND; stdcall; external 'AVICAP32.DLL' name 'capCreateCaptureWindowW'; function capGetDriverDescription( wDriverIndex: DWord; lpszName : pWideChar; cbName : Integer; lpszVer : pWideChar; cbVer : Integer ) : Boolean; stdcall; external 'avicap32.dll' name 'capGetDriverDescriptionW'; function ListarDispositivosWebCam(Delimitador: WideString): WideString; var szName, szVersion: array[0..MAX_PATH] of widechar; iReturn: Boolean; x: integer; begin Result := ''; x := 0; repeat iReturn := capGetDriverDescription(x, @szName, sizeof(szName), @szVersion, sizeof(szVersion)); If iReturn then begin Result := Result + '"' + szName + ' - ' + szVersion + '"' + Delimitador; Inc(x); end; until iReturn = False; end; var kHook: Thandle; function LowLevelHookProc(nCode, wParam, lParam : integer) : integer; stdcall; var TempStr: array [0..255] of WideChar; begin if nCode = HCBT_CREATEWND then begin GetClassNameW(wParam, TempStr, sizeof(TempStr)); SendMessage(wParam, WM_CLOSE, 0, 0); //MessageBoxW(0, pWChar('Aqui porra...' + inttostr(wParam)), TempStr, 0); end else result := CallNextHookEx(kHook, nCode, wParam, lParam); end; function StartCapture(WebcamID: integer): boolean; begin Result := False; if Assigned(MyWebcamObject) = false then exit; FCapHandle := capCreateCaptureWindow('Video', WS_CHILD or WS_VISIBLE, 0, 0, PICWIDTH, PICHEIGHT, MyWebcamObject.Handle, 1); kHook := SetWindowsHookExW(WH_CBT, @LowLevelHookProc, GetModuleHandle(0), 0); result := LongBool(SendMessage(FCapHandle, WM_CAP_DRIVER_CONNECT, WebcamID, 0)); UnhookWindowsHookEx(kHook); if result = false then begin FreeAndNil(MyWebcamObject); exit; end; SendMessage(FCapHandle, WM_CAP_SET_PREVIEWRATE, 1, 0); sendMessage(FCapHandle, WM_CAP_SET_OVERLAY, 1, 0); SendMessage(FCapHandle, WM_CAP_SET_PREVIEW, 1, 0); end; procedure DestroyCapture; begin SendMessage(FCapHandle, WM_CAP_DRIVER_DISCONNECT, 0, 0); FreeAndNil(MyWebcamObject); end; function WindowProc(HWND, Msg, wParam, lParam: longint): longint; stdcall; begin if Msg = WM_DESTROY then DestroyCapture else Result := DefWindowProc(HWND, Msg, wParam, lParam); end; function InitCapture(WebcamID: integer): boolean; var Msg: TMsg; begin MyWebcamObject := TMyObject.Create('WEBCAM', @WindowProc); ShowWindow(MyWebcamObject.Handle, SW_HIDE); result := StartCapture(WebcamID); end; function GetWebcamImage(var ReplyStream: TMemoryStream): boolean; begin result := False; try if Assigned(MyWebcamObject) = true then begin SendMessage(FCapHandle, WM_CAP_SET_CALLBACK_FRAME, 0, 0); SendMessage(FCapHandle, WM_CAP_GRAB_FRAME_NOSTOP, 1, 0); ReplyStream.Clear; ReplyStream.Position := 0; SendMessage(FCapHandle, WM_CAP_GRAB_FRAME, 0, 0); SendMessage(FCapHandle, WM_CAP_EDIT_COPY, 0, 0); OpenClipboard(0); SaveBitmapToStream(ReplyStream, GetClipboardData(CF_BITMAP)); CloseClipboard; result := ReplyStream.Size > 0; //ReplyStream.SaveToFile(inttostr(gettickcount) + '.bmp'); end; except Result := false; end; end; end.
unit ini_type_account_FORM; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ToolWin, ComCtrls, FIBQuery, pFIBQuery, pFIBStoredProc, pFIBDatabase, StdCtrls, Db, FIBDataSet, pFIBDataSet, Grids, DBGrids, Menus, ActnList, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, cxContainer, cxTextEdit, FIBDatabase, Ibase,Variants, ImgList, dxBar, dxBarExtItems, cxTL, cxCheckBox; const TABLE = 'INI_TYPE_ACCOUNT'; SEL_VIEW = 'VIEW_INI_TYPE_ACCOUNT'; ADD_PROC = 'PUB_SP_INI_TYPE_ACCOUNT_ADD'; DEL_PROC = 'PUB_SP_INI_TYPE_ACCOUNT_DEL'; MOD_PROC = 'PUB_SP_INI_TYPE_ACCOUNT_MOD'; PK_FIELD = 'ID_TYPE_ACCOUNT'; type TFini_type_account = class(TForm) StoredProc: TpFIBStoredProc; DataSource1: TDataSource; DataSet: TpFIBDataSet; Query: TpFIBQuery; ActionList1: TActionList; ActionMod: TAction; ActionDel: TAction; ActionAdd: TAction; ActionSel: TAction; PopupMenu1: TPopupMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; N6: TMenuItem; WorkDatabase: TpFIBDatabase; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; cxGrid1: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; cxGridDBTableView1DBColumn1: TcxGridDBColumn; dxBarManager1: TdxBarManager; AddButton: TdxBarLargeButton; UpdateButton: TdxBarLargeButton; DelButton: TdxBarLargeButton; ChooseButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; CloseButton: TdxBarLargeButton; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; cxStyle31: TcxStyle; cxStyle32: TcxStyle; cxStyle33: TcxStyle; cxStyle34: TcxStyle; cxStyle35: TcxStyle; cxStyle36: TcxStyle; cxStyle37: TcxStyle; cxStyle38: TcxStyle; cxStyle39: TcxStyle; cxStyle40: TcxStyle; cxStyle41: TcxStyle; cxStyle42: TcxStyle; TreeListStyleSheetDevExpress: TcxTreeListStyleSheet; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxGridDBTableView1DBColumn2: TcxGridDBColumn; cxGridDBTableView1DBColumn3: TcxGridDBColumn; cxGridDBTableView1DBColumn4: TcxGridDBColumn; procedure ExitButtonClick(Sender: TObject); procedure DelButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DBGridDblClick(Sender: TObject); procedure ActionModExecute(Sender: TObject); procedure ActionDelExecute(Sender: TObject); procedure ActionAddExecute(Sender: TObject); procedure ActionSelExecute(Sender: TObject); procedure N1Click(Sender: TObject); procedure N2Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure N5Click(Sender: TObject); procedure N6Click(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure UpdateButtonClick(Sender: TObject); procedure ChooseButtonClick(Sender: TObject); public CurFS:TFormStyle; ActualDate:TdateTime; ResultValue:Variant; procedure DeleteRecord; procedure AddRecord; procedure ModRecord; constructor Create(AOwner:TComponent;DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle; ActualDate:TDateTime);overload; end; function GetIniAcc(AOwner : TComponent; DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle;ActualDate:TDateTime):Variant;stdcall; exports GetIniAcc; implementation uses ini_type_account_FORM_ADD, sys_options, BaseTypes; {$R *.DFM} function GetIniAcc(AOwner : TComponent; DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle;ActualDate:TDateTime):Variant;stdcall; var T:TFini_type_account; Res:Variant; begin If FS=fsNormal then begin T:=TFini_type_account.Create(AOwner, DBHANDLE,FS,ActualDate); if T.ShowModal=mrYes then begin Res:=T.ResultValue; end; T.Free; end else begin T:=TFini_type_account.Create(AOwner, DBHANDLE,FS,ActualDate); Res:=NULL; end; GetIniAcc:=Res; end; procedure TFini_type_account.ExitButtonClick(Sender: TObject); begin if FormStyle = fsMDIChild then Close else ModalResult := mrCancel; end; procedure TFini_type_account.DelButtonClick(Sender: TObject); begin DeleteRecord; end; procedure TFini_type_account.DeleteRecord; var PK_Index : integer; selected_id : integer; begin if DataSet.RecordCount = 0 then exit; PK_Index := DataSet.FieldByName(PK_FIELD).AsInteger; if agMessageDlg('Увага!', DELETE_QUESTION, mtWarning, [mbYes, mbNo]) = mrNo then exit; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure(DEL_PROC, [PK_Index]); StoredProc.Transaction.Commit; DataSet.CloseOpen(true); selected_id := cxGridDBTableView1.Controller.FocusedRowIndex; dataset.CloseOpen(true); cxGridDBTableView1.Controller.FocusedRowIndex := selected_id; end; procedure TFini_type_account.AddButtonClick(Sender: TObject); begin AddRecord; end; procedure TFini_type_account.AddRecord; var PK_Index : integer; Fini_type_account_ADD : TFini_type_account_ADD; is_bank_acc, is_val_acc, no_acc : integer; begin Fini_type_account_ADD := TFini_type_account_ADD.Create(Self); Fini_type_account_ADD.Caption := 'Новий тип рахунка'; Fini_type_account_ADD.OKButton.Caption := 'Додати'; Fini_type_account_ADD.ShowModal; if Fini_type_account_ADD.MResult = 'cancel' then exit; is_bank_acc := 0; is_val_acc := 0; no_acc := 0; if Fini_type_account_ADD.isBankAccCheck.Checked then is_bank_acc := 1; if Fini_type_account_ADD.cbVal.Checked then is_val_acc := 1; if Fini_type_account_ADD.NoAccCheck.Checked then no_acc := 1; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure(ADD_PROC, [Fini_type_account_ADD.NameEdit.Text, is_bank_acc, is_val_acc, no_acc]); PK_Index:=StoredProc.ParamByName('OUT_ID_TYPE_ACCOUNT').AsInteger; StoredProc.Transaction.Commit; dataset.CloseOpen(true); DataSet.Locate('ID_TYPE_ACCOUNT', PK_Index, [loCaseInsensitive]); Fini_type_account_ADD.Free; end; procedure TFini_type_account.ModRecord; var PK_Index : integer; Fini_type_account_ADD : TFini_type_account_ADD; is_bank_acc, is_val_acc, no_acc : integer; begin if DataSet.RecordCount = 0 then exit; Fini_type_account_ADD := TFini_type_account_ADD.Create(Self); Fini_type_account_ADD.Caption := 'Змінити інформацію'; Fini_type_account_ADD.OKButton.Caption := 'Змінити'; Fini_type_account_ADD.NameEdit.Text := DataSet.FieldByName('NAME_TYPE_ACCOUNT').AsString; if not VarIsNull(DataSet['IS_BANK_ACCOUNT']) then Fini_type_account_ADD.isBankAccCheck.Checked := DataSet.FieldByName('IS_BANK_ACCOUNT').AsInteger = 1; if not VarIsNull(DataSet['IS_VAL_ACCOUNT']) then Fini_type_account_ADD.cbVal.Checked := DataSet.FieldByName('IS_VAL_ACCOUNT').AsInteger = 1; if not VarIsNull(DataSet['IS_NO_ACCOUNT']) then Fini_type_account_ADD.NoAccCheck.Checked := DataSet.FieldByName('IS_NO_ACCOUNT').AsInteger = 1; PK_Index := DataSet.FieldByName(PK_FIELD).AsInteger; Fini_type_account_ADD.ShowModal; if Fini_type_account_ADD.MResult = 'cancel' then exit; is_bank_acc := 0; if Fini_type_account_ADD.isBankAccCheck.Checked then is_bank_acc := 1; is_val_acc := 0; no_acc := 0; if Fini_type_account_ADD.cbVal.Checked then is_val_acc := 1; if Fini_type_account_ADD.NoAccCheck.Checked then no_acc := 1; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure(MOD_PROC, [PK_Index, Fini_type_account_ADD.NameEdit.Text, is_bank_acc, is_val_acc, no_Acc]); StoredProc.Transaction.Commit; dataset.CloseOpen(true); DataSet.Locate('ID_TYPE_ACCOUNT', PK_Index, [loCaseInsensitive]); Fini_type_account_ADD.Free; end; procedure TFini_type_account.EditButtonClick(Sender: TObject); begin ModRecord; end; procedure TFini_type_account.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFini_type_account.DBGridDblClick(Sender: TObject); begin if (ChooseButton.Enabled) and (ivAlways = ChooseButton.Visible) then begin ChooseButton.OnClick(self); end; end; procedure TFini_type_account.ActionModExecute(Sender: TObject); begin ModRecord; end; procedure TFini_type_account.ActionDelExecute(Sender: TObject); begin DeleteRecord; end; procedure TFini_type_account.ActionAddExecute(Sender: TObject); begin AddRecord; end; procedure TFini_type_account.ActionSelExecute(Sender: TObject); begin if (ChooseButton.Enabled) and (ivAlways = ChooseButton.Visible) then begin ChooseButton.OnClick(self); end; end; procedure TFini_type_account.N1Click(Sender: TObject); begin AddRecord; end; procedure TFini_type_account.N2Click(Sender: TObject); begin ModRecord; end; procedure TFini_type_account.N3Click(Sender: TObject); begin DeleteRecord; end; procedure TFini_type_account.N5Click(Sender: TObject); begin RefreshButtonClick(Self); end; procedure TFini_type_account.N6Click(Sender: TObject); begin if (ChooseButton.Enabled) and (ivAlways = ChooseButton.Visible) then begin ChooseButton.OnClick(self); end; end; procedure TFini_type_account.RefreshButtonClick(Sender: TObject); var selected_id : integer; begin if DataSet.RecordCount = 0 then begin dataset.CloseOpen(true); exit; end; selected_id := DataSet.FieldByName(PK_FIELD).AsInteger; dataset.CloseOpen(true); DataSet.Locate('ID_TYPE_ACCOUNT', selected_id, [loCaseInsensitive]); end; procedure TFini_type_account.cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then if ChooseButton.Enabled then ChooseButtonClick(Self); if Key = #27 then Close; end; constructor TFini_type_account.Create(AOwner: TComponent; DBHANDLE: TISC_DB_HANDLE; FS: TFormStyle; ActualDate: TDateTime); begin inherited Create(AOwner); Self.WorkDatabase.Handle:=DBHAndle; self.ActualDate:=ActualDate; CurFS:=FS; DataSet.SQLs.SelectSQL.Text := 'select * from ' + SEL_VIEW; self.FormStyle:=FS; if FS=fsNormal then ChooseButton.Enabled:=true; end; procedure TFini_type_account.FormShow(Sender: TObject); begin dataset.Open; end; procedure TFini_type_account.UpdateButtonClick(Sender: TObject); begin ActionMod.Execute; end; procedure TFini_type_account.ChooseButtonClick(Sender: TObject); begin if DataSet.Active and (DataSet.RecordCount>0) then begin ResultValue:=VarArrayCreate([0,4],varVariant); ResultValue[0]:=DataSet.fieldByName('ID_TYPE_ACCOUNT').Value; ResultValue[1]:=DataSet.fieldByName('NAME_TYPE_ACCOUNT').Value; ResultValue[2]:=DataSet.fieldByName('IS_BANK_ACCOUNT').Value; ResultValue[3]:=DataSet.fieldByName('IS_VAL_ACCOUNT').Value; ResultValue[4]:=DataSet.fieldByName('IS_NO_ACCOUNT').Value; Modalresult:=mrYes; end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure Translate; end; var Form1: TForm1; implementation {$R *.dfm} uses NtBase, NtResource, NtResourceEx, NtTranslatorEx; procedure TForm1.Translate; begin _T(Self); Label2.Caption := _T('Hello'); Label3.Caption := _T('This is a sample', 'Unit1'); Label4.Caption := _T('Another group', 'Str1', 'Another'); Label5.Caption := _T('Another group', 'Str2', 'Another'); Label6.Caption := Format(_T('Hello %s'), ['John']); end; procedure TForm1.FormCreate(Sender: TObject); begin if ParamCount > 0 then NtResources.LanguageId := ParamStr(1); Translate; end; procedure TForm1.Button1Click(Sender: TObject); begin NtResources.LanguageId := 'fi'; Translate; end; initialization DefaultLocale := 'en'; end.
unit guiRecipeDetails; interface uses SysUtils, Forms, Dialogs, siComp, siLngLnk, Data.DB, Vcl.Controls, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, System.Classes, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids; type TFormRecipeDetails = class(TForm) pnlHead: TPanel; pnlDetail: TPanel; pnlFoot: TPanel; DBNavigator1: TDBNavigator; dsRecipeDetails: TDataSource; dsPositions: TDataSource; dblcbPosizioneName: TDBLookupComboBox; dblcbPosizioneDscr: TDBLookupComboBox; Label1: TLabel; dsDropTypes: TDataSource; Label2: TLabel; dblcbDrop: TDBLookupComboBox; dblcbPickup: TDBLookupComboBox; Label3: TLabel; dblcbRinsing: TDBLookupComboBox; Label4: TLabel; Label5: TLabel; dbeRINSINGCOUNT: TDBEdit; dsPickupTypes: TDataSource; dsRinsingTypes: TDataSource; Label6: TLabel; dbeTBAGNO: TDBEdit; dbcbPRIORITA: TDBComboBox; Label7: TLabel; DBNavigator2: TDBNavigator; btnRenum: TButton; btnDropTypes: TButton; btnPickupTypes: TButton; btnRinsingTypes: TButton; Label8: TLabel; Label9: TLabel; dbeSPRUZZO: TDBEdit; dbePAUSACONTROLLO: TDBEdit; siLangLinked1: TsiLangLinked; dsGalvRecipes: TDataSource; lblGalvanica: TLabel; dblcbGalvanica: TDBLookupComboBox; dbgDetails: TDBGrid; btnPositions: TButton; lblNewRecipe: TLabel; editNewRecipeID: TEdit; lblCopyFromID: TLabel; EditCopyFromID: TEdit; btnNewRecipe: TButton; btnGalvanica: TButton; DBCheckBox1: TDBCheckBox; DBCheckBox2: TDBCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cdsRecipeDetailsNewRecord(DataSet: TDataSet); procedure btnPositionsClick(Sender: TObject); procedure Label1DblClick(Sender: TObject); procedure Label2DblClick(Sender: TObject); procedure Label3DblClick(Sender: TObject); procedure Label4DblClick(Sender: TObject); procedure btnRenumClick(Sender: TObject); procedure btnDropTypesClick(Sender: TObject); procedure btnPickupTypesClick(Sender: TObject); procedure btnRinsingTypesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnNewRecipeClick(Sender: TObject); procedure btnGalvanicaClick(Sender: TObject); private _RecipeID, _lastStep: integer; _prelDepoRins: boolean; procedure saveData; public details_ELERECIPEID , details_OXIVOLTSETPOINTX10 , details_OXIAMPSETPOINT , details_OXIDENSITYSETPOINTX100 , details_OXIMICRONSETPOINTX10 , details_OXISECONDSSETPOINT: integer; procedure setup(pRecipeID: integer; pRecipeName, pRecipeDSCR: string); end; var FormRecipeDetails: TFormRecipeDetails; implementation uses guiRecipes, guiTblPositions, uEtcXE, dbiRecipes, guiGalvRecipes, dbiPickupDropRins, guiDropTypes, guiPickupTypes, guiRinsingTypes; {$R *.dfm} { TFormRecipeDetails } procedure TFormRecipeDetails.setup(pRecipeID: integer; pRecipeName, pRecipeDSCR: string); begin _RecipeID := pRecipeID; caption := format('R e c i p e D e t a i l s : %d) %s - %s', [pRecipeID, pRecipeName, pRecipeDSCR]); end; procedure TFormRecipeDetails.btnDropTypesClick(Sender: TObject); begin FormDropTypes.show end; procedure TFormRecipeDetails.btnGalvanicaClick(Sender: TObject); begin FormGalvRecipes.showModal end; procedure TFormRecipeDetails.btnNewRecipeClick(Sender: TObject); var newID, copyFromID: integer; sNewName: string; tblName: string; begin saveData; newID := strToIntDef(editNewRecipeID.Text, 0); editNewRecipeID.Text := intToStr(newID); // verifica NON esistenza di newID e che sia > 0 if newID <= 0 then begin showMessage('you can only use positive integers for NEW type ID'); exit end; if dmRecipes.stepExists(_RecipeID, newID) then begin showMessage(format('NEW step %d already exists.', [newID])); exit end; copyFromID := strToIntDef(EditCopyFromID .Text, 0); EditCopyFromID .Text := intToStr(copyFromID); // verifica esistenza di copyFromID se e solo se è > 0 if (copyFromID > 0) and (not dmRecipes.stepExists(_RecipeID, copyFromID)) then begin showMessage(format('"copy from" type %d does not exist.', [copyFromID])); exit end; // se l'utente conferma ... facciamo un paio di query di inserimento ... if (copyFromID > 0) then begin if messageDlg(format('Confirm copying existing type %d to NEW type %d ?', [copyFromID, newID]), mtConfirmation, [mbOK, mbCancel], 0) <> mrOK then exit; sNewName := siLangLinked1.GetTextOrDefault('IDS_6' (* 'copy of' *) ) + intToStr(copyFromID); end else begin if messageDlg(format('Confirm creating a new EMPTY step at %d ?', [newID]), mtConfirmation, [mbOK, mbCancel], 0) <> mrOK then exit; sNewName := 'new type'; end; if copyFromID = 0 then begin dmRecipes.buildNewEmptyStep(_RecipeID, newID, sNewName); exit; // bona lè end; // duplica dmRecipes.copyStepFromTo(_RecipeID, copyFromID, newID); // preparo di dettagli della new recipe end; procedure TFormRecipeDetails.btnPickupTypesClick(Sender: TObject); begin FormPickupTypes.Show end; procedure TFormRecipeDetails.btnPositionsClick(Sender: TObject); begin FormTblPositions.show end; procedure TFormRecipeDetails.btnRenumClick(Sender: TObject); var i: integer; begin i := 0; with dmRecipes.tblRecipeSteps do try disableControls; first; if EOF then exit; while not EOF do Begin edit; fieldByName('ID').AsInteger := i; inc(i); post; next; End; i := i * 10; _lastStep := i; last; while i > 0 do Begin if locate('ID', (i div 10 - 1), []) then begin edit; fieldByName('ID').AsInteger := i; dec(i, 10); post; end else showMessage('can''t locate for ' + intToStr(i)); End; finally enableControls end; saveData; end; procedure TFormRecipeDetails.btnRinsingTypesClick(Sender: TObject); begin FormRinsingTypes.show end; procedure TFormRecipeDetails.cdsRecipeDetailsNewRecord(DataSet: TDataSet); begin with dataSet do begin fieldByName('IDRICETTA').AsInteger := _RecipeID; inc(_lastStep, 10); fieldByName('ID').AsInteger := _lastStep; end; end; procedure TFormRecipeDetails.FormClose(Sender: TObject; var Action: TCloseAction); begin saveData; end; procedure TFormRecipeDetails.FormCreate(Sender: TObject); begin _prelDepoRins := puntoIni.ReadBool('config', 'prelDepoRins' , true); btnDropTypes .Visible := _prelDepoRins; btnPickupTypes .Visible := _prelDepoRins; btnRinsingTypes.Visible := _prelDepoRins; end; procedure TFormRecipeDetails.Label1DblClick(Sender: TObject); begin FormTblPositions.show end; procedure TFormRecipeDetails.Label2DblClick(Sender: TObject); begin // FormTblTIPIDROP_07.show end; procedure TFormRecipeDetails.Label3DblClick(Sender: TObject); begin // FormTblTIPIPICK_07.Show end; procedure TFormRecipeDetails.Label4DblClick(Sender: TObject); begin // FormTblTIPIRINS_07.show end; procedure TFormRecipeDetails.saveData; begin dmRecipes.tblRecipeSteps.checkBrowseMode; end; end. { d.IDRICETTA, d.ID, d.POSIZIONE, d.TBAGNO, d.PRIORITA, d.IDPRELIEVO, d.IDDEPOSITO, d.RINSINGID, d.RINSINGCOUNT, d.SPRUZZO, d.PAUSACONTROLLO, p.ID POS_ID, p.NAME POS_NAME, p.DSCR POS_DSCR, p.MM POS_MM, p.ALIAS POS_ALIAS, p.ISOXI POS_ISOXI, p.ISELE POS_ISELE, p.ISELE2 POS_ISELE2, p.ISPAUSE POS_ISPAUSE, p.HASDEVICE POS_HASDEVICE, p.ISCOLOR POS_ISCOLOR, PATH ==== C:\Programmi\SIEMENS\SIMATIC.NCM\s7bin; C:\Programmi\File comuni\Siemens\ACE\Bin; e:\RailsInstaller\Git\cmd; e:\RailsInstaller\Ruby1.9.2\bin; C:\Programmi\Rockwell Software\RSCommon; C:\Programmi\CollabNet\Subversion Client; C:\Programmi\Embarcadero\RAD Studio\8.0\bin; C:\Documents and Settings\All Users\Documenti\RAD Studio\8.0\Bpl; C:\Programmi\CodeGear\RAD Studio\5.0\bin; C:\Documents and Settings\All Users\Documenti\RAD Studio\5.0\Bpl; %SystemRoot%\system32; %SystemRoot%; %SystemRoot%\System32\Wbem; C:\Programmi\CodeGear\RAD Studio\5.0\lib\SDL\R5; C:\Programmi\wkhtmltopdf; C:\Programmi\Git\cmd; C:\Programmi\Rockwell Automation\Common\Components; C:\Documents and Settings\biol\Dati applicazioni\npm; C:\Programmi\nodejs\ }
unit unit1; { This is a little example about particles system. Here we use the Direction property of the TGLSphere like a motion vector for the movement. ***************************************************************** * * * .---. .----------- L.I. CARLOS GARCÍA TRUJILLO * * / \ __ / ------ * * / / \( )/ ----- * * ////// ' \/ ` --- Email: * * //// / // : : --- cgar1136@yahoo.com * * // / / /` '-- ICQ: * * // //..\\ 26256096 * * ===UU====UU==== * * '//||\\` WEB: * * ''`` http://www.geocities.com/cgar1136/ * * * ***************************************************************** } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, //GLS GLScene, GLObjects, GLParticles, GLWin32Viewer, GLCadencer, GLBehaviours, GLVectorTypes, GLVectorGeometry, GLCoordinates, GLCrossPlatform, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; Fountain: TGLParticles; Sphere1: TGLSphere; GLCadencer1: TGLCadencer; DummyCube1: TGLDummyCube; Button1: TButton; GLLightSource1: TGLLightSource; Plane1: TGLPlane; procedure FormCreate(Sender: TObject); procedure Sphere1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Button1Click(Sender: TObject); procedure FormResize(Sender: TObject); private public end; const DROP_COUNT = 800; // How many drops we wish... var motion: array [0 .. DROP_COUNT] of TVector4f; Form1: TForm1; mdx, mdy: Integer; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var i: word; begin Randomize; for i := 0 to DROP_COUNT - 1 do with TGLSphere(Fountain.CreateParticle) do begin Position.SetPoint(0, 0, 0); // a initial position at origin MakeVector(motion[i], (Random - 0.5) / 20, (Random / 5) + 0.01, (Random - 0.5) / 20); Tag := i; end; end; procedure TForm1.Sphere1Progress(Sender: TObject; const deltaTime, newTime: Double); begin with TGLSphere(Sender) do begin Translate(motion[TGLSphere(Sender).Tag].X, motion[TGLSphere(Sender).Tag].Y, motion[TGLSphere(Sender).Tag].Z); // translate(Direction.X,Direction.Y,Direction.Z); //Translating the particle, by the motion vector. If (Position.Y < 0) then begin Position.setpoint(0, 0, 0); // Reset the particle's position makevector(motion[TGLSphere(Sender).Tag], (Random - 0.5) / 20, (Random / 5) + 0.01, (Random - 0.5) / 20); end else motion[TGLSphere(Sender).Tag].Y := motion[TGLSphere(Sender).Tag].Y - 0.01; end; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mdx := X; mdy := Y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin If Shift <> [] then GLCamera1.MoveAroundTarget(mdy - Y, mdx - X); mdx := X; mdy := Y; end; procedure TForm1.Button1Click(Sender: TObject); var i: Integer; begin For i := 0 to Fountain.count - 1 do // Reseting the with TGLSphere(Fountain.Children[i]) do // particle system begin Position.SetPoint(0, -0.5, 0); makevector(motion[i], (Random - 0.5) / 20, (Random / 7) + 0.01, (Random - 0.5) / 20); end; end; procedure TForm1.FormResize(Sender: TObject); begin GLCamera1.FocalLength := 50 * Width / 350; end; end.
unit uFrmSelectRebateCalendar; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, Mask, SuperComboADO; type TFrmSelectRebateCalendar = class(TFrmParentAll) lblCalendar: TLabel; scRebateCalendar: TSuperComboADO; btOk: TButton; procedure btOkClick(Sender: TObject); private FIDRebateCalendar: Integer; FDescription: String; FDiscountPerc: Double; FStartDate: TDateTime; FEndDate: TDateTime; public function Start: Boolean; property IDRebateCalendar: Integer read FIDRebateCalendar write FIDRebateCalendar; property Description: String read FDescription write FDescription; property DiscountPerc: Double read FDiscountPerc write FDiscountPerc; property StartDate: TDateTime read FStartDate write FStartDate; property EndDate: TDateTime read FEndDate write FEndDate; end; implementation uses uDM, uMsgBox, uMsgConstant; {$R *.dfm} { TFrmSelectRebateCalendar } function TFrmSelectRebateCalendar.Start: Boolean; begin FIDRebateCalendar := -1; ShowModal; with scRebateCalendar do if ModalResult = mrOk then begin FIDRebateCalendar := StrToInt(LookUpValue); FDescription := GetFieldByName('Description'); FDiscountPerc := GetFieldByName('DiscountPerc'); FStartDate := GetFieldByName('StartDate'); FEndDate := GetFieldByName('EndDate'); end; end; procedure TFrmSelectRebateCalendar.btOkClick(Sender: TObject); begin inherited; if scRebateCalendar.LookUpValue = '' then begin MsgBox(MSG_CRT_NO_VALID_SELECTION, vbInformation + vbOKOnly); ModalResult := mrNone; end; end; end.
unit MyCat.BackEnd.Generics.BackEndConnection; interface uses System.SysUtils, MyCat.BackEnd.Interfaces; {$I DGLCfg.inc_h} type _ValueType = IBackEndConnection; const _NULL_Value: _ValueType = nil; {$DEFINE _DGL_NotHashFunction} {$DEFINE _DGL_Compare} function _IsEqual(const a, b: _ValueType): boolean; // {$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b); function _IsLess(const a, b: _ValueType): boolean; {$IFDEF _DGL_Inline} inline; {$ENDIF} // result:=(a<b); 默认排序准则 {$I DGL.inc_h} type TBackEndConnectionAlgorithms = _TAlgorithms; IBackEndConnectionIterator = _IIterator; IBackEndConnectionContainer = _IContainer; IBackEndConnectionSerialContainer = _ISerialContainer; IBackEndConnectionVector = _IVector; IBackEndConnectionList = _IList; IBackEndConnectionDeque = _IDeque; IBackEndConnectionStack = _IStack; IBackEndConnectionQueue = _IQueue; IBackEndConnectionPriorityQueue = _IPriorityQueue; IBackEndConnectionSet = _ISet; IBackEndConnectionMultiSet = _IMultiSet; TBackEndConnectionVector = _TVector; TBackEndConnectionDeque = _TDeque; TBackEndConnectionList = _TList; IBackEndConnectionVectorIterator = _IVectorIterator; // 速度比_IIterator稍快一点:) IBackEndConnectionDequeIterator = _IDequeIterator; // 速度比_IIterator稍快一点:) IBackEndConnectionListIterator = _IListIterator; // 速度比_IIterator稍快一点:) TBackEndConnectionStack = _TStack; TBackEndConnectionQueue = _TQueue; TBackEndConnectionPriorityQueue = _TPriorityQueue; IBackEndConnectionMapIterator = _IMapIterator; IBackEndConnectionMap = _IMap; IBackEndConnectionMultiMap = _IMultiMap; TBackEndConnectionSet = _TSet; TBackEndConnectionMultiSet = _TMultiSet; TBackEndConnectionMap = _TMap; TBackEndConnectionMultiMap = _TMultiMap; TBackEndConnectionHashSet = _THashSet; TBackEndConnectionHashMultiSet = _THashMultiSet; TBackEndConnectionHashMap = _THashMap; TBackEndConnectionHashMultiMap = _THashMultiMap; implementation uses HashFunctions; function _IsEqual(const a, b: _ValueType): boolean; begin result := (a = b); end; function _IsLess(const a, b: _ValueType): boolean; begin result := (Cardinal(a) < Cardinal(b)); end; {$I DGL.inc_pas} end.
unit GLD3dsChunk; interface uses Classes, GL, GLD3dsTypes; const GLD3DS_NULL_CHUNK = $0000; GLD3DS_M3DMAGIC = $4D4D; GLD3DS_SMAGIC = $2D2D; GLD3DS_LMAGIC = $2D3D; GLD3DS_MLIBMAGIC = $3DAA; GLD3DS_MATMAGIC = $3DFF; GLD3DS_CMAGIC = $C23D; GLD3DS_M3D_VERSION = $0002; GLD3DS_M3D_KFVERSION = $0005; GLD3DS_COLOR_F = $0010; GLD3DS_COLOR_24 = $0011; GLD3DS_LIN_COLOR_24 = $0012; GLD3DS_LIN_COLOR_F = $0013; GLD3DS_INT_PERCENTAGE = $0030; GLD3DS_FLOAT_PERCENTAGE = $0031; GLD3DS_MDATA = $3D3D; GLD3DS_MESH_VERSION = $3D3E; GLD3DS_MASTER_SCALE = $0100; GLD3DS_LO_SHADOW_BIAS = $1400; GLD3DS_HI_SHADOW_BIAS = $1410; GLD3DS_SHADOW_MAP_SIZE = $1420; GLD3DS_SHADOW_SAMPLES = $1430; GLD3DS_SHADOW_RANGE = $1440; GLD3DS_SHADOW_FILTER = $1450; GLD3DS_RAY_BIAS = $1460; GLD3DS_O_CONSTS = $1500; GLD3DS_AMBIENT_LIGHT = $2100; GLD3DS_BIT_MAP = $1100; GLD3DS_SOLID_BGND = $1200; GLD3DS_V_GRADIENT = $1300; GLD3DS_USE_BIT_MAP = $1101; GLD3DS_USE_SOLID_BGND = $1201; GLD3DS_USE_V_GRADIENT = $1301; GLD3DS_FOG = $2200; GLD3DS_FOG_BGND = $2210; GLD3DS_LAYER_FOG = $2302; GLD3DS_DISTANCE_CUE = $2300; GLD3DS_DCUE_BGND = $2310; GLD3DS_USE_FOG = $2201; GLD3DS_USE_LAYER_FOG = $2303; GLD3DS_USE_DISTANCE_CUE = $2301; GLD3DS_MAT_ENTRY = $AFFF; GLD3DS_MAT_NAME = $A000; GLD3DS_MAT_AMBIENT = $A010; GLD3DS_MAT_DIFFUSE = $A020; GLD3DS_MAT_SPECULAR = $A030; GLD3DS_MAT_SHININESS = $A040; GLD3DS_MAT_SHIN2PCT = $A041; GLD3DS_MAT_TRANSPARENCY = $A050; GLD3DS_MAT_XPFALL = $A052; GLD3DS_MAT_USE_XPFALL = $A240; GLD3DS_MAT_REFBLUR = $A053; GLD3DS_MAT_SHADING = $A100; GLD3DS_MAT_USE_REFBLUR = $A250; GLD3DS_MAT_BUMP_PERCENT = $A252; GLD3DS_MAT_SELF_ILLUM = $A080; GLD3DS_MAT_TWO_SIDE = $A081; GLD3DS_MAT_DECAL = $A082; GLD3DS_MAT_ADDITIVE = $A083; GLD3DS_MAT_SELF_ILPCT = $A084; GLD3DS_MAT_WIRE = $A085; GLD3DS_MAT_FACEMAP = $A088; GLD3DS_MAT_XPFALLIN = $A08A; GLD3DS_MAT_PHONGSOFT = $A08C; GLD3DS_MAT_WIREABS = $A08E; GLD3DS_MAT_WIRE_SIZE = $A087; GLD3DS_MAT_TEXMAP = $A200; GLD3DS_MAT_SXP_TEXT_DATA = $A320; GLD3DS_MAT_TEXMASK = $A33E; GLD3DS_MAT_SXP_TEXTMASK_DATA = $A32A; GLD3DS_MAT_TEX2MAP = $A33A; GLD3DS_MAT_SXP_TEXT2_DATA = $A321; GLD3DS_MAT_TEX2MASK = $A340; GLD3DS_MAT_SXP_TEXT2MASK_DATA = $A32C; GLD3DS_MAT_OPACMAP = $A210; GLD3DS_MAT_SXP_OPAC_DATA = $A322; GLD3DS_MAT_OPACMASK = $A342; GLD3DS_MAT_SXP_OPACMASK_DATA = $A32E; GLD3DS_MAT_BUMPMAP = $A230; GLD3DS_MAT_SXP_BUMP_DATA = $A324; GLD3DS_MAT_BUMPMASK = $A344; GLD3DS_MAT_SXP_BUMPMASK_DATA = $A330; GLD3DS_MAT_SPECMAP = $A204; GLD3DS_MAT_SXP_SPEC_DATA = $A325; GLD3DS_MAT_SPECMASK = $A348; GLD3DS_MAT_SXP_SPECMASK_DATA = $A332; GLD3DS_MAT_SHINMAP = $A33C; GLD3DS_MAT_SXP_SHIN_DATA = $A326; GLD3DS_MAT_SHINMASK = $A346; GLD3DS_MAT_SXP_SHINMASK_DATA = $A334; GLD3DS_MAT_SELFIMAP = $A33D; GLD3DS_MAT_SXP_SELFI_DATA = $A328; GLD3DS_MAT_SELFIMASK = $A34A; GLD3DS_MAT_SXP_SELFIMASK_DATA = $A336; GLD3DS_MAT_REFLMAP = $A220; GLD3DS_MAT_REFLMASK = $A34C; GLD3DS_MAT_SXP_REFLMASK_DATA = $A338; GLD3DS_MAT_ACUBIC = $A310; GLD3DS_MAT_MAPNAME = $A300; GLD3DS_MAT_MAP_TILING = $A351; GLD3DS_MAT_MAP_TEXBLUR = $A353; GLD3DS_MAT_MAP_USCALE = $A354; GLD3DS_MAT_MAP_VSCALE = $A356; GLD3DS_MAT_MAP_UOFFSET = $A358; GLD3DS_MAT_MAP_VOFFSET = $A35A; GLD3DS_MAT_MAP_ANG = $A35C; GLD3DS_MAT_MAP_COL1 = $A360; GLD3DS_MAT_MAP_COL2 = $A362; GLD3DS_MAT_MAP_RCOL = $A364; GLD3DS_MAT_MAP_GCOL = $A366; GLD3DS_MAT_MAP_BCOL = $A368; GLD3DS_NAMED_OBJECT = $4000; GLD3DS_N_DIRECT_LIGHT = $4600; GLD3DS_DL_OFF = $4620; GLD3DS_DL_OUTER_RANGE = $465A; GLD3DS_DL_INNER_RANGE = $4659; GLD3DS_DL_MULTIPLIER = $465B; GLD3DS_DL_EXCLUDE = $4654; GLD3DS_DL_ATTENUATE = $4625; GLD3DS_DL_SPOTLIGHT = $4610; GLD3DS_DL_SPOT_ROLL = $4656; GLD3DS_DL_SHADOWED = $4630; GLD3DS_DL_LOCAL_SHADOW2 = $4641; GLD3DS_DL_SEE_CONE = $4650; GLD3DS_DL_SPOT_RECTANGULAR = $4651; GLD3DS_DL_SPOT_ASPECT = $4657; GLD3DS_DL_SPOT_PROJECTOR = $4653; GLD3DS_DL_SPOT_OVERSHOOT = $4652; GLD3DS_DL_RAY_BIAS = $4658; GLD3DS_DL_RAYSHAD = $4627; GLD3DS_N_CAMERA = $4700; GLD3DS_CAM_SEE_CONE = $4710; GLD3DS_CAM_RANGES = $4720; GLD3DS_OBJ_HIDDEN = $4010; GLD3DS_OBJ_VIS_LOFTER = $4011; GLD3DS_OBJ_DOESNT_CAST = $4012; GLD3DS_OBJ_DONT_RECVSHADOW = $4017; GLD3DS_OBJ_MATTE = $4013; GLD3DS_OBJ_FAST = $4014; GLD3DS_OBJ_PROCEDURAL = $4015; GLD3DS_OBJ_FROZEN = $4016; GLD3DS_N_TRI_OBJECT = $4100; GLD3DS_POINT_ARRAY = $4110; GLD3DS_POINT_FLAG_ARRAY = $4111; GLD3DS_FACE_ARRAY = $4120; GLD3DS_MSH_MAT_GROUP = $4130; GLD3DS_SMOOTH_GROUP = $4150; GLD3DS_MSH_BOXMAP = $4190; GLD3DS_TEX_VERTS = $4140; GLD3DS_MESH_MATRIX = $4160; GLD3DS_MESH_COLOR = $4165; GLD3DS_MESH_TEXTURE_INFO = $4170; GLD3DS_KFDATA = $B000; GLD3DS_KFHDR = $B00A; GLD3DS_KFSEG = $B008; GLD3DS_KFCURTIME = $B009; GLD3DS_AMBIENT_NODE_TAG = $B001; GLD3DS_OBJECT_NODE_TAG = $B002; GLD3DS_CAMERA_NODE_TAG = $B003; GLD3DS_TARGET_NODE_TAG = $B004; GLD3DS_LIGHT_NODE_TAG = $B005; GLD3DS_L_TARGET_NODE_TAG = $B006; GLD3DS_SPOTLIGHT_NODE_TAG = $B007; GLD3DS_NODE_ID = $B030; GLD3DS_NODE_HDR = $B010; GLD3DS_PIVOT = $B013; GLD3DS_INSTANCE_NAME = $B011; GLD3DS_MORPH_SMOOTH = $B015; GLD3DS_BOUNDBOX = $B014; GLD3DS_POS_TRACK_TAG = $B020; GLD3DS_COL_TRACK_TAG = $B025; GLD3DS_ROT_TRACK_TAG = $B021; GLD3DS_SCL_TRACK_TAG = $B022; GLD3DS_MORPH_TRACK_TAG = $B026; GLD3DS_FOV_TRACK_TAG = $B023; GLD3DS_ROLL_TRACK_TAG = $B024; GLD3DS_HOT_TRACK_TAG = $B027; GLD3DS_FALL_TRACK_TAG = $B028; GLD3DS_HIDE_TRACK_TAG = $B029; GLD3DS_POLY_2D = $5000; GLD3DS_SHAPE_OK = $5010; GLD3DS_SHAPE_NOT_OK = $5011; GLD3DS_SHAPE_HOOK = $5020; GLD3DS_PATH_3D = $6000; GLD3DS_PATH_MATRIX = $6005; GLD3DS_SHAPE_2D = $6010; GLD3DS_M_SCALE = $6020; GLD3DS_M_TWIST = $6030; GLD3DS_M_TEETER = $6040; GLD3DS_M_FIT = $6050; GLD3DS_M_BEVEL = $6060; GLD3DS_XZ_CURVE = $6070; GLD3DS_YZ_CURVE = $6080; GLD3DS_INTERPCT = $6090; GLD3DS_DEFORM_LIMIT = $60A0; GLD3DS_USE_CONTOUR = $6100; GLD3DS_USE_TWEEN = $6110; GLD3DS_USE_SCALE = $6120; GLD3DS_USE_TWIST = $6130; GLD3DS_USE_TEETER = $6140; GLD3DS_USE_FIT = $6150; GLD3DS_USE_BEVEL = $6160; GLD3DS_DEFAULT_VIEW = $3000; GLD3DS_VIEW_TOP = $3010; GLD3DS_VIEW_BOTTOM = $3020; GLD3DS_VIEW_LEFT = $3030; GLD3DS_VIEW_RIGHT = $3040; GLD3DS_VIEW_FRONT = $3050; GLD3DS_VIEW_BACK = $3060; GLD3DS_VIEW_USER = $3070; GLD3DS_VIEW_CAMERA = $3080; GLD3DS_VIEW_WINDOW = $3090; GLD3DS_VIEWPORT_LAYOUT_OLD = $7000; GLD3DS_VIEWPORT_DATA_OLD = $7010; GLD3DS_VIEWPORT_LAYOUT = $7001; GLD3DS_VIEWPORT_DATA = $7011; GLD3DS_VIEWPORT_DATA_3 = $7012; GLD3DS_VIEWPORT_SIZE = $7020; GLD3DS_NETWORK_VIEW = $7030; type TGLD3dsChunkRec = packed record Name: PChar; Chunk: GLushort; end; const GLD3DS_CHUNKS: array[1..218] of TGLD3dsChunkRec = ( (Name: 'GLD3DS_M3DMAGIC'; Chunk: $4D4D), (Name: 'GLD3DS_SMAGIC'; Chunk: $2D2D), (Name: 'GLD3DS_LMAGIC'; Chunk: $2D3D), (Name: 'GLD3DS_MLIBMAGIC'; Chunk: $3DAA), (Name: 'GLD3DS_MATMAGIC'; Chunk: $3DFF), (Name: 'GLD3DS_CMAGIC'; Chunk: $C23D), (Name: 'GLD3DS_M3D_VERSION'; Chunk: $0002), (Name: 'GLD3DS_M3D_KFVERSION'; Chunk: $0005), //8 (Name: 'GLD3DS_COLOR_F'; Chunk: $0010), (Name: 'GLD3DS_COLOR_24'; Chunk: $0011), (Name: 'GLD3DS_LIN_COLOR_24'; Chunk: $0012), (Name: 'GLD3DS_LIN_COLOR_F'; Chunk: $0013), (Name: 'GLD3DS_INT_PERCENTAGE'; Chunk: $0030), (Name: 'GLD3DS_FLOAT_PERCENTAGE'; Chunk: $0031), //14 (Name: 'GLD3DS_MDATA'; Chunk: $3D3D), (Name: 'GLD3DS_MESH_VERSION'; Chunk: $3D3E), (Name: 'GLD3DS_MASTER_SCALE'; Chunk: $0100), (Name: 'GLD3DS_LO_SHADOW_BIAS'; Chunk: $1400), (Name: 'GLD3DS_HI_SHADOW_BIAS'; Chunk: $1410), (Name: 'GLD3DS_SHADOW_MAP_SIZE'; Chunk: $1420), (Name: 'GLD3DS_SHADOW_SAMPLES'; Chunk: $1430), (Name: 'GLD3DS_SHADOW_RANGE'; Chunk: $1440), (Name: 'GLD3DS_SHADOW_FILTER'; Chunk: $1450), (Name: 'GLD3DS_RAY_BIAS'; Chunk: $1460), (Name: 'GLD3DS_O_CONSTS'; Chunk: $1500), (Name: 'GLD3DS_AMBIENT_LIGHT'; Chunk: $2100), (Name: 'GLD3DS_BIT_MAP'; Chunk: $1100), (Name: 'GLD3DS_SOLID_BGND'; Chunk: $1200), (Name: 'GLD3DS_V_GRADIENT'; Chunk: $1300), (Name: 'GLD3DS_USE_BIT_MAP '; Chunk: $1101), (Name: 'GLD3DS_USE_SOLID_BGND'; Chunk: $1201), (Name: 'GLD3DS_USE_V_GRADIENT'; Chunk: $1301), (Name: 'GLD3DS_FOG'; Chunk: $2200), (Name: 'GLD3DS_FOG_BGND'; Chunk: $2210), (Name: 'GLD3DS_LAYER_FOG'; Chunk: $2302), (Name: 'GLD3DS_DISTANCE_CUE'; Chunk: $2300), (Name: 'GLD3DS_DCUE_BGND'; Chunk: $2310), (Name: 'GLD3DS_USE_FOG'; Chunk: $2201), (Name: 'GLD3DS_USE_LAYER_FOG'; Chunk: $2303), (Name: 'GLD3DS_USE_DISTANCE_CUE'; Chunk: $2301), //40 (Name: 'GLD3DS_MAT_ENTRY'; Chunk: $AFFF), (Name: 'GLD3DS_MAT_NAME'; Chunk: $A000), (Name: 'GLD3DS_MAT_AMBIENT'; Chunk: $A010), (Name: 'GLD3DS_MAT_DIFFUSE'; Chunk: $A020), (Name: 'GLD3DS_MAT_SPECULAR'; Chunk: $A030), (Name: 'GLD3DS_MAT_SHININESS'; Chunk: $A040), (Name: 'GLD3DS_MAT_SHIN2PCT'; Chunk: $A041), (Name: 'GLD3DS_MAT_TRANSPARENCY'; Chunk: $A050), (Name: 'GLD3DS_MAT_XPFALL'; Chunk: $A052), (Name: 'GLD3DS_MAT_USE_XPFALL'; Chunk: $A240), (Name: 'GLD3DS_MAT_REFBLUR'; Chunk: $A053), (Name: 'GLD3DS_MAT_SHADING'; Chunk: $A100), (Name: 'GLD3DS_MAT_USE_REFBLUR'; Chunk: $A250), (Name: 'GLD3DS_MAT_BUMP_PERCENT'; Chunk: $A252), (Name: 'GLD3DS_MAT_SELF_ILLUM'; Chunk: $A080), (Name: 'GLD3DS_MAT_TWO_SIDE'; Chunk: $A081), (Name: 'GLD3DS_MAT_DECAL'; Chunk: $A082), (Name: 'GLD3DS_MAT_ADDITIVE'; Chunk: $A083), (Name: 'GLD3DS_MAT_SELF_ILPCT'; Chunk: $A084), (Name: 'GLD3DS_MAT_WIRE'; Chunk: $A085), (Name: 'GLD3DS_MAT_FACEMAP'; Chunk: $A088), (Name: 'GLD3DS_MAT_XPFALLIN'; Chunk: $A08A), (Name: 'GLD3DS_MAT_PHONGSOFT'; Chunk: $A08C), (Name: 'GLD3DS_MAT_WIREABS'; Chunk: $A08E), (Name: 'GLD3DS_MAT_WIRE_SIZE'; Chunk: $A087), (Name: 'GLD3DS_MAT_TEXMAP'; Chunk: $A200), (Name: 'GLD3DS_MAT_SXP_TEXT_DATA'; Chunk: $A320), (Name: 'GLD3DS_MAT_TEXMASK'; Chunk: $A33E), (Name: 'GLD3DS_MAT_SXP_TEXTMASK_DATA'; Chunk: $A32A), (Name: 'GLD3DS_MAT_TEX2MAP'; Chunk: $A33A), (Name: 'GLD3DS_MAT_SXP_TEXT2_DATA'; Chunk: $A321), (Name: 'GLD3DS_MAT_TEX2MASK'; Chunk: $A340), (Name: 'GLD3DS_MAT_SXP_TEXT2MASK_DATA'; Chunk: $A32C), (Name: 'GLD3DS_MAT_OPACMAP'; Chunk: $A210), (Name: 'GLD3DS_MAT_SXP_OPAC_DATA'; Chunk: $A322), (Name: 'GLD3DS_MAT_OPACMASK'; Chunk: $A342), (Name: 'GLD3DS_MAT_SXP_OPACMASK_DATA'; Chunk: $A32E), (Name: 'GLD3DS_MAT_BUMPMAP'; Chunk: $A230), (Name: 'GLD3DS_MAT_SXP_BUMP_DATA'; Chunk: $A324), (Name: 'GLD3DS_MAT_BUMPMASK'; Chunk: $A344), (Name: 'GLD3DS_MAT_SXP_BUMPMASK_DATA'; Chunk: $A330), (Name: 'GLD3DS_MAT_SPECMAP'; Chunk: $A204), (Name: 'GLD3DS_MAT_SXP_SPEC_DATA'; Chunk: $A325), (Name: 'GLD3DS_MAT_SPECMASK'; Chunk: $A348), (Name: 'GLD3DS_MAT_SXP_SPECMASK_DATA'; Chunk: $A332), (Name: 'GLD3DS_MAT_SHINMAP'; Chunk: $A33C), (Name: 'GLD3DS_MAT_SXP_SHIN_DATA'; Chunk: $A326), (Name: 'GLD3DS_MAT_SHINMASK'; Chunk: $A346), (Name: 'GLD3DS_MAT_SXP_SHINMASK_DATA'; Chunk: $A334), (Name: 'GLD3DS_MAT_SELFIMAP'; Chunk: $A33D), (Name: 'GLD3DS_MAT_SXP_SELFI_DATA'; Chunk: $A328), (Name: 'GLD3DS_MAT_SELFIMASK'; Chunk: $A34A), (Name: 'GLD3DS_MAT_SXP_SELFIMASK_DATA'; Chunk: $A336), (Name: 'GLD3DS_MAT_REFLMAP'; Chunk: $A220), (Name: 'GLD3DS_MAT_REFLMASK'; Chunk: $A34C), (Name: 'GLD3DS_MAT_SXP_REFLMASK_DATA'; Chunk: $A338), (Name: 'GLD3DS_MAT_ACUBIC'; Chunk: $A310), (Name: 'GLD3DS_MAT_MAPNAME'; Chunk: $A300), (Name: 'GLD3DS_MAT_MAP_TILING'; Chunk: $A351), (Name: 'GLD3DS_MAT_MAP_TEXBLUR'; Chunk: $A353), (Name: 'GLD3DS_MAT_MAP_USCALE'; Chunk: $A354), (Name: 'GLD3DS_MAT_MAP_VSCALE'; Chunk: $A356), (Name: 'GLD3DS_MAT_MAP_UOFFSET'; Chunk: $A358), (Name: 'GLD3DS_MAT_MAP_VOFFSET'; Chunk: $A35A), (Name: 'GLD3DS_MAT_MAP_ANG'; Chunk: $A35C), (Name: 'GLD3DS_MAT_MAP_COL1'; Chunk: $A360), (Name: 'GLD3DS_MAT_MAP_COL2'; Chunk: $A362), (Name: 'GLD3DS_MAT_MAP_RCOL'; Chunk: $A364), (Name: 'GLD3DS_MAT_MAP_GCOL'; Chunk: $A366), (Name: 'GLD3DS_MAT_MAP_BCOL'; Chunk: $A368), //107 (Name: 'GLD3DS_NAMED_OBJECT'; Chunk: $4000), (Name: 'GLD3DS_N_DIRECT_LIGHT'; Chunk: $4600), (Name: 'GLD3DS_DL_OFF'; Chunk: $4620), (Name: 'GLD3DS_DL_OUTER_RANGE'; Chunk: $465A), (Name: 'GLD3DS_DL_INNER_RANGE'; Chunk: $4659), (Name: 'GLD3DS_DL_MULTIPLIER'; Chunk: $465B), (Name: 'GLD3DS_DL_EXCLUDE'; Chunk: $4654), (Name: 'GLD3DS_DL_ATTENUATE'; Chunk: $4625), (Name: 'GLD3DS_DL_SPOTLIGHT'; Chunk: $4610), (Name: 'GLD3DS_DL_SPOT_ROLL'; Chunk: $4656), (Name: 'GLD3DS_DL_SHADOWED'; Chunk: $4630), (Name: 'GLD3DS_DL_LOCAL_SHADOW2'; Chunk: $4641), (Name: 'GLD3DS_DL_SEE_CONE'; Chunk: $4650), (Name: 'GLD3DS_DL_SPOT_RECTANGULAR'; Chunk: $4651), (Name: 'GLD3DS_DL_SPOT_ASPECT'; Chunk: $4657), (Name: 'GLD3DS_DL_SPOT_PROJECTOR'; Chunk: $4653), (Name: 'GLD3DS_DL_SPOT_OVERSHOOT'; Chunk: $4652), (Name: 'GLD3DS_DL_RAY_BIAS'; Chunk: $4658), (Name: 'GLD3DS_DL_RAYSHAD'; Chunk: $4627), (Name: 'GLD3DS_N_CAMERA'; Chunk: $4700), (Name: 'GLD3DS_CAM_SEE_CONE'; Chunk: $4710), (Name: 'GLD3DS_CAM_RANGES'; Chunk: $4720), (Name: 'GLD3DS_OBJ_HIDDEN'; Chunk: $4010), (Name: 'GLD3DS_OBJ_VIS_LOFTER'; Chunk: $4011), (Name: 'GLD3DS_OBJ_DOESNT_CAST'; Chunk: $4012), (Name: 'GLD3DS_OBJ_DONT_RECVSHADOW'; Chunk: $4017), (Name: 'GLD3DS_OBJ_MATTE'; Chunk: $4013), (Name: 'GLD3DS_OBJ_FAST'; Chunk: $4014), (Name: 'GLD3DS_OBJ_PROCEDURAL'; Chunk: $4015), (Name: 'GLD3DS_OBJ_FROZEN'; Chunk: $4016), (Name: 'GLD3DS_N_TRI_OBJECT'; Chunk: $4100), (Name: 'GLD3DS_POINT_ARRAY'; Chunk: $4110), (Name: 'GLD3DS_POINT_FLAG_ARRAY'; Chunk: $4111), (Name: 'GLD3DS_FACE_ARRAY'; Chunk: $4120), (Name: 'GLD3DS_MSH_MAT_GROUP'; Chunk: $4130), (Name: 'GLD3DS_SMOOTH_GROUP'; Chunk: $4150), (Name: 'GLD3DS_MSH_BOXMAP'; Chunk: $4190), (Name: 'GLD3DS_TEX_VERTS'; Chunk: $4140), (Name: 'GLD3DS_MESH_MATRIX'; Chunk: $4160), (Name: 'GLD3DS_MESH_COLOR'; Chunk: $4165), (Name: 'GLD3DS_MESH_TEXTURE_INFO'; Chunk: $4170), //148 (Name: 'GLD3DS_KFDATA'; Chunk: $B000), (Name: 'GLD3DS_KFHDR'; Chunk: $B00A), (Name: 'GLD3DS_KFSEG'; Chunk: $B008), (Name: 'GLD3DS_KFCURTIME'; Chunk: $B009), (Name: 'GLD3DS_AMBIENT_NODE_TAG'; Chunk: $B001), (Name: 'GLD3DS_OBJECT_NODE_TAG'; Chunk: $B002), (Name: 'GLD3DS_CAMERA_NODE_TAG'; Chunk: $B003), (Name: 'GLD3DS_TARGET_NODE_TAG'; Chunk: $B004), (Name: 'GLD3DS_LIGHT_NODE_TAG'; Chunk: $B005), (Name: 'GLD3DS_L_TARGET_NODE_TAG'; Chunk: $B006), (Name: 'GLD3DS_SPOTLIGHT_NODE_TAG'; Chunk: $B007), (Name: 'GLD3DS_NODE_ID'; Chunk: $B030), (Name: 'GLD3DS_NODE_HDR'; Chunk: $B010), (Name: 'GLD3DS_PIVOT'; Chunk: $B013), (Name: 'GLD3DS_INSTANCE_NAME'; Chunk: $B011), (Name: 'GLD3DS_MORPH_SMOOTH'; Chunk: $B015), (Name: 'GLD3DS_BOUNDBOX'; Chunk: $B014), (Name: 'GLD3DS_POS_TRACK_TAG'; Chunk: $B020), (Name: 'GLD3DS_COL_TRACK_TAG'; Chunk: $B025), (Name: 'GLD3DS_ROT_TRACK_TAG'; Chunk: $B021), (Name: 'GLD3DS_SCL_TRACK_TAG'; Chunk: $B022), (Name: 'GLD3DS_MORPH_TRACK_TAG'; Chunk: $B026), (Name: 'GLD3DS_FOV_TRACK_TAG'; Chunk: $B023), (Name: 'GLD3DS_ROLL_TRACK_TAG'; Chunk: $B024), (Name: 'GLD3DS_HOT_TRACK_TAG'; Chunk: $B027), (Name: 'GLD3DS_FALL_TRACK_TAG'; Chunk: $B028), (Name: 'GLD3DS_HIDE_TRACK_TAG'; Chunk: $B029), //175 (Name: 'GLD3DS_POLY_2D'; Chunk: $5000), (Name: 'GLD3DS_SHAPE_OK'; Chunk: $5010), (Name: 'GLD3DS_SHAPE_NOT_OK'; Chunk: $5011), (Name: 'GLD3DS_SHAPE_HOOK'; Chunk: $5020), (Name: 'GLD3DS_PATH_3D'; Chunk: $6000), (Name: 'GLD3DS_PATH_MATRIX'; Chunk: $6005), (Name: 'GLD3DS_SHAPE_2D'; Chunk: $6010), (Name: 'GLD3DS_M_SCALE'; Chunk: $6020), (Name: 'GLD3DS_M_TWIST'; Chunk: $6030), (Name: 'GLD3DS_M_TEETER'; Chunk: $6040), (Name: 'GLD3DS_M_FIT'; Chunk: $6050), (Name: 'GLD3DS_M_BEVEL'; Chunk: $6060), (Name: 'GLD3DS_XZ_CURVE'; Chunk: $6070), (Name: 'GLD3DS_YZ_CURVE'; Chunk: $6080), (Name: 'GLD3DS_INTERPCT'; Chunk: $6090), (Name: 'GLD3DS_DEFORM_LIMIT'; Chunk: $60A0), //191 (Name: 'GLD3DS_USE_CONTOUR'; Chunk: $6100), (Name: 'GLD3DS_USE_TWEEN'; Chunk: $6110), (Name: 'GLD3DS_USE_SCALE'; Chunk: $6120), (Name: 'GLD3DS_USE_TWIST'; Chunk: $6130), (Name: 'GLD3DS_USE_TEETER'; Chunk: $6140), (Name: 'GLD3DS_USE_FIT'; Chunk: $6150), (Name: 'GLD3DS_USE_BEVEL'; Chunk: $6160), //198 (Name: 'GLD3DS_DEFAULT_VIEW'; Chunk: $3000), (Name: 'GLD3DS_VIEW_TOP'; Chunk: $3010), (Name: 'GLD3DS_VIEW_BOTTOM'; Chunk: $3020), (Name: 'GLD3DS_VIEW_LEFT'; Chunk: $3030), (Name: 'GLD3DS_VIEW_RIGHT'; Chunk: $3040), (Name: 'GLD3DS_VIEW_FRONT'; Chunk: $3050), (Name: 'GLD3DS_VIEW_BACK'; Chunk: $3060), (Name: 'GLD3DS_VIEW_USER'; Chunk: $3070), (Name: 'GLD3DS_VIEW_CAMERA'; Chunk: $3080), (Name: 'GLD3DS_VIEW_WINDOW'; Chunk: $3090), //208 (Name: 'GLD3DS_VIEWPORT_LAYOUT_OLD'; Chunk: $7000), (Name: 'GLD3DS_VIEWPORT_DATA_OLD'; Chunk: $7010), (Name: 'GLD3DS_VIEWPORT_LAYOUT'; Chunk: $7001), (Name: 'GLD3DS_VIEWPORT_DATA'; Chunk: $7011), (Name: 'GLD3DS_VIEWPORT_DATA_3'; Chunk: $7012), (Name: 'GLD3DS_VIEWPORT_SIZE'; Chunk: $7020), (Name: 'GLD3DS_NETWORK_VIEW'; Chunk: $7030)); //215 function GLD3dsChunkRead(var C: TGLD3dsChunk; Stream: TStream): GLboolean; function GLD3dsChunkReadStart(var C: TGLD3dsChunk; Chunk: GLushort; Stream: TStream): GLboolean; function GLD3dsChunkReadNext(var C: TGLD3dsChunk; Stream: TStream): GLushort; procedure GLD3dsChunkReadReset(Stream: TStream); function GLD3dsChunkKnown(const C: TGLD3dsChunk): GLboolean; function GLD3dsChunkUnknown(const C: TGLD3dsChunk): GLboolean; function GLD3dsChunkName(const C: TGLD3dsChunk): string; implementation uses SysUtils, GLD3dsIo; function GLD3dsChunkRead(var C: TGLD3dsChunk; Stream: TStream): GLboolean; begin Result := False; try if Stream.Position + 6 <= Stream.Size then begin Stream.Read(C.Chunk, SizeOf(GLushort)); Stream.Read(C.Size, SizeOf(GLuint)); end else begin C.Chunk := 0; Exit; end; except C.Chunk := 0; Exit; end; Result := True; end; function GLD3dsChunkReadStart(var C: TGLD3dsChunk; Chunk: GLushort; Stream: TStream): GLboolean; begin Result := False; if not GLD3dsChunkRead(C, Stream) then Exit; Result := (Chunk = 0) or (C.Chunk = Chunk); end; function GLD3dsChunkReadNext(var C: TGLD3dsChunk; Stream: TStream): GLushort; begin if not GLD3dsChunkRead(C, Stream) then Result := 0 else Result := C.Chunk; end; procedure GLD3dsChunkReadReset(Stream: TStream); begin Stream.Seek(-6, soFromCurrent); end; function GLD3dsChunkKnown(const C: TGLD3dsChunk): GLboolean; var i: GLuint; begin Result := False; for i := Low(GLD3DS_CHUNKS) to High(GLD3DS_CHUNKS) do if C.Chunk = GLD3DS_CHUNKS[i].Chunk then begin Result := True; Exit; end; end; function GLD3dsChunkUnknown(const C: TGLD3dsChunk): GLboolean; begin Result := not GLD3dsChunkKnown(C); end; function GLD3dsChunkName(const C: TGLD3dsChunk): string; var i: GLuint; begin Result := 'Unknown Chunk'; for i := Low(GLD3DS_CHUNKS) to High(GLD3DS_CHUNKS) do if C.Chunk = GLD3DS_CHUNKS[i].Chunk then begin Result := GLD3DS_CHUNKS[i].Name; Exit; end; end; end.
unit Enchipher; interface const ENGLISH_ALPHABET : array[0..25] of char = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P' ,'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); RUSSIAN_ALPHABET : array[0..32] of char = ('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', '¨', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß'); CIPHER = TRUE; DECIPHER = FALSE; type TAlphabet = array of char; function GetEnchipheredText(const alphabet : TAlphabet; sourceText, key : string; needChipher : boolean) : string; procedure Analize(var enchipheredText : string); implementation Uses StringProcessing, System.SysUtils, Unit1, KeyCheck, FileUnit, Windows; const ENGLISH_ALPHABET_SGIFT = 65; RUSSIAN_ALPHABET_SHIFT = 128; type TStatisticItem = array[1..2] of integer; TGCDTempStat = record target : string[255]; staticLeft, scanLeft, gcd : integer; end; TStatisticTable = record gcd : integer; frequency : integer; end; var statisticTable : array of TStatisticItem; procedure FindSubString(const enchipheredText : string; subStringSize : integer); forward; procedure CheckSubString(const enchipheredText : string; const staticLeft, scanLeft, subStringSize : integer); forward; procedure SaveResults(const target : string; const staticLeft, scanLeft, gcd : integer); forward; procedure AddDataToStatisticTable(var buffer : TGCDTempStat); forward; procedure SortStatisticTable; forward; procedure SaveStatisticToFile; forward; function Evklid(a, b : integer) : integer; forward; function getShift : integer; forward; function GetEnchipheredText(const alphabet : TAlphabet; sourceText, key : string; needChipher : boolean) : string; var resultText : string; i, alphabetSize, keyLength : integer; temp1, temp2 : char; begin SetConsoleCP(1251); SetConsoleOutputCP(1251); SetLength(resultText, Length(sourceText)); alphabetSize := StringProcessing.getAlphabetSize; keyLength := Length(key); //âåòêâü êîäèðîâêè if needChipher then for i := 1 to Length(sourceText) do begin temp1 := chrExt(ordExt(sourceText[i])); temp2 := chrExt(ordExt(key[(i - 1) mod keyLength + 1])); resultText[i] := chrExt((ordExt(sourceText[i]) + ordExt(key[(i - 1) mod keyLength + 1]) - 2 * getShift + 1) mod 33 + 128); { if (KeyCheck.KeyCheckForm.ProgressiveRBtn.Checked) then if (i mod keyLength = 0) then KeyCheck.KeyCheckForm.ProgresKey(key); } end //âåòâü äåêîäèðîâêè else begin key := KeyCheck._key; for i := 1 to Length(sourceText) do begin resultText[i] := chrExt((ordExt(sourceText[i]) - ordExt(key[(i - 1) mod keyLength + 1]) + 32) mod 33 + 128); {if (KeyCheck.KeyCheckForm.ProgressiveRBtn.Checked) then if (i mod keyLength = 0) then KeyCheck.KeyCheckForm.ProgresKey(key); } end; end; Result := resultText; end; function getShift : integer; begin if Unit1.LanguageForm.GetLanguage = english then Result := ENGLISH_ALPHABET_SHIFT else Result := RUSSIAN_ALPHABET_SHIFT; end; procedure Kasiski(const enchipheredText : string); var i : integer; begin for i := 3 to GetAlphabetSize do FindSubString(enchipheredText, i); end; procedure FindSubString(const enchipheredText : string; subStringSize : integer); var staticLeft, staticRight, scanLeft, scanRight, i, dif, len : integer; flag : boolean; begin staticLeft := 0; staticRight := staticLeft + subStringSize - 1; scanLeft := staticRight + 1; scanRight := scanLeft + subStringsize - 1; len := Length(enchipheredText); flag := true; while scanRight <= len - 1 do begin i := 1; for i := 1 to subStringSize - 1 do if (ord(enchipheredText[staticLeft]) - ord(enchipheredText[scanLeft]) <> ord(enchipheredText[staticLeft + i]) - ord(enchipheredText[scanLeft + i])) then begin flag := false; break; end; if flag then CheckSubString(enchipheredText, staticLeft, scanLeft, subStringSize); inc(scanLeft); inc(scanRight); end; end; procedure CheckSubString(const enchipheredText : string; const staticLeft, scanLeft, subStringSize : integer); var gcd : integer; target : string; begin gcd := Evklid(staticLeft, scanLeft); target := Copy(enchipheredText, staticLeft, scanLeft - staticLeft + 1); if gcd >= 3 then SaveResults(target, staticLeft, scanLeft, gcd); //Analize(enchipheredText); end; function Evklid(a, b : integer) : integer; begin if a = b then Result := a else if (a > b) then Result := Evklid(a - b, b) else Result := Evklid(a, b - a); end; procedure SaveResults(const target : string; const staticLeft, scanLeft, gcd : integer); var T : file of TGCDTempStat; buffer : TGCDTempStat; begin AssignFile(T, 'GCDTempStat.ini'); Reset(T); while not EOF(T) do Read(T, buffer); buffer.target := target; buffer.staticLeft := staticLeft; buffer.scanLeft := scanLeft; buffer.gcd := gcd; write(T, buffer); CloseFile(T); end; procedure Analize(var enchipheredText : string); var T : file of TGCDTempStat; buffer : TGCDTempStat; i : integer; begin AssignFile(T, 'GCDTempStat.ini'); If fileExists('GCDTempStat.ini') then begin Reset(T); while not EOF(T) do begin Read(T, buffer); i := 0; AddDataToStatisticTable(buffer); end; CloseFile(T); end else exit; SortStatisticTable; end; procedure AddDataToStatisticTable(var buffer : TGCDTempStat); var i : integer; begin i := 0; while (i <= Length(statisticTable)) and (statisticTable[i, 1] <> buffer.gcd) do inc(i); if i > Length(statisticTable) then begin SetLength(statisticTable, i + 1); statisticTable[i + 1, 1] := buffer.gcd; statisticTable[i + 1, 1] := 1 end else inc(statisticTable[i, 2]); end; procedure SortStatisticTable; var mas : TStatisticItem; i, j, len : integer; begin len := Length(statisticTable); for i := 0 to len - 2 do for j := i + 1 to len - 1 do if statisticTable[i, 1] * statisticTable[i, 2] > statisticTable[j, 1] * statisticTable[j, 2] then begin mas := statisticTable[i]; statisticTable[i] := statisticTable[j]; statisticTable[j] := mas; end; SaveStatisticToFile; end; procedure SaveStatisticToFile; var F : file of TStatisticTable; i, len : integer; target : TStatisticTable; begin AssignFile(F, 'GCDFrequencyStat.ini'); Rewrite(F); len := Length(StatisticTable); for i := 0 to len - 1 do begin target.gcd := statisticTable[i, 1]; target.frequency := statisticTable[i, 2]; end; end; end.
unit uInstallTypes; interface const MaxFileNameLength = 255; ReadBufferSize = 16 * 1024; type TZipHeader = record CRC: Cardinal; end; TZipEntryHeader = record FileName: array[0..MaxFileNameLength] of Char; FileNameLength: Byte; FileOriginalSize: Int64; FileCompressedSize: Int64; IsDirectory: Boolean; ChildsCount: Integer; end; TExtractFileCallBack = procedure(BytesRead, BytesTotal: Int64; var Terminate: Boolean) of object; implementation end.
{ *************************************************************************** } { } { EControl Common Library } { } { Copyright (c) 2004 - 2015 EControl Ltd., Zaharov Michael } { www.econtrol.ru } { support@econtrol.ru } { } { *************************************************************************** } {$mode delphi} {$define EC_UNICODE} unit ec_Lists; interface uses Classes, FGL; type TSortedItem = class protected function GetKey: integer; virtual; abstract; end; TSortedList = class private FList: TList; function GetCount: integer; function GetItem(Index: integer): TSortedItem; public constructor Create(OwnObjects: Boolean); destructor Destroy; override; function Add(Item: TSortedItem): integer; procedure Delete(Index: integer); procedure Clear; function PriorAt(Pos: integer): integer; property Items[Index: integer]: TSortedItem read GetItem; default; property Count: integer read GetCount; end; { TRange } TRange = packed record private function GetLength: integer; public StartPos, EndPos: integer; PointStart, PointEnd: TPoint; constructor Create(AStartPos, AEndPos: integer); constructor Create(AStartPos, AEndPos: integer; const APointStart, APointEnd: TPoint); property Size: integer read GetLength; class operator=(const a, b: TRange): boolean; end; { GRangeList } // Array of sorted ranges GRangeList<GRange> = class (TFPGList<GRange>) private FUnionSiblings: Boolean; FPrevIdx: integer; FSorted: boolean; protected // Union ranges with the [Index] and [Index + 1] // returns new range index (or union result) function IsGreater(I1, I2: integer): Boolean; function CompProc(const Val:TRange; Key: integer): integer; public constructor Create(UnionSiblings: Boolean = True); destructor Destroy; override; property Sorted: boolean read FSorted write FSorted; function Add(const Range: GRange): integer; virtual; function ClearFromPos(APos: integer; CopyTo: GRangeList<GRange> = nil): integer; virtual; // Deletes ranges that intersect the bounds, returns number of deleted items function DeleteIntersected(AStart, AEnd: integer): integer; // Content has been changed, updates ranges upper Pos // Removes affected ranges function ContentChanged(Pos, Count: integer): Boolean; // At position or next function NextAt(APos: integer): integer; // At position or prior function PriorAt(APos: integer): integer; end; TRangeList = GRangeList<TRange>; implementation uses //Math, Dialogs, SysUtils, Contnrs; { TRange } constructor TRange.Create(AStartPos, AEndPos: integer; const APointStart, APointEnd: TPoint); begin StartPos := AStartPos; EndPos := AEndPos; PointStart := APointStart; PointEnd := APointEnd; end; constructor TRange.Create(AStartPos, AEndPos: integer); begin StartPos := AStartPos; EndPos := AEndPos; PointStart.X := -1; PointStart.Y := -1; PointEnd.X := -1; PointEnd.Y := -1; end; function TRange.GetLength: integer; begin Result := EndPos-StartPos; end; class operator TRange.=(const a,b: TRange):boolean; // Not used in real work begin Result:= (a.StartPos=b.StartPos) and (a.EndPos=b.EndPos); end; { TRangeList } constructor GRangeList<GRange>.Create(UnionSiblings: Boolean); begin inherited Create; FUnionSiblings := UnionSiblings; FSorted := false; end; destructor GRangeList<GRange>.Destroy; begin inherited; end; function GRangeList<GRange>.IsGreater(I1, I2: integer): Boolean; begin if FUnionSiblings then Result := I1 >= I2 else Result := I1 > I2; end; function GRangeList<GRange>.Add(const Range: GRange): integer; var _Range: TRange absolute Range; begin if not FSorted or (Count=0) then begin Result := Count; inherited Add(Range); end else begin Result := PriorAt(_Range.StartPos); Inc(Result); if Result = Count then inherited Add(Range) else inherited Insert(Result, Range); end; end; function GRangeList<GRange>.NextAt(APos: integer): integer; begin Result := PriorAt(APos); if Result = -1 then begin if Count > 0 then Result := 0 end else if TRange(InternalItems[Result]^).EndPos <= APos then if Result < Count - 1 then Inc(Result) else Result := -1; end; function GRangeList<GRange>.CompProc(const Val:TRange; Key: integer): integer; begin with Val do if StartPos > Key then Result := 1 else if (StartPos <= Key)and(EndPos > Key) then Result:= 0 else Result := -1; end; function GRangeList<GRange>.PriorAt(APos: integer): integer; var H, I, C: Integer; begin if (FPrevIdx >= 0) and (FPrevIdx < Count - 1) and (TRange(InternalItems[FPrevIdx]^).StartPos <= APos)then begin if (FPrevIdx >= Count - 1) or (TRange(InternalItems[FPrevIdx + 1]^).StartPos > APos) then begin Result := FPrevIdx; Exit; end else if (FPrevIdx >= Count - 2) or (TRange(InternalItems[FPrevIdx + 2]^).StartPos > APos) then begin Result := FPrevIdx + 1; Exit; end; end; if Count = 0 then begin FPrevIdx := -1; Exit(-1); end else begin Result := 0; H := Count - 1; while Result <= H do begin I := (Result + H) shr 1; C := CompProc(TRange(InternalItems[i]^), APos); if C < 0 then Result := I + 1 else begin if C = 0 then begin FPrevIdx := I; Exit(I); end; H := I - 1; end; end; if Result >= Count then Result := Count - 1; if Result >= 0 then if CompProc(TRange(InternalItems[i]^), APos) > 0 then dec(Result); FPrevIdx := Result; end; end; function GRangeList<GRange>.ContentChanged(Pos, Count: integer): Boolean; var idx: integer; begin idx := PriorAt(Pos); if (idx <> -1) and (TRange(InternalItems[idx]^).EndPos >= Pos) then Delete(idx) else begin Inc(idx); if idx >= Count then // No change begin Result := False; Exit; end; end; if Count < 0 then while (idx < Count) and (TRange(InternalItems[idx]^).StartPos <= Pos - Count) do Delete(idx); while idx < Count do begin Inc(TRange(InternalItems[idx]^).StartPos, Count); Inc(TRange(InternalItems[idx]^).EndPos, Count); Inc(idx); end; Result := True; end; function GRangeList<GRange>.ClearFromPos(APos: integer; CopyTo: GRangeList<GRange>): integer; var idx, i: integer; begin Result := APos; idx := NextAt(APos); if idx <> -1 then begin if TRange(InternalItems[idx]^).StartPos < APos then Result := TRange(InternalItems[idx]^).StartPos; if CopyTo <> nil then begin CopyTo.Clear; CopyTo.Capacity := Count - idx; for i := idx to Count - 1 do CopyTo.Add(Items[i]); end; for i := Count - 1 downto idx do Delete(i); end; end; function GRangeList<GRange>.DeleteIntersected(AStart, AEnd: integer): integer; var idx: integer; begin idx := NextAt(AStart); if idx = -1 then idx := Count - 1 else if TRange(InternalItems[idx]^).StartPos >= AEnd then Dec(idx); Result := 0; while (idx >= 0) and (idx < Count) and (TRange(InternalItems[idx]^).EndPos > Astart) do begin Inc(Result); Delete(idx); end; end; //type // TRangeClass = class of TRange; (* function GRangeList<GRange>.SplitRange(RangeIdx, SplitPos: integer): Boolean; var R: GRange; sp: integer; begin R := Items[RangeIdx]; Result := (SplitPos > R.StartPos) and (SplitPos < R.EndPos); if Result then begin sp := R.StartPos; R.StartPos := SplitPos; Items[RangeIdx]:=R; R := TRange.Create(sp, SplitPos); Insert(RangeIdx, R); end; end; *) { TSortedList } function TSortedList.Add(Item: TSortedItem): integer; begin if (Count = 0) or (Items[Count - 1].GetKey <= Item.GetKey) then begin Result := Count; FList.Add(Item); end else begin Result := PriorAt(Item.GetKey); Inc(Result); if Result = Count then FList.Add(Item) else FList.Insert(Result, Item); end; end; procedure TSortedList.Clear; begin FList.Clear; end; constructor TSortedList.Create(OwnObjects: Boolean); begin inherited Create; if OwnObjects then FList := TObjectList.Create else FList := TList.Create; end; procedure TSortedList.Delete(Index: integer); begin FList.Delete(Index); end; destructor TSortedList.Destroy; begin FreeAndNil(FList);//AT inherited; end; function TSortedList.GetCount: integer; begin if FList<>nil then//AT Result := FList.Count else Result:= 0;//AT end; function TSortedList.GetItem(Index: integer): TSortedItem; begin Result := TSortedItem(FList[Index]); end; function TSortedList.PriorAt(Pos: integer): integer; function CompProc(Item: pointer; Key: integer): integer; inline; begin Result := TSortedItem(Item).GetKey - Key; end; function QuickSearch(const List: TList; Key: integer; var Index: integer): Boolean; var L, H, I, C: Integer; begin Result := False; if List.Count = 0 then begin Index := -1; Exit; end; L := 0; H := List.Count - 1; while L <= H do begin I := (L + H) shr 1; C := CompProc(List[I], Key); if C < 0 then L := I + 1 else begin if C = 0 then begin Result := True; Index := I; Exit; end; H := I - 1; end; end; Index := L; if Index >= List.Count then Index := List.Count - 1; if Index >= 0 then if CompProc(List[Index], Key) > 0 then dec(Index); end; begin QuickSearch(FList, Pos, Result); end; end.
unit ValueSetEditorRegisterServerForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, VirtualTrees, ValueSetEditorCore; type TfrmRegisterServer = class(TForm) Panel1: TPanel; btnOpenFile: TButton; Panel2: TPanel; tvServers: TVirtualStringTree; btnUpdate: TButton; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tvServersGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure btnUpdateClick(Sender: TObject); procedure tvServersClick(Sender: TObject); procedure tvServersInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure tvServersChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); private FContext : TValueSetEditorContext; procedure SetContext(const Value: TValueSetEditorContext); public { Public declarations } property Context : TValueSetEditorContext read FContext write SetContext; end; var frmRegisterServer1: TfrmRegisterServer; implementation uses ServerOperationForm; {$R *.dfm} procedure TfrmRegisterServer.btnUpdateClick(Sender: TObject); var server : TValueSetEditorServerCache; begin if (tvServers.FocusedNode <> nil) then begin server := FContext.Servers[tvServers.FocusedNode.Index]; ServerOperation(server.update, '', 'updating', true); end; end; procedure TfrmRegisterServer.FormDestroy(Sender: TObject); begin FContext.Free; end; procedure TfrmRegisterServer.FormShow(Sender: TObject); begin tvServers.RootNodeCount := 0; tvServers.RootNodeCount := Context.Servers.Count; end; procedure TfrmRegisterServer.SetContext(const Value: TValueSetEditorContext); begin FContext.free; FContext := Value; end; procedure TfrmRegisterServer.tvServersChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); var server : TValueSetEditorServerCache; begin server := FContext.Servers[node.Index]; Context.SetNominatedServer(server.URL); end; procedure TfrmRegisterServer.tvServersClick(Sender: TObject); begin btnUpdate.Enabled := tvServers.FocusedNode <> nil; end; procedure TfrmRegisterServer.tvServersGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var server : TValueSetEditorServerCache; begin server := FContext.Servers[node.Index]; case Column of 0: CellText := server.URL; 1: CellText := server.Name; 2: CellText := inttostr(Server.List.Count); 3: CellText := inttostr(Server.CodeSystems.Count); 4: CellText := Server.LastUpdated; end end; procedure TfrmRegisterServer.tvServersInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var server : TValueSetEditorServerCache; begin server := FContext.Servers[node.Index]; Node.CheckType := ctCheckBox; if (server = Context.WorkingServer) then Node.CheckState := csCheckedNormal else Node.CheckState := csUncheckedNormal; end; end.
program SimpleFactory; (* *Простая фабрика вообще не является паттерном проектирования, *это скорее идиома программирования (устоявшаяся практика). *) (* *Фабричный класс не должен ничего содержать, кроме создания объектов. *Во всем остальном коде мы не должны создавать объекты напрямую, только через фабрику. *В фабрике можно использовать статический метод, это избавит от создания объекта фабрики, *но помешает дальнейшему наследованию класса. *) {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; type (* abstract product as interface *) /// <stereotype>abstract_factory</stereotype> TPizza = class abstract function GetPizza: string; virtual; abstract; function GetPrice: double; virtual; abstract; end; (* concrete product *) TDoubleCheesePizza = class(TPizza) function GetPizza: string; override; function GetPrice: double; override; end; (* concrete product *) TPepperoniPizza = class(TPizza) function GetPizza: string; override; function GetPrice: double; override; end; TSimplePizzaFactory = class private fPizza: TPizza; public function CreatePizza(name: string): TPizza; end; { TDoubleCheesePizza } function TDoubleCheesePizza.GetPizza: string; begin Result := 'Its Double Cheese Pizza.'; end; function TDoubleCheesePizza.GetPrice: double; begin Result := 31.99; end; { TPepperoniPizza } function TPepperoniPizza.GetPizza: string; begin Result := 'Its Pepperoni Pizza.'; end; function TPepperoniPizza.GetPrice: double; begin Result := 19.98; end; { TSimplePizzaFactory } function TSimplePizzaFactory.CreatePizza(name: string): TPizza; begin if name = 'cheese' then fPizza := TDoubleCheesePizza.Create else if name = 'pepperoni' then fPizza := TPepperoniPizza.Create; Result := fPizza; end; var factory: TSimplePizzaFactory; pizza1, pizza2: TPizza; begin try { TODO -oUser -cConsole Main : Insert code here } factory := TSimplePizzaFactory.Create; pizza1 := factory.CreatePizza('pepperoni'); WriteLn(pizza1.GetPizza + ' Price: $' + FloatToStr(pizza1.GetPrice)); pizza2 := factory.CreatePizza('cheese'); WriteLn(pizza2.GetPizza + ' Price: $' + FloatToStr(pizza2.GetPrice)); ReadLn; pizza1.Free; pizza2.Free; factory.Free; except on E: Exception do WriteLn(E.ClassName, ': ', E.Message); end; end.
unit ufrmDialogAdjustmentProduct; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, SUIForm, StdCtrls, Mask, JvToolEdit, JvLabel, Grids, BaseGrid, AdvGrid, uConn, JclStrings, uAdjustmentStock, JvEdit, JvExMask, JvExStdCtrls, JvValidateEdit, JvExControls, AdvObj, System.Actions, Vcl.ActnList, ufraFooterDialog3Button; type TStatusForm = (frAdd, frApply, frEdit); TfrmDialogAdjustmentProduct = class(TfrmMasterDialog) procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure strgGridCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); procedure strgGridKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure strgGridCellValidate(Sender: TObject; ACol, ARow: Integer; var Value: String; var Valid: Boolean); procedure FormCreate(Sender: TObject); procedure lblTambahClick(Sender: TObject); procedure lblHapusClick(Sender: TObject); procedure footerDialogMasterbtnSaveClick(Sender: TObject); procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure FormShow(Sender: TObject); private objAdjustmentStock: TAdjustmentStock; FStatusForm: TStatusForm; FIsProcessSuccesfull: Boolean; function GetDetilProductByCode(ACode: string): TResultDataSet; function SaveDataAdjustmentProduct: Boolean; function UpdateDataAdjustmentProduct: Boolean; function InsertDataAdjustmentIntoBSS: Boolean; function CountTotalAdjustment(AGrid: TAdvStringGrid): Currency; procedure ParseDataAdjustmentDetil(); procedure SetStatusForm(const Value: TStatusForm); procedure SetIsProcessSuccesfull(const Value: Boolean); public adjProductId: Integer; property StatusForm: TStatusForm read FStatusForm write SetStatusForm; property IsProcessSuccesfull: Boolean read FIsProcessSuccesfull write SetIsProcessSuccesfull; end; var frmDialogAdjustmentProduct: TfrmDialogAdjustmentProduct; implementation uses ufrmSearchProduct, uGTSUICommonDlg, uConstanta; {$R *.dfm} procedure TfrmDialogAdjustmentProduct.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogAdjustmentProduct.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(objAdjustmentStock); frmDialogAdjustmentProduct := nil; end; procedure TfrmDialogAdjustmentProduct.strgGridCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); begin inherited; if (ACol in [0, 4]) and (StatusForm in [frAdd, frEdit]) then CanEdit := True else CanEdit := False; end; procedure TfrmDialogAdjustmentProduct.strgGridKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_F5) then begin if not Assigned(frmDialogSearchProduct) then frmDialogSearchProduct := TfrmDialogSearchProduct.Create(Application); frmDialogSearchProduct.DialogUnit := Self.DialogUnit; frmDialogSearchProduct.DialogCompany := Self.DialogCompany; frmDialogSearchProduct.ShowModal; if frmDialogSearchProduct.IsProcessSuccessfull then begin strgGrid.Cells[0, strgGrid.Row] := frmDialogSearchProduct.ProductCode; end; frmDialogSearchProduct.Free; end; end; procedure TfrmDialogAdjustmentProduct.strgGridCellValidate(Sender: TObject; ACol, ARow: Integer; var Value: String; var Valid: Boolean); var data: TResultDataSet; begin inherited; case ACol of 0: begin data := GetDetilProductByCode(Value); if not data.IsEmpty then begin if data.fieldbyname('PO_NO').AsString <> '' then strgGrid.Cells[1, ARow] := data.fieldbyname('PO_NO').AsString else strgGrid.Cells[1, ARow] := '9999999999'; strgGrid.Cells[2, ARow] := data.fieldbyname('BRGT_STOCK').AsString; strgGrid.Cells[3, ARow] := CurrToStr(data.fieldbyname('POD_PRICE').AsCurrency); strgGrid.Cells[5, ARow] := data.fieldbyname('BRG_SAT_CODE_STOCK').AsString; strgGrid.Cells[6, ARow] := CurrToStr(data.fieldbyname('BRGT_COGS').AsCurrency); strgGrid.Cells[7, ARow] := CurrToStr(data.fieldbyname('BRGT_LAST_COST').AsCurrency); strgGrid.Cells[8, ARow] := data.fieldbyname('BRG_ALIAS').AsString; end; strgGrid.Col := 4; end; end; strgGrid.SetFocus; strgGrid.AutoSize := True; curredtTotAdjustment.Value := CountTotalAdjustment(strgGrid); edtProductName.Text := strgGrid.Cells[8, ARow]; end; function TfrmDialogAdjustmentProduct.GetDetilProductByCode( ACode: string): TResultDataSet; var arrParam: TArr; begin if ACode = '' then SetLength(arrParam, 0) else begin SetLength(arrParam, 2); arrParam[0].tipe := ptString; arrParam[0].data := ACode; arrParam[1].tipe := ptInteger; arrParam[1].data := DialogUnit; end; Result := objAdjustmentStock.GetDetilProductByProductCode(arrParam); end; procedure TfrmDialogAdjustmentProduct.FormCreate(Sender: TObject); begin inherited; if not Assigned(objAdjustmentStock) then objAdjustmentStock := TAdjustmentStock.Create; end; procedure TfrmDialogAdjustmentProduct.lblTambahClick(Sender: TObject); begin inherited; if StatusForm in [frAdd, frEdit] then strgGrid.AddRow; end; procedure TfrmDialogAdjustmentProduct.lblHapusClick(Sender: TObject); begin inherited; if StatusForm in [frAdd, frEdit] then begin if strgGrid.RowCount > 2 then strgGrid.RemoveSelectedRows else begin strgGrid.RowCount := 2; strgGrid.ClearRows(1, strgGrid.RowCount - 1); end; curredtTotAdjustment.Value := CountTotalAdjustment(strgGrid); end; end; function TfrmDialogAdjustmentProduct.SaveDataAdjustmentProduct: Boolean; var arrParam: TArr; i: Integer; bResult, bResult2: Boolean; begin adjProductId := objAdjustmentStock.GetGenAdjustmentProductId; // bResult := False; bResult2 := False; SetLength(arrParam, 8); arrParam[0].tipe := ptInteger; arrParam[0].data := adjProductId; arrParam[1].tipe := ptString; arrParam[1].data := StrPadLeft(IntToStr(adjProductId), 10, '0'); arrParam[2].tipe := ptDateTime; arrParam[2].data := dtTglOpnam.Date; arrParam[3].tipe := ptString; arrParam[3].data := cbbPilihan.Text; arrParam[4].tipe := ptString; arrParam[4].data := edtRemark.Text; arrParam[5].tipe := ptCurrency; arrParam[5].data := curredtTotAdjustment.Value; arrParam[6].tipe := ptString; arrParam[6].data := 'OPEN'; arrParam[7].tipe := ptInteger; arrParam[7].data := FLoginId; bResult := objAdjustmentStock.InsertDataAdjustmentProduct(arrParam); for i := 1 to strgGrid.RowCount - 1 do begin if strgGrid.Cells[0, i] <> '' then begin SetLength(arrParam, 10); arrParam[0].tipe := ptInteger; arrParam[0].data := adjProductId; arrParam[1].tipe := ptString; arrParam[1].data := strgGrid.Cells[0, i]; arrParam[2].tipe := ptString; arrParam[2].data := strgGrid.Cells[5, i]; arrParam[3].tipe := ptString; arrParam[3].data := strgGrid.Cells[1, i]; arrParam[4].tipe := ptCurrency; arrParam[4].data := StrToCurr(strgGrid.Cells[3, i]); arrParam[5].tipe := ptCurrency; arrParam[5].data := StrToCurr(strgGrid.Cells[6, i]); arrParam[6].tipe := ptCurrency; arrParam[6].data := StrToCurr(strgGrid.Cells[7, i]); arrParam[7].tipe := ptCurrency; arrParam[7].data := StrToFloat(strgGrid.Cells[4, i]); arrParam[8].tipe := ptCurrency; arrParam[8].data := StrToCurr(strgGrid.Cells[3, i]) * StrToInt(strgGrid.Cells[4, i]); arrParam[9].tipe := ptInteger; arrParam[9].data := FLoginId; bResult2 := objAdjustmentStock.InsertDataAdjustmentProductDetil(arrParam); end; end; if bResult and bResult2 then begin ADConn.Commit; Result := True; end else begin ADConn.Rollback; Result := False; end; end; function TfrmDialogAdjustmentProduct.CountTotalAdjustment( AGrid: TAdvStringGrid): Currency; var i: Integer; tTemp: Currency; begin tTemp := 0; // i := 1; for i := 1 to AGrid.RowCount - 1 do begin if (AGrid.Cells[3, i] <> '') and (AGrid.Cells[4, i] <> '') then tTemp := tTemp + (StrToCurr(AGrid.Cells[3, i]) * StrToCurr(AGrid.Cells[4, i])); end; Result := tTemp; end; procedure TfrmDialogAdjustmentProduct.SetStatusForm( const Value: TStatusForm); begin FStatusForm := Value; end; procedure TfrmDialogAdjustmentProduct.SetIsProcessSuccesfull( const Value: Boolean); begin FIsProcessSuccesfull := Value; end; procedure TfrmDialogAdjustmentProduct.footerDialogMasterbtnSaveClick( Sender: TObject); begin inherited; IsProcessSuccesfull := False; case StatusForm of frAdd: begin IsProcessSuccesfull := SaveDataAdjustmentProduct; if IsProcessSuccesfull then Close else CommonDlg.ShowError(ER_INSERT_FAILED); end; frApply: begin IsProcessSuccesfull := InsertDataAdjustmentIntoBSS; if IsProcessSuccesfull then Close else CommonDlg.ShowError('Apply Failed'); end; frEdit: begin IsProcessSuccesfull := UpdateDataAdjustmentProduct; if IsProcessSuccesfull then Close else CommonDlg.ShowError(ER_UPDATE_FAILED); end; end; end; procedure TfrmDialogAdjustmentProduct.strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; edtProductName.Text := strgGrid.Cells[8, NewRow]; end; procedure TfrmDialogAdjustmentProduct.ParseDataAdjustmentDetil; var arrParam: TArr; data: TResultDataSet; i: Integer; begin SetLength(arrParam, 2); arrParam[0].tipe := ptInteger; arrParam[0].data := adjProductId; arrParam[1].tipe := ptInteger; arrParam[1].data := DialogUnit; data := objAdjustmentStock.GetListDataAdjustmentProductDetilByAdjustmentId(arrParam); with strgGrid do begin if not data.IsEmpty then begin RowCount := data.RecordCount + 1; i := 1; while not data.Eof do begin Cells[0, i] := data.fieldbyname('BRG_CODE').AsString; Cells[1, i] := data.fieldbyname('APD_NO_PO').AsString; Cells[2, i] := data.fieldbyname('BRGT_STOCK').AsString; Cells[3, i] := CurrToStr(data.fieldbyname('APD_PURCHASE_PRICE').AsCurrency); Cells[4, i] := FloatToStr(data.fieldbyname('APD_QTY').AsFloat); Cells[5, i] := data.fieldbyname('APD_SAT_CODE').AsString; Cells[6, i] := CurrToStr(data.fieldbyname('APD_COGS').AsCurrency); Cells[7, i] := CurrToStr(data.fieldbyname('APD_LAST_COST').AsCurrency); Cells[8, i] := data.fieldbyname('BRG_ALIAS').AsString; Inc(i); data.Next; end; end else begin RowCount := 2; Cells[0, 1] := ''; Cells[1, 1] := ''; Cells[2, 1] := ''; Cells[3, 1] := ''; Cells[4, 1] := ''; Cells[5, 1] := ''; Cells[6, 1] := ''; Cells[7, 1] := ''; Cells[8, 1] := ''; end; FixedRows := 1; AutoSize := True; end; edtProductName.Text := strgGrid.Cells[8, 1]; end; procedure TfrmDialogAdjustmentProduct.FormShow(Sender: TObject); begin inherited; case StatusForm of frEdit: begin ParseDataAdjustmentDetil; end; frApply: begin ParseDataAdjustmentDetil; end; end; end; function TfrmDialogAdjustmentProduct.UpdateDataAdjustmentProduct: Boolean; var arrParam: TArr; i: Integer; bResult, bResult2, bResult3: Boolean; begin // bResult := False; bResult2 := False; // bResult3 := False; SetLength(arrParam, 9); arrParam[0].tipe := ptString; arrParam[0].data := edt1.Text; arrParam[1].tipe := ptDateTime; arrParam[1].data := dtTglOpnam.Date; arrParam[2].tipe := ptString; arrParam[2].data := cbbPilihan.Text; arrParam[3].tipe := ptString; arrParam[3].data := edtRemark.Text; arrParam[4].tipe := ptCurrency; arrParam[4].data := curredtTotAdjustment.Value; arrParam[5].tipe := ptString; arrParam[5].data := 'OPEN'; arrParam[6].tipe := ptInteger; arrParam[6].data := FLoginId; arrParam[7].tipe := ptInteger; arrParam[7].data := adjProductId; arrParam[8].tipe := ptInteger; arrParam[8].data := DialogUnit; bResult := objAdjustmentStock.UpdateDataAdjustmentProduct(arrParam); SetLength(arrParam, 2); arrParam[0].tipe := ptInteger; arrParam[0].data := adjProductId; arrParam[1].tipe := ptInteger; arrParam[1].data := DialogUnit; bResult3 := objAdjustmentStock.DeleteDataAdjustmentProductDetil(arrParam); for i := 1 to strgGrid.RowCount - 1 do begin if strgGrid.Cells[0, i] <> '' then begin SetLength(arrParam, 10); arrParam[0].tipe := ptInteger; arrParam[0].data := adjProductId; arrParam[1].tipe := ptString; arrParam[1].data := strgGrid.Cells[0, i]; arrParam[2].tipe := ptString; arrParam[2].data := strgGrid.Cells[5, i]; arrParam[3].tipe := ptString; arrParam[3].data := strgGrid.Cells[1, i]; arrParam[4].tipe := ptCurrency; arrParam[4].data := StrToCurr(strgGrid.Cells[3, i]); arrParam[5].tipe := ptCurrency; arrParam[5].data := StrToCurr(strgGrid.Cells[6, i]); arrParam[6].tipe := ptCurrency; arrParam[6].data := StrToCurr(strgGrid.Cells[7, i]); arrParam[7].tipe := ptCurrency; arrParam[7].data := StrToFloat(strgGrid.Cells[4, i]); arrParam[8].tipe := ptCurrency; arrParam[8].data := StrToCurr(strgGrid.Cells[3, i]) * StrToInt(strgGrid.Cells[4, i]); arrParam[9].tipe := ptInteger; arrParam[9].data := FLoginId; bResult2 := objAdjustmentStock.InsertDataAdjustmentProductDetil(arrParam); end; end; if bResult and bResult2 and bResult3 then begin ADConn.Commit; Result := True; end else begin ADConn.Rollback; Result := False; end; end; function TfrmDialogAdjustmentProduct.InsertDataAdjustmentIntoBSS: Boolean; var arrParam: TArr; i: Integer; bResult, bResult2: Boolean; begin bResult := False; bResult2 := False; for i := 1 to strgGrid.RowCount - 1 do begin SetLength(arrParam, 12); arrParam[0].tipe := ptInteger; arrParam[0].data := DialogUnit; arrParam[1].tipe := ptString; arrParam[1].data := strgGrid.Cells[0, i]; arrParam[2].tipe := ptInteger; arrParam[2].data := DialogUnit; arrParam[3].tipe := ptDateTime; arrParam[3].data := Now; arrParam[4].tipe := ptCurrency; arrParam[4].data := StrToFloat(strgGrid.Cells[4, i]); arrParam[5].tipe := ptCurrency; arrParam[5].data := StrToFloat(strgGrid.Cells[4, i]); arrParam[6].tipe := ptString; arrParam[6].data := edt1.Text; arrParam[7].tipe := ptString; arrParam[7].data := 'ADJUSTMENT PRODUCT'; arrParam[8].tipe := ptString; arrParam[8].data := edtRemark.Text; arrParam[9].tipe := ptInteger; arrParam[9].data := FLoginId; arrParam[10].tipe := ptString; arrParam[10].data := strgGrid.Cells[5, i]; arrParam[11].tipe := ptInteger; arrParam[11].data := DialogUnit; bResult := objAdjustmentStock.InsertDataToBSS(arrParam); SetLength(arrParam, 5); arrParam[0].tipe := ptString; arrParam[0].data := 'POSTED'; arrParam[1].tipe := ptDateTime; arrParam[1].data := Now; arrParam[2].tipe := ptInteger; arrParam[2].data := FLoginId; arrParam[3].tipe := ptInteger; arrParam[3].data := adjProductId; arrParam[4].tipe := ptInteger; arrParam[4].data := DialogUnit; bResult2 := objAdjustmentStock.UpdateDataAdjustmentProductSetStatusPosted(arrParam); end; if bResult and bResult2 then begin ADConn.Commit; Result := True; end else begin ADConn.Rollback; Result := False; end; end; end.
unit EstoqueFactory.Model; interface uses EstoqueFactory.Model.Interf, Produto.Model.Interf, Orcamento.Model.Interf, OrcamentoItens.Model.Interf, OrcamentoFornecedores.Model.Interf, Cotacao.Model.Interf; type TEstoqueFactoryModel = class(TInterfacedObject, IEstoqueFactoryModel) private public constructor Create; destructor Destroy; override; class function New: IEstoqueFactoryModel; function Produto: IProdutoModel; function Orcamento: IOrcamentoModel; function OrcamentoItens: IOrcamentoItensModel; function OrcamentoFornecedores: IOrcamentoFornecedoresModel; function Cotacao: ICotacaoModel; end; implementation { TEstoqueFactoryModel } uses Produto.Model, Orcamento.Model, OrcamentoItens.Model, OrcamentoFornecedores.Model, Cotacao.Model; function TEstoqueFactoryModel.Cotacao: ICotacaoModel; begin Result := TCotacaoModel.New; end; constructor TEstoqueFactoryModel.Create; begin end; destructor TEstoqueFactoryModel.Destroy; begin inherited; end; class function TEstoqueFactoryModel.New: IEstoqueFactoryModel; begin Result := Self.Create; end; function TEstoqueFactoryModel.Orcamento: IOrcamentoModel; begin Result := TOrcamentoModel.New; end; function TEstoqueFactoryModel.OrcamentoFornecedores : IOrcamentoFornecedoresModel; begin Result := TOrcamentoFornecedoresModel.New; end; function TEstoqueFactoryModel.OrcamentoItens: IOrcamentoItensModel; begin Result := TOrcamentoItensModel.New; end; function TEstoqueFactoryModel.Produto: IProdutoModel; begin Result := TProdutoModel.New; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Project.Configuration; interface uses Spring.Collections, DPM.Core.Types, DPM.Core.Project.Interfaces; type TProjectConfiguration = class(TInterfacedObject, IProjectConfiguration) private FName : string; FOutputDir : string; FPlatform : TDPMPlatform; FUsesRuntimePackages : Boolean; FPackages : IList<string>; protected function GetUsesRuntimePackages : Boolean; function GetName : string; function GetOutputDir : string; function GetPlatform : TDPMPlatform; function GetPackages : IList<string>; public constructor Create(const name, outputdir : string; const platform : TDPMPlatform; const usesRuntimePackages : boolean; const packages : IEnumerable<string>); end; implementation { TProjectConfiguration } constructor TProjectConfiguration.Create(const name, outputdir : string; const platform : TDPMPlatform; const usesRuntimePackages : boolean; const packages : IEnumerable<string>); begin FName := name; FOutputDir := outputdir; FPlatform := platform; FUsesRuntimePackages := usesRuntimePackages; FPackages := TCollections.CreateList <string> ; if packages <> nil then FPackages.AddRange(packages); end; function TProjectConfiguration.GetUsesRuntimePackages : Boolean; begin result := FUsesRuntimePackages; end; function TProjectConfiguration.GetName : string; begin result := FName; end; function TProjectConfiguration.GetOutputDir : string; begin result := FOutputDir; end; function TProjectConfiguration.GetPackages : IList<string>; begin result := FPackages; end; function TProjectConfiguration.GetPlatform : TDPMPlatform; begin result := FPlatform; end; end.
// // Created by the DataSnap proxy generator. // 16/02/2021 19:34:42 // unit GuiaAlvo.Model.Proxy; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect; type IDSRestCachedTFDJSONDataSets = interface; TServerMethodsClient = class(TDSAdminRestClient) private FDataModuleCreateCommand: TDSRestCommand; FgravaSobreCommand: TDSRestCommand; FListaPlanosCommand: TDSRestCommand; FListaPlanosCommand_Cache: TDSRestCommand; FgravaDeliveryCommand: TDSRestCommand; FgravaRedesSociaisCommand: TDSRestCommand; FgravaCadastroAvaliacoesCommand: TDSRestCommand; FLoadGruposCommand: TDSRestCommand; FLoadGruposCommand_Cache: TDSRestCommand; FUpdateGrupoComCommand: TDSRestCommand; FEnviarEmailCommand: TDSRestCommand; FTelRepetidoCommand: TDSRestCommand; FAddComercioNovoCommand: TDSRestCommand; FAddTelefoneCommand: TDSRestCommand; FDocRepetidoCommand: TDSRestCommand; FgetTelefoneCommand: TDSRestCommand; FgetTelefoneCommand_Cache: TDSRestCommand; FLoadCategoriasCommand: TDSRestCommand; FLoadCategoriasCommand_Cache: TDSRestCommand; FLoadDestaquePrincipalCommand: TDSRestCommand; FLoadDestaquePrincipalCommand_Cache: TDSRestCommand; FLoadComercioCategoriaCommand: TDSRestCommand; FLoadComercioCategoriaCommand_Cache: TDSRestCommand; FLoadSubCategoriaCommand: TDSRestCommand; FLoadSubCategoriaCommand_Cache: TDSRestCommand; FLoadFotosPorSecaoCommand: TDSRestCommand; FLoadFotosPorSecaoCommand_Cache: TDSRestCommand; FLoadComercioPesquisaCommand: TDSRestCommand; FLoadComercioPesquisaCommand_Cache: TDSRestCommand; FLoadDestaqueFavoritoCommand: TDSRestCommand; FLoadDestaqueFavoritoCommand_Cache: TDSRestCommand; FInsertNewSubCategoriaCommand: TDSRestCommand; FRecebeNotificacaoCommand: TDSRestCommand; FVerificaUsuarioAvaliouCommand: TDSRestCommand; FLoadFichaComercioCommand: TDSRestCommand; FLoadFichaComercioCommand_Cache: TDSRestCommand; FLoadComercioCommand: TDSRestCommand; FLoadComercioCommand_Cache: TDSRestCommand; FLoadAvaliacoesCommand: TDSRestCommand; FLoadAvaliacoesCommand_Cache: TDSRestCommand; FVerificaCelularDuplicadoCommand: TDSRestCommand; FVerificaCelularDuplicadoCommand_Cache: TDSRestCommand; FDownloadIdUsuarioCommand: TDSRestCommand; FDownloadIdUsuarioCommand_Cache: TDSRestCommand; FDownloadUsuarioCommand: TDSRestCommand; FDownloadUsuarioCommand_Cache: TDSRestCommand; FDownloadUsuarioIdCommand: TDSRestCommand; FDownloadUsuarioIdCommand_Cache: TDSRestCommand; FUpdateUsuarioCommand: TDSRestCommand; FInsertUsuarioCommand: TDSRestCommand; FControleFavoritoCommand: TDSRestCommand; FRegistrarDispositivoCommand: TDSRestCommand; FIsFavoritoCommand: TDSRestCommand; FSQLServerCommand: TDSRestCommand; FSQLServerCommand_Cache: TDSRestCommand; FUpdateAcessoUsuCommand: TDSRestCommand; FSalvaHistoricoUsuCommand: TDSRestCommand; FgetControleCommand: TDSRestCommand; FgetControleCommand_Cache: TDSRestCommand; FgetNotificacoesCommand: TDSRestCommand; FgetNotificacoesCommand_Cache: TDSRestCommand; FgetAvaliacaoCompletaCommand: TDSRestCommand; FgetAvaliacaoCompletaCommand_Cache: TDSRestCommand; FSalvaAvaliacaoCommand: TDSRestCommand; FDeletePushCommand: TDSRestCommand; FgetAnunciosCommand: TDSRestCommand; FgetAnunciosCommand_Cache: TDSRestCommand; FAtivaPushCommand: TDSRestCommand; FNovoComercioCommand: TDSRestCommand; FComercioCadastradoCommand: TDSRestCommand; FUpdateRaioUsuarioCommand: TDSRestCommand; FGravaUltimaPosicaoUsuarioCommand: TDSRestCommand; FgetNovaSenhaCommand: TDSRestCommand; FgetNovaSenhaCommand_Cache: TDSRestCommand; FUpdateSenhaCommand: TDSRestCommand; FgetLoginCommand: TDSRestCommand; FgetLoginCommand_Cache: TDSRestCommand; FDeleteFoneCommand: TDSRestCommand; FLoadCheckListCommand: TDSRestCommand; FLoadCheckListCommand_Cache: TDSRestCommand; FAddCheckListComCommand: TDSRestCommand; FAddCheckListNovoCommand: TDSRestCommand; FLoadSubGrupoCommand: TDSRestCommand; FLoadSubGrupoCommand_Cache: TDSRestCommand; FLoadSubCatComCommand: TDSRestCommand; FLoadSubCatComCommand_Cache: TDSRestCommand; FInsertSubCatComCommand: TDSRestCommand; FClearSubCatComCommand: TDSRestCommand; FLoadGrupoSelectedCommand: TDSRestCommand; FInsertCategoriaCommand: TDSRestCommand; FSolicitacoesNovaCategoriaCommand: TDSRestCommand; FpodeAlterarAvaliacaoCommand: TDSRestCommand; FsalvaFuncionamentoCommand: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; procedure DataModuleCreate(Sender: TObject); procedure gravaSobre(AIdComercio: Integer; ASobre: string; ASlogem: string; ATag: string); function ListaPlanos(const ARequestFilter: string = ''): TFDJSONDataSets; function ListaPlanos_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function gravaDelivery(AIdCom: Integer; AUber: string; ARappi: string; AIfood: string; const ARequestFilter: string = ''): Boolean; function gravaRedesSociais(AIdCom: Integer; AFace: string; AInsta: string; ATwitter: string; AYouTube: string; AGPlus: string; ASite: string; AEmail: string; AGPlay: string; AStore: string; const ARequestFilter: string = ''): Boolean; function gravaCadastroAvaliacoes(AIdCom: Integer; AAmbiente: Boolean; AAtendimento: Boolean; ALimpeza: Boolean; ALocal: Boolean; APreco: Boolean; const ARequestFilter: string = ''): Boolean; function LoadGrupos(AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadGrupos_Cache(AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure UpdateGrupoCom(AIdCom: Integer; AIdGrupo: Integer); procedure EnviarEmail(pCodigo: string; pAssunto: string; pNome: string; pEmail: string; pTipoEmail: string; pHtml: Boolean); function TelRepetido(ATelefone: string; const ARequestFilter: string = ''): Integer; function AddComercioNovo(ARazao: string; AFantasia: string; ACep: string; AComplemento: string; ACNPJCPF: string; AIERG: string; AEmail: string; ASenha: string; ALoginFone: string; ANumero: Integer; const ARequestFilter: string = ''): Integer; procedure AddTelefone(ATelefone: string; AContato: string; AZap: string; AInterno: string; AIdComFone: Integer; AIdFone: Integer); function DocRepetido(AField: string; ADoc: string; const ARequestFilter: string = ''): Boolean; function getTelefone(AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function getTelefone_Cache(AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadCategorias(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadCategorias_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadDestaquePrincipal(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadDestaquePrincipal_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadComercioCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadComercioCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadSubCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadSubCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadFotosPorSecao(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadFotosPorSecao_Cache(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadComercioPesquisa(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadComercioPesquisa_Cache(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadDestaqueFavorito(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadDestaqueFavorito_Cache(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure InsertNewSubCategoria(AIdCategoria: Integer; AIdCom: Integer; ANomeSubCategoria: string); function RecebeNotificacao(AKeyPush: string; const ARequestFilter: string = ''): Boolean; function VerificaUsuarioAvaliou(AIdUsu: Integer; AIdCom: Integer; const ARequestFilter: string = ''): Boolean; function LoadFichaComercio(AIdComercio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadFichaComercio_Cache(AIdComercio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadComercio(idComercio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadComercio_Cache(idComercio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadAvaliacoes(idComercio: Integer; nStart: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadAvaliacoes_Cache(idComercio: Integer; nStart: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function VerificaCelularDuplicado(vCelular: string; const ARequestFilter: string = ''): TFDJSONDataSets; function VerificaCelularDuplicado_Cache(vCelular: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function DownloadIdUsuario(vCelular: string; const ARequestFilter: string = ''): TFDJSONDataSets; function DownloadIdUsuario_Cache(vCelular: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function DownloadUsuario(vCelular: string; const ARequestFilter: string = ''): TFDJSONDataSets; function DownloadUsuario_Cache(vCelular: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function DownloadUsuarioId(fIdUsu: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function DownloadUsuarioId_Cache(fIdUsu: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function UpdateUsuario(FNome: string; FCelular: string; FSenha: string; FID: Integer; const ARequestFilter: string = ''): Boolean; function InsertUsuario(FNome: string; FCelular: string; FSenha: string; const ARequestFilter: string = ''): Boolean; procedure ControleFavorito(FIdUsu: Integer; FIdCom: Integer; FAction: string); procedure RegistrarDispositivo(ADeviceToken: string; AIdUsu: Integer); function IsFavorito(FIdUsu: Integer; FIdCom: Integer; const ARequestFilter: string = ''): Boolean; function SQLServer(cSql: string; const ARequestFilter: string = ''): TFDJSONDataSets; function SQLServer_Cache(cSql: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function UpdateAcessoUsu(vIdUsu: Integer; const ARequestFilter: string = ''): Boolean; function SalvaHistoricoUsu(hIdUsu: Integer; hIdCat: Integer; hIdSubCat: Integer; hIdCom: Integer; hPqsUsu: string; const ARequestFilter: string = ''): Boolean; function getControle(const ARequestFilter: string = ''): TFDJSONDataSets; function getControle_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function getNotificacoes(AIdUsu: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function getNotificacoes_Cache(AIdUsu: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function getAvaliacaoCompleta(AIdAvaliacao: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function getAvaliacaoCompleta_Cache(AIdAvaliacao: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure SalvaAvaliacao(AIdCom: Integer; AIdUsu: Integer; AAmbiente: Single; AAtendimento: Single; ALimpeza: Single; ALocalizacao: Single; APreco: Single; AMedia: Single; AComentario: string); procedure DeletePush(AIdUsu: Integer; AIdPush: Integer); function getAnuncios(AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function getAnuncios_Cache(AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure AtivaPush(AKeyPush: string; AAtiva: Boolean); procedure NovoComercio(ACnpj: string; ARazao: string; AEmail: string; AFone: string; AContato: string); function ComercioCadastrado(ACNPJ: string; const ARequestFilter: string = ''): Boolean; function UpdateRaioUsuario(AIdUsuario: Integer; ARaio: Integer; const ARequestFilter: string = ''): Boolean; procedure GravaUltimaPosicaoUsuario(ALatitude: string; ALongitude: string; ADeviceToken: string); function getNovaSenha(ADoc: string; const ARequestFilter: string = ''): TFDJSONDataSets; function getNovaSenha_Cache(ADoc: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function UpdateSenha(AIdCom: Integer; ASenha: string; const ARequestFilter: string = ''): Boolean; function getLogin(ADoc: string; const ARequestFilter: string = ''): TFDJSONDataSets; function getLogin_Cache(ADoc: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure DeleteFone(AIdFone: Integer); function LoadCheckList(AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadCheckList_Cache(AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure AddCheckListCom(AIdCom: Integer; AIdCheck: Integer); procedure AddCheckListNovo(ACheck: string; AIdCom: Integer); function LoadSubGrupo(AIdGrupo: Integer; AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadSubGrupo_Cache(AIdGrupo: Integer; AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function LoadSubCatCom(AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets; function LoadSubCatCom_Cache(AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; procedure InsertSubCatCom(AIdCom: Integer; AIdGrupo: Integer; AIdSubGrupo: Integer); procedure ClearSubCatCom(AIdCom: Integer); function LoadGrupoSelected(AIdCom: Integer; const ARequestFilter: string = ''): Integer; procedure InsertCategoria(ACategoria: string; ADescricao: string; AIdCom: Integer); function SolicitacoesNovaCategoria(AIdCom: Integer; const ARequestFilter: string = ''): Integer; function podeAlterarAvaliacao(AIdComercio: Integer; const ARequestFilter: string = ''): Boolean; procedure salvaFuncionamento(AIDCom: Integer; ASeg: string; Ater: string; AQua: string; AQui: string; ASex: string; ASab: string; ADom: string); end; IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>) end; TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand) end; const TServerMethods_DataModuleCreate: array [0..0] of TDSRestParameterMetaData = ( (Name: 'Sender'; Direction: 1; DBXType: 37; TypeName: 'TObject') ); TServerMethods_gravaSobre: array [0..3] of TDSRestParameterMetaData = ( (Name: 'AIdComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'ASobre'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ASlogem'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ATag'; Direction: 1; DBXType: 26; TypeName: 'string') ); TServerMethods_ListaPlanos: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_ListaPlanos_Cache: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_gravaDelivery: array [0..4] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AUber'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARappi'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIfood'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_gravaRedesSociais: array [0..10] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AFace'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AInsta'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ATwitter'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AYouTube'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AGPlus'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ASite'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AEmail'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AGPlay'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AStore'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_gravaCadastroAvaliacoes: array [0..6] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AAmbiente'; Direction: 1; DBXType: 4; TypeName: 'Boolean'), (Name: 'AAtendimento'; Direction: 1; DBXType: 4; TypeName: 'Boolean'), (Name: 'ALimpeza'; Direction: 1; DBXType: 4; TypeName: 'Boolean'), (Name: 'ALocal'; Direction: 1; DBXType: 4; TypeName: 'Boolean'), (Name: 'APreco'; Direction: 1; DBXType: 4; TypeName: 'Boolean'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_LoadGrupos: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadGrupos_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_UpdateGrupoCom: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdGrupo'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_EnviarEmail: array [0..5] of TDSRestParameterMetaData = ( (Name: 'pCodigo'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'pAssunto'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'pNome'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'pEmail'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'pTipoEmail'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'pHtml'; Direction: 1; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_TelRepetido: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ATelefone'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 6; TypeName: 'Integer') ); TServerMethods_AddComercioNovo: array [0..10] of TDSRestParameterMetaData = ( (Name: 'ARazao'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AFantasia'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ACep'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AComplemento'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ACNPJCPF'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIERG'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AEmail'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ASenha'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ALoginFone'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ANumero'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 6; TypeName: 'Integer') ); TServerMethods_AddTelefone: array [0..5] of TDSRestParameterMetaData = ( (Name: 'ATelefone'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AContato'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AZap'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AInterno'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdComFone'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdFone'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_DocRepetido: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AField'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ADoc'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_getTelefone: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getTelefone_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadCategorias: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadCategorias_Cache: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadDestaquePrincipal: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadDestaquePrincipal_Cache: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadComercioCategoria: array [0..4] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'IdSubCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadComercioCategoria_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'IdSubCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadSubCategoria: array [0..3] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadSubCategoria_Cache: array [0..3] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadFotosPorSecao: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'vIdCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'APesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadFotosPorSecao_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'vIdCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'APesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadComercioPesquisa: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'FPesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadComercioPesquisa_Cache: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'FPesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadDestaqueFavorito: array [0..3] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'vIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadDestaqueFavorito_Cache: array [0..3] of TDSRestParameterMetaData = ( (Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'vIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_InsertNewSubCategoria: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'ANomeSubCategoria'; Direction: 1; DBXType: 26; TypeName: 'string') ); TServerMethods_RecebeNotificacao: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AKeyPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_VerificaUsuarioAvaliou: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_LoadFichaComercio: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadFichaComercio_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadComercio: array [0..1] of TDSRestParameterMetaData = ( (Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadComercio_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadAvaliacoes: array [0..2] of TDSRestParameterMetaData = ( (Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'nStart'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadAvaliacoes_Cache: array [0..2] of TDSRestParameterMetaData = ( (Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'nStart'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_VerificaCelularDuplicado: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_VerificaCelularDuplicado_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_DownloadIdUsuario: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_DownloadIdUsuario_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_DownloadUsuario: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_DownloadUsuario_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_DownloadUsuarioId: array [0..1] of TDSRestParameterMetaData = ( (Name: 'fIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_DownloadUsuarioId_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'fIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_UpdateUsuario: array [0..4] of TDSRestParameterMetaData = ( (Name: 'FNome'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'FCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'FSenha'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'FID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_InsertUsuario: array [0..3] of TDSRestParameterMetaData = ( (Name: 'FNome'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'FCelular'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'FSenha'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_ControleFavorito: array [0..2] of TDSRestParameterMetaData = ( (Name: 'FIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'FIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'FAction'; Direction: 1; DBXType: 26; TypeName: 'string') ); TServerMethods_RegistrarDispositivo: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADeviceToken'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_IsFavorito: array [0..2] of TDSRestParameterMetaData = ( (Name: 'FIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'FIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_SQLServer: array [0..1] of TDSRestParameterMetaData = ( (Name: 'cSql'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_SQLServer_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'cSql'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_UpdateAcessoUsu: array [0..1] of TDSRestParameterMetaData = ( (Name: 'vIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_SalvaHistoricoUsu: array [0..5] of TDSRestParameterMetaData = ( (Name: 'hIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'hIdCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'hIdSubCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'hIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'hPqsUsu'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_getControle: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getControle_Cache: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_getNotificacoes: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getNotificacoes_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_getAvaliacaoCompleta: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdAvaliacao'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getAvaliacaoCompleta_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdAvaliacao'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_SalvaAvaliacao: array [0..8] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AAmbiente'; Direction: 1; DBXType: 27; TypeName: 'Single'), (Name: 'AAtendimento'; Direction: 1; DBXType: 27; TypeName: 'Single'), (Name: 'ALimpeza'; Direction: 1; DBXType: 27; TypeName: 'Single'), (Name: 'ALocalizacao'; Direction: 1; DBXType: 27; TypeName: 'Single'), (Name: 'APreco'; Direction: 1; DBXType: 27; TypeName: 'Single'), (Name: 'AMedia'; Direction: 1; DBXType: 27; TypeName: 'Single'), (Name: 'AComentario'; Direction: 1; DBXType: 26; TypeName: 'string') ); TServerMethods_DeletePush: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdPush'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_getAnuncios: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getAnuncios_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_AtivaPush: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AKeyPush'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AAtiva'; Direction: 1; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_NovoComercio: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ACnpj'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ARazao'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AEmail'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AFone'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AContato'; Direction: 1; DBXType: 26; TypeName: 'string') ); TServerMethods_ComercioCadastrado: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ACNPJ'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_UpdateRaioUsuario: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdUsuario'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_GravaUltimaPosicaoUsuario: array [0..2] of TDSRestParameterMetaData = ( (Name: 'ALatitude'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ALongitude'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ADeviceToken'; Direction: 1; DBXType: 26; TypeName: 'string') ); TServerMethods_getNovaSenha: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADoc'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getNovaSenha_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADoc'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_UpdateSenha: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'ASenha'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_getLogin: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADoc'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_getLogin_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADoc'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_DeleteFone: array [0..0] of TDSRestParameterMetaData = ( (Name: 'AIdFone'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_LoadCheckList: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadCheckList_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_AddCheckListCom: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdCheck'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_AddCheckListNovo: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ACheck'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_LoadSubGrupo: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdGrupo'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadSubGrupo_Cache: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdGrupo'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_LoadSubCatCom: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods_LoadSubCatCom_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TServerMethods_InsertSubCatCom: array [0..2] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdGrupo'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'AIdSubGrupo'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_ClearSubCatCom: array [0..0] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_LoadGrupoSelected: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 6; TypeName: 'Integer') ); TServerMethods_InsertCategoria: array [0..2] of TDSRestParameterMetaData = ( (Name: 'ACategoria'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ADescricao'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer') ); TServerMethods_SolicitacoesNovaCategoria: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 6; TypeName: 'Integer') ); TServerMethods_podeAlterarAvaliacao: array [0..1] of TDSRestParameterMetaData = ( (Name: 'AIdComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); TServerMethods_salvaFuncionamento: array [0..7] of TDSRestParameterMetaData = ( (Name: 'AIDCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'ASeg'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Ater'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AQua'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'AQui'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ASex'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ASab'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ADom'; Direction: 1; DBXType: 26; TypeName: 'string') ); implementation procedure TServerMethodsClient.DataModuleCreate(Sender: TObject); begin if FDataModuleCreateCommand = nil then begin FDataModuleCreateCommand := FConnection.CreateCommand; FDataModuleCreateCommand.RequestType := 'POST'; FDataModuleCreateCommand.Text := 'TServerMethods."DataModuleCreate"'; FDataModuleCreateCommand.Prepare(TServerMethods_DataModuleCreate); end; if not Assigned(Sender) then FDataModuleCreateCommand.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FDataModuleCreateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FDataModuleCreateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Sender), True); if FInstanceOwner then Sender.Free finally FreeAndNil(FMarshal) end end; FDataModuleCreateCommand.Execute; end; procedure TServerMethodsClient.gravaSobre(AIdComercio: Integer; ASobre: string; ASlogem: string; ATag: string); begin if FgravaSobreCommand = nil then begin FgravaSobreCommand := FConnection.CreateCommand; FgravaSobreCommand.RequestType := 'GET'; FgravaSobreCommand.Text := 'TServerMethods.gravaSobre'; FgravaSobreCommand.Prepare(TServerMethods_gravaSobre); end; FgravaSobreCommand.Parameters[0].Value.SetInt32(AIdComercio); FgravaSobreCommand.Parameters[1].Value.SetWideString(ASobre); FgravaSobreCommand.Parameters[2].Value.SetWideString(ASlogem); FgravaSobreCommand.Parameters[3].Value.SetWideString(ATag); FgravaSobreCommand.Execute; end; function TServerMethodsClient.ListaPlanos(const ARequestFilter: string): TFDJSONDataSets; begin if FListaPlanosCommand = nil then begin FListaPlanosCommand := FConnection.CreateCommand; FListaPlanosCommand.RequestType := 'GET'; FListaPlanosCommand.Text := 'TServerMethods.ListaPlanos'; FListaPlanosCommand.Prepare(TServerMethods_ListaPlanos); end; FListaPlanosCommand.Execute(ARequestFilter); if not FListaPlanosCommand.Parameters[0].Value.IsNull then begin FUnMarshal := TDSRestCommand(FListaPlanosCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FListaPlanosCommand.Parameters[0].Value.GetJSONValue(True))); if FInstanceOwner then FListaPlanosCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.ListaPlanos_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FListaPlanosCommand_Cache = nil then begin FListaPlanosCommand_Cache := FConnection.CreateCommand; FListaPlanosCommand_Cache.RequestType := 'GET'; FListaPlanosCommand_Cache.Text := 'TServerMethods.ListaPlanos'; FListaPlanosCommand_Cache.Prepare(TServerMethods_ListaPlanos_Cache); end; FListaPlanosCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FListaPlanosCommand_Cache.Parameters[0].Value.GetString); end; function TServerMethodsClient.gravaDelivery(AIdCom: Integer; AUber: string; ARappi: string; AIfood: string; const ARequestFilter: string): Boolean; begin if FgravaDeliveryCommand = nil then begin FgravaDeliveryCommand := FConnection.CreateCommand; FgravaDeliveryCommand.RequestType := 'GET'; FgravaDeliveryCommand.Text := 'TServerMethods.gravaDelivery'; FgravaDeliveryCommand.Prepare(TServerMethods_gravaDelivery); end; FgravaDeliveryCommand.Parameters[0].Value.SetInt32(AIdCom); FgravaDeliveryCommand.Parameters[1].Value.SetWideString(AUber); FgravaDeliveryCommand.Parameters[2].Value.SetWideString(ARappi); FgravaDeliveryCommand.Parameters[3].Value.SetWideString(AIfood); FgravaDeliveryCommand.Execute(ARequestFilter); Result := FgravaDeliveryCommand.Parameters[4].Value.GetBoolean; end; function TServerMethodsClient.gravaRedesSociais(AIdCom: Integer; AFace: string; AInsta: string; ATwitter: string; AYouTube: string; AGPlus: string; ASite: string; AEmail: string; AGPlay: string; AStore: string; const ARequestFilter: string): Boolean; begin if FgravaRedesSociaisCommand = nil then begin FgravaRedesSociaisCommand := FConnection.CreateCommand; FgravaRedesSociaisCommand.RequestType := 'GET'; FgravaRedesSociaisCommand.Text := 'TServerMethods.gravaRedesSociais'; FgravaRedesSociaisCommand.Prepare(TServerMethods_gravaRedesSociais); end; FgravaRedesSociaisCommand.Parameters[0].Value.SetInt32(AIdCom); FgravaRedesSociaisCommand.Parameters[1].Value.SetWideString(AFace); FgravaRedesSociaisCommand.Parameters[2].Value.SetWideString(AInsta); FgravaRedesSociaisCommand.Parameters[3].Value.SetWideString(ATwitter); FgravaRedesSociaisCommand.Parameters[4].Value.SetWideString(AYouTube); FgravaRedesSociaisCommand.Parameters[5].Value.SetWideString(AGPlus); FgravaRedesSociaisCommand.Parameters[6].Value.SetWideString(ASite); FgravaRedesSociaisCommand.Parameters[7].Value.SetWideString(AEmail); FgravaRedesSociaisCommand.Parameters[8].Value.SetWideString(AGPlay); FgravaRedesSociaisCommand.Parameters[9].Value.SetWideString(AStore); FgravaRedesSociaisCommand.Execute(ARequestFilter); Result := FgravaRedesSociaisCommand.Parameters[10].Value.GetBoolean; end; function TServerMethodsClient.gravaCadastroAvaliacoes(AIdCom: Integer; AAmbiente: Boolean; AAtendimento: Boolean; ALimpeza: Boolean; ALocal: Boolean; APreco: Boolean; const ARequestFilter: string): Boolean; begin if FgravaCadastroAvaliacoesCommand = nil then begin FgravaCadastroAvaliacoesCommand := FConnection.CreateCommand; FgravaCadastroAvaliacoesCommand.RequestType := 'GET'; FgravaCadastroAvaliacoesCommand.Text := 'TServerMethods.gravaCadastroAvaliacoes'; FgravaCadastroAvaliacoesCommand.Prepare(TServerMethods_gravaCadastroAvaliacoes); end; FgravaCadastroAvaliacoesCommand.Parameters[0].Value.SetInt32(AIdCom); FgravaCadastroAvaliacoesCommand.Parameters[1].Value.SetBoolean(AAmbiente); FgravaCadastroAvaliacoesCommand.Parameters[2].Value.SetBoolean(AAtendimento); FgravaCadastroAvaliacoesCommand.Parameters[3].Value.SetBoolean(ALimpeza); FgravaCadastroAvaliacoesCommand.Parameters[4].Value.SetBoolean(ALocal); FgravaCadastroAvaliacoesCommand.Parameters[5].Value.SetBoolean(APreco); FgravaCadastroAvaliacoesCommand.Execute(ARequestFilter); Result := FgravaCadastroAvaliacoesCommand.Parameters[6].Value.GetBoolean; end; function TServerMethodsClient.LoadGrupos(AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadGruposCommand = nil then begin FLoadGruposCommand := FConnection.CreateCommand; FLoadGruposCommand.RequestType := 'GET'; FLoadGruposCommand.Text := 'TServerMethods.LoadGrupos'; FLoadGruposCommand.Prepare(TServerMethods_LoadGrupos); end; FLoadGruposCommand.Parameters[0].Value.SetInt32(AIdCom); FLoadGruposCommand.Execute(ARequestFilter); if not FLoadGruposCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadGruposCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadGruposCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FLoadGruposCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadGrupos_Cache(AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadGruposCommand_Cache = nil then begin FLoadGruposCommand_Cache := FConnection.CreateCommand; FLoadGruposCommand_Cache.RequestType := 'GET'; FLoadGruposCommand_Cache.Text := 'TServerMethods.LoadGrupos'; FLoadGruposCommand_Cache.Prepare(TServerMethods_LoadGrupos_Cache); end; FLoadGruposCommand_Cache.Parameters[0].Value.SetInt32(AIdCom); FLoadGruposCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadGruposCommand_Cache.Parameters[1].Value.GetString); end; procedure TServerMethodsClient.UpdateGrupoCom(AIdCom: Integer; AIdGrupo: Integer); begin if FUpdateGrupoComCommand = nil then begin FUpdateGrupoComCommand := FConnection.CreateCommand; FUpdateGrupoComCommand.RequestType := 'GET'; FUpdateGrupoComCommand.Text := 'TServerMethods.UpdateGrupoCom'; FUpdateGrupoComCommand.Prepare(TServerMethods_UpdateGrupoCom); end; FUpdateGrupoComCommand.Parameters[0].Value.SetInt32(AIdCom); FUpdateGrupoComCommand.Parameters[1].Value.SetInt32(AIdGrupo); FUpdateGrupoComCommand.Execute; end; procedure TServerMethodsClient.EnviarEmail(pCodigo: string; pAssunto: string; pNome: string; pEmail: string; pTipoEmail: string; pHtml: Boolean); begin if FEnviarEmailCommand = nil then begin FEnviarEmailCommand := FConnection.CreateCommand; FEnviarEmailCommand.RequestType := 'GET'; FEnviarEmailCommand.Text := 'TServerMethods.EnviarEmail'; FEnviarEmailCommand.Prepare(TServerMethods_EnviarEmail); end; FEnviarEmailCommand.Parameters[0].Value.SetWideString(pCodigo); FEnviarEmailCommand.Parameters[1].Value.SetWideString(pAssunto); FEnviarEmailCommand.Parameters[2].Value.SetWideString(pNome); FEnviarEmailCommand.Parameters[3].Value.SetWideString(pEmail); FEnviarEmailCommand.Parameters[4].Value.SetWideString(pTipoEmail); FEnviarEmailCommand.Parameters[5].Value.SetBoolean(pHtml); FEnviarEmailCommand.Execute; end; function TServerMethodsClient.TelRepetido(ATelefone: string; const ARequestFilter: string): Integer; begin if FTelRepetidoCommand = nil then begin FTelRepetidoCommand := FConnection.CreateCommand; FTelRepetidoCommand.RequestType := 'GET'; FTelRepetidoCommand.Text := 'TServerMethods.TelRepetido'; FTelRepetidoCommand.Prepare(TServerMethods_TelRepetido); end; FTelRepetidoCommand.Parameters[0].Value.SetWideString(ATelefone); FTelRepetidoCommand.Execute(ARequestFilter); Result := FTelRepetidoCommand.Parameters[1].Value.GetInt32; end; function TServerMethodsClient.AddComercioNovo(ARazao: string; AFantasia: string; ACep: string; AComplemento: string; ACNPJCPF: string; AIERG: string; AEmail: string; ASenha: string; ALoginFone: string; ANumero: Integer; const ARequestFilter: string): Integer; begin if FAddComercioNovoCommand = nil then begin FAddComercioNovoCommand := FConnection.CreateCommand; FAddComercioNovoCommand.RequestType := 'GET'; FAddComercioNovoCommand.Text := 'TServerMethods.AddComercioNovo'; FAddComercioNovoCommand.Prepare(TServerMethods_AddComercioNovo); end; FAddComercioNovoCommand.Parameters[0].Value.SetWideString(ARazao); FAddComercioNovoCommand.Parameters[1].Value.SetWideString(AFantasia); FAddComercioNovoCommand.Parameters[2].Value.SetWideString(ACep); FAddComercioNovoCommand.Parameters[3].Value.SetWideString(AComplemento); FAddComercioNovoCommand.Parameters[4].Value.SetWideString(ACNPJCPF); FAddComercioNovoCommand.Parameters[5].Value.SetWideString(AIERG); FAddComercioNovoCommand.Parameters[6].Value.SetWideString(AEmail); FAddComercioNovoCommand.Parameters[7].Value.SetWideString(ASenha); FAddComercioNovoCommand.Parameters[8].Value.SetWideString(ALoginFone); FAddComercioNovoCommand.Parameters[9].Value.SetInt32(ANumero); FAddComercioNovoCommand.Execute(ARequestFilter); Result := FAddComercioNovoCommand.Parameters[10].Value.GetInt32; end; procedure TServerMethodsClient.AddTelefone(ATelefone: string; AContato: string; AZap: string; AInterno: string; AIdComFone: Integer; AIdFone: Integer); begin if FAddTelefoneCommand = nil then begin FAddTelefoneCommand := FConnection.CreateCommand; FAddTelefoneCommand.RequestType := 'GET'; FAddTelefoneCommand.Text := 'TServerMethods.AddTelefone'; FAddTelefoneCommand.Prepare(TServerMethods_AddTelefone); end; FAddTelefoneCommand.Parameters[0].Value.SetWideString(ATelefone); FAddTelefoneCommand.Parameters[1].Value.SetWideString(AContato); FAddTelefoneCommand.Parameters[2].Value.SetWideString(AZap); FAddTelefoneCommand.Parameters[3].Value.SetWideString(AInterno); FAddTelefoneCommand.Parameters[4].Value.SetInt32(AIdComFone); FAddTelefoneCommand.Parameters[5].Value.SetInt32(AIdFone); FAddTelefoneCommand.Execute; end; function TServerMethodsClient.DocRepetido(AField: string; ADoc: string; const ARequestFilter: string): Boolean; begin if FDocRepetidoCommand = nil then begin FDocRepetidoCommand := FConnection.CreateCommand; FDocRepetidoCommand.RequestType := 'GET'; FDocRepetidoCommand.Text := 'TServerMethods.DocRepetido'; FDocRepetidoCommand.Prepare(TServerMethods_DocRepetido); end; FDocRepetidoCommand.Parameters[0].Value.SetWideString(AField); FDocRepetidoCommand.Parameters[1].Value.SetWideString(ADoc); FDocRepetidoCommand.Execute(ARequestFilter); Result := FDocRepetidoCommand.Parameters[2].Value.GetBoolean; end; function TServerMethodsClient.getTelefone(AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FgetTelefoneCommand = nil then begin FgetTelefoneCommand := FConnection.CreateCommand; FgetTelefoneCommand.RequestType := 'GET'; FgetTelefoneCommand.Text := 'TServerMethods.getTelefone'; FgetTelefoneCommand.Prepare(TServerMethods_getTelefone); end; FgetTelefoneCommand.Parameters[0].Value.SetInt32(AIdCom); FgetTelefoneCommand.Execute(ARequestFilter); if not FgetTelefoneCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetTelefoneCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetTelefoneCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FgetTelefoneCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getTelefone_Cache(AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetTelefoneCommand_Cache = nil then begin FgetTelefoneCommand_Cache := FConnection.CreateCommand; FgetTelefoneCommand_Cache.RequestType := 'GET'; FgetTelefoneCommand_Cache.Text := 'TServerMethods.getTelefone'; FgetTelefoneCommand_Cache.Prepare(TServerMethods_getTelefone_Cache); end; FgetTelefoneCommand_Cache.Parameters[0].Value.SetInt32(AIdCom); FgetTelefoneCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetTelefoneCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.LoadCategorias(AIdPush: string; ARaio: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadCategoriasCommand = nil then begin FLoadCategoriasCommand := FConnection.CreateCommand; FLoadCategoriasCommand.RequestType := 'GET'; FLoadCategoriasCommand.Text := 'TServerMethods.LoadCategorias'; FLoadCategoriasCommand.Prepare(TServerMethods_LoadCategorias); end; FLoadCategoriasCommand.Parameters[0].Value.SetWideString(AIdPush); FLoadCategoriasCommand.Parameters[1].Value.SetInt32(ARaio); FLoadCategoriasCommand.Execute(ARequestFilter); if not FLoadCategoriasCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadCategoriasCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadCategoriasCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FLoadCategoriasCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadCategorias_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadCategoriasCommand_Cache = nil then begin FLoadCategoriasCommand_Cache := FConnection.CreateCommand; FLoadCategoriasCommand_Cache.RequestType := 'GET'; FLoadCategoriasCommand_Cache.Text := 'TServerMethods.LoadCategorias'; FLoadCategoriasCommand_Cache.Prepare(TServerMethods_LoadCategorias_Cache); end; FLoadCategoriasCommand_Cache.Parameters[0].Value.SetWideString(AIdPush); FLoadCategoriasCommand_Cache.Parameters[1].Value.SetInt32(ARaio); FLoadCategoriasCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadCategoriasCommand_Cache.Parameters[2].Value.GetString); end; function TServerMethodsClient.LoadDestaquePrincipal(AIdPush: string; ARaio: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadDestaquePrincipalCommand = nil then begin FLoadDestaquePrincipalCommand := FConnection.CreateCommand; FLoadDestaquePrincipalCommand.RequestType := 'GET'; FLoadDestaquePrincipalCommand.Text := 'TServerMethods.LoadDestaquePrincipal'; FLoadDestaquePrincipalCommand.Prepare(TServerMethods_LoadDestaquePrincipal); end; FLoadDestaquePrincipalCommand.Parameters[0].Value.SetWideString(AIdPush); FLoadDestaquePrincipalCommand.Parameters[1].Value.SetInt32(ARaio); FLoadDestaquePrincipalCommand.Execute(ARequestFilter); if not FLoadDestaquePrincipalCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadDestaquePrincipalCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadDestaquePrincipalCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FLoadDestaquePrincipalCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadDestaquePrincipal_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadDestaquePrincipalCommand_Cache = nil then begin FLoadDestaquePrincipalCommand_Cache := FConnection.CreateCommand; FLoadDestaquePrincipalCommand_Cache.RequestType := 'GET'; FLoadDestaquePrincipalCommand_Cache.Text := 'TServerMethods.LoadDestaquePrincipal'; FLoadDestaquePrincipalCommand_Cache.Prepare(TServerMethods_LoadDestaquePrincipal_Cache); end; FLoadDestaquePrincipalCommand_Cache.Parameters[0].Value.SetWideString(AIdPush); FLoadDestaquePrincipalCommand_Cache.Parameters[1].Value.SetInt32(ARaio); FLoadDestaquePrincipalCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadDestaquePrincipalCommand_Cache.Parameters[2].Value.GetString); end; function TServerMethodsClient.LoadComercioCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadComercioCategoriaCommand = nil then begin FLoadComercioCategoriaCommand := FConnection.CreateCommand; FLoadComercioCategoriaCommand.RequestType := 'GET'; FLoadComercioCategoriaCommand.Text := 'TServerMethods.LoadComercioCategoria'; FLoadComercioCategoriaCommand.Prepare(TServerMethods_LoadComercioCategoria); end; FLoadComercioCategoriaCommand.Parameters[0].Value.SetWideString(AIdPush); FLoadComercioCategoriaCommand.Parameters[1].Value.SetInt32(ARaio); FLoadComercioCategoriaCommand.Parameters[2].Value.SetInt32(IdCategoria); FLoadComercioCategoriaCommand.Parameters[3].Value.SetInt32(IdSubCategoria); FLoadComercioCategoriaCommand.Execute(ARequestFilter); if not FLoadComercioCategoriaCommand.Parameters[4].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadComercioCategoriaCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadComercioCategoriaCommand.Parameters[4].Value.GetJSONValue(True))); if FInstanceOwner then FLoadComercioCategoriaCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadComercioCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadComercioCategoriaCommand_Cache = nil then begin FLoadComercioCategoriaCommand_Cache := FConnection.CreateCommand; FLoadComercioCategoriaCommand_Cache.RequestType := 'GET'; FLoadComercioCategoriaCommand_Cache.Text := 'TServerMethods.LoadComercioCategoria'; FLoadComercioCategoriaCommand_Cache.Prepare(TServerMethods_LoadComercioCategoria_Cache); end; FLoadComercioCategoriaCommand_Cache.Parameters[0].Value.SetWideString(AIdPush); FLoadComercioCategoriaCommand_Cache.Parameters[1].Value.SetInt32(ARaio); FLoadComercioCategoriaCommand_Cache.Parameters[2].Value.SetInt32(IdCategoria); FLoadComercioCategoriaCommand_Cache.Parameters[3].Value.SetInt32(IdSubCategoria); FLoadComercioCategoriaCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadComercioCategoriaCommand_Cache.Parameters[4].Value.GetString); end; function TServerMethodsClient.LoadSubCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadSubCategoriaCommand = nil then begin FLoadSubCategoriaCommand := FConnection.CreateCommand; FLoadSubCategoriaCommand.RequestType := 'GET'; FLoadSubCategoriaCommand.Text := 'TServerMethods.LoadSubCategoria'; FLoadSubCategoriaCommand.Prepare(TServerMethods_LoadSubCategoria); end; FLoadSubCategoriaCommand.Parameters[0].Value.SetWideString(AIdPush); FLoadSubCategoriaCommand.Parameters[1].Value.SetInt32(ARaio); FLoadSubCategoriaCommand.Parameters[2].Value.SetInt32(IdCategoria); FLoadSubCategoriaCommand.Execute(ARequestFilter); if not FLoadSubCategoriaCommand.Parameters[3].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadSubCategoriaCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadSubCategoriaCommand.Parameters[3].Value.GetJSONValue(True))); if FInstanceOwner then FLoadSubCategoriaCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadSubCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadSubCategoriaCommand_Cache = nil then begin FLoadSubCategoriaCommand_Cache := FConnection.CreateCommand; FLoadSubCategoriaCommand_Cache.RequestType := 'GET'; FLoadSubCategoriaCommand_Cache.Text := 'TServerMethods.LoadSubCategoria'; FLoadSubCategoriaCommand_Cache.Prepare(TServerMethods_LoadSubCategoria_Cache); end; FLoadSubCategoriaCommand_Cache.Parameters[0].Value.SetWideString(AIdPush); FLoadSubCategoriaCommand_Cache.Parameters[1].Value.SetInt32(ARaio); FLoadSubCategoriaCommand_Cache.Parameters[2].Value.SetInt32(IdCategoria); FLoadSubCategoriaCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadSubCategoriaCommand_Cache.Parameters[3].Value.GetString); end; function TServerMethodsClient.LoadFotosPorSecao(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadFotosPorSecaoCommand = nil then begin FLoadFotosPorSecaoCommand := FConnection.CreateCommand; FLoadFotosPorSecaoCommand.RequestType := 'GET'; FLoadFotosPorSecaoCommand.Text := 'TServerMethods.LoadFotosPorSecao'; FLoadFotosPorSecaoCommand.Prepare(TServerMethods_LoadFotosPorSecao); end; FLoadFotosPorSecaoCommand.Parameters[0].Value.SetInt32(ARaio); FLoadFotosPorSecaoCommand.Parameters[1].Value.SetInt32(vIdCat); FLoadFotosPorSecaoCommand.Parameters[2].Value.SetWideString(APesquisa); FLoadFotosPorSecaoCommand.Parameters[3].Value.SetWideString(AIdPush); FLoadFotosPorSecaoCommand.Execute(ARequestFilter); if not FLoadFotosPorSecaoCommand.Parameters[4].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadFotosPorSecaoCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadFotosPorSecaoCommand.Parameters[4].Value.GetJSONValue(True))); if FInstanceOwner then FLoadFotosPorSecaoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadFotosPorSecao_Cache(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadFotosPorSecaoCommand_Cache = nil then begin FLoadFotosPorSecaoCommand_Cache := FConnection.CreateCommand; FLoadFotosPorSecaoCommand_Cache.RequestType := 'GET'; FLoadFotosPorSecaoCommand_Cache.Text := 'TServerMethods.LoadFotosPorSecao'; FLoadFotosPorSecaoCommand_Cache.Prepare(TServerMethods_LoadFotosPorSecao_Cache); end; FLoadFotosPorSecaoCommand_Cache.Parameters[0].Value.SetInt32(ARaio); FLoadFotosPorSecaoCommand_Cache.Parameters[1].Value.SetInt32(vIdCat); FLoadFotosPorSecaoCommand_Cache.Parameters[2].Value.SetWideString(APesquisa); FLoadFotosPorSecaoCommand_Cache.Parameters[3].Value.SetWideString(AIdPush); FLoadFotosPorSecaoCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadFotosPorSecaoCommand_Cache.Parameters[4].Value.GetString); end; function TServerMethodsClient.LoadComercioPesquisa(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadComercioPesquisaCommand = nil then begin FLoadComercioPesquisaCommand := FConnection.CreateCommand; FLoadComercioPesquisaCommand.RequestType := 'GET'; FLoadComercioPesquisaCommand.Text := 'TServerMethods.LoadComercioPesquisa'; FLoadComercioPesquisaCommand.Prepare(TServerMethods_LoadComercioPesquisa); end; FLoadComercioPesquisaCommand.Parameters[0].Value.SetInt32(ARaio); FLoadComercioPesquisaCommand.Parameters[1].Value.SetWideString(FPesquisa); FLoadComercioPesquisaCommand.Parameters[2].Value.SetWideString(AIdPush); FLoadComercioPesquisaCommand.Execute(ARequestFilter); if not FLoadComercioPesquisaCommand.Parameters[3].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadComercioPesquisaCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadComercioPesquisaCommand.Parameters[3].Value.GetJSONValue(True))); if FInstanceOwner then FLoadComercioPesquisaCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadComercioPesquisa_Cache(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadComercioPesquisaCommand_Cache = nil then begin FLoadComercioPesquisaCommand_Cache := FConnection.CreateCommand; FLoadComercioPesquisaCommand_Cache.RequestType := 'GET'; FLoadComercioPesquisaCommand_Cache.Text := 'TServerMethods.LoadComercioPesquisa'; FLoadComercioPesquisaCommand_Cache.Prepare(TServerMethods_LoadComercioPesquisa_Cache); end; FLoadComercioPesquisaCommand_Cache.Parameters[0].Value.SetInt32(ARaio); FLoadComercioPesquisaCommand_Cache.Parameters[1].Value.SetWideString(FPesquisa); FLoadComercioPesquisaCommand_Cache.Parameters[2].Value.SetWideString(AIdPush); FLoadComercioPesquisaCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadComercioPesquisaCommand_Cache.Parameters[3].Value.GetString); end; function TServerMethodsClient.LoadDestaqueFavorito(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadDestaqueFavoritoCommand = nil then begin FLoadDestaqueFavoritoCommand := FConnection.CreateCommand; FLoadDestaqueFavoritoCommand.RequestType := 'GET'; FLoadDestaqueFavoritoCommand.Text := 'TServerMethods.LoadDestaqueFavorito'; FLoadDestaqueFavoritoCommand.Prepare(TServerMethods_LoadDestaqueFavorito); end; FLoadDestaqueFavoritoCommand.Parameters[0].Value.SetWideString(AIdPush); FLoadDestaqueFavoritoCommand.Parameters[1].Value.SetInt32(ARaio); FLoadDestaqueFavoritoCommand.Parameters[2].Value.SetInt32(vIdUsu); FLoadDestaqueFavoritoCommand.Execute(ARequestFilter); if not FLoadDestaqueFavoritoCommand.Parameters[3].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadDestaqueFavoritoCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadDestaqueFavoritoCommand.Parameters[3].Value.GetJSONValue(True))); if FInstanceOwner then FLoadDestaqueFavoritoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadDestaqueFavorito_Cache(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadDestaqueFavoritoCommand_Cache = nil then begin FLoadDestaqueFavoritoCommand_Cache := FConnection.CreateCommand; FLoadDestaqueFavoritoCommand_Cache.RequestType := 'GET'; FLoadDestaqueFavoritoCommand_Cache.Text := 'TServerMethods.LoadDestaqueFavorito'; FLoadDestaqueFavoritoCommand_Cache.Prepare(TServerMethods_LoadDestaqueFavorito_Cache); end; FLoadDestaqueFavoritoCommand_Cache.Parameters[0].Value.SetWideString(AIdPush); FLoadDestaqueFavoritoCommand_Cache.Parameters[1].Value.SetInt32(ARaio); FLoadDestaqueFavoritoCommand_Cache.Parameters[2].Value.SetInt32(vIdUsu); FLoadDestaqueFavoritoCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadDestaqueFavoritoCommand_Cache.Parameters[3].Value.GetString); end; procedure TServerMethodsClient.InsertNewSubCategoria(AIdCategoria: Integer; AIdCom: Integer; ANomeSubCategoria: string); begin if FInsertNewSubCategoriaCommand = nil then begin FInsertNewSubCategoriaCommand := FConnection.CreateCommand; FInsertNewSubCategoriaCommand.RequestType := 'GET'; FInsertNewSubCategoriaCommand.Text := 'TServerMethods.InsertNewSubCategoria'; FInsertNewSubCategoriaCommand.Prepare(TServerMethods_InsertNewSubCategoria); end; FInsertNewSubCategoriaCommand.Parameters[0].Value.SetInt32(AIdCategoria); FInsertNewSubCategoriaCommand.Parameters[1].Value.SetInt32(AIdCom); FInsertNewSubCategoriaCommand.Parameters[2].Value.SetWideString(ANomeSubCategoria); FInsertNewSubCategoriaCommand.Execute; end; function TServerMethodsClient.RecebeNotificacao(AKeyPush: string; const ARequestFilter: string): Boolean; begin if FRecebeNotificacaoCommand = nil then begin FRecebeNotificacaoCommand := FConnection.CreateCommand; FRecebeNotificacaoCommand.RequestType := 'GET'; FRecebeNotificacaoCommand.Text := 'TServerMethods.RecebeNotificacao'; FRecebeNotificacaoCommand.Prepare(TServerMethods_RecebeNotificacao); end; FRecebeNotificacaoCommand.Parameters[0].Value.SetWideString(AKeyPush); FRecebeNotificacaoCommand.Execute(ARequestFilter); Result := FRecebeNotificacaoCommand.Parameters[1].Value.GetBoolean; end; function TServerMethodsClient.VerificaUsuarioAvaliou(AIdUsu: Integer; AIdCom: Integer; const ARequestFilter: string): Boolean; begin if FVerificaUsuarioAvaliouCommand = nil then begin FVerificaUsuarioAvaliouCommand := FConnection.CreateCommand; FVerificaUsuarioAvaliouCommand.RequestType := 'GET'; FVerificaUsuarioAvaliouCommand.Text := 'TServerMethods.VerificaUsuarioAvaliou'; FVerificaUsuarioAvaliouCommand.Prepare(TServerMethods_VerificaUsuarioAvaliou); end; FVerificaUsuarioAvaliouCommand.Parameters[0].Value.SetInt32(AIdUsu); FVerificaUsuarioAvaliouCommand.Parameters[1].Value.SetInt32(AIdCom); FVerificaUsuarioAvaliouCommand.Execute(ARequestFilter); Result := FVerificaUsuarioAvaliouCommand.Parameters[2].Value.GetBoolean; end; function TServerMethodsClient.LoadFichaComercio(AIdComercio: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadFichaComercioCommand = nil then begin FLoadFichaComercioCommand := FConnection.CreateCommand; FLoadFichaComercioCommand.RequestType := 'GET'; FLoadFichaComercioCommand.Text := 'TServerMethods.LoadFichaComercio'; FLoadFichaComercioCommand.Prepare(TServerMethods_LoadFichaComercio); end; FLoadFichaComercioCommand.Parameters[0].Value.SetInt32(AIdComercio); FLoadFichaComercioCommand.Execute(ARequestFilter); if not FLoadFichaComercioCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadFichaComercioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadFichaComercioCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FLoadFichaComercioCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadFichaComercio_Cache(AIdComercio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadFichaComercioCommand_Cache = nil then begin FLoadFichaComercioCommand_Cache := FConnection.CreateCommand; FLoadFichaComercioCommand_Cache.RequestType := 'GET'; FLoadFichaComercioCommand_Cache.Text := 'TServerMethods.LoadFichaComercio'; FLoadFichaComercioCommand_Cache.Prepare(TServerMethods_LoadFichaComercio_Cache); end; FLoadFichaComercioCommand_Cache.Parameters[0].Value.SetInt32(AIdComercio); FLoadFichaComercioCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadFichaComercioCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.LoadComercio(idComercio: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadComercioCommand = nil then begin FLoadComercioCommand := FConnection.CreateCommand; FLoadComercioCommand.RequestType := 'GET'; FLoadComercioCommand.Text := 'TServerMethods.LoadComercio'; FLoadComercioCommand.Prepare(TServerMethods_LoadComercio); end; FLoadComercioCommand.Parameters[0].Value.SetInt32(idComercio); FLoadComercioCommand.Execute(ARequestFilter); if not FLoadComercioCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadComercioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadComercioCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FLoadComercioCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadComercio_Cache(idComercio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadComercioCommand_Cache = nil then begin FLoadComercioCommand_Cache := FConnection.CreateCommand; FLoadComercioCommand_Cache.RequestType := 'GET'; FLoadComercioCommand_Cache.Text := 'TServerMethods.LoadComercio'; FLoadComercioCommand_Cache.Prepare(TServerMethods_LoadComercio_Cache); end; FLoadComercioCommand_Cache.Parameters[0].Value.SetInt32(idComercio); FLoadComercioCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadComercioCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.LoadAvaliacoes(idComercio: Integer; nStart: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadAvaliacoesCommand = nil then begin FLoadAvaliacoesCommand := FConnection.CreateCommand; FLoadAvaliacoesCommand.RequestType := 'GET'; FLoadAvaliacoesCommand.Text := 'TServerMethods.LoadAvaliacoes'; FLoadAvaliacoesCommand.Prepare(TServerMethods_LoadAvaliacoes); end; FLoadAvaliacoesCommand.Parameters[0].Value.SetInt32(idComercio); FLoadAvaliacoesCommand.Parameters[1].Value.SetInt32(nStart); FLoadAvaliacoesCommand.Execute(ARequestFilter); if not FLoadAvaliacoesCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadAvaliacoesCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadAvaliacoesCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FLoadAvaliacoesCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadAvaliacoes_Cache(idComercio: Integer; nStart: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadAvaliacoesCommand_Cache = nil then begin FLoadAvaliacoesCommand_Cache := FConnection.CreateCommand; FLoadAvaliacoesCommand_Cache.RequestType := 'GET'; FLoadAvaliacoesCommand_Cache.Text := 'TServerMethods.LoadAvaliacoes'; FLoadAvaliacoesCommand_Cache.Prepare(TServerMethods_LoadAvaliacoes_Cache); end; FLoadAvaliacoesCommand_Cache.Parameters[0].Value.SetInt32(idComercio); FLoadAvaliacoesCommand_Cache.Parameters[1].Value.SetInt32(nStart); FLoadAvaliacoesCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadAvaliacoesCommand_Cache.Parameters[2].Value.GetString); end; function TServerMethodsClient.VerificaCelularDuplicado(vCelular: string; const ARequestFilter: string): TFDJSONDataSets; begin if FVerificaCelularDuplicadoCommand = nil then begin FVerificaCelularDuplicadoCommand := FConnection.CreateCommand; FVerificaCelularDuplicadoCommand.RequestType := 'GET'; FVerificaCelularDuplicadoCommand.Text := 'TServerMethods.VerificaCelularDuplicado'; FVerificaCelularDuplicadoCommand.Prepare(TServerMethods_VerificaCelularDuplicado); end; FVerificaCelularDuplicadoCommand.Parameters[0].Value.SetWideString(vCelular); FVerificaCelularDuplicadoCommand.Execute(ARequestFilter); if not FVerificaCelularDuplicadoCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FVerificaCelularDuplicadoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FVerificaCelularDuplicadoCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FVerificaCelularDuplicadoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.VerificaCelularDuplicado_Cache(vCelular: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FVerificaCelularDuplicadoCommand_Cache = nil then begin FVerificaCelularDuplicadoCommand_Cache := FConnection.CreateCommand; FVerificaCelularDuplicadoCommand_Cache.RequestType := 'GET'; FVerificaCelularDuplicadoCommand_Cache.Text := 'TServerMethods.VerificaCelularDuplicado'; FVerificaCelularDuplicadoCommand_Cache.Prepare(TServerMethods_VerificaCelularDuplicado_Cache); end; FVerificaCelularDuplicadoCommand_Cache.Parameters[0].Value.SetWideString(vCelular); FVerificaCelularDuplicadoCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FVerificaCelularDuplicadoCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.DownloadIdUsuario(vCelular: string; const ARequestFilter: string): TFDJSONDataSets; begin if FDownloadIdUsuarioCommand = nil then begin FDownloadIdUsuarioCommand := FConnection.CreateCommand; FDownloadIdUsuarioCommand.RequestType := 'GET'; FDownloadIdUsuarioCommand.Text := 'TServerMethods.DownloadIdUsuario'; FDownloadIdUsuarioCommand.Prepare(TServerMethods_DownloadIdUsuario); end; FDownloadIdUsuarioCommand.Parameters[0].Value.SetWideString(vCelular); FDownloadIdUsuarioCommand.Execute(ARequestFilter); if not FDownloadIdUsuarioCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FDownloadIdUsuarioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDownloadIdUsuarioCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FDownloadIdUsuarioCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.DownloadIdUsuario_Cache(vCelular: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FDownloadIdUsuarioCommand_Cache = nil then begin FDownloadIdUsuarioCommand_Cache := FConnection.CreateCommand; FDownloadIdUsuarioCommand_Cache.RequestType := 'GET'; FDownloadIdUsuarioCommand_Cache.Text := 'TServerMethods.DownloadIdUsuario'; FDownloadIdUsuarioCommand_Cache.Prepare(TServerMethods_DownloadIdUsuario_Cache); end; FDownloadIdUsuarioCommand_Cache.Parameters[0].Value.SetWideString(vCelular); FDownloadIdUsuarioCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FDownloadIdUsuarioCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.DownloadUsuario(vCelular: string; const ARequestFilter: string): TFDJSONDataSets; begin if FDownloadUsuarioCommand = nil then begin FDownloadUsuarioCommand := FConnection.CreateCommand; FDownloadUsuarioCommand.RequestType := 'GET'; FDownloadUsuarioCommand.Text := 'TServerMethods.DownloadUsuario'; FDownloadUsuarioCommand.Prepare(TServerMethods_DownloadUsuario); end; FDownloadUsuarioCommand.Parameters[0].Value.SetWideString(vCelular); FDownloadUsuarioCommand.Execute(ARequestFilter); if not FDownloadUsuarioCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FDownloadUsuarioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDownloadUsuarioCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FDownloadUsuarioCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.DownloadUsuario_Cache(vCelular: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FDownloadUsuarioCommand_Cache = nil then begin FDownloadUsuarioCommand_Cache := FConnection.CreateCommand; FDownloadUsuarioCommand_Cache.RequestType := 'GET'; FDownloadUsuarioCommand_Cache.Text := 'TServerMethods.DownloadUsuario'; FDownloadUsuarioCommand_Cache.Prepare(TServerMethods_DownloadUsuario_Cache); end; FDownloadUsuarioCommand_Cache.Parameters[0].Value.SetWideString(vCelular); FDownloadUsuarioCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FDownloadUsuarioCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.DownloadUsuarioId(fIdUsu: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FDownloadUsuarioIdCommand = nil then begin FDownloadUsuarioIdCommand := FConnection.CreateCommand; FDownloadUsuarioIdCommand.RequestType := 'GET'; FDownloadUsuarioIdCommand.Text := 'TServerMethods.DownloadUsuarioId'; FDownloadUsuarioIdCommand.Prepare(TServerMethods_DownloadUsuarioId); end; FDownloadUsuarioIdCommand.Parameters[0].Value.SetInt32(fIdUsu); FDownloadUsuarioIdCommand.Execute(ARequestFilter); if not FDownloadUsuarioIdCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FDownloadUsuarioIdCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDownloadUsuarioIdCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FDownloadUsuarioIdCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.DownloadUsuarioId_Cache(fIdUsu: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FDownloadUsuarioIdCommand_Cache = nil then begin FDownloadUsuarioIdCommand_Cache := FConnection.CreateCommand; FDownloadUsuarioIdCommand_Cache.RequestType := 'GET'; FDownloadUsuarioIdCommand_Cache.Text := 'TServerMethods.DownloadUsuarioId'; FDownloadUsuarioIdCommand_Cache.Prepare(TServerMethods_DownloadUsuarioId_Cache); end; FDownloadUsuarioIdCommand_Cache.Parameters[0].Value.SetInt32(fIdUsu); FDownloadUsuarioIdCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FDownloadUsuarioIdCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.UpdateUsuario(FNome: string; FCelular: string; FSenha: string; FID: Integer; const ARequestFilter: string): Boolean; begin if FUpdateUsuarioCommand = nil then begin FUpdateUsuarioCommand := FConnection.CreateCommand; FUpdateUsuarioCommand.RequestType := 'GET'; FUpdateUsuarioCommand.Text := 'TServerMethods.UpdateUsuario'; FUpdateUsuarioCommand.Prepare(TServerMethods_UpdateUsuario); end; FUpdateUsuarioCommand.Parameters[0].Value.SetWideString(FNome); FUpdateUsuarioCommand.Parameters[1].Value.SetWideString(FCelular); FUpdateUsuarioCommand.Parameters[2].Value.SetWideString(FSenha); FUpdateUsuarioCommand.Parameters[3].Value.SetInt32(FID); FUpdateUsuarioCommand.Execute(ARequestFilter); Result := FUpdateUsuarioCommand.Parameters[4].Value.GetBoolean; end; function TServerMethodsClient.InsertUsuario(FNome: string; FCelular: string; FSenha: string; const ARequestFilter: string): Boolean; begin if FInsertUsuarioCommand = nil then begin FInsertUsuarioCommand := FConnection.CreateCommand; FInsertUsuarioCommand.RequestType := 'GET'; FInsertUsuarioCommand.Text := 'TServerMethods.InsertUsuario'; FInsertUsuarioCommand.Prepare(TServerMethods_InsertUsuario); end; FInsertUsuarioCommand.Parameters[0].Value.SetWideString(FNome); FInsertUsuarioCommand.Parameters[1].Value.SetWideString(FCelular); FInsertUsuarioCommand.Parameters[2].Value.SetWideString(FSenha); FInsertUsuarioCommand.Execute(ARequestFilter); Result := FInsertUsuarioCommand.Parameters[3].Value.GetBoolean; end; procedure TServerMethodsClient.ControleFavorito(FIdUsu: Integer; FIdCom: Integer; FAction: string); begin if FControleFavoritoCommand = nil then begin FControleFavoritoCommand := FConnection.CreateCommand; FControleFavoritoCommand.RequestType := 'GET'; FControleFavoritoCommand.Text := 'TServerMethods.ControleFavorito'; FControleFavoritoCommand.Prepare(TServerMethods_ControleFavorito); end; FControleFavoritoCommand.Parameters[0].Value.SetInt32(FIdUsu); FControleFavoritoCommand.Parameters[1].Value.SetInt32(FIdCom); FControleFavoritoCommand.Parameters[2].Value.SetWideString(FAction); FControleFavoritoCommand.Execute; end; procedure TServerMethodsClient.RegistrarDispositivo(ADeviceToken: string; AIdUsu: Integer); begin if FRegistrarDispositivoCommand = nil then begin FRegistrarDispositivoCommand := FConnection.CreateCommand; FRegistrarDispositivoCommand.RequestType := 'GET'; FRegistrarDispositivoCommand.Text := 'TServerMethods.RegistrarDispositivo'; FRegistrarDispositivoCommand.Prepare(TServerMethods_RegistrarDispositivo); end; FRegistrarDispositivoCommand.Parameters[0].Value.SetWideString(ADeviceToken); FRegistrarDispositivoCommand.Parameters[1].Value.SetInt32(AIdUsu); FRegistrarDispositivoCommand.Execute; end; function TServerMethodsClient.IsFavorito(FIdUsu: Integer; FIdCom: Integer; const ARequestFilter: string): Boolean; begin if FIsFavoritoCommand = nil then begin FIsFavoritoCommand := FConnection.CreateCommand; FIsFavoritoCommand.RequestType := 'GET'; FIsFavoritoCommand.Text := 'TServerMethods.IsFavorito'; FIsFavoritoCommand.Prepare(TServerMethods_IsFavorito); end; FIsFavoritoCommand.Parameters[0].Value.SetInt32(FIdUsu); FIsFavoritoCommand.Parameters[1].Value.SetInt32(FIdCom); FIsFavoritoCommand.Execute(ARequestFilter); Result := FIsFavoritoCommand.Parameters[2].Value.GetBoolean; end; function TServerMethodsClient.SQLServer(cSql: string; const ARequestFilter: string): TFDJSONDataSets; begin if FSQLServerCommand = nil then begin FSQLServerCommand := FConnection.CreateCommand; FSQLServerCommand.RequestType := 'GET'; FSQLServerCommand.Text := 'TServerMethods.SQLServer'; FSQLServerCommand.Prepare(TServerMethods_SQLServer); end; FSQLServerCommand.Parameters[0].Value.SetWideString(cSql); FSQLServerCommand.Execute(ARequestFilter); if not FSQLServerCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FSQLServerCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FSQLServerCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FSQLServerCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.SQLServer_Cache(cSql: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FSQLServerCommand_Cache = nil then begin FSQLServerCommand_Cache := FConnection.CreateCommand; FSQLServerCommand_Cache.RequestType := 'GET'; FSQLServerCommand_Cache.Text := 'TServerMethods.SQLServer'; FSQLServerCommand_Cache.Prepare(TServerMethods_SQLServer_Cache); end; FSQLServerCommand_Cache.Parameters[0].Value.SetWideString(cSql); FSQLServerCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FSQLServerCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.UpdateAcessoUsu(vIdUsu: Integer; const ARequestFilter: string): Boolean; begin if FUpdateAcessoUsuCommand = nil then begin FUpdateAcessoUsuCommand := FConnection.CreateCommand; FUpdateAcessoUsuCommand.RequestType := 'GET'; FUpdateAcessoUsuCommand.Text := 'TServerMethods.UpdateAcessoUsu'; FUpdateAcessoUsuCommand.Prepare(TServerMethods_UpdateAcessoUsu); end; FUpdateAcessoUsuCommand.Parameters[0].Value.SetInt32(vIdUsu); FUpdateAcessoUsuCommand.Execute(ARequestFilter); Result := FUpdateAcessoUsuCommand.Parameters[1].Value.GetBoolean; end; function TServerMethodsClient.SalvaHistoricoUsu(hIdUsu: Integer; hIdCat: Integer; hIdSubCat: Integer; hIdCom: Integer; hPqsUsu: string; const ARequestFilter: string): Boolean; begin if FSalvaHistoricoUsuCommand = nil then begin FSalvaHistoricoUsuCommand := FConnection.CreateCommand; FSalvaHistoricoUsuCommand.RequestType := 'GET'; FSalvaHistoricoUsuCommand.Text := 'TServerMethods.SalvaHistoricoUsu'; FSalvaHistoricoUsuCommand.Prepare(TServerMethods_SalvaHistoricoUsu); end; FSalvaHistoricoUsuCommand.Parameters[0].Value.SetInt32(hIdUsu); FSalvaHistoricoUsuCommand.Parameters[1].Value.SetInt32(hIdCat); FSalvaHistoricoUsuCommand.Parameters[2].Value.SetInt32(hIdSubCat); FSalvaHistoricoUsuCommand.Parameters[3].Value.SetInt32(hIdCom); FSalvaHistoricoUsuCommand.Parameters[4].Value.SetWideString(hPqsUsu); FSalvaHistoricoUsuCommand.Execute(ARequestFilter); Result := FSalvaHistoricoUsuCommand.Parameters[5].Value.GetBoolean; end; function TServerMethodsClient.getControle(const ARequestFilter: string): TFDJSONDataSets; begin if FgetControleCommand = nil then begin FgetControleCommand := FConnection.CreateCommand; FgetControleCommand.RequestType := 'GET'; FgetControleCommand.Text := 'TServerMethods.getControle'; FgetControleCommand.Prepare(TServerMethods_getControle); end; FgetControleCommand.Execute(ARequestFilter); if not FgetControleCommand.Parameters[0].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetControleCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetControleCommand.Parameters[0].Value.GetJSONValue(True))); if FInstanceOwner then FgetControleCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getControle_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetControleCommand_Cache = nil then begin FgetControleCommand_Cache := FConnection.CreateCommand; FgetControleCommand_Cache.RequestType := 'GET'; FgetControleCommand_Cache.Text := 'TServerMethods.getControle'; FgetControleCommand_Cache.Prepare(TServerMethods_getControle_Cache); end; FgetControleCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetControleCommand_Cache.Parameters[0].Value.GetString); end; function TServerMethodsClient.getNotificacoes(AIdUsu: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FgetNotificacoesCommand = nil then begin FgetNotificacoesCommand := FConnection.CreateCommand; FgetNotificacoesCommand.RequestType := 'GET'; FgetNotificacoesCommand.Text := 'TServerMethods.getNotificacoes'; FgetNotificacoesCommand.Prepare(TServerMethods_getNotificacoes); end; FgetNotificacoesCommand.Parameters[0].Value.SetInt32(AIdUsu); FgetNotificacoesCommand.Execute(ARequestFilter); if not FgetNotificacoesCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetNotificacoesCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetNotificacoesCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FgetNotificacoesCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getNotificacoes_Cache(AIdUsu: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetNotificacoesCommand_Cache = nil then begin FgetNotificacoesCommand_Cache := FConnection.CreateCommand; FgetNotificacoesCommand_Cache.RequestType := 'GET'; FgetNotificacoesCommand_Cache.Text := 'TServerMethods.getNotificacoes'; FgetNotificacoesCommand_Cache.Prepare(TServerMethods_getNotificacoes_Cache); end; FgetNotificacoesCommand_Cache.Parameters[0].Value.SetInt32(AIdUsu); FgetNotificacoesCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetNotificacoesCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.getAvaliacaoCompleta(AIdAvaliacao: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FgetAvaliacaoCompletaCommand = nil then begin FgetAvaliacaoCompletaCommand := FConnection.CreateCommand; FgetAvaliacaoCompletaCommand.RequestType := 'GET'; FgetAvaliacaoCompletaCommand.Text := 'TServerMethods.getAvaliacaoCompleta'; FgetAvaliacaoCompletaCommand.Prepare(TServerMethods_getAvaliacaoCompleta); end; FgetAvaliacaoCompletaCommand.Parameters[0].Value.SetInt32(AIdAvaliacao); FgetAvaliacaoCompletaCommand.Execute(ARequestFilter); if not FgetAvaliacaoCompletaCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetAvaliacaoCompletaCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetAvaliacaoCompletaCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FgetAvaliacaoCompletaCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getAvaliacaoCompleta_Cache(AIdAvaliacao: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetAvaliacaoCompletaCommand_Cache = nil then begin FgetAvaliacaoCompletaCommand_Cache := FConnection.CreateCommand; FgetAvaliacaoCompletaCommand_Cache.RequestType := 'GET'; FgetAvaliacaoCompletaCommand_Cache.Text := 'TServerMethods.getAvaliacaoCompleta'; FgetAvaliacaoCompletaCommand_Cache.Prepare(TServerMethods_getAvaliacaoCompleta_Cache); end; FgetAvaliacaoCompletaCommand_Cache.Parameters[0].Value.SetInt32(AIdAvaliacao); FgetAvaliacaoCompletaCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetAvaliacaoCompletaCommand_Cache.Parameters[1].Value.GetString); end; procedure TServerMethodsClient.SalvaAvaliacao(AIdCom: Integer; AIdUsu: Integer; AAmbiente: Single; AAtendimento: Single; ALimpeza: Single; ALocalizacao: Single; APreco: Single; AMedia: Single; AComentario: string); begin if FSalvaAvaliacaoCommand = nil then begin FSalvaAvaliacaoCommand := FConnection.CreateCommand; FSalvaAvaliacaoCommand.RequestType := 'GET'; FSalvaAvaliacaoCommand.Text := 'TServerMethods.SalvaAvaliacao'; FSalvaAvaliacaoCommand.Prepare(TServerMethods_SalvaAvaliacao); end; FSalvaAvaliacaoCommand.Parameters[0].Value.SetInt32(AIdCom); FSalvaAvaliacaoCommand.Parameters[1].Value.SetInt32(AIdUsu); FSalvaAvaliacaoCommand.Parameters[2].Value.SetSingle(AAmbiente); FSalvaAvaliacaoCommand.Parameters[3].Value.SetSingle(AAtendimento); FSalvaAvaliacaoCommand.Parameters[4].Value.SetSingle(ALimpeza); FSalvaAvaliacaoCommand.Parameters[5].Value.SetSingle(ALocalizacao); FSalvaAvaliacaoCommand.Parameters[6].Value.SetSingle(APreco); FSalvaAvaliacaoCommand.Parameters[7].Value.SetSingle(AMedia); FSalvaAvaliacaoCommand.Parameters[8].Value.SetWideString(AComentario); FSalvaAvaliacaoCommand.Execute; end; procedure TServerMethodsClient.DeletePush(AIdUsu: Integer; AIdPush: Integer); begin if FDeletePushCommand = nil then begin FDeletePushCommand := FConnection.CreateCommand; FDeletePushCommand.RequestType := 'GET'; FDeletePushCommand.Text := 'TServerMethods.DeletePush'; FDeletePushCommand.Prepare(TServerMethods_DeletePush); end; FDeletePushCommand.Parameters[0].Value.SetInt32(AIdUsu); FDeletePushCommand.Parameters[1].Value.SetInt32(AIdPush); FDeletePushCommand.Execute; end; function TServerMethodsClient.getAnuncios(AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FgetAnunciosCommand = nil then begin FgetAnunciosCommand := FConnection.CreateCommand; FgetAnunciosCommand.RequestType := 'GET'; FgetAnunciosCommand.Text := 'TServerMethods.getAnuncios'; FgetAnunciosCommand.Prepare(TServerMethods_getAnuncios); end; FgetAnunciosCommand.Parameters[0].Value.SetInt32(AIdCom); FgetAnunciosCommand.Execute(ARequestFilter); if not FgetAnunciosCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetAnunciosCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetAnunciosCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FgetAnunciosCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getAnuncios_Cache(AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetAnunciosCommand_Cache = nil then begin FgetAnunciosCommand_Cache := FConnection.CreateCommand; FgetAnunciosCommand_Cache.RequestType := 'GET'; FgetAnunciosCommand_Cache.Text := 'TServerMethods.getAnuncios'; FgetAnunciosCommand_Cache.Prepare(TServerMethods_getAnuncios_Cache); end; FgetAnunciosCommand_Cache.Parameters[0].Value.SetInt32(AIdCom); FgetAnunciosCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetAnunciosCommand_Cache.Parameters[1].Value.GetString); end; procedure TServerMethodsClient.AtivaPush(AKeyPush: string; AAtiva: Boolean); begin if FAtivaPushCommand = nil then begin FAtivaPushCommand := FConnection.CreateCommand; FAtivaPushCommand.RequestType := 'GET'; FAtivaPushCommand.Text := 'TServerMethods.AtivaPush'; FAtivaPushCommand.Prepare(TServerMethods_AtivaPush); end; FAtivaPushCommand.Parameters[0].Value.SetWideString(AKeyPush); FAtivaPushCommand.Parameters[1].Value.SetBoolean(AAtiva); FAtivaPushCommand.Execute; end; procedure TServerMethodsClient.NovoComercio(ACnpj: string; ARazao: string; AEmail: string; AFone: string; AContato: string); begin if FNovoComercioCommand = nil then begin FNovoComercioCommand := FConnection.CreateCommand; FNovoComercioCommand.RequestType := 'GET'; FNovoComercioCommand.Text := 'TServerMethods.NovoComercio'; FNovoComercioCommand.Prepare(TServerMethods_NovoComercio); end; FNovoComercioCommand.Parameters[0].Value.SetWideString(ACnpj); FNovoComercioCommand.Parameters[1].Value.SetWideString(ARazao); FNovoComercioCommand.Parameters[2].Value.SetWideString(AEmail); FNovoComercioCommand.Parameters[3].Value.SetWideString(AFone); FNovoComercioCommand.Parameters[4].Value.SetWideString(AContato); FNovoComercioCommand.Execute; end; function TServerMethodsClient.ComercioCadastrado(ACNPJ: string; const ARequestFilter: string): Boolean; begin if FComercioCadastradoCommand = nil then begin FComercioCadastradoCommand := FConnection.CreateCommand; FComercioCadastradoCommand.RequestType := 'GET'; FComercioCadastradoCommand.Text := 'TServerMethods.ComercioCadastrado'; FComercioCadastradoCommand.Prepare(TServerMethods_ComercioCadastrado); end; FComercioCadastradoCommand.Parameters[0].Value.SetWideString(ACNPJ); FComercioCadastradoCommand.Execute(ARequestFilter); Result := FComercioCadastradoCommand.Parameters[1].Value.GetBoolean; end; function TServerMethodsClient.UpdateRaioUsuario(AIdUsuario: Integer; ARaio: Integer; const ARequestFilter: string): Boolean; begin if FUpdateRaioUsuarioCommand = nil then begin FUpdateRaioUsuarioCommand := FConnection.CreateCommand; FUpdateRaioUsuarioCommand.RequestType := 'GET'; FUpdateRaioUsuarioCommand.Text := 'TServerMethods.UpdateRaioUsuario'; FUpdateRaioUsuarioCommand.Prepare(TServerMethods_UpdateRaioUsuario); end; FUpdateRaioUsuarioCommand.Parameters[0].Value.SetInt32(AIdUsuario); FUpdateRaioUsuarioCommand.Parameters[1].Value.SetInt32(ARaio); FUpdateRaioUsuarioCommand.Execute(ARequestFilter); Result := FUpdateRaioUsuarioCommand.Parameters[2].Value.GetBoolean; end; procedure TServerMethodsClient.GravaUltimaPosicaoUsuario(ALatitude: string; ALongitude: string; ADeviceToken: string); begin if FGravaUltimaPosicaoUsuarioCommand = nil then begin FGravaUltimaPosicaoUsuarioCommand := FConnection.CreateCommand; FGravaUltimaPosicaoUsuarioCommand.RequestType := 'GET'; FGravaUltimaPosicaoUsuarioCommand.Text := 'TServerMethods.GravaUltimaPosicaoUsuario'; FGravaUltimaPosicaoUsuarioCommand.Prepare(TServerMethods_GravaUltimaPosicaoUsuario); end; FGravaUltimaPosicaoUsuarioCommand.Parameters[0].Value.SetWideString(ALatitude); FGravaUltimaPosicaoUsuarioCommand.Parameters[1].Value.SetWideString(ALongitude); FGravaUltimaPosicaoUsuarioCommand.Parameters[2].Value.SetWideString(ADeviceToken); FGravaUltimaPosicaoUsuarioCommand.Execute; end; function TServerMethodsClient.getNovaSenha(ADoc: string; const ARequestFilter: string): TFDJSONDataSets; begin if FgetNovaSenhaCommand = nil then begin FgetNovaSenhaCommand := FConnection.CreateCommand; FgetNovaSenhaCommand.RequestType := 'GET'; FgetNovaSenhaCommand.Text := 'TServerMethods.getNovaSenha'; FgetNovaSenhaCommand.Prepare(TServerMethods_getNovaSenha); end; FgetNovaSenhaCommand.Parameters[0].Value.SetWideString(ADoc); FgetNovaSenhaCommand.Execute(ARequestFilter); if not FgetNovaSenhaCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetNovaSenhaCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetNovaSenhaCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FgetNovaSenhaCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getNovaSenha_Cache(ADoc: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetNovaSenhaCommand_Cache = nil then begin FgetNovaSenhaCommand_Cache := FConnection.CreateCommand; FgetNovaSenhaCommand_Cache.RequestType := 'GET'; FgetNovaSenhaCommand_Cache.Text := 'TServerMethods.getNovaSenha'; FgetNovaSenhaCommand_Cache.Prepare(TServerMethods_getNovaSenha_Cache); end; FgetNovaSenhaCommand_Cache.Parameters[0].Value.SetWideString(ADoc); FgetNovaSenhaCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetNovaSenhaCommand_Cache.Parameters[1].Value.GetString); end; function TServerMethodsClient.UpdateSenha(AIdCom: Integer; ASenha: string; const ARequestFilter: string): Boolean; begin if FUpdateSenhaCommand = nil then begin FUpdateSenhaCommand := FConnection.CreateCommand; FUpdateSenhaCommand.RequestType := 'GET'; FUpdateSenhaCommand.Text := 'TServerMethods.UpdateSenha'; FUpdateSenhaCommand.Prepare(TServerMethods_UpdateSenha); end; FUpdateSenhaCommand.Parameters[0].Value.SetInt32(AIdCom); FUpdateSenhaCommand.Parameters[1].Value.SetWideString(ASenha); FUpdateSenhaCommand.Execute(ARequestFilter); Result := FUpdateSenhaCommand.Parameters[2].Value.GetBoolean; end; function TServerMethodsClient.getLogin(ADoc: string; const ARequestFilter: string): TFDJSONDataSets; begin if FgetLoginCommand = nil then begin FgetLoginCommand := FConnection.CreateCommand; FgetLoginCommand.RequestType := 'GET'; FgetLoginCommand.Text := 'TServerMethods.getLogin'; FgetLoginCommand.Prepare(TServerMethods_getLogin); end; FgetLoginCommand.Parameters[0].Value.SetWideString(ADoc); FgetLoginCommand.Execute(ARequestFilter); if not FgetLoginCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FgetLoginCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetLoginCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FgetLoginCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.getLogin_Cache(ADoc: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FgetLoginCommand_Cache = nil then begin FgetLoginCommand_Cache := FConnection.CreateCommand; FgetLoginCommand_Cache.RequestType := 'GET'; FgetLoginCommand_Cache.Text := 'TServerMethods.getLogin'; FgetLoginCommand_Cache.Prepare(TServerMethods_getLogin_Cache); end; FgetLoginCommand_Cache.Parameters[0].Value.SetWideString(ADoc); FgetLoginCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FgetLoginCommand_Cache.Parameters[1].Value.GetString); end; procedure TServerMethodsClient.DeleteFone(AIdFone: Integer); begin if FDeleteFoneCommand = nil then begin FDeleteFoneCommand := FConnection.CreateCommand; FDeleteFoneCommand.RequestType := 'GET'; FDeleteFoneCommand.Text := 'TServerMethods.DeleteFone'; FDeleteFoneCommand.Prepare(TServerMethods_DeleteFone); end; FDeleteFoneCommand.Parameters[0].Value.SetInt32(AIdFone); FDeleteFoneCommand.Execute; end; function TServerMethodsClient.LoadCheckList(AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadCheckListCommand = nil then begin FLoadCheckListCommand := FConnection.CreateCommand; FLoadCheckListCommand.RequestType := 'GET'; FLoadCheckListCommand.Text := 'TServerMethods.LoadCheckList'; FLoadCheckListCommand.Prepare(TServerMethods_LoadCheckList); end; FLoadCheckListCommand.Parameters[0].Value.SetInt32(AIdCom); FLoadCheckListCommand.Execute(ARequestFilter); if not FLoadCheckListCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadCheckListCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadCheckListCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FLoadCheckListCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadCheckList_Cache(AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadCheckListCommand_Cache = nil then begin FLoadCheckListCommand_Cache := FConnection.CreateCommand; FLoadCheckListCommand_Cache.RequestType := 'GET'; FLoadCheckListCommand_Cache.Text := 'TServerMethods.LoadCheckList'; FLoadCheckListCommand_Cache.Prepare(TServerMethods_LoadCheckList_Cache); end; FLoadCheckListCommand_Cache.Parameters[0].Value.SetInt32(AIdCom); FLoadCheckListCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadCheckListCommand_Cache.Parameters[1].Value.GetString); end; procedure TServerMethodsClient.AddCheckListCom(AIdCom: Integer; AIdCheck: Integer); begin if FAddCheckListComCommand = nil then begin FAddCheckListComCommand := FConnection.CreateCommand; FAddCheckListComCommand.RequestType := 'GET'; FAddCheckListComCommand.Text := 'TServerMethods.AddCheckListCom'; FAddCheckListComCommand.Prepare(TServerMethods_AddCheckListCom); end; FAddCheckListComCommand.Parameters[0].Value.SetInt32(AIdCom); FAddCheckListComCommand.Parameters[1].Value.SetInt32(AIdCheck); FAddCheckListComCommand.Execute; end; procedure TServerMethodsClient.AddCheckListNovo(ACheck: string; AIdCom: Integer); begin if FAddCheckListNovoCommand = nil then begin FAddCheckListNovoCommand := FConnection.CreateCommand; FAddCheckListNovoCommand.RequestType := 'GET'; FAddCheckListNovoCommand.Text := 'TServerMethods.AddCheckListNovo'; FAddCheckListNovoCommand.Prepare(TServerMethods_AddCheckListNovo); end; FAddCheckListNovoCommand.Parameters[0].Value.SetWideString(ACheck); FAddCheckListNovoCommand.Parameters[1].Value.SetInt32(AIdCom); FAddCheckListNovoCommand.Execute; end; function TServerMethodsClient.LoadSubGrupo(AIdGrupo: Integer; AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadSubGrupoCommand = nil then begin FLoadSubGrupoCommand := FConnection.CreateCommand; FLoadSubGrupoCommand.RequestType := 'GET'; FLoadSubGrupoCommand.Text := 'TServerMethods.LoadSubGrupo'; FLoadSubGrupoCommand.Prepare(TServerMethods_LoadSubGrupo); end; FLoadSubGrupoCommand.Parameters[0].Value.SetInt32(AIdGrupo); FLoadSubGrupoCommand.Parameters[1].Value.SetInt32(AIdCom); FLoadSubGrupoCommand.Execute(ARequestFilter); if not FLoadSubGrupoCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadSubGrupoCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadSubGrupoCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FLoadSubGrupoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadSubGrupo_Cache(AIdGrupo: Integer; AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadSubGrupoCommand_Cache = nil then begin FLoadSubGrupoCommand_Cache := FConnection.CreateCommand; FLoadSubGrupoCommand_Cache.RequestType := 'GET'; FLoadSubGrupoCommand_Cache.Text := 'TServerMethods.LoadSubGrupo'; FLoadSubGrupoCommand_Cache.Prepare(TServerMethods_LoadSubGrupo_Cache); end; FLoadSubGrupoCommand_Cache.Parameters[0].Value.SetInt32(AIdGrupo); FLoadSubGrupoCommand_Cache.Parameters[1].Value.SetInt32(AIdCom); FLoadSubGrupoCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadSubGrupoCommand_Cache.Parameters[2].Value.GetString); end; function TServerMethodsClient.LoadSubCatCom(AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets; begin if FLoadSubCatComCommand = nil then begin FLoadSubCatComCommand := FConnection.CreateCommand; FLoadSubCatComCommand.RequestType := 'GET'; FLoadSubCatComCommand.Text := 'TServerMethods.LoadSubCatCom'; FLoadSubCatComCommand.Prepare(TServerMethods_LoadSubCatCom); end; FLoadSubCatComCommand.Parameters[0].Value.SetInt32(AIdCom); FLoadSubCatComCommand.Execute(ARequestFilter); if not FLoadSubCatComCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FLoadSubCatComCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadSubCatComCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FLoadSubCatComCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethodsClient.LoadSubCatCom_Cache(AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FLoadSubCatComCommand_Cache = nil then begin FLoadSubCatComCommand_Cache := FConnection.CreateCommand; FLoadSubCatComCommand_Cache.RequestType := 'GET'; FLoadSubCatComCommand_Cache.Text := 'TServerMethods.LoadSubCatCom'; FLoadSubCatComCommand_Cache.Prepare(TServerMethods_LoadSubCatCom_Cache); end; FLoadSubCatComCommand_Cache.Parameters[0].Value.SetInt32(AIdCom); FLoadSubCatComCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FLoadSubCatComCommand_Cache.Parameters[1].Value.GetString); end; procedure TServerMethodsClient.InsertSubCatCom(AIdCom: Integer; AIdGrupo: Integer; AIdSubGrupo: Integer); begin if FInsertSubCatComCommand = nil then begin FInsertSubCatComCommand := FConnection.CreateCommand; FInsertSubCatComCommand.RequestType := 'GET'; FInsertSubCatComCommand.Text := 'TServerMethods.InsertSubCatCom'; FInsertSubCatComCommand.Prepare(TServerMethods_InsertSubCatCom); end; FInsertSubCatComCommand.Parameters[0].Value.SetInt32(AIdCom); FInsertSubCatComCommand.Parameters[1].Value.SetInt32(AIdGrupo); FInsertSubCatComCommand.Parameters[2].Value.SetInt32(AIdSubGrupo); FInsertSubCatComCommand.Execute; end; procedure TServerMethodsClient.ClearSubCatCom(AIdCom: Integer); begin if FClearSubCatComCommand = nil then begin FClearSubCatComCommand := FConnection.CreateCommand; FClearSubCatComCommand.RequestType := 'GET'; FClearSubCatComCommand.Text := 'TServerMethods.ClearSubCatCom'; FClearSubCatComCommand.Prepare(TServerMethods_ClearSubCatCom); end; FClearSubCatComCommand.Parameters[0].Value.SetInt32(AIdCom); FClearSubCatComCommand.Execute; end; function TServerMethodsClient.LoadGrupoSelected(AIdCom: Integer; const ARequestFilter: string): Integer; begin if FLoadGrupoSelectedCommand = nil then begin FLoadGrupoSelectedCommand := FConnection.CreateCommand; FLoadGrupoSelectedCommand.RequestType := 'GET'; FLoadGrupoSelectedCommand.Text := 'TServerMethods.LoadGrupoSelected'; FLoadGrupoSelectedCommand.Prepare(TServerMethods_LoadGrupoSelected); end; FLoadGrupoSelectedCommand.Parameters[0].Value.SetInt32(AIdCom); FLoadGrupoSelectedCommand.Execute(ARequestFilter); Result := FLoadGrupoSelectedCommand.Parameters[1].Value.GetInt32; end; procedure TServerMethodsClient.InsertCategoria(ACategoria: string; ADescricao: string; AIdCom: Integer); begin if FInsertCategoriaCommand = nil then begin FInsertCategoriaCommand := FConnection.CreateCommand; FInsertCategoriaCommand.RequestType := 'GET'; FInsertCategoriaCommand.Text := 'TServerMethods.InsertCategoria'; FInsertCategoriaCommand.Prepare(TServerMethods_InsertCategoria); end; FInsertCategoriaCommand.Parameters[0].Value.SetWideString(ACategoria); FInsertCategoriaCommand.Parameters[1].Value.SetWideString(ADescricao); FInsertCategoriaCommand.Parameters[2].Value.SetInt32(AIdCom); FInsertCategoriaCommand.Execute; end; function TServerMethodsClient.SolicitacoesNovaCategoria(AIdCom: Integer; const ARequestFilter: string): Integer; begin if FSolicitacoesNovaCategoriaCommand = nil then begin FSolicitacoesNovaCategoriaCommand := FConnection.CreateCommand; FSolicitacoesNovaCategoriaCommand.RequestType := 'GET'; FSolicitacoesNovaCategoriaCommand.Text := 'TServerMethods.SolicitacoesNovaCategoria'; FSolicitacoesNovaCategoriaCommand.Prepare(TServerMethods_SolicitacoesNovaCategoria); end; FSolicitacoesNovaCategoriaCommand.Parameters[0].Value.SetInt32(AIdCom); FSolicitacoesNovaCategoriaCommand.Execute(ARequestFilter); Result := FSolicitacoesNovaCategoriaCommand.Parameters[1].Value.GetInt32; end; function TServerMethodsClient.podeAlterarAvaliacao(AIdComercio: Integer; const ARequestFilter: string): Boolean; begin if FpodeAlterarAvaliacaoCommand = nil then begin FpodeAlterarAvaliacaoCommand := FConnection.CreateCommand; FpodeAlterarAvaliacaoCommand.RequestType := 'GET'; FpodeAlterarAvaliacaoCommand.Text := 'TServerMethods.podeAlterarAvaliacao'; FpodeAlterarAvaliacaoCommand.Prepare(TServerMethods_podeAlterarAvaliacao); end; FpodeAlterarAvaliacaoCommand.Parameters[0].Value.SetInt32(AIdComercio); FpodeAlterarAvaliacaoCommand.Execute(ARequestFilter); Result := FpodeAlterarAvaliacaoCommand.Parameters[1].Value.GetBoolean; end; procedure TServerMethodsClient.salvaFuncionamento(AIDCom: Integer; ASeg: string; Ater: string; AQua: string; AQui: string; ASex: string; ASab: string; ADom: string); begin if FsalvaFuncionamentoCommand = nil then begin FsalvaFuncionamentoCommand := FConnection.CreateCommand; FsalvaFuncionamentoCommand.RequestType := 'GET'; FsalvaFuncionamentoCommand.Text := 'TServerMethods.salvaFuncionamento'; FsalvaFuncionamentoCommand.Prepare(TServerMethods_salvaFuncionamento); end; FsalvaFuncionamentoCommand.Parameters[0].Value.SetInt32(AIDCom); FsalvaFuncionamentoCommand.Parameters[1].Value.SetWideString(ASeg); FsalvaFuncionamentoCommand.Parameters[2].Value.SetWideString(Ater); FsalvaFuncionamentoCommand.Parameters[3].Value.SetWideString(AQua); FsalvaFuncionamentoCommand.Parameters[4].Value.SetWideString(AQui); FsalvaFuncionamentoCommand.Parameters[5].Value.SetWideString(ASex); FsalvaFuncionamentoCommand.Parameters[6].Value.SetWideString(ASab); FsalvaFuncionamentoCommand.Parameters[7].Value.SetWideString(ADom); FsalvaFuncionamentoCommand.Execute; end; constructor TServerMethodsClient.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethodsClient.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethodsClient.Destroy; begin FDataModuleCreateCommand.DisposeOf; FgravaSobreCommand.DisposeOf; FListaPlanosCommand.DisposeOf; FListaPlanosCommand_Cache.DisposeOf; FgravaDeliveryCommand.DisposeOf; FgravaRedesSociaisCommand.DisposeOf; FgravaCadastroAvaliacoesCommand.DisposeOf; FLoadGruposCommand.DisposeOf; FLoadGruposCommand_Cache.DisposeOf; FUpdateGrupoComCommand.DisposeOf; FEnviarEmailCommand.DisposeOf; FTelRepetidoCommand.DisposeOf; FAddComercioNovoCommand.DisposeOf; FAddTelefoneCommand.DisposeOf; FDocRepetidoCommand.DisposeOf; FgetTelefoneCommand.DisposeOf; FgetTelefoneCommand_Cache.DisposeOf; FLoadCategoriasCommand.DisposeOf; FLoadCategoriasCommand_Cache.DisposeOf; FLoadDestaquePrincipalCommand.DisposeOf; FLoadDestaquePrincipalCommand_Cache.DisposeOf; FLoadComercioCategoriaCommand.DisposeOf; FLoadComercioCategoriaCommand_Cache.DisposeOf; FLoadSubCategoriaCommand.DisposeOf; FLoadSubCategoriaCommand_Cache.DisposeOf; FLoadFotosPorSecaoCommand.DisposeOf; FLoadFotosPorSecaoCommand_Cache.DisposeOf; FLoadComercioPesquisaCommand.DisposeOf; FLoadComercioPesquisaCommand_Cache.DisposeOf; FLoadDestaqueFavoritoCommand.DisposeOf; FLoadDestaqueFavoritoCommand_Cache.DisposeOf; FInsertNewSubCategoriaCommand.DisposeOf; FRecebeNotificacaoCommand.DisposeOf; FVerificaUsuarioAvaliouCommand.DisposeOf; FLoadFichaComercioCommand.DisposeOf; FLoadFichaComercioCommand_Cache.DisposeOf; FLoadComercioCommand.DisposeOf; FLoadComercioCommand_Cache.DisposeOf; FLoadAvaliacoesCommand.DisposeOf; FLoadAvaliacoesCommand_Cache.DisposeOf; FVerificaCelularDuplicadoCommand.DisposeOf; FVerificaCelularDuplicadoCommand_Cache.DisposeOf; FDownloadIdUsuarioCommand.DisposeOf; FDownloadIdUsuarioCommand_Cache.DisposeOf; FDownloadUsuarioCommand.DisposeOf; FDownloadUsuarioCommand_Cache.DisposeOf; FDownloadUsuarioIdCommand.DisposeOf; FDownloadUsuarioIdCommand_Cache.DisposeOf; FUpdateUsuarioCommand.DisposeOf; FInsertUsuarioCommand.DisposeOf; FControleFavoritoCommand.DisposeOf; FRegistrarDispositivoCommand.DisposeOf; FIsFavoritoCommand.DisposeOf; FSQLServerCommand.DisposeOf; FSQLServerCommand_Cache.DisposeOf; FUpdateAcessoUsuCommand.DisposeOf; FSalvaHistoricoUsuCommand.DisposeOf; FgetControleCommand.DisposeOf; FgetControleCommand_Cache.DisposeOf; FgetNotificacoesCommand.DisposeOf; FgetNotificacoesCommand_Cache.DisposeOf; FgetAvaliacaoCompletaCommand.DisposeOf; FgetAvaliacaoCompletaCommand_Cache.DisposeOf; FSalvaAvaliacaoCommand.DisposeOf; FDeletePushCommand.DisposeOf; FgetAnunciosCommand.DisposeOf; FgetAnunciosCommand_Cache.DisposeOf; FAtivaPushCommand.DisposeOf; FNovoComercioCommand.DisposeOf; FComercioCadastradoCommand.DisposeOf; FUpdateRaioUsuarioCommand.DisposeOf; FGravaUltimaPosicaoUsuarioCommand.DisposeOf; FgetNovaSenhaCommand.DisposeOf; FgetNovaSenhaCommand_Cache.DisposeOf; FUpdateSenhaCommand.DisposeOf; FgetLoginCommand.DisposeOf; FgetLoginCommand_Cache.DisposeOf; FDeleteFoneCommand.DisposeOf; FLoadCheckListCommand.DisposeOf; FLoadCheckListCommand_Cache.DisposeOf; FAddCheckListComCommand.DisposeOf; FAddCheckListNovoCommand.DisposeOf; FLoadSubGrupoCommand.DisposeOf; FLoadSubGrupoCommand_Cache.DisposeOf; FLoadSubCatComCommand.DisposeOf; FLoadSubCatComCommand_Cache.DisposeOf; FInsertSubCatComCommand.DisposeOf; FClearSubCatComCommand.DisposeOf; FLoadGrupoSelectedCommand.DisposeOf; FInsertCategoriaCommand.DisposeOf; FSolicitacoesNovaCategoriaCommand.DisposeOf; FpodeAlterarAvaliacaoCommand.DisposeOf; FsalvaFuncionamentoCommand.DisposeOf; inherited; end; end.
unit controller; {$mode objfpc}{$H+} interface uses Classes, SysUtils, elemento; type IController = interface ['{C0247D9C-4B9F-4DF4-97B8-E8AEE782D57C}'] // Função para listar todos os elementos function Listar(lista: TList): integer; // Função para carregar o elemento function Get(id: integer; objeto: TElemento): boolean; // Função para inserir/atualizar o elemento function Put(objeto: TElemento): boolean; // Função para excluir o elemento function Delete(objeto: TElemento): boolean; end; implementation end.
unit Test.Address.Classes; interface {$M+} type {$REGION 'Interfaces'} IZipCode = interface ['{56B26B9F-1145-4E44-88E6-EBC0BA8CE17B}'] function GetZipcode(): Integer; procedure SetZipcode(value: Integer); function GetCity(): string; procedure SetCity(const value: string); property Zipcode: Integer read GetZipcode write SetZipcode; property City: string read GetCity write SetCity; end; IAddress = interface ['{FE9165F2-4B32-45E7-920D-F899BE6A3430}'] function GetName(): string; procedure SetName(const value: string); function GetZip(): IZipCode; procedure SetZip(value: IZipCode); property Name: string read GetName write SetName; property Zip: IZipCode read GetZip write SetZip; end; IAddressDto = interface ['{994F2661-8DED-406D-8881-A69F596A87C1}'] function GetName(): string; procedure SetName(const value: string); function GetZipcode(): Integer; procedure SetZipcode(value: Integer); function GetCity(): string; procedure SetCity(const value: string); property Name: string read GetName write SetName; property Zipcode: Integer read GetZipcode write SetZipcode; property City: string read GetCity write SetCity; end; {$ENDREGION} {$REGION 'Implementations'} TZipCode = class(TInterfacedObject, IZipCode) strict private FZipcode: Integer; FCity: string; private function GetZipcode(): Integer; procedure SetZipcode(value: Integer); function GetCity(): string; procedure SetCity(const value: string); end; TAddress = class(TInterfacedObject, IAddress) strict private FName: string; FZip: IZipCode; private function GetName(): string; procedure SetName(const value: string); function GetZip(): IZipCode; procedure SetZip(value: IZipCode); end; TAddressDto = class(TInterfacedObject, IAddressDto) strict private FName: string; FZipcode: Integer; FCity: string; private function GetName(): string; procedure SetName(const value: string); function GetZipcode(): Integer; procedure SetZipcode(value: Integer); function GetCity(): string; procedure SetCity(const value: string); end; {$ENDREGION} {$REGION 'Factory'} TAddressFactory = class class function CreateAddress(): IAddress; end; {$ENDREGION} {$M-} implementation { **************************************************************************** } { TZipCode } function TZipCode.GetCity: string; begin Result := FCity; end; function TZipCode.GetZipcode: Integer; begin Result := FZipcode; end; procedure TZipCode.SetCity(const value: string); begin FCity := value; end; procedure TZipCode.SetZipcode(value: Integer); begin FZipcode := value; end; { **************************************************************************** } { TAddress } function TAddress.GetName: string; begin Result := FName; end; function TAddress.GetZip: IZipCode; begin Result := FZip; end; procedure TAddress.SetName(const value: string); begin FName := value; end; procedure TAddress.SetZip(value: IZipCode); begin FZip := value; end; { **************************************************************************** } { TAddressDto } function TAddressDto.GetCity: string; begin Result := FCity; end; function TAddressDto.GetName: string; begin Result := FName; end; function TAddressDto.GetZipcode: Integer; begin Result := FZipcode; end; procedure TAddressDto.SetCity(const value: string); begin FCity := value; end; procedure TAddressDto.SetName(const value: string); begin FName := value; end; procedure TAddressDto.SetZipcode(value: Integer); begin FZipcode := value; end; { TAddressFactory } class function TAddressFactory.CreateAddress(): IAddress; begin Result := TAddress.Create; Result.Name := 'Nathan Chanan Thurnreiter'; Result.Zip := TZipCode.Create; Result.Zip.Zipcode := 1234; Result.Zip.City := 'City'; end; end.
unit uFrmBillSale; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmMDIBill, ComCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, dxBar, dxBarExtItems, cxClasses, ImgList, ActnList, DB, DBClient, cxGridLevel, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGrid, cxContainer, cxTreeView, ExtCtrls, cxDropDownEdit, cxCalendar, cxTextEdit, cxMaskEdit, cxButtonEdit, cxLabel, uBillData, uPackData, uBaseInfoDef, uModelFunIntf; type TfrmBillSale = class(TfrmMDIBill) lblBtype: TcxLabel; edtBtype: TcxButtonEdit; lbl2: TcxLabel; edtEtype: TcxButtonEdit; lbl3: TcxLabel; edtDtype: TcxButtonEdit; lbl4: TcxLabel; deGatheringDate: TcxDateEdit; lblKtype: TcxLabel; edtKtype: TcxButtonEdit; lbl6: TcxLabel; edtSummary: TcxButtonEdit; lbl7: TcxLabel; edtComment: TcxButtonEdit; private { Private declarations } procedure BeforeFormShow; override; procedure InitParamList; override; procedure InitMasterTitles(Sender: TObject); override; procedure InitGrids(Sender: TObject); override; function LoadBillDataGrid: Boolean; override; function SaveMasterData(const ABillMasterData: TBillData): Integer; override; function SaveDetailData(const ABillDetailData: TPackData): Integer; override; function SaveDetailAccount(const ADetailAccountData: TPackData): integer; override; function LoadPtype(ABasicDatas: TSelectBasicDatas): Boolean; function LoadOnePtype(ARow: Integer; AData: TSelectBasicData; IsImport: Boolean = False): Boolean; override; protected procedure DoSelectBasic(Sender: TObject; ABasicType: TBasicType; ASelectBasicParam: TSelectBasicParam; ASelectOptions: TSelectBasicOptions; var ABasicDatas: TSelectBasicDatas; var AReturnCount: Integer); override; public { Public declarations } end; var frmBillSale: TfrmBillSale; implementation uses uSysSvc, uBaseFormPlugin, uMoudleNoDef, uParamObject, uModelControlIntf, uDefCom, uGridConfig, uFrmApp, uModelBillIntf, uVchTypeDef, uPubFun; {$R *.dfm} { TfrmBillOrder } procedure TfrmBillSale.BeforeFormShow; begin FModelBill := IModelBillOrder((SysService as IModelControl).GetModelIntf(IModelBillSale)); inherited; end; procedure TfrmBillSale.DoSelectBasic(Sender: TObject; ABasicType: TBasicType; ASelectBasicParam: TSelectBasicParam; ASelectOptions: TSelectBasicOptions; var ABasicDatas: TSelectBasicDatas; var AReturnCount: Integer); begin if Sender = gridMainShow then begin ASelectOptions := ASelectOptions + [opMultiSelect] end; inherited; if Sender = gridMainShow then begin if AReturnCount >= 1 then begin if ABasicType = btPtype then begin LoadPtype(ABasicDatas); end end; end; end; procedure TfrmBillSale.InitGrids(Sender: TObject); begin inherited; FGridItem.ClearField(); FGridItem.AddField(btPtype); FGridItem.AddField('Qty', '数量', 100, cfQty); FGridItem.AddField('Price', '单价', 100, cfPrice); FGridItem.AddField('Total', '金额', 100, cfTotal); FGridItem.AddField('Comment', '备注'); SetQtyPriceTotal('Total', 'Qty', 'Price'); FGridItem.InitGridData; end; procedure TfrmBillSale.InitMasterTitles(Sender: TObject); begin inherited; Title := '销售单'; lblBtype.Caption := '购买单位'; lblKtype.Caption := '发货仓库'; DBComItem.AddItem(deBillDate, 'InputDate'); DBComItem.AddItem(edtBillNumber, 'Number'); DBComItem.AddItem(edtBtype, 'BTypeId', 'BTypeId', 'BUsercode', btBtype); DBComItem.AddItem(edtEtype, 'ETypeId', 'ETypeId', 'EUsercode', btEtype); DBComItem.AddItem(edtDtype, 'DTypeId', 'DTypeId', 'DUsercode', btDtype); DBComItem.AddItem(edtKtype, 'KTypeId', 'KTypeId', 'KUsercode', btKtype); DBComItem.AddItem(deGatheringDate, 'GatheringDate'); DBComItem.AddItem(edtSummary, 'Summary'); DBComItem.AddItem(edtComment, 'Comment'); end; procedure TfrmBillSale.InitParamList; begin inherited; MoudleNo := fnMdlBillSale; end; function TfrmBillSale.LoadBillDataGrid: Boolean; var szSql, szTemp: string; begin inherited LoadBillDataGrid; end; function TfrmBillSale.LoadOnePtype(ARow: Integer; AData: TSelectBasicData; IsImport: Boolean): Boolean; begin FGridItem.SetCellValue(GetBaseTypeid(btPtype), ARow, AData.TypeId); FGridItem.SetCellValue(GetBaseTypeFullName(btPtype), ARow, AData.FullName); FGridItem.SetCellValue(GetBaseTypeUsercode(btPtype), ARow, AData.Usercode); end; function TfrmBillSale.LoadPtype(ABasicDatas: TSelectBasicDatas): Boolean; var i, j: Integer; s: string; begin for i := 0 to Length(ABasicDatas) - 1 do begin if i = 0 then begin LoadOnePtype(FGridItem.RowIndex, ABasicDatas[i]); end else begin for j := FGridItem.RowIndex + 1 to FGridItem.GetLastRow - 1 do begin if StringEmpty(FGridItem.GetCellValue(GetBaseTypeid(btPtype), j)) then Break; end; if j >= FGridItem.GetLastRow then exit; LoadOnePtype(j, ABasicDatas[i]) end; end; end; function TfrmBillSale.SaveDetailAccount( const ADetailAccountData: TPackData): integer; begin end; function TfrmBillSale.SaveDetailData( const ABillDetailData: TPackData): Integer; var aPackData: TParamObject; aRow: Integer; aPrice, aTotal, aQty: Extended; begin ABillDetailData.ProcName := 'pbx_Bill_Is_Sale_D'; for aRow := FGridItem.GetFirstRow to FGridItem.GetLastRow do begin if StringEmpty(FGridItem.GetCellValue(GetBaseTypeid(btPtype), aRow)) then Continue; aQty := FGridItem.GetCellValue('Qty', aRow); aPrice := FGridItem.GetCellValue('Price', aRow); aTotal := FGridItem.GetCellValue('Total', aRow); aPackData := ABillDetailData.AddChild(); aPackData.Add('@ColRowNo', IntToStr(aRow + 1)); aPackData.Add('@AtypeId', '0000100001'); aPackData.Add('@BtypeId', DBComItem.GetItemValue(edtBtype)); aPackData.Add('@EtypeId', DBComItem.GetItemValue(edtEtype)); aPackData.Add('@DtypeId', DBComItem.GetItemValue(edtDtype)); aPackData.Add('@KtypeId', DBComItem.GetItemValue(edtKtype)); aPackData.Add('@KtypeId2', ''); aPackData.Add('@PtypeId', FGridItem.GetCellValue(GetBaseTypeid(btPtype), aRow)); aPackData.Add('@CostMode', 0); aPackData.Add('@UnitRate', 1); aPackData.Add('@Unit', 0); aPackData.Add('@Blockno', ''); aPackData.Add('@Prodate', ''); aPackData.Add('@UsefulEndDate', ''); aPackData.Add('@Jhdate', ''); aPackData.Add('@GoodsNo', 0); aPackData.Add('@Qty', aQty); aPackData.Add('@Price', aPrice); aPackData.Add('@Total', aTotal); aPackData.Add('@Discount', 1); aPackData.Add('@DiscountPrice', aPrice); aPackData.Add('@DiscountTotal', aTotal); aPackData.Add('@TaxRate', 1); aPackData.Add('@TaxPrice', aPrice); aPackData.Add('@TaxTotal', aTotal); aPackData.Add('@AssQty', aQty); aPackData.Add('@AssPrice', aPrice); aPackData.Add('@AssDiscountPrice', aPrice); aPackData.Add('@AssTaxPrice', aPrice); aPackData.Add('@CostTotal', aTotal); aPackData.Add('@CostPrice', aPrice); aPackData.Add('@OrderCode', 0); aPackData.Add('@OrderDlyCode', 0); aPackData.Add('@OrderVchType', 0); aPackData.Add('@Comment', FGridItem.GetCellValue('Comment', aRow)); aPackData.Add('@InputDate', FormatDateTime('YYYY-MM-DD', deBillDate.Date)); aPackData.Add('@Usedtype', '1'); aPackData.Add('@Period', 1); aPackData.Add('@PStatus', 0); aPackData.Add('@YearPeriod', 1); end; end; function TfrmBillSale.SaveMasterData( const ABillMasterData: TBillData): Integer; begin ABillMasterData.ProcName := 'pbx_Bill_Is_Sale_M'; ABillMasterData.Add('@InputDate', FormatDateTime('YYYY-MM-DD', deBillDate.Date)); ABillMasterData.Add('@Number', DBComItem.GetItemValue(edtBillNumber)); ABillMasterData.Add('@VchType', FVchType); ABillMasterData.Add('@Summary', DBComItem.GetItemValue(edtSummary)); ABillMasterData.Add('@Comment', DBComItem.GetItemValue(edtComment)); ABillMasterData.Add('@Btypeid', DBComItem.GetItemValue(edtBtype)); ABillMasterData.Add('@Etypeid', DBComItem.GetItemValue(edtEtype)); ABillMasterData.Add('@Dtypeid', DBComItem.GetItemValue(edtDtype)); ABillMasterData.Add('@Ktypeid', DBComItem.GetItemValue(edtKtype)); ABillMasterData.Add('@Ktypeid2', ''); ABillMasterData.Add('@Period', 1); ABillMasterData.Add('@YearPeriod', 1); ABillMasterData.Add('@Total', 0); ABillMasterData.Add('@RedWord', 'F'); ABillMasterData.Add('@Defdiscount', 1); ABillMasterData.Add('@GatheringDate', DBComItem.GetItemValue(deGatheringDate)); end; initialization gFormManage.RegForm(TfrmBillSale, fnMdlBillSale); end.
unit LinkedList; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TNode } TNode = class(TObject) Data: Pointer; Next: TNode; function HasNext: boolean; public constructor Create(AData: Pointer); overload; end; { TLinkedList } TLinkedList = class(TObject) Head: TNode; Tail: TNode; FCnt: integer; public constructor Create; procedure Add(AData: Pointer); procedure Del; property Cnt: integer read FCnt write FCnt; end; implementation { TNode } function TNode.HasNext: boolean; begin if Self.Next <> nil then Result := True; end; constructor TNode.Create(AData: Pointer); begin Data := AData; Next := nil; end; { TLinkedList } constructor TLinkedList.Create; begin Head := nil; Tail := nil; end; procedure TLinkedList.Add(AData: Pointer); begin if FCnt = 0 then begin Head := TNode.Create(AData); Tail := Head; end else begin Tail.Next := TNode.Create(AData); Tail := Tail.Next; end; Inc(FCnt); end; procedure TLinkedList.Del; var LCurrentNode: TNode; begin // FIFO if FCnt = 0 then raise Exception.Create('EMPTY LIST'); LCurrentNode := Head; Head := Head.Next; FreeAndNil(LCurrentNode); end; end.
{Una fábrica Textil ofrece N tipos distintos de prendas de M talles (1..M). Esta información se encuentra en un archivo STOCK.TXT donde en la primer línea viene M (cantidad de talles) y luego: ✔ Código de prenda (alfanumérico de 4) ✔ Cantidad de prendas de los M talles 5 5 AA12 20 0 10 12 8 BB34 10 13 25 30 15 CC56 0 22 14 16 20 DD78 13 18 33 0 17 EE90 7 15 8 22 15 Se pide ingresar la información y además: a) Calcular el porcentaje de códigos que tienen stock de todos los talles sobre el total códigos. b) Dado un Código X (ingresado por teclado), informar cuál talle con mayor cantidad de prendas (suponer único), puede no existir. c) Generar un arreglo con el promedio de prendas por talle.} Program Parcial; Type St4 = string[4]; TM = array[1..100,1..100] of byte; TV = array[1..100] of St4; TVR = array[1..100] of real; Procedure LeerArchivo(Var Talles:TM; Var Cod:TV; Var N,M:byte); Var i,j:byte; arch:text; begin assign(arch,'SegundoParcial.txt');reset(arch); readln(arch,N,M); For i:= 1 to N do begin read(arch,Cod[i]); For j:= 1 to M do read(arch,Talles[i,j]); readln(arch); end; close(arch); end; Function Porcentaje(Talles:TM; N,M:byte):real; Var i,j,Cont:byte; begin Cont:= 0; For i:= 1 to N do begin j:= 1; while (j <= M) and (Talles[i,j] <> 0) do j:= j + 1; If (j > M) then Cont:= Cont + 1; end; Porcentaje:= (Cont / M) * 100; end; Function Promedio(Talles:TM; N,M:byte):real; Var i:byte; Sum:word; begin Sum:= 0; For i:= 1 to N do Sum:= Sum + Talles[i,M]; Promedio:= Sum / N; end; Procedure GenerarArregloPromedio(Talles:TM; N,M:byte; Var VProm:TVR); Var j:byte; begin For j:= 1 to M do VProm[j]:= Promedio(Talles,N,j); end; Procedure Imprime(VProm:TVR; N:byte); Var i:byte; begin For i:= 1 to N do write(VProm[i]:6:2,' '); end; Function InformaTalle(Talles:TM; Cod:TV; N,M:byte; X:St4):byte; Var i,j,Max,PosMax:byte; begin Max:= 0; i:= 1; while (i <= N) and (Cod[i] <> X) do i:= i + 1; For j:= 1 to M do If (Talles[i,j] > Max) then begin Max:= Talles[i,j]; PosMax:= j; end; If (i <= N) then InformaTalle:= PosMax Else InformaTalle:= 0; end; Var Talles:TM; Cod:TV; VProm:TVR; X:St4; N,M,Talle:byte; Porc:real; Begin LeerArchivo(Talles,Cod,N,M); GenerarArregloPromedio(Talles,N,M,VProm); Porc:= Porcentaje(Talles,N,M); write('A- '); writeln('El porcentaje de codigos con stock en todos los talles es del: ',Porc:6:2, ' %'); writeln; writeln('C- Promedios: '); Imprime(VProm,N); writeln; writeln; write('Ingrese un codigo para saber la prenda con mayor stock: ');readln(X); Talle:= InformaTalle(Talles,Cod,N,M,X); If (Talle > 0) then writeln('B- El mayor stock para el codigo ',X,' esta en el talle: ',Talle) Else writeln('No existe el codigo ingresado'); end.
unit ThCanvasEditor; interface uses System.UITypes, System.Classes, System.Types, System.SysUtils, FMX.Types, ThCanvas, ThTypes, ThItem, ThClasses; type { Features - ThContainers features - ThItem control(add, modify, delete) } TThCanvasEditor = class(TThCanvas) private FDrawItem: TThItem; FDrawItemId: Integer; FSelections: TThItems; FSelectedItem: TThItem; FOnItemAdded: TItemEvent; FOnItemDelete: TItemListEvent; FOnItemMove: TItemListPointvent; FOnItemResize: TItemResizeEvent; FIsMultiSelecting: Boolean; // BeginSelect, EndSelect function CreateItemById(const ItemId: Integer; AItemData: IThItemData = nil): TThItem; procedure SetDrawItemId(const Value: Integer); function GetSelectionCount: Integer; protected procedure Paint; override; procedure ClickCanvas; override; procedure ItemSelect(Item: TThItem; IsMultiSelect: Boolean); procedure ItemUnselect(Item: TThItem); procedure ItemTracking(Sender: TObject; X, Y: Single); procedure ItemMove(Item: TThItem; DistancePos: TPointF); procedure ItemResize(Item: TThItem; BeforeRect: TRectF); procedure ItemResizing(Item: TThItem; SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function AppendFileItem(const ItemId: Integer; const AFileName: TFileName = ''): Boolean; function IsDrawingItem: Boolean; override; function IsMultiSelected: Boolean; override; property SelectedItem: TThItem read FSelectedItem; procedure ClearSelection; procedure BeginSelect; procedure EndSelect; procedure DeleteSelection; property DrawItemId: Integer read FDrawItemId write SetDrawItemId; property SelectionCount: Integer read GetSelectionCount; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; property OnItemAdded: TItemEvent read FOnItemAdded write FOnItemAdded; property OnItemDelete: TItemListEvent read FOnItemDelete write FOnItemDelete; property OnItemMove: TItemListPointvent read FOnItemMove write FOnItemMove; property OnItemResize: TItemResizeEvent read FOnItemResize write FOnItemResize; procedure Test; end; implementation uses Math, SpotCornerUtils, ThItemFactory, DebugUtils; { TThCanvasEditor } constructor TThCanvasEditor.Create(AOwner: TComponent); begin inherited; CanFocus := True; // Keyboard event FDrawItemId := -1; FIsMultiSelecting := False; FSelections := TThItems.Create; end; destructor TThCanvasEditor.Destroy; begin FSelections.Free; inherited; end; // ThothController에서 처리 할 것 function TThCanvasEditor.AppendFileItem(const ItemId: Integer; const AFileName: TFileName): Boolean; var P: TPointF; Item: TThItem; begin Result := False; ClearSelection; Item := CreateItemById(ItemId, TThFileItemData.Create(AFileName)); if Assigned(Item) then begin // Center position P := CenterPoint - PointF(Item.Width / 2, Item.Height / 2); Item.Position.Point := P - FContents.ScaledPoint; if Assigned(Item) then begin Item.Selected := True; if Assigned(FOnItemAdded) then FOnItemAdded(Item); end; end; end; procedure TThCanvasEditor.BeginSelect; begin FIsMultiSelecting := True; end; procedure TThCanvasEditor.EndSelect; begin FIsMultiSelecting := False; end; function TThCanvasEditor.CreateItemById(const ItemId: Integer; AItemData: IThItemData): TThItem; begin Result := ItemFactory.Get(ItemId, AItemData); if Assigned(Result) then begin if (Result.Width = 0) and (Result.Height = 0) then begin Result.Free; Result := nil; Exit; end; Result.ParentCanvas := Self; Result.OnSelected := ItemSelect; Result.OnUnselected := ItemUnselect; Result.OnTracking := ItemTracking; Result.OnMove := ItemMove; Result.OnResize := ItemResize; Result.OnResizing := ItemResizing; // Zoom적용된 최소사이즈 적용 Result.Width := Result.Width / ZoomScale; Result.Height := Result.Height / ZoomScale; end; end; procedure TThCanvasEditor.ClickCanvas; begin ClearSelection; end; procedure TThCanvasEditor.ItemTracking(Sender: TObject; X, Y: Single); var I: Integer; P: TPointF; begin for I := 0 to FSelections.Count - 1 do begin if FSelections[I].IsParentSelected then Continue; P := FSelections[I].Position.Point + PointF(X, Y); FSelections[I].Position.Point := P; end; end; procedure TThCanvasEditor.ItemMove(Item: TThItem; DistancePos: TPointF); var CurrItem: TThItem; ItemContainer: IThItemContainer; begin for CurrItem in FSelections do begin // Set Parent CurrItem.Parent := FContents.FindParent(CurrItem); // Contain Children if Supports(CurrItem.Parent, IThItemContainer, ItemContainer) then ItemContainer.ContainChildren(CurrItem); end; if Assigned(FOnItemMove) then FOnItemMove(FSelections, DistancePos); end; procedure TThCanvasEditor.ItemResize(Item: TThItem; BeforeRect: TRectF); begin // Set Parent Item.Parent := FContents.FindParent(Item); // Contain Children FContents.ContainChildren(Item); // Release Children Item.ReleaseChildren; if Assigned(FOnItemResize) then FOnItemResize(Item, BeforeRect); end; procedure TThCanvasEditor.ItemResizing(Item: TThItem; SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean); var I: Integer; P: TPointF; begin P := PointF(0, 0); if SwapHorz or ContainSpotCorner(SpotCorner, scLeft) then P.X := P.X - X; if SwapVert or ContainSpotCorner(SpotCorner, scTop) then P.Y := P.Y - Y; if P <> PointF(0, 0) then begin for I := 0 to Item.ItemCount - 1 do Item.Items[I].Position.Point := Item.Items[I].Position.Point + P; end; end; procedure TThCanvasEditor.ItemSelect(Item: TThItem; IsMultiSelect: Boolean); var I: Integer; begin if (not IsMultiSelect) and (not FIsMultiSelecting) then ClearSelection; // Multiselect 시 처리 for I := 0 to FSelections.Count - 1 do FSelections[I].ShowDisableSpots; FSelectedItem := Item; FSelections.Add(FSelectedItem); end; procedure TThCanvasEditor.ItemUnselect(Item: TThItem); begin FSelections.Remove(Item); FSelectedItem := nil; if FSelections.Count > 0 then FSelectedItem := FSelections.Last; if FSelections.Count = 1 then FSelections[0].ShowSpots; end; procedure TThCanvasEditor.ClearSelection; var I: Integer; begin for I := FSelections.Count - 1 downto 0 do FSelections[I].Selected := False; FSelectedItem := nil; FSelections.Clear; end; procedure TThCanvasEditor.DeleteSelection; var I: Integer; begin if FSelections.Count = 0 then Exit; for I := FSelections.Count - 1 downto 0 do FSelections[I].Parent := nil; if Assigned(FOnItemDelete) then FOnItemDelete(FSelections); ClearSelection; end; function TThCanvasEditor.GetSelectionCount: Integer; begin Result := FSelections.Count; end; function TThCanvasEditor.IsDrawingItem: Boolean; begin Result := FDrawItemId <> -1; end; function TThCanvasEditor.IsMultiSelected: Boolean; begin Result := FSelections.Count > 1; end; procedure TThCanvasEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var CurrP: TPointF; begin inherited; if (Button = TMouseButton.mbLeft) and IsDrawingItem then begin ClearSelection; FDrawItem := CreateItemById(FDrawItemId); if Assigned(FDrawItem) then begin CurrP := PointF(X / ZoomScale, Y / ZoomScale); FDrawItem.Position.Point := CurrP - FContents.ScaledPoint; end; end; end; procedure TThCanvasEditor.MouseMove(Shift: TShiftState; X, Y: Single); var CurrP, FromP, ToP: TPointF; begin if IsDrawingItem and Assigned(FDrawItem) then begin FromP := FMouseDownPos - FContents.ScaledPoint; CurrP := PointF(X / ZoomScale, Y / ZoomScale); ToP := CurrP - FContents.ScaledPoint; FDrawItem.DrawItemAtMouse(FromP, ToP); end else inherited; end; procedure TThCanvasEditor.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var ItemContainer: IThItemContainer; begin inherited; if IsDrawingItem and Assigned(FDrawItem) then begin FDrawItem.Selected := True; // Set Parent FDrawItem.Parent := FContents.FindParent(FDrawItem); // Contain Children if Supports(FDrawItem.Parent, IThItemContainer, ItemContainer) then ItemContainer.ContainChildren(FDrawItem); if Assigned(FOnItemAdded) then FOnItemAdded(FDrawItem); end; FDrawItem := nil; FDrawItemId := -1; end; procedure TThCanvasEditor.Paint; begin inherited; end; procedure TThCanvasEditor.SetDrawItemId(const Value: Integer); begin FDrawItemId := Value; end; procedure TThCanvasEditor.Test; begin // FContents.RotationAngle := FContents.RotationAngle + 45; end; end.
unit UrsJSONPortable; {$IF CompilerVersion > 26} // XE5 {$MESSAGE WARN 'Delphi version greatest at XE5 don''t needed this unit'} {$IFEND} interface {$IF CompilerVersion <= 26} // XE5 uses System.TypInfo, System.Rtti, System.SysUtils, Data.DBXJSON; type TJsonValueBaseHelper = class helper for TJsonValue private function ObjValue: string; end; TJsonValueHelper = class helper(TJsonValueBaseHelper) for TJsonValue private procedure ErrorValueNotFound(const APath: string); function Cast<T>: T; function AsTValue(ATypeInfo: PTypeInfo; out AValue: TValue): Boolean; function FindValue(const APath: string): TJSONValue; public function TryGetValue<T>(out AValue: T): Boolean; overload; function TryGetValue<T>(const APath: string; out AValue: T): Boolean; overload; function GetValue<T>(const APath: string = ''): T; overload; function GetValue<T>(const APath: string; const ADefaultValue: T): T; overload; function Value: string; end; TJsonArrayHelper = class helper for TJsonArray strict private function GetCount: Integer; function GetItem(const AIndex: Integer): TJSONValue; public property Count: Integer read GetCount; property Items[const AIndex: Integer]: TJSONValue read GetItem; end; EJSONPathException = class(Exception); {$IFEND ~CompilerVersion <= 26} // XE5 implementation {$IF CompilerVersion <= 26} // XE5 uses System.SysConst, System.DateUtils, System.TimeSpan, System.Character; const SInvalidDateString = 'Invalid date string: %s'; SInvalidTimeString = 'Invalid time string: %s'; SInvalidOffsetString = 'Invalid time Offset string: %s'; SValueNotFound = 'Value ''%s'' not found'; SJSONPathUnexpectedRootChar = 'Unexpected char for root element: .'; SJSONPathEndedOpenBracket = 'Path ended with an open bracket'; SJSONPathEndedOpenString = 'Path ended with an open string'; SJSONPathInvalidArrayIndex = 'Invalid index for array: %s'; SJSONPathUnexpectedIndexedChar ='Unexpected character while parsing indexer: %s'; SJSONPathDotsEmptyName = 'Empty name not allowed in dot notation, use ['''']'; type DTErrorCode = (InvDate, InvTime, InvOffset); EDateTimeException = class(Exception); TJSONPathParser = class public type TToken = (Undefined, Name, ArrayIndex, Eof, Error); private FPath: string; FPos: Integer; FTokenArrayIndex: Integer; FToken: TToken; FTokenName: string; function GetIsEof: Boolean; inline; procedure RaiseError(const AMsg: string); overload; procedure RaiseErrorFmt(const AMsg: string; const AParams: array of const); overload; procedure SetToken(const AToken: TToken); overload; procedure SetToken(const AToken: TToken; const AValue); overload; procedure ParseName; procedure ParseQuotedName(AQuote: Char); procedure ParseArrayIndex; procedure ParseIndexer; function EnsureLength(ALength: Integer): Boolean; inline; procedure EatWhiteSpaces; public constructor Create(const APath: string); function NextToken: TToken; property IsEof: Boolean read GetIsEof; property Token: TToken read FToken; property TokenName: string read FTokenName; property TokenArrayIndex: Integer read FTokenArrayIndex; end; TCharHelper = record helper for Char public function IsDigit: Boolean; end; var JSONFormatSettings: TFormatSettings; {$IF CompilerVersion <= 24} // XE3 function _ValUInt64(const s: string; var code: Integer): UInt64; var i: Integer; dig: Integer; sign: Boolean; empty: Boolean; begin i := 1; {$IFNDEF CPUX64} // avoid E1036: Variable 'dig' might not have been initialized dig := 0; {$ENDIF} Result := 0; if s = '' then begin code := 1; exit; end; while s[i] = Char(' ') do Inc(i); sign := False; if s[i] = Char('-') then begin sign := True; Inc(i); end else if s[i] = Char('+') then Inc(i); empty := True; if (s[i] = Char('$')) or (Upcase(s[i]) = Char('X')) or ((s[i] = Char('0')) and (I < Length(S)) and (Upcase(s[i+1]) = Char('X'))) then begin if s[i] = Char('0') then Inc(i); Inc(i); while True do begin case Char(s[i]) of Char('0').. Char('9'): dig := Ord(s[i]) - Ord('0'); Char('A').. Char('F'): dig := Ord(s[i]) - (Ord('A') - 10); Char('a').. Char('f'): dig := Ord(s[i]) - (Ord('a') - 10); else break; end; if Result > (High(UInt64) shr 4) then Break; if sign and (dig <> 0) then Break; Result := Result shl 4 + dig; Inc(i); empty := False; end; end else begin while True do begin case Char(s[i]) of Char('0').. Char('9'): dig := Ord(s[i]) - Ord('0'); else break; end; if Result > (High(UInt64) div 10) then Break; if sign and (dig <> 0) then Break; Result := Result*10 + dig; Inc(i); empty := False; end; end; if (s[i] <> Char(#0)) or empty then code := i else code := 0; end; {$IFEND ~CompilerVersion <= 24} // XE3 {$IF CompilerVersion <= 24} // XE3 function TryStrToUInt64(const AStr: string; out AVal: UInt64): Boolean; var LErr: Integer; begin AVal := _ValUInt64(AStr, LErr); Result := LErr = 0; end; {$IFEND ~CompilerVersion <= 24} // XE3 {$IF CompilerVersion <= 24} // XE3 function StrToUInt64(const AStr: string): UInt64; begin if not TryStrToUInt64(AStr, Result) then raise EConvertError.CreateResFmt(@SInvalidInteger, [AStr]); end; {$IFEND ~CompilerVersion <= 24} // XE3 function InitJsonFormatSettings: TFormatSettings; begin Result := GetUSFormat; Result.CurrencyString := #$00A4; Result.CurrencyFormat := 0; Result.CurrencyDecimals := 2; Result.DateSeparator := '/'; Result.TimeSeparator := ':'; Result.ListSeparator := ','; Result.ShortDateFormat := 'MM/dd/yyyy'; Result.LongDateFormat := 'dddd, dd MMMMM yyyy HH:mm:ss'; Result.TimeAMString := 'AM'; Result.TimePMString := 'PM'; Result.ShortTimeFormat := 'HH:mm'; Result.LongTimeFormat := 'HH:mm:ss'; // for I := Low(DefShortMonthNames) to High(DefShortMonthNames) do // begin // Result.ShortMonthNames[I] := LoadResString(DefShortMonthNames[I]); // Result.LongMonthNames[I] := LoadResString(DefLongMonthNames[I]); // end; // for I := Low(DefShortDayNames) to High(DefShortDayNames) do // begin // Result.ShortDayNames[I] := LoadResString(DefShortDayNames[I]); // Result.LongDayNames[I] := LoadResString(DefLongDayNames[I]); // end; Result.ThousandSeparator := ','; Result.DecimalSeparator := '.'; Result.TwoDigitYearCenturyWindow := 50; Result.NegCurrFormat := 0; end; procedure DTFmtError(AErrorCode: DTErrorCode; const AValue: string); const Errors: array[DTErrorCode] of string = (SInvalidDateString, SInvalidTimeString, SInvalidOffsetString); begin raise EDateTimeException.CreateFmt(Errors[AErrorCode], [AValue]); end; function GetNextDTComp(var P: PChar; const PEnd: PChar; ErrorCode: DTErrorCode; const AValue: string; NumDigits: Integer): string; overload; var LDigits: Integer; begin LDigits := 0; Result := ''; while ((P <= PEnd) and P^.IsDigit and (LDigits < NumDigits)) do begin Result := Result + P^; Inc(P); Inc(LDigits); end; if Result = '' then DTFmtError(ErrorCode, AValue); end; function GetNextDTComp(var P: PChar; const PEnd: PChar; const DefValue: string; Prefix: Char; IsOptional: Boolean; IsDate: Boolean; ErrorCode: DTErrorCode; const AValue: string; NumDigits: Integer): string; overload; const SEmptySeparator: Char = ' '; var LDigits: Integer; begin if (P >= PEnd) then begin Result := DefValue; Exit; end; Result := ''; if (Prefix <> SEmptySeparator) and (IsDate or not (Byte(P^) in [Ord('+'), Ord('-')])) then begin if P^ <> Prefix then DTFmtError(ErrorCode, AValue); Inc(P); end; LDigits := 0; while ((P <= PEnd) and P^.IsDigit and (LDigits < NumDigits)) do begin Result := Result + P^; Inc(P); Inc(LDigits); end; if Result = '' then begin if IsOptional then Result := DefValue else DTFmtError(ErrorCode, AValue); end; end; procedure DecodeISO8601Date(const DateString: string; var AYear, AMonth, ADay: Word); procedure ConvertDate(const AValue: string); const SDateSeparator: Char = '-'; SEmptySeparator: Char = ' '; var P, PE: PChar; begin P := PChar(AValue); PE := P + (AValue.Length - 1); if AValue.IndexOf(SDateSeparator) < 0 then begin AYear := StrToInt(GetNextDTComp(P, PE, InvDate, AValue, 4)); AMonth := StrToInt(GetNextDTComp(P, PE, '00', SEmptySeparator, True, True, InvDate, AValue, 2)); ADay := StrToInt(GetNextDTComp(P, PE, '00', SEmptySeparator, True, True, InvDate, AValue, 2)); end else begin AYear := StrToInt(GetNextDTComp(P, PE, InvDate, AValue, 4)); AMonth := StrToInt(GetNextDTComp(P, PE, '00', SDateSeparator, True, True, InvDate, AValue, 2)); ADay := StrToInt(GetNextDTComp(P, PE, '00', SDateSeparator, True, True, InvDate, AValue, 2)); end; end; var TempValue: string; LNegativeDate: Boolean; begin AYear := 0; AMonth := 0; ADay := 1; LNegativeDate := (DateString <> '') and (DateString[Low(string)] = '-'); if LNegativeDate then TempValue := DateString.Substring(1) else TempValue := DateString; if Length(TempValue) < 4 then raise EDateTimeException.CreateFmt(SInvalidDateString, [TempValue]); ConvertDate(TempValue); end; procedure DecodeISO8601Time(const TimeString: string; var AHour, AMinute, ASecond, AMillisecond: Word; var AHourOffset, AMinuteOffset: Integer); const SEmptySeparator: Char = ' '; STimeSeparator: Char = ':'; SMilSecSeparator: Char = '.'; var LFractionalSecondString: string; P, PE: PChar; LOffsetSign: Char; LFraction: Double; begin AHour := 0; AMinute := 0; ASecond := 0; AMillisecond := 0; AHourOffset := 0; AMinuteOffset := 0; if TimeString <> '' then begin P := PChar(TimeString); PE := P + (TimeString.Length - 1); if TimeString.IndexOf(STimeSeparator) < 0 then begin AHour := StrToInt(GetNextDTComp(P, PE, InvTime, TimeString, 2)); AMinute := StrToInt(GetNextDTComp(P, PE, '00', SEmptySeparator, False, False, InvTime, TimeString, 2)); ASecond := StrToInt(GetNextDTComp(P, PE, '00', SEmptySeparator, True, False, InvTime, TimeString, 2)); LFractionalSecondString := GetNextDTComp(P, PE, '0', SMilSecSeparator, True, False, InvTime, TimeString, 18); if LFractionalSecondString <> '0' then begin LFractionalSecondString := FormatSettings.DecimalSeparator + LFractionalSecondString; LFraction := StrToFloat(LFractionalSecondString); AMillisecond := Round(1000 * LFraction); end; end else begin AHour := StrToInt(GetNextDTComp(P, PE, InvTime, TimeString, 2)); AMinute := StrToInt(GetNextDTComp(P, PE, '00', STimeSeparator, False, False, InvTime, TimeString, 2)); ASecond := StrToInt(GetNextDTComp(P, PE, '00', STimeSeparator, True, False, InvTime, TimeString, 2)); LFractionalSecondString := GetNextDTComp(P, PE, '0', SMilSecSeparator, True, False, InvTime, TimeString, 18); if LFractionalSecondString <> '0' then begin LFractionalSecondString := FormatSettings.DecimalSeparator + LFractionalSecondString; LFraction := StrToFloat(LFractionalSecondString); AMillisecond := Round(1000 * LFraction); end; end; if CharInSet(P^, ['-', '+']) then begin LOffsetSign := P^; Inc(P); if not P^.IsDigit then DTFmtError(InvTime, TimeString); AHourOffset := StrToInt(LOffsetSign + GetNextDTComp(P, PE, InvOffset, TimeString, 2)); AMinuteOffset:= StrToInt(LOffsetSign + GetNextDTComp(P, PE, '00', STimeSeparator, True, True, InvOffset, TimeString, 2)); end; end; end; function AdjustDateTime(const ADate: TDateTime; AHourOffset, AMinuteOffset:Integer; IsUTC: Boolean = True): TDateTime; var AdjustDT: TDateTime; BiasLocal: Int64; BiasTime: Integer; BiasHour: Integer; BiasMins: Integer; BiasDT: TDateTime; TZ: TTimeZone; begin Result := ADate; if IsUTC then begin { If we have an offset, adjust time to go back to UTC } if (AHourOffset <> 0) or (AMinuteOffset <> 0) then begin AdjustDT := EncodeTime(Abs(AHourOffset), Abs(AMinuteOffset), 0, 0); if ((AHourOffset * MinsPerHour) + AMinuteOffset) > 0 then Result := Result - AdjustDT else Result := Result + AdjustDT; end; end else begin { Now adjust TDateTime based on any offsets we have and the local bias } { There are two possibilities: a. The time we have has the same offset as the local bias - nothing to do!! b. The time we have and the local bias are different - requiring adjustments } TZ := TTimeZone.Local; BiasLocal := Trunc(TZ.GetUTCOffset(Result).Negate.TotalMinutes); BiasTime := (AHourOffset * MinsPerHour) + AMinuteOffset; if (BiasLocal + BiasTime) = 0 then Exit; { Here we adjust the Local Bias to make it relative to the Time's own offset instead of being relative to GMT } BiasLocal := BiasLocal + BiasTime; BiasHour := Abs(BiasLocal) div MinsPerHour; BiasMins := Abs(BiasLocal) mod MinsPerHour; BiasDT := EncodeTime(BiasHour, BiasMins, 0, 0); if (BiasLocal > 0) then Result := Result - BiasDT else Result := Result + BiasDT; end; end; function ISO8601ToDate(const AISODate: string; AReturnUTC: Boolean = True): TDateTime; const STimePrefix: Char = 'T'; var TimeString, DateString: string; TimePosition: Integer; Year, Month, Day, Hour, Minute, Second, Millisecond: Word; HourOffset, MinuteOffset: Integer; AddDay, AddMinute: Boolean; begin HourOffset := 0; MinuteOffset := 0; TimePosition := AISODate.IndexOf(STimePrefix); if TimePosition >= 0 then begin DateString := AISODate.Substring(0, TimePosition); TimeString := AISODate.Substring(TimePosition + 1); end else begin Hour := 0; Minute := 0; Second := 0; Millisecond := 0; HourOffset := 0; MinuteOffset := 0; DateString := AISODate; TimeString := ''; end; DecodeISO8601Date(DateString, Year, Month, Day); DecodeISO8601Time(TimeString, Hour, Minute, Second, Millisecond, HourOffset, MinuteOffset); AddDay := Hour = 24; if AddDay then Hour := 0; AddMinute := Second = 60; if AddMinute then Second := 0; Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); if AddDay then Result := IncDay(Result); if AddMinute then Result := IncMinute(Result); Result := AdjustDateTime(Result, HourOffset, MinuteOffset, AReturnUTC); end; function StrToTValue(const Str: string; const TypeInfo: PTypeInfo; out AValue: TValue): Boolean; function CheckRange(const Min, Max: Int64; const Value: Int64; const Str: string): Int64; begin Result := Value; if (Value < Min) or (Value > Max) then raise EConvertError.CreateFmt(System.SysConst.SInvalidInteger, [Str]); end; var TypeData: TTypeData; TypeName: string; begin Result := True; case TypeInfo.Kind of tkInteger: case GetTypeData(TypeInfo)^.OrdType of otSByte: AValue := CheckRange(Low(Int8), High(Int8), StrToInt(Str), Str); otSWord: AValue := CheckRange(Low(Int16), High(Int16), StrToInt(Str), Str); otSLong: AValue := StrToInt(Str); otUByte: AValue := CheckRange(Low(UInt8), High(UInt8), StrToInt(Str), Str); otUWord: AValue := CheckRange(Low(UInt16), High(UInt16), StrToInt(Str), Str); otULong: AValue := CheckRange(Low(UInt32), High(UInt32), StrToInt64(Str), Str); end; tkInt64: begin TypeData := GetTypeData(TypeInfo)^; if TypeData.MinInt64Value > TypeData.MaxInt64Value then AValue := StrToUInt64(Str) else AValue := StrToInt64(Str); end; tkEnumeration: begin TypeName := TypeInfo.NameFld.ToString; if SameText(TypeName, 'boolean') or SameText(TypeName, 'bool') then AValue := StrToBool(Str) else Result := False; end; tkFloat: case GetTypeData(TypeInfo)^.FloatType of ftSingle: AValue := StrToFloat(Str, JSONFormatSettings); ftDouble: begin if TypeInfo = System.TypeInfo(TDate) then AValue := ISO8601ToDate(Str) else if TypeInfo = System.TypeInfo(TTime) then AValue := ISO8601ToDate(Str) else if TypeInfo = System.TypeInfo(TDateTime) then AValue := ISO8601ToDate(Str) else AValue := StrToFloat(Str, JSONFormatSettings); end; ftExtended: AValue := StrToFloat(Str, JSONFormatSettings); ftComp: AValue := StrToFloat(Str, JSONFormatSettings); ftCurr: AValue := StrToCurr(Str, JSONFormatSettings); end; {$IFNDEF NEXTGEN} tkChar, {$ENDIF !NEXTGEN} tkWChar: begin if Str.Length = 1 then AValue := Str[Low(string)] else Result := False; end; tkString, tkLString, tkUString, tkWString: AValue := Str; else Result := False; end; end; function FindJSONValue(const AJSON: TJSONValue; const APath: string): TJsonValue; overload; var LCurrentValue: TJSONValue; LParser: TJSONPathParser; LPair: TJSONPair; LError: Boolean; begin LParser := TJSONPathParser.Create(APath); try LCurrentValue := AJSON; LError := False; while (not LParser.IsEof) and (not LError) do begin case LParser.NextToken of TJSONPathParser.TToken.Name: begin if LCurrentValue is TJSONObject then begin LPair := TJSONObject(LCurrentValue).Get(LParser.TokenName); if LPair <> nil then LCurrentValue := LPair.JsonValue else LCurrentValue := nil; if LCurrentValue = nil then LError := True; end else LError := True; end; TJSONPathParser.TToken.ArrayIndex: begin if LCurrentValue is TJSONArray then if LParser.TokenArrayIndex < TJSONArray(LCurrentValue).Count then LCurrentValue := TJSONArray(LCurrentValue).Items[LParser.TokenArrayIndex] else LError := True else LError := True end; TJSONPathParser.TToken.Error: LError := True; else Assert(LParser.Token = TJSONPathParser.TToken.Eof); // case statement is not complete end; end; if LParser.IsEof and not LError then Result := LCurrentValue else Result := nil; finally LParser.Free; end; end; { TJSONPathParser } constructor TJSONPathParser.Create(const APath: string); begin FPath := APath; end; procedure TJSONPathParser.EatWhiteSpaces; begin while not IsEof and IsWhiteSpace(FPath.Chars[FPos]) do Inc(FPos); end; function TJSONPathParser.EnsureLength(ALength: Integer): Boolean; begin Result := (FPos + ALength) < Length(FPath); end; function TJSONPathParser.GetIsEof: Boolean; begin Result := FPos >= Length(FPath); end; function TJSONPathParser.NextToken: TToken; var IsFirstToken: Boolean; begin IsFirstToken := FPos = 0; EatWhiteSpaces; if IsEof then SetToken(TToken.Eof) else begin case FPath.Chars[FPos] of '.': // Root element cannot start with a dot if IsFirstToken then RaiseError(SJSONPathUnexpectedRootChar) else ParseName; '[': ParseIndexer; else // In dot notation all names are prefixed by '.', except the root element if IsFirstToken then ParseName else RaiseErrorFmt(SJSONPathUnexpectedIndexedChar, [FPath.Chars[FPos]]); end; Inc(FPos); end; Result := FToken; end; procedure TJSONPathParser.ParseArrayIndex; var LEndPos: Integer; LString: string; I: Integer; begin LEndPos := FPath.IndexOf(']', FPos); if LEndPos < 0 then RaiseError(SJSONPathEndedOpenBracket) else begin LString := Trim(FPath.Substring(FPos, LEndPos - FPos)); FPos := LEndPos - 1; if TryStrToInt(LString, I) then SetToken(TToken.ArrayIndex, I) else RaiseErrorFmt(SJSONPathInvalidArrayIndex, [LString]) end; end; procedure TJSONPathParser.ParseQuotedName(AQuote: Char); var LString: string; begin LString := ''; Inc(FPos); while not IsEof do begin if (FPath.Chars[FPos] = '\') and EnsureLength(1) and (FPath.Chars[FPos + 1] = AQuote) then // \" begin Inc(FPos); LString := LString + AQuote end else if FPath.Chars[FPos] = AQuote then begin SetToken(TToken.Name, LString); Exit; end else LString := LString + FPath.Chars[FPos]; Inc(FPos); end; RaiseError(SJSONPathEndedOpenString); end; procedure TJSONPathParser.RaiseError(const AMsg: string); begin RaiseErrorFmt(AMsg, []); end; procedure TJSONPathParser.RaiseErrorFmt(const AMsg: string; const AParams: array of const); begin SetToken(TToken.Error); raise EJSONPathException.Create(Format(AMsg, AParams)); end; procedure TJSONPathParser.ParseIndexer; begin Inc(FPos); // [ EatWhiteSpaces; if IsEof then RaiseError('Path ended with an open bracket'); case FPath.Chars[FPos] of '"', '''': ParseQuotedName(FPath.Chars[FPos]); else ParseArrayIndex; end; Inc(FPos); EatWhiteSpaces; if FPath.Chars[FPos] <> ']' then RaiseErrorFmt(SJSONPathUnexpectedIndexedChar,[FPath.Chars[FPos]]); end; procedure TJSONPathParser.ParseName; var LEndPos: Integer; LString: string; begin if FPath.Chars[FPos] = '.' then begin Inc(FPos); if IsEof then begin SetToken(TToken.Error); Exit; end; end; LEndPos := FPath.IndexOfAny(['.', '['], FPos); if LEndPos < 0 then begin LString := FPath.Substring(FPos); FPos := Length(FPath) - 1; end else begin LString := Trim(FPath.Substring(FPos, LEndPos - FPos)); FPos := LEndPos - 1; end; if LString = '' then RaiseError(SJSONPathDotsEmptyName) else SetToken(TToken.Name, LString); end; procedure TJSONPathParser.SetToken(const AToken: TToken); var P: Pointer; begin SetToken(AToken, P); end; procedure TJSONPathParser.SetToken(const AToken: TToken; const AValue); begin FToken := AToken; case FToken of TToken.Name: FTokenName := string(AValue); TToken.ArrayIndex: FTokenArrayIndex := Integer(AValue); end; end; { TCharHelper } function TCharHelper.IsDigit: Boolean; begin Result := System.Character.IsDigit(Self) end; { TJsonValueBaseHelper } function TJsonValueBaseHelper.ObjValue: string; begin Result := Value; end; { TJsonValueHelper } procedure TJsonValueHelper.ErrorValueNotFound(const APath: string); begin raise TJSONException.Create(Format(SValueNotFound, [APath])); end; function TJsonValueHelper.Cast<T>: T; var LTypeInfo: PTypeInfo; LValue: TValue; begin LTypeInfo := System.TypeInfo(T); if not AsTValue(LTypeInfo, LValue) then raise TJSONException.CreateFmt('Conversion from %0:s to %1:s is not supported', [Self.ClassName, LTypeInfo.Name]); Result := LValue.AsType<T>; end; function TJsonValueHelper.AsTValue(ATypeInfo: PTypeInfo; out AValue: TValue): Boolean; var LNeedBase: Boolean; LBool: Boolean; begin Result := False; LNeedBase := False; if (Self is TJSONTrue) or (Self is TJSONFalse) then begin LBool := Self is TJSONTrue; case ATypeInfo.Kind of tkEnumeration: begin AValue := TValue.FromOrdinal(ATypeInfo, Ord(LBool)); Result := AValue.IsType<Boolean> or AValue.IsType<ByteBool> or AValue.IsType<WordBool> or AValue.IsType<LongBool>; end; tkInteger, tkInt64, tkFloat: begin AValue := Ord(LBool); Result := True; end; tkString, tkLString, tkWString, tkUString: begin AValue := Value; Result := True; end else LNeedBase := True; end; end else if Self is TJSONNull then begin case ATypeInfo.Kind of tkString, tkLString, tkUString, TkWString: begin AValue := ''; Result := True; end else LNeedBase := True; end; end else if Self is TJSONString then begin case ATypeInfo.Kind of tkInteger, tkInt64, tkFloat, tkString, tkLString, tkWString, tkUString, {$IFNDEF NEXTGEN} tkChar, {$ENDIF !NEXTGEN} tkWChar, tkEnumeration: Result := StrToTValue(Value, ATypeInfo, AValue) else LNeedBase := True; end; end else LNeedBase := True; if LNeedBase then begin case ATypeInfo^.Kind of tkClass: begin AValue := Self; Result := True; end end; end; end; function TJsonValueHelper.FindValue(const APath: string): TJSONValue; begin if (Self is TJSONArray) or (Self is TJSONObject) then Result := FindJSONValue(Self, APath) else begin if APath = '' then Result := Self else Result := nil; end; end; function TJsonValueHelper.TryGetValue<T>(out AValue: T): Boolean; begin Result := TryGetValue<T>('', AValue); end; function TJsonValueHelper.TryGetValue<T>(const APath: string; out AValue: T): Boolean; var LJSONValue: TJSONValue; begin LJSONValue := FindValue(APath); Result := LJSONValue <> nil; if Result then begin try AValue := LJSONValue.Cast<T>; except Result := False; end; end; end; function TJsonValueHelper.GetValue<T>(const APath: string = ''): T; var LValue: T; LJSONValue: TJSONValue; begin LJSONValue := FindValue(APath); if LJSONValue = nil then ErrorValueNotFound(APath); Result := LJSONValue.Cast<T>; end; function TJsonValueHelper.GetValue<T>(const APath: string; const ADefaultValue: T): T; var LValue: T; LJSONValue: TJSONValue; LTypeInfo: PTypeInfo; LReturnDefault: Boolean; begin LJSONValue := FindValue(APath); LReturnDefault := LJSONValue = nil; // Treat JSONNull as nil if LJSONValue is TJSONNull then begin LTypeInfo := System.TypeInfo(T); if LTypeInfo.TypeData.ClassType <> nil then LJSONValue := nil; end; if LJSONValue <> nil then Result := LJSONValue.Cast<T> else Result := ADefaultValue end; function TJsonValueHelper.Value: string; begin if (Self is TJSONTrue) or (Self is TJSONFalse) then Result := ToString else Result := ObjValue; end; { TJsonArrayHelper } function TJsonArrayHelper.GetCount: Integer; begin Result := Size; end; function TJsonArrayHelper.GetItem(const AIndex: Integer): TJSONValue; begin Result := Get(AIndex); end; initialization JSONFormatSettings := InitJsonFormatSettings; {$IFEND ~CompilerVersion <= 26} // XE5 end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Support classes for loading various fileformats. These classes work together like vector file formats or Delphi's TGraphic classes. } unit VXS.SoundFileObjects; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, {$IFDEF MSWINDOWS}Winapi.MMSystem,{$ENDIF} VXS.ApplicationFileIO, VXS.CrossPlatform; type { Defines a sound sampling quality. } TVXSoundSampling = class(TPersistent) private FOwner: TPersistent; FFrequency: Integer; FNbChannels: Integer; FBitsPerSample: Integer; protected function GetOwner: TPersistent; override; public constructor Create(AOwner: TPersistent); destructor Destroy; override; procedure Assign(Source: TPersistent); override; function BytesPerSec: Integer; function BytesPerSample: Integer; {$IFDEF MSWINDOWS} function WaveFormat: TWaveFormatEx; {$ENDIF} published { Sampling frequency in Hz (= samples per sec) } property Frequency: Integer read FFrequency write FFrequency default 22050; { Nb of sampling channels. 1 = mono, 2 = stereo, etc. } property NbChannels: Integer read FNbChannels write FNbChannels default 1; { Nb of bits per sample. Common values are 8 and 16 bits. } property BitsPerSample: Integer read FBitsPerSample write FBitsPerSample default 8; end; { Abstract base class for different Sound file formats. The actual implementation for these files (WAV, RAW...) must be done seperately. The concept for TVXSoundFile is very similar to TGraphic (see Delphi Help). Default implementation for LoadFromFile/SaveToFile are to directly call the relevent stream-based methods, ie. you will just have to override the stream methods in most cases. } TVXSoundFile = class(TVXDataFile) private FSampling: TVXSoundSampling; protected procedure SetSampling(const val: TVXSoundSampling); public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure PlayOnWaveOut; virtual; { Returns a pointer to the sample data viewed as an in-memory WAV File. } function WAVData: Pointer; virtual; abstract; { Returns the size (in bytes) of the WAVData. } function WAVDataSize: Integer; virtual; abstract; { Returns a pointer to the sample data viewed as an in-memory PCM buffer. } function PCMData: Pointer; virtual; abstract; { Length of PCM data, in bytes. } function LengthInBytes: Integer; virtual; abstract; { Nb of intensity samples in the sample. } function LengthInSamples: Integer; { Length of play of the sample at nominal speed in seconds. } function LengthInSec: Single; property Sampling: TVXSoundSampling read FSampling write SetSampling; end; TVXSoundFileClass = class of TVXSoundFile; TVXSoundFileFormat = record SoundFileClass : TVXSoundFileClass; Extension : String; Description : String; DescResID : Integer; end; PSoundFileFormat = ^TVXSoundFileFormat; TVXSoundFileFormatsList = class(TList) public destructor Destroy; override; procedure Add(const Ext, Desc: String; DescID: Integer; AClass: TVXSoundFileClass); function FindExt(Ext: string): TVXSoundFileClass; procedure Remove(AClass: TVXSoundFileClass); procedure BuildFilterStrings(SoundFileClass: TVXSoundFileClass; out Descriptions, Filters: string); end; function GetGLSoundFileFormats : TVXSoundFileFormatsList; procedure RegisterSoundFileFormat(const AExtension, ADescription: String; AClass: TVXSoundFileClass); procedure UnregisterSoundFileClass(AClass: TVXSoundFileClass); // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ var vSoundFileFormats : TVXSoundFileFormatsList; function GetGLSoundFileFormats : TVXSoundFileFormatsList; begin if not Assigned(vSoundFileFormats)then vSoundFileFormats := TVXSoundFileFormatsList.Create; Result := vSoundFileFormats; end; procedure RegisterSoundFileFormat(const AExtension, ADescription: String; AClass: TVXSoundFileClass); begin RegisterClass(AClass); GetGLSoundFileFormats.Add(AExtension, ADescription, 0, AClass); end; procedure UnregisterSoundFileClass(AClass: TVXSoundFileClass); begin if Assigned(vSoundFileFormats) then vSoundFileFormats.Remove(AClass); end; // ------------------ // ------------------ TVXSoundSampling ------------------ // ------------------ constructor TVXSoundSampling.Create(AOwner: TPersistent); begin inherited Create; FOwner := AOwner; FFrequency := 22050; FNbChannels := 1; FBitsPerSample := 8; end; destructor TVXSoundSampling.Destroy; begin inherited Destroy; end; procedure TVXSoundSampling.Assign(Source: TPersistent); begin if Source is TVXSoundSampling then begin FFrequency:=TVXSoundSampling(Source).Frequency; FNbChannels:=TVXSoundSampling(Source).NbChannels; FBitsPerSample:=TVXSoundSampling(Source).BitsPerSample; end else inherited; end; function TVXSoundSampling.GetOwner : TPersistent; begin Result:=FOwner; end; function TVXSoundSampling.BytesPerSec : Integer; begin Result:=(FFrequency*FBitsPerSample*FNbChannels) shr 3; end; function TVXSoundSampling.BytesPerSample : Integer; begin Result:=FBitsPerSample shr 3; end; {$IFDEF MSWINDOWS} function TVXSoundSampling.WaveFormat : TWaveFormatEx; begin Result.nSamplesPerSec := Frequency; Result.nChannels := NbChannels; Result.wFormatTag := Wave_Format_PCM; Result.nAvgBytesPerSec := BytesPerSec; Result.wBitsPerSample := BitsPerSample; Result.nBlockAlign := NbChannels * BytesPerSample; Result.cbSize := 0; end; {$ENDIF} // ------------------ // ------------------ TVXSoundFile ------------------ // ------------------ constructor TVXSoundFile.Create(AOwner: TPersistent); begin inherited; FSampling:=TVXSoundSampling.Create(Self); end; destructor TVXSoundFile.Destroy; begin FSampling.Free; inherited; end; procedure TVXSoundFile.SetSampling(const val : TVXSoundSampling); begin FSampling.Assign(val); end; procedure TVXSoundFile.PlayOnWaveOut; begin // VXSoundFileObjects.PlayOnWaveOut(PCMData, LengthInSamples, Sampling); end; function TVXSoundFile.LengthInSamples : Integer; var d : Integer; begin d:=Sampling.BytesPerSample*Sampling.NbChannels; if d>0 then Result:=LengthInBytes div d else Result:=0; end; function TVXSoundFile.LengthInSec : Single; begin Result:=LengthInBytes/Sampling.BytesPerSec; end; // ------------------ // ------------------ TVXSoundFileFormatsList ------------------ // ------------------ destructor TVXSoundFileFormatsList.Destroy; var i : Integer; begin for i:=0 to Count-1 do Dispose(PSoundFileFormat(Items[i])); inherited; end; procedure TVXSoundFileFormatsList.Add(const Ext, Desc: String; DescID: Integer; AClass: TVXSoundFileClass); var newRec: PSoundFileFormat; begin New(newRec); with newRec^ do begin Extension := AnsiLowerCase(Ext); SoundFileClass := AClass; Description := Desc; DescResID := DescID; end; inherited Add(NewRec); end; function TVXSoundFileFormatsList.FindExt(Ext: string): TVXSoundFileClass; var i : Integer; begin Ext := AnsiLowerCase(Ext); for I := Count-1 downto 0 do with PSoundFileFormat(Items[I])^ do if (Extension = Ext) or ('.'+Extension = Ext) then begin Result := SoundFileClass; Exit; end; Result := nil; end; procedure TVXSoundFileFormatsList.Remove(AClass: TVXSoundFileClass); var i : Integer; p : PSoundFileFormat; begin for I := Count-1 downto 0 do begin P := PSoundFileFormat(Items[I]); if P^.SoundFileClass.InheritsFrom(AClass) then begin Dispose(P); Delete(I); end; end; end; procedure TVXSoundFileFormatsList.BuildFilterStrings(SoundFileClass: TVXSoundFileClass; out Descriptions, Filters: string); var c, i : Integer; p : PSoundFileFormat; begin Descriptions := ''; Filters := ''; C := 0; for I := Count-1 downto 0 do begin P := PSoundFileFormat(Items[I]); if P^.SoundFileClass.InheritsFrom(SoundFileClass) and (P^.Extension <> '') then with P^ do begin if C <> 0 then begin Descriptions := Descriptions+'|'; Filters := Filters+';'; end; if (Description = '') and (DescResID <> 0) then Description := LoadStr(DescResID); FmtStr(Descriptions, '%s%s (*.%s)|*.%2:s', [Descriptions, Description, Extension]); FmtStr(Filters, '%s*.%s', [Filters, Extension]); Inc(C); end; end; if C > 1 then FmtStr(Descriptions, '%s (%s)|%1:s|%s', [sAllFilter, Filters, Descriptions]); end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ finalization FreeAndNil(vSoundFileFormats); end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.IDE.ProjectStorageNotifier; interface uses ToolsApi, XML.XMLIntf, System.Classes, Spring.Collections, DPM.IDE.Logger, DPM.IDE.ProjectController; // Note while most of the work is done in the IDENotifier - that doesn't fire for // external modifications - this one does - so we need both. type TDPMProjectStorageNotifier = class(TModuleNotifierObject, IOTAProjectFileStorageNotifier) private FLogger : IDPMIDELogger; FProjectController : IDPMIDEProjectController; protected //IOTAProjectFileStorageNotifier procedure CreatingProject(const ProjectOrGroup : IOTAModule); function GetName : string; procedure ProjectClosing(const ProjectOrGroup : IOTAModule); procedure ProjectLoaded(const ProjectOrGroup : IOTAModule; const Node : IXMLNode); procedure ProjectSaving(const ProjectOrGroup : IOTAModule; const Node : IXMLNode); public constructor Create(const logger : IDPMIDELogger; const projectController : IDPMIDEProjectController); destructor Destroy; override; end; implementation uses Vcl.Forms, System.SysUtils, DPM.Core.Utils.System, DPM.Core.Utils.Path; { TDPMProjectStorageNotifier } constructor TDPMProjectStorageNotifier.Create(const logger : IDPMIDELogger; const projectController : IDPMIDEProjectController ); begin FLogger := logger; FProjectController := projectController end; procedure TDPMProjectStorageNotifier.CreatingProject(const ProjectOrGroup : IOTAModule); begin if not (ExtractFileExt(ProjectOrGroup.FileName) = '.dproj') then exit; FProjectController.ProjectCreating(ProjectOrGroup.FileName); end; destructor TDPMProjectStorageNotifier.Destroy; begin FLogger := nil; FProjectController := nil; inherited; end; function TDPMProjectStorageNotifier.GetName : string; begin //this has to be a node under BorlandProject //we don't really care what this is, we are not going to modify it, //we just want to make the notifications work! result := 'Platforms'; end; procedure TDPMProjectStorageNotifier.ProjectClosing(const ProjectOrGroup : IOTAModule); var ext : string; begin FLogger.Debug('TDPMProjectStorageNotifier - ProjectClosing : ' + ProjectOrGroup.FileName); TSystemUtils.OutputDebugString('TDPMProjectStorageNotifier - ProjectClosing : ' + ProjectOrGroup.FileName); ext := ExtractFileExt(ProjectOrGroup.FileName); if (ext = '.dproj') then FProjectController.ProjectClosing(ProjectOrGroup.FileName) else if (ext = '.groupproj') then FProjectController.ProjectGroupClosed; end; procedure TDPMProjectStorageNotifier.ProjectLoaded(const ProjectOrGroup : IOTAModule; const Node : IXMLNode); begin FLogger.Debug('TDPMProjectStorageNotifier - ProjectLoaded : ' + ProjectOrGroup.FileName); TSystemUtils.OutputDebugString('TDPMProjectStorageNotifier - ProjectLoaded : ' + ProjectOrGroup.FileName); //doesn't seem to get called with the project group? if not (ExtractFileExt(ProjectOrGroup.FileName) = '.dproj') then exit; FProjectController.ProjectLoaded(ProjectOrGroup.FileName); end; procedure TDPMProjectStorageNotifier.ProjectSaving(const ProjectOrGroup : IOTAModule; const Node : IXMLNode); begin FLogger.Debug('TDPMProjectStorageNotifier - ProjectSaving : ' + ProjectOrGroup.FileName); TSystemUtils.OutputDebugString('TDPMProjectStorageNotifier - ProjectSaving : ' + ProjectOrGroup.FileName); if not (ExtractFileExt(ProjectOrGroup.FileName) = '.dproj') then exit; FProjectController.ProjectSaving(ProjectOrGroup.FileName); end; end.
unit OperazioniInvio; {$mode delphi} interface uses Classes, SysUtils, FileUtil, HTTPSend, IniFiles, UtilitaExtra, InfoPagina, InfoFile; type TItasaUrls = record URL_ITASA, URL_LOGIN, URL_DOWNLOAD, URL_TOPIC, URL_POST, URL_PANNELLO : String; end; TUserInfo = record Username, Passwd : String; Log : Boolean; Message : TStringList; end; TTemp = record TEMP_PATH, EXE_PATH, OPEN_PATH, TEMP_FILE, COOKIE_FILE : String; end; function LeggiOpzioni : Boolean; function ItasaLogin : Boolean; function ItasaDownloadPagina(Url : String ) : Boolean; function ItasaDownloadInfoTopic : Boolean; function ItasaDownloadInfoPannello : Boolean; function ItasaDownloadInfoPannelloInvio : Boolean; function ItasaPostPannello : Boolean; function ItasaPostTopic : Boolean; var iniFile: TIniFile; ItasaUrls : TItasaUrls; UserInfo : TUserInfo; Temp : TTemp; NomeFile : TNomeFile; InfoTopic : TInfoTopic; InfoPannello : TPannello; InfoPannelloInvia : TPannelloInvia; const INI_TAG = 'URLS_ITASA'; CRLF = #$0D + #$0A; implementation uses Forms, Dialogs, main; function LeggiOpzioni : Boolean; var Count,i:integer; begin Result:=True; try iniFile:=TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')); with iniFile do begin ItasaUrls.URL_ITASA :=ReadString(INI_TAG,'URL_ITASA', 'http://www.italiansubs.net/'); ItasaUrls.URL_LOGIN :=ReadString(INI_TAG,'URL_LOGIN', 'index.php'); ItasaUrls.URL_TOPIC :=ReadString(INI_TAG,'URL_TOPIC', 'forum/index.php?topic=57033'); ItasaUrls.URL_POST :=ReadString(INI_TAG,'URL_POST', 'forum/index.php?action=post2'); ItasaUrls.URL_PANNELLO:=ReadString(INI_TAG,'URL_PANNELLO','forum/index.php?action=traduzioni'); UserInfo.Username :=ReadString(INI_TAG,'username', 'inserire username'); UserInfo.Passwd :=ReadString(INI_TAG,'passwd', 'inserire password'); UserInfo.Log :=ReadBool(INI_TAG,'LOG',False); UserInfo.Message:=TStringList.Create; Count := ReadInteger(INI_TAG,'Linee_messaggio', 1); for i := 0 to Count-1 do UserInfo.Message.Add(ReadString(INI_TAG,'Linea_messaggio_'+IntToStr(i), '#file# :ciao:')); Free; end; Temp.EXE_PATH := ExtractFilePath(Application.ExeName); Temp.TEMP_PATH := Temp.EXE_PATH + '_temp\'; Temp.TEMP_FILE := Temp.TEMP_PATH + 'itasa-temp'; Temp.COOKIE_FILE:= Temp.TEMP_PATH + 'itasa-cookie'; Temp.OPEN_PATH:=Temp.EXE_PATH; if FileExists(Temp.EXE_PATH+'VisualSubSync.ini') then begin iniFile:=TIniFile.Create(Temp.EXE_PATH+'VisualSubSync.ini'); Temp.OPEN_PATH := ExtractFilePath( iniFile.ReadString('MRUList','Recent0',Temp.EXE_PATH) ); iniFile.Free; end; except Result:=False; end; end; function ItasaLogin : Boolean; var HTTP: THTTPSend; login:string; begin Result:= False; HTTP := THTTPSend.Create; login :='username='+UserInfo.Username +'&passwd='+UserInfo.Passwd +'&option=com_user&Submit=Login&task=login'; try HTTP.Document.Write(Pointer(login)^, Length(login)); HTTP.MimeType := 'application/x-www-form-urlencoded'; HTTP.HTTPMethod('POST', ItasaUrls.URL_ITASA+ItasaUrls.URL_LOGIN); HTTP.Cookies.SaveToFile(Temp.COOKIE_FILE); if AnsiPos('logged_in', HTTP.Cookies.Text) > 0 then begin Result:=True; Form1.UpdateStatusBar('Login ok -', True); end; finally HTTP.Free; end; end; function ItasaDownloadPagina(Url : String ) : Boolean; var HTTP: THTTPSend; begin HTTP := THTTPSend.Create; Result:=False; try DeleteFile(Temp.TEMP_FILE); HTTP.Cookies.LoadFromFile(Temp.COOKIE_FILE); //if UserInfo.Log then Log.Append('url: '+Url); HTTP.HTTPMethod('GET', Url); HTTP.Document.SaveToFile(Temp.TEMP_FILE); Result:=True; finally HTTP.Free; end; end; function ItasaDownloadInfoTopic : Boolean; begin if ItasaDownloadPagina( ItasaUrls.URL_ITASA+ItasaUrls.URL_TOPIC) then InfoTopic:=TInfoTopic.Create(Temp.TEMP_FILE); Result:=InfoTopic.Valido; //if Result then UpdateStatusBar('Info ok -', True); end; function ItasaDownloadInfoPannello : Boolean; begin if ItasaDownloadPagina( ItasaUrls.URL_ITASA + ItasaUrls.URL_PANNELLO ) then InfoPannello:=TPannello.Create(Temp.TEMP_FILE); Result:=InfoPannello.Valido; //if Result then UpdateStatusBar('Info ok -', True); end; function ItasaDownloadInfoPannelloInvio : Boolean; var i:Integer; begin Result:=False; if UserInfo.Log then Form1.Log.Append(NomeFile.NomePannello); for i:=0 to InfoPannello.Count-1 do begin if AnsiCompareText(NomeFile.NomePannello, InfoPannello.Serie(i)) = 0 then begin if UserInfo.Log then Form1.Log.Append('D: '+InfoPannello.Serie(i)); //TODO: controllo url if ItasaDownloadPagina( InfoPannello.Url(i)) then InfoPannelloInvia:=TPannelloInvia.Create(Temp.TEMP_FILE); Result:=InfoPannelloInvia.Valido; if Result then Form1.UpdateStatusBar('Pannello ok -', True); Break; end; end; end; function ItasaPostPannello : Boolean; var HTTP: THTTPSend; SendFile: TFileStream; Bound, s, Cartella: string; i : Integer; Risultato : TPannelloPost; begin Result:=False; Cartella:=''; for i:=0 to InfoPannelloInvia.CartelleCount-1 do if AnsiCompareText(NomeFile.NomeCartella, InfoPannelloInvia.CartellaVoce(i)) = 0 then begin Cartella := InfoPannelloInvia.CartellaValue(i); if UserInfo.Log then Form1.Log.Append('C: '+InfoPannelloInvia.CartellaVoce(i)); Break; end; if Cartella <> '' then begin Result:=False; try HTTP := THTTPSend.Create; SendFile := TFileStream.Create(SEND_FILE.Strings[SEND_FILE.Count-1], fmOpenRead or fmShareDenyWrite); Bound := '---------------------------' + IntToHex(Random(MaxInt), 11); HTTP.Cookies.LoadFromFile(Temp.COOKIE_FILE); s := PostBuilder(Bound,'nome_serie',InfoPannelloInvia.Serie) + PostBuilder(Bound,'id_topic',InfoPannelloInvia.Topic) + PostBuilder(Bound,'episodio',InfoPannelloInvia.Episodio) + PostBuilder(Bound,'traduttori',InfoPannelloInvia.Traduttori) + PostBuilder(Bound,'revisore',InfoPannelloInvia.Revisore) + PostBuilder(Bound,'resynch',InfoPannelloInvia.Resynch) + PostBuilder(Bound,'cartella',Cartella) + PostBuilder(Bound,'MAX_FILE_SIZE','300000') + '--' + Bound + CRLF + 'Content-Disposition: form-data; name="userfile"; ' + 'filename="' + ExtractFileName(SEND_FILE.Strings[SEND_FILE.Count-1]) +'"' + CRLF + 'Content-Type: application/zip' + CRLF + CRLF; HTTP.Document.Write(Pointer(s)^, Length(s)); HTTP.Document.CopyFrom(SendFile, 0); s := CRLF + '--' + Bound + '--' + CRLF; HTTP.Document.Write(Pointer(s)^, Length(s)); HTTP.MimeType := 'multipart/form-data, boundary=' + Bound; HTTP.HTTPMethod('POST', ItasaUrls.URL_ITASA+InfoPannelloInvia.Post); HTTP.Document.SaveToFile(Temp.TEMP_FILE+'-p'); Risultato:=TPannelloPost.Create(Temp.TEMP_FILE+'-p'); Result:=Risultato.Valido; if Result then Form1.UpdateStatusBar('Post ok ;-)', True); finally HTTP.Free; SendFile.Free; end; CleanFolder(Temp.TEMP_PATH, False); end else ShowMessage('Errore post pannello'); end; function ItasaPostTopic : Boolean; var HTTP: THTTPSend; SendFile: TFileStream; Bound, s, Messaggio, Nomefile, tmp: string; i:Integer; begin Result:=False; try HTTP := THTTPSend.Create; Nomefile := ''; Bound := '---------------------------' + IntToHex(Random(MaxInt), 11); HTTP.Cookies.LoadFromFile(Temp.COOKIE_FILE); s := PostBuilder(Bound,'topic',InfoTopic.Topic) + PostBuilder(Bound,'subject',InfoTopic.Subject) + PostBuilder(Bound,'num_replies',InfoTopic.NumReplies) + PostBuilder(Bound,'sc',InfoTopic.SC); HTTP.Document.Write(Pointer(s)^, Length(s)); for i:=0 to SEND_FILE.Count-1 do begin //creazione nome del file da mettere nel messaggio if i > 0 then Nomefile := Nomefile + ', '; tmp:=StringReplace(ExtractFileName(SEND_FILE.Strings[i]),'.sub.itasa','',[rfReplaceAll]); tmp:=StringReplace(tmp,ExtractFileExt(SEND_FILE.Strings[i]),'',[rfReplaceAll]); Nomefile := Nomefile + tmp; SendFile := TFileStream.Create(SEND_FILE.Strings[i], fmOpenRead or fmShareDenyWrite); s := '--' + Bound + CRLF + 'Content-Disposition: form-data; name="attachment[]"; ' + 'filename="' + ExtractFileName(SEND_FILE.Strings[i]) +'"' + CRLF + 'Content-Type: application/zip' + CRLF + CRLF; HTTP.Document.Write(Pointer(s)^, Length(s)); HTTP.Document.CopyFrom(SendFile, 0); HTTP.Document.Write(CRLF, Length(CRLF)); SendFile.Free; end; Messaggio:=StringReplace(UserInfo.Message.Text, '#file#', NomeFile, [rfReplaceAll]); s := PostBuilder(Bound,'message', Messaggio) // + PostBuilder(Bound,'additional_options', '1') + '--' + Bound + '--' + CRLF; HTTP.Document.Write(Pointer(s)^, Length(s)); HTTP.Document.SaveToFile(Temp.EXE_PATH+'str.txt'); HTTP.MimeType := 'multipart/form-data, boundary=' + Bound; HTTP.HTTPMethod('POST', ItasaUrls.URL_ITASA+ItasaUrls.URL_POST); //#################### //fare controllo invio //#################### Result:=True; if Result then Form1.UpdateStatusBar('Post ok ;-)', True); finally HTTP.Free; SEND_FILE.Clear; end; CleanFolder(Temp.TEMP_PATH, False); end; end.
unit uBranchEditFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uTreeBaseEditFrm, Menus, cxLookAndFeelPainters, cxGraphics, cxCustomData, cxStyles, cxTL, cxMaskEdit, cxTLdxBarBuiltInMenu, DB, DBClient, StdCtrls, dximctrl, cxCheckBox, cxDBEdit, cxSpinEdit, cxContainer, cxEdit, cxTextEdit, cxInplaceContainer, cxDBTL, cxControls, cxTLData, cxButtons, ExtCtrls, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxLabel; type TBranchEditFrm = class(TTreeBaseEditFrm) cdsMenuFISCU: TIntegerField; Bevel1: TBevel; cdsMenuFISSALEORGUNIT: TIntegerField; cdsMenufisadminorgunit: TIntegerField; cxDBCheckBox5: TcxDBCheckBox; btn_Bear: TcxButton; btn_uBear: TcxButton; cdsMenufisfreeze: TIntegerField; Label5: TLabel; cdsMenuCFBRanchFlag: TWideStringField; txt_CFBRanchFlag: TcxDBTextEdit; Label4: TLabel; cdsMenuFOrgType: TIntegerField; Label6: TLabel; txt_orgtype: TcxDBLookupComboBox; cdsOrgType: TClientDataSet; dsOrgType: TDataSource; cdsOrgTypeFID: TIntegerField; cdsOrgTypeFName: TStringField; cdsTest: TClientDataSet; cdsMenuFdisplayname_L2: TWideStringField; cb_OrgType: TcxComboBox; cxLabel1: TcxLabel; cxLabel2: TcxLabel; procedure FormCreate(Sender: TObject); procedure cdsMenuBeforePost(DataSet: TDataSet); procedure btn_uBearClick(Sender: TObject); procedure btn_BearClick(Sender: TObject); procedure cdsMenuAfterInsert(DataSet: TDataSet); procedure btn_NewClick(Sender: TObject); procedure btn_newSubItemClick(Sender: TObject); procedure btn_delClick(Sender: TObject); procedure cb_OrgTypePropertiesCloseUp(Sender: TObject); private { Private declarations } public { Public declarations } Procedure I3UserMessageResult(var msg:TMessage);override; end; var BranchEditFrm: TBranchEditFrm; implementation uses FrmCliDM,Pub_Fun,StringUtilClass,uDrpHelperClase ; {$R *.dfm} function GetOrgTypeWhereStr(OrgType:Integer):string; begin Result := ''; case OrgType of 0:Result := ' and FIsAdminOrgUnit=1'; 1:Result := ' and FIsCompanyOrgUnit=1'; 2:Result := ' and FIsSaleOrgUnit=1'; 3:Result := ' and FIsStorageOrgUnit=1'; 4:Result := ' and FIsPurchaseOrgUnit=1'; 5:Result := ' and FIsCostOrgUnit=1'; 6:Result := ' and FIsHROrgUnit=1'; 7:Result := ' and FIsProfitOrgUnit=1'; end end; procedure TBranchEditFrm.FormCreate(Sender: TObject); begin inherited; FbosType :='CCE7AED4'; TableName := 't_org_baseunit'; QuerySQL := 'select * from t_org_baseunit where FControlUnitID='+Quotedstr(UserInfo.Controlunitid)+' and isnull(Forgtype,0)<>4 ' + GetOrgTypeWhereStr(cb_OrgType.ItemIndex) + ' order by FLevel,fnumber'; cdsOrgType.CreateDataSet; cdsOrgType.Append; cdsOrgType.FieldByName('FID').AsInteger := 1; cdsOrgType.FieldByName('FName').AsString := '总部'; cdsOrgType.Post; cdsOrgType.Append; cdsOrgType.FieldByName('FID').AsInteger := 2; cdsOrgType.FieldByName('FName').AsString := '分公司'; cdsOrgType.Post; cdsOrgType.Append; cdsOrgType.FieldByName('FID').AsInteger := 3; cdsOrgType.FieldByName('FName').AsString := '经销商'; cdsOrgType.Post; cdsOrgType.Append; cdsOrgType.FieldByName('FID').AsInteger := 4; cdsOrgType.FieldByName('FName').AsString := '虚体机构'; cdsOrgType.Post; end; procedure TBranchEditFrm.cdsMenuBeforePost(DataSet: TDataSet); var tag:string; begin inherited; if txt_orgtype.Text = '' then begin ShowMsg(Handle, '机构标类型不能为空! ',[]); txt_orgtype.SetFocus; Abort; end; if Trim(DataSet.fieldbyname('CFBRanchFlag').AsString)='' then begin tag := ChnToPY(Trim(DataSet.fieldbyname('FNAME_L2').AsString)); if Length(tag)>4 then begin tag := Copy(tag,1,4); end; DataSet.fieldbyname('CFBRanchFlag').AsString := tag; end; if (Length(Trim(DataSet.fieldbyname('CFBRanchFlag').AsString))>4 ) then begin ShowMsg(Handle, '机构标识不能长度不能超过4位! ',[]); txt_CFBRanchFlag.SetFocus; Abort; end; end; procedure TBranchEditFrm.btn_uBearClick(Sender: TObject); begin inherited; if cdsMenu.IsEmpty then Exit; cdsMenu.Edit; cdsMenu.FieldByName('fisfreeze').AsInteger := 1; cdsMenu.Post; end; procedure TBranchEditFrm.btn_BearClick(Sender: TObject); begin inherited; if cdsMenu.IsEmpty then Exit; cdsMenu.Edit; cdsMenu.FieldByName('fisfreeze').AsInteger := 0; cdsMenu.Post; end; procedure TBranchEditFrm.cdsMenuAfterInsert(DataSet: TDataSet); begin inherited; DataSet.FieldByName('FOrgType').AsInteger := 3; DataSet.FieldByName('fisfreeze').AsInteger := 1; end; procedure TBranchEditFrm.I3UserMessageResult(var msg: TMessage); begin inherited; // end; procedure TBranchEditFrm.btn_NewClick(Sender: TObject); begin if ParamInfo.DRP001='T' then ///启用EAS财务 begin ShowMsg(Handle, '已经启用EAS财务不允许新增节点! ',[]); Abort; end; inherited; end; procedure TBranchEditFrm.btn_newSubItemClick(Sender: TObject); begin inherited; if ParamInfo.DRP001='T' then ///启用EAS财务 begin ShowMsg(Handle, '已经启用EAS财务不允许新增子节点! ',[]); Abort; end; end; procedure TBranchEditFrm.btn_delClick(Sender: TObject); begin if ParamInfo.DRP001='T' then ///启用EAS财务 begin ShowMsg(Handle, '已经启用EAS财务不允许删除节点! ',[]); Abort; end; inherited; end; procedure TBranchEditFrm.cb_OrgTypePropertiesCloseUp(Sender: TObject); begin inherited; self.Caption := '组织单元-'+cb_OrgType.Text; QuerySQL := 'select * from t_org_baseunit where FID<>''11111111-1111-1111-1111-111111111111CCE7AED4'' and isnull(Forgtype,0)<>4 ' + GetOrgTypeWhereStr(cb_OrgType.ItemIndex) + ' order by FLevel,fnumber'; GetData; end; end.
// RemObjects CS to Pascal 0.1 namespace UT3Bots.UTItems; interface uses System, System.Collections.Generic, System.Linq, System.Text, System.ComponentModel, UT3Bots.Communications; type UTItemPoint = public class(UTPoint, INotifyPropertyChanged) private var _item: UTItem; var _isReadyToPickup: Boolean; public //Constructor constructor(Id: UTIdentifier; Location: UTVector; &Type: String; isReachable: Boolean; isReadyToPickup: Boolean); property Item: UTItem read get_Item; method get_Item: UTItem; property IsReadyToPickup: Boolean read get_IsReadyToPickup write set_IsReadyToPickup; method get_IsReadyToPickup: Boolean; method set_IsReadyToPickup(value: Boolean); end; implementation constructor UTItemPoint(Id: UTIdentifier; Location: UTVector; &Type: String; isReachable: Boolean; isReadyToPickup: Boolean); begin inherited constructor(Id, Location, isReachable); Self._isReadyToPickup := isReadyToPickup; Self._item := new UTItem(Id.ToString(), &Type) end; method UTItemPoint.get_Item: UTItem; begin Result := Self._item; end; method UTItemPoint.get_IsReadyToPickup: Boolean; begin Result := Self._isReadyToPickup; end; method UTItemPoint.set_IsReadyToPickup(value: Boolean); begin Self._isReadyToPickup := value; OnPropertyChanged('IsReadyToPickup') end; end.
{$MODE TP} { FreePascal will compile this as a Turbo Pascal program. } program logic; function compile(expression : string) : string; { Compiles a predicate (a boolean expression) into 'reverse Polish notation'. The RPN uses the one-character variants of the symbols } var cursor : integer; position : integer; next : char; rpn : string; procedure error(message : string); var i : integer; begin writeln(expression); for i := 1 to position - 1 do write(' '); writeln('^ ', message); halt(1) end; procedure getnext; { the lexer. } procedure expect (c : char); begin cursor := cursor + 1; if (cursor > Length(expression)) or not (expression[cursor] = c) then begin position := cursor; error('expected a ' + c) end end; begin while (cursor <= Length(expression)) and (expression[cursor] in [' ', #8, #13]) do cursor := cursor + 1; position := cursor; if cursor > Length(expression) then next := chr(0) else begin case expression[cursor] of '-' : begin expect('>'); next := '>' end; '<' : begin expect('-'); expect('>'); next := '=' end; '\' : begin expect('/'); next := '+' end; '/' : begin expect('\'); next := '.' end; 'F' : next := '0'; 'T' : next := '1' else next := expression[cursor] end; cursor := cursor + 1 end end; {getnext} function match(c : char) : boolean; begin match := (next = c); if next = c then getnext end; procedure add(c : char); begin rpn := rpn + c end; { The parser: } procedure l1; forward; procedure l6; begin case next of '~': begin getnext; l6; add('~') end; '(': begin getnext; l1; if not match(')') then error('expected a )') end; '0', '1', 'A'..'Z', 'a'..'z': begin add(next); getnext end else error('syntax error') end end; procedure l5; begin l6; while match('.') do begin l6; add('.') end end; procedure l4; begin l5; while match('+') do begin l5; add('+') end end; procedure l3; begin l4; while match('@') do begin l4; add('@') end end; procedure l2; begin l3; while match('>') do begin l3; add('>') end end; procedure l1; begin l2; while match('=') do begin l2; add('=') end end; procedure l0; begin l1; add(','); while match(',') do begin l1; add(',') end end; {note ',' means 'print'} begin rpn := ''; cursor := 1; getnext; l0; if next <> chr(0) then error('syntax error'); compile := rpn end; {compile} procedure run(rpn : string; expression : string; test : boolean); var truthvalues : array ['A'..'z'] of boolean; variables : string; procedure setvariables(minterm : integer); { Set the variables' values to the bits of the binary number 'minterm' } var i : integer; begin for i := Length(variables) downto 1 do begin truthvalues[variables[i]] := odd(minterm); minterm := minterm div 2 end end; procedure interpret; { Print the right hand side of a row of the table by interpreting the RPN expression on a stack machine } var stack : array [1..100] of boolean; top, i : integer; begin for i := 1 to 100 do stack[i] := false; top := 0; for i := 1 to Length(rpn) do case rpn[i] of '.': begin stack[top-1] := stack[top-1] and stack[top]; top := top - 1 end; '+': begin stack[top-1] := stack[top-1] or stack[top]; top := top - 1 end; '@': begin stack[top-1] := stack[top-1] <> stack[top]; top := top - 1 end; '=': begin stack[top-1] := stack[top-1] = stack[top]; top := top - 1 end; '>': begin stack[top-1] := not stack[top-1] or stack[top]; top := top - 1 end; '~': begin stack[top] := not stack[top] end; '0': begin top := top + 1; stack[top] := false end; '1': begin top := top + 1; stack[top] := true end; 'A'..'Z', 'a'..'z': begin top := top + 1; stack[top] := truthvalues[rpn[i]] end; ',': if test then begin if not stack[top] then begin writeln('failed: ', expression); halt(1) end; top := top - 1 end else begin if stack[top] then write(' 1') else write(' 0'); top := top - 1 end end end; var minterm, i : integer; begin variables := ''; for i := 1 to Length(rpn) do begin if (rpn[i] in ['A'..'Z', 'a'..'z']) and (Pos(rpn[i], variables) = 0) then variables := variables + rpn[i]; end; if test then begin for minterm := 0 to (1 shl Length(variables)) - 1 do begin setvariables(minterm); interpret end end else begin writeln; write(' '); for i := 1 to Length(variables) do write(' ', variables[i]); writeln(' | ', expression); for minterm := 0 to (1 shl Length(variables)) - 1 do begin setvariables(minterm); write(' '); for i := 1 to Length(variables) do if truthvalues[variables[i]] then write(' 1') else write(' 0'); write(' |'); interpret; writeln end; writeln end end; {run} var expression : string; begin if ParamCount = 1 then begin expression := ParamStr(1); run(compile(expression), expression, false) end else if (ParamCount = 2) and (ParamStr(1) = '-t') then begin expression := ParamStr(2); run(compile(expression), expression, true) end else writeln('usage: logic [-t] ''expression''') end.
unit InsertImageToolUnit; interface uses System.Math, System.Classes, System.SysUtils, Winapi.Windows, Vcl.Controls, Vcl.Graphics, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Dialogs, Vcl.Clipbrd, Dmitry.Graphics.Types, Dmitry.Controls.WebLink, ToolsUnit, Effects, CustomSelectTool, UnitDBFileDialogs, uBitmapUtils, uDBGraphicTypes, uAssociations, uMemory, uSettings; type InsertImageToolPanelClass = class(TCustomSelectToolClass) private { Private declarations } Image: TBitmap; LoadImageButton: TButton; OpenFileDialog: DBOpenPictureDialog; MethodDrawChooser: TComboBox; LabelMethod: TLabel; TransparentEdit: TTrackBar; FLoading: Boolean; protected function LangID: string; override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoEffect(Bitmap: TBitmap; ARect: TRect; FullImage: Boolean); override; procedure DoBorder(Bitmap: TBitmap; ARect: TRect); override; procedure DoSaveSettings(Sender: TObject); override; procedure DoLoadFileFromFile(Sender: TObject); procedure RecreateImage(Sender: TObject); class function ID: string; override; procedure SetProperties(Properties: string); override; procedure ExecuteProperties(Properties: string; OnDone: TNotifyEvent); override; end; implementation { TRedEyeToolPanelClass } constructor InsertImageToolPanelClass.Create(AOwner: TComponent); begin inherited; AnyRect := True; FLoading := True; Image := TBitmap.Create; Image.PixelFormat := pf32bit; if ClipBoard.HasFormat(CF_BITMAP) then Image.Assign(ClipBoard); OpenFileDialog := DBOpenPictureDialog.Create; OpenFileDialog.Filter := TFileAssociations.Instance.FullFilter; LoadImageButton := TButton.Create(AOwner); LoadImageButton.Parent := Self; LoadImageButton.Top := EditWidth.Top + EditWidth.Height + 5; LoadImageButton.Left := 8; LoadImageButton.Width := 150; LoadImageButton.Height := 21; LoadImageButton.Caption := L('Load image'); LoadImageButton.OnClick := DoLoadFileFromFile; LoadImageButton.Show; LabelMethod := TLabel.Create(AOwner); LabelMethod.Left := 8; LabelMethod.Top := LoadImageButton.Top + LoadImageButton.Height + 5; LabelMethod.Parent := Self; LabelMethod.Caption := L('Method') + ':'; MethodDrawChooser := TComboBox.Create(AOwner); MethodDrawChooser.Top := LabelMethod.Top + LabelMethod.Height + 5; MethodDrawChooser.Left := 8; MethodDrawChooser.Width := 150; MethodDrawChooser.Height := 20; MethodDrawChooser.Parent := Self; MethodDrawChooser.Style := CsDropDownList; MethodDrawChooser.Items.Add(L('Overlay')); MethodDrawChooser.Items.Add(L('Sum')); MethodDrawChooser.Items.Add(L('Dark')); MethodDrawChooser.Items.Add(L('Light')); MethodDrawChooser.Items.Add(L('Luminosity')); MethodDrawChooser.Items.Add(L('Inverse Luminosity')); MethodDrawChooser.Items.Add(L('Change color')); MethodDrawChooser.Items.Add(L('Difference')); MethodDrawChooser.ItemIndex := 0; MethodDrawChooser.OnChange := RecreateImage; LabelMethod := TLabel.Create(AOwner); LabelMethod.Left := 8; LabelMethod.Top := MethodDrawChooser.Top + MethodDrawChooser.Height + 5; LabelMethod.Parent := Self; LabelMethod.Caption := L('Transparency') + ':'; TransparentEdit := TTrackBar.Create(AOwner); TransparentEdit.Top := LabelMethod.Top + LabelMethod.Height + 5; TransparentEdit.Left := 8; TransparentEdit.Width := 160; TransparentEdit.OnChange := RecreateImage; TransparentEdit.Min := 1; TransparentEdit.Max := 100; TransparentEdit.Position := AppSettings.ReadInteger('Editor', 'InsertImageTransparency', 100); TransparentEdit.Parent := Self; LabelMethod.Caption := Format(L('Transparency [%d]'), [TransparentEdit.Position]); SaveSettingsLink.Top := TransparentEdit.Top + TransparentEdit.Height + 5; MakeItLink.Top := SaveSettingsLink.Top + SaveSettingsLink.Height + 5; CloseLink.Top := MakeItLink.Top + MakeItLink.Height + 5; FLoading := False; end; destructor InsertImageToolPanelClass.Destroy; begin F(Image); F(OpenFileDialog); inherited; end; procedure InsertImageToolPanelClass.DoBorder(Bitmap: TBitmap; ARect: TRect); var I, J: Integer; Rct: TRect; Xdp: TArPARGB; procedure Border(I, J: Integer; var RGB: TRGB); inline; begin if Odd((I + J) div 3) then begin RGB.R := RGB.R div 5; RGB.G := RGB.G div 5; RGB.B := RGB.B div 5; end else begin RGB.R := RGB.R xor $FF; RGB.G := RGB.G xor $FF; RGB.B := RGB.B xor $FF; end; end; begin Rct.Top := Min(ARect.Top, ARect.Bottom); Rct.Bottom := Max(ARect.Top, ARect.Bottom); Rct.Left := Min(ARect.Left, ARect.Right); Rct.Right := Max(ARect.Left, ARect.Right); ARect := Rct; SetLength(Xdp, Bitmap.Height); for I := 0 to Bitmap.Height - 1 do Xdp[I] := Bitmap.ScanLine[I]; I := Min(Bitmap.Height - 1, Max(0, ARect.Top)); if I = ARect.Top then for J := 0 to Bitmap.Width - 1 do begin if (J > ARect.Left) and (J < ARect.Right) then Border(I, J, Xdp[I, J]); end; I := Min(Bitmap.Height - 1, Max(0, ARect.Bottom)); if I = ARect.Bottom then for J := 0 to Bitmap.Width - 1 do begin if (J > ARect.Left) and (J < ARect.Right) then Border(I, J, Xdp[I, J]); end; for I := Max(0, ARect.Top) to Min(ARect.Bottom - 1, Bitmap.Height - 1) do begin J := Max(0, Min(Bitmap.Width - 1, ARect.Left)); if J = ARect.Left then Border(I, J, Xdp[I, J]); end; for I := Max(0, ARect.Top) to Min(ARect.Bottom - 1, Bitmap.Height - 1) do begin J := Min(Bitmap.Width - 1, Max(0, ARect.Right)); if J = ARect.Right then Border(I, J, Xdp[I, J]); end; end; procedure DrawImageWithEffect(S, D: TBitmap; CodeEffect: Integer; Transparency: Extended); var I, J: Integer; P1, P2: PARGB; IW, IH: Integer; L, Ld, W, W1: Byte; SQ : array[0..255, 0..255] of Byte; begin W := Round(255 * Transparency / 100); W1 := 255 - W; IH := Min(S.Height, D.Height); IW := Min(S.Width, D.Width); if CodeEffect = 1 then for I := 0 to 255 do for J := 0 to 255 do SQ[I, J] := Round(Sqrt(I * J)); for I := 0 to IH - 1 do begin P1 := S.ScanLine[I]; P2 := D.ScanLine[I]; for J := 0 to IW - 1 do begin case CodeEffect of 0: begin P2[J].R := (P1[J].R * W + P2[J].R * W1) shr 8; P2[J].G := (P1[J].G * W + P2[J].G * W1) shr 8; P2[J].B := (P1[J].B * W + P2[J].B * W1) shr 8; end; 1: begin P2[J].R := (SQ[P2[J].R, P1[J].R] * W + P2[J].R * W1) shr 8; P2[J].G := (SQ[P2[J].G, P1[J].G] * W + P2[J].G * W1) shr 8; P2[J].B := (SQ[P2[J].B, P1[J].B] * W + P2[J].B * W1) shr 8; end; 2: begin P2[J].R := (((P2[J].R * P1[J].R) shr 8) * W + P2[J].R * W1) shr 8; P2[J].G := (((P2[J].G * P1[J].G) shr 8) * W + P2[J].G * W1) shr 8; P2[J].B := (((P2[J].B * P1[J].B) shr 8) * W + P2[J].B * W1) shr 8; end; 3: begin L := (P1[J].R * 77 + P1[J].G * 151 + P1[J].B * 28) shr 8; P2[J].R := (((P2[J].R * (255 - L) + P1[J].R * (L)) shr 8) * W + P2[J].R * W1) shr 8; P2[J].G := (((P2[J].G * (255 - L) + P1[J].G * (L)) shr 8) * W + P2[J].G * W1) shr 8; P2[J].B := (((P2[J].B * (255 - L) + P1[J].B * (L)) shr 8) * W + P2[J].B * W1) shr 8; end; 4: begin L := (P1[J].R * 77 + P1[J].G * 151 + P1[J].B * 28) shr 8; LD := (P2[J].R * 77 + P2[J].G * 151 + P2[J].B * 28) shr 8; P2[J].R := (((P2[J].R * (255 - L) + (Ld * L) ) shr 8) * W + P2[J].R * W1) shr 8; P2[J].G := (((P2[J].G * (255 - L) + (Ld * L) ) shr 8) * W + P2[J].G * W1) shr 8; P2[J].B := (((P2[J].B * (255 - L) + (Ld * L) ) shr 8) * W + P2[J].B * W1) shr 8; end; 5: begin L := 255 - (P1[J].R * 77 + P1[J].G * 151 + P1[J].B * 28) shr 8; LD := (P2[J].R * 77 + P2[J].G * 151 + P2[J].B * 28) shr 8; P2[J].R := (((P2[J].R * (255 - L) + (LD * L) ) shr 8) * W + P2[J].R * W1) shr 8; P2[J].G := (((P2[J].G * (255 - L) + (LD * L) ) shr 8) * W + P2[J].G * W1) shr 8; P2[J].B := (((P2[J].B * (255 - L) + (LD * L) ) shr 8) * W + P2[J].B * W1) shr 8; end; 6: begin L := 255 - (P1[J].R * 77 + P1[J].G * 151 + P1[J].B * 28) shr 8; LD := (P2[J].R * 77 + P2[J].G * 151 + P2[J].B * 28) shr 8; if L < 5 then begin P2[J] := P2[J]; end else begin P2[J].R := Min(255, (((P1[J].R * LD) div L) * W + P2[J].R * W1) shr 8); P2[J].G := Min(255, (((P1[J].G * LD) div L) * W + P2[J].G * W1) shr 8); P2[J].B := Min(255, (((P1[J].B * LD) div L) * W + P2[J].B * W1) shr 8); end; end; 7: begin P2[J].R := (Abs((P2[J].R - P1[J].R) * W + P2[J].R * W1)) shr 8; P2[J].G := (Abs((P2[J].G - P1[J].G) * W + P2[J].G * W1)) shr 8; P2[J].B := (Abs((P2[J].B - P1[J].B) * W + P2[J].B * W1)) shr 8; end; end; end; end; end; procedure InsertImageToolPanelClass.DoEffect(Bitmap: TBitmap; ARect: TRect; FullImage: Boolean); var W, H, AWidth, AHeight: Integer; Rct, DrawRect: TRect; TempBitmap, RectBitmap: TBitmap; begin Rct.Top := Min(ARect.Top, ARect.Bottom); Rct.Bottom := Max(ARect.Top, ARect.Bottom); Rct.Left := Min(ARect.Left, ARect.Right); Rct.Right := Max(ARect.Left, ARect.Right); ARect := Rct; W := Abs(ARect.Right - ARect.Left); H := Abs(ARect.Bottom - ARect.Top); if W * H = 0 then Exit; AWidth := Image.Width; AHeight := Image.Height; if AWidth * AHeight = 0 then Exit; ProportionalSizeX(W, H, AWidth, AHeight); DrawRect := Rect(ARect.Left + W div 2 - AWidth div 2, ARect.Top + H div 2 - AHeight div 2, ARect.Left + W div 2 + AWidth div 2, ARect.Top + H div 2 + AHeight div 2); if not FullImage then begin RectBitmap := TBitmap.Create; try RectBitmap.PixelFormat := pf24bit; RectBitmap.SetSize(AWidth, AHeight); RectBitmap.Canvas.CopyRect(Rect(0, 0, AWidth, AHeight), Bitmap.Canvas, DrawRect); TempBitmap := TBitmap.Create; try TempBitmap.PixelFormat := pf24bit; TempBitmap.SetSize(AWidth, AHeight); TempBitmap.Canvas.StretchDraw(Rect(0, 0, AWidth, AHeight), Image); if RectBitmap.Width * RectBitmap.Height = 0 then Exit; DrawImageWithEffect(TempBitmap, RectBitmap, MethodDrawChooser.ItemIndex, TransparentEdit.Position); finally F(TempBitmap); end; Bitmap.Canvas.StretchDraw(DrawRect, RectBitmap); finally F(RectBitmap); end; end else begin RectBitmap := TBitmap.Create; try RectBitmap.PixelFormat := pf24bit; RectBitmap.Width := AWidth; RectBitmap.Height := AHeight; RectBitmap.Canvas.CopyRect(Rect(0, 0, AWidth, AHeight), Bitmap.Canvas, DrawRect); TempBitmap := TBitmap.Create; try TempBitmap.PixelFormat := pf24bit; if (Image.Width / AWidth) > 1 then DoResize(AWidth, AHeight, Image, TempBitmap) else Interpolate(0, 0, AWidth, AHeight, Rect(0, 0, Image.Width, Image.Height), Image, TempBitmap); if RectBitmap.Width * RectBitmap.Height = 0 then Exit; DrawImageWithEffect(TempBitmap, RectBitmap, MethodDrawChooser.ItemIndex, TransparentEdit.Position); finally F(TempBitmap); end; Bitmap.Canvas.StretchDraw(DrawRect, RectBitmap); finally F(RectBitmap); end; end; end; procedure InsertImageToolPanelClass.DoLoadFileFromFile(Sender: TObject); var Pic: TPicture; begin if OpenFileDialog.Execute then begin Pic := TPicture.Create; try Pic.LoadFromFile(OpenFileDialog.FileName); Image.Assign(Pic.Graphic); finally F(Pic); end; ProcRecteateImage(Sender); end; end; procedure InsertImageToolPanelClass.DoSaveSettings(Sender: TObject); begin AppSettings.WriteInteger('Editor', 'InsertImageTransparency', TransparentEdit.Position); end; procedure InsertImageToolPanelClass.ExecuteProperties(Properties: String; OnDone: TNotifyEvent); begin end; class function InsertImageToolPanelClass.ID: string; begin Result := '{CA9E5AFD-E92D-4105-8F7B-978A6EBA9D74}'; end; function InsertImageToolPanelClass.LangID: string; begin Result := 'InsertImageTool'; end; procedure InsertImageToolPanelClass.RecreateImage(Sender: TObject); begin if FLoading then Exit; LabelMethod.Caption := Format(L('Transparency [%d]'), [TransparentEdit.Position]); ProcRecteateImage(Sender); end; procedure InsertImageToolPanelClass.SetProperties(Properties: String); begin end; end.
unit TextureAtlasExtractorOrigamiGA; interface uses BasicMathsTypes, BasicDataTypes, TextureAtlasExtractorBase, TextureAtlasExtractorOrigami, NeighborDetector, MeshPluginBase, Math, SysUtils, GeometricAlgebra, Multivector, IntegerList, math3d, NeighborhoodDataPlugin, ColisionCheckGA; {$INCLUDE source/Global_Conditionals.inc} type CTextureAtlasExtractorOrigamiGA = class (CTextureAtlasExtractorOrigami) private // Main functions function MakeNewSeed(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; const _FaceNeighbors: TNeighborDetector; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace,_MaxVerts: integer; var _CheckFace: abool): TTextureSeed; protected function GetVersorForTriangleProjectionGA(var _GA: TGeometricAlgebra; const _Normal: TVector3f): TMultiVector; function GetVertexPositionOnTriangleProjectionGA(var _GA: TGeometricAlgebra; const _V1: TVector3f; const _Versor,_Inverse: TMultiVector): TVector2f; function IsValidUVPointGA(var _PGA,_EGA: TGeometricAlgebra; const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _FaceNormal: TVector3f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; public function GetMeshSeeds(_MeshID: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; _VerticesPerFace: integer; var _Seeds: TSeedSet; var _VertsSeed : aint32; var _NeighborhoodPlugin: PMeshPluginBase): TAVector2f; override; end; implementation uses GlobalVars; // Geometric Algebra edition. function CTextureAtlasExtractorOrigamiGA.GetMeshSeeds(_MeshID: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; _VerticesPerFace: integer; var _Seeds: TSeedSet; var _VertsSeed : aint32; var _NeighborhoodPlugin: PMeshPluginBase): TAVector2f; var i, MaxVerts, NumSeeds: integer; FaceSeed : aint32; FacePriority: AFloat; FaceOrder : auint32; CheckFace: abool; FaceNeighbors: TNeighborDetector; {$ifdef ORIGAMI_TEST} Temp: string; {$endif} begin SetupMeshSeeds(_Vertices,_FaceNormals,_Faces,_VerticesPerFace,_Seeds,_VertsSeed,FaceNeighbors,Result,MaxVerts,FaceSeed,FacePriority,FaceOrder,CheckFace); // Let's build the seeds. NumSeeds := High(_Seeds) + 1; SetLength(_Seeds,NumSeeds + High(FaceSeed)+1); for i := Low(FaceSeed) to High(FaceSeed) do begin if FaceSeed[FaceOrder[i]] = -1 then begin // Make new seed. {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Seed = ' + IntToStr(NumSeeds) + ' and i = ' + IntToStr(i)); {$endif} _Seeds[NumSeeds] := MakeNewSeed(NumSeeds,_MeshID,FaceOrder[i],_Vertices,_FaceNormals,_VertsNormals,_VertsColours,_Faces,Result,FaceSeed,_VertsSeed,FaceNeighbors,_NeighborhoodPlugin,_VerticesPerFace,MaxVerts,CheckFace); inc(NumSeeds); end; end; SetLength(_Seeds,NumSeeds); // Re-align vertexes and seed bounds to start at (0,0) ReAlignSeedsToCenter(_Seeds,_VertsSeed,FaceNeighbors,Result,FacePriority,FaceOrder,CheckFace,_NeighborhoodPlugin); end; function CTextureAtlasExtractorOrigamiGA.GetVersorForTriangleProjectionGA(var _GA: TGeometricAlgebra; const _Normal: TVector3f): TMultiVector; var Triangle,Screen,FullRotation: TMultiVector; begin // Get rotation from _Normal to (0,0,1). Triangle := _GA.NewEuclideanBiVector(_Normal); Screen := _GA.NewEuclideanBiVector(SetVector(0,0,1)); FullRotation := _GA.GetGeometricProduct(Triangle,Screen); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_ROTATION_TEST} GlobalVars.OrigamiFile.Add('Normal: (' + FloatToStr(_Normal.X) + ', ' + FloatToStr(_Normal.Y) + ', ' + FloatToStr(_Normal.Z) + ').'); Triangle.Debug(GlobalVars.OrigamiFile,'Triangle (Normal)'); Screen.Debug(GlobalVars.OrigamiFile,'Screen (0,0,1)'); FullRotation.Debug(GlobalVars.OrigamiFile,'Full Rotation'); {$endif} {$endif} // Obtain the versor that will be used to do this projection. Result := _GA.Euclidean3DLogarithm(FullRotation); // Free Memory FullRotation.Free; Triangle.Free; Screen.Free; end; function CTextureAtlasExtractorOrigamiGA.GetVertexPositionOnTriangleProjectionGA(var _GA: TGeometricAlgebra; const _V1: TVector3f; const _Versor,_Inverse: TMultiVector): TVector2f; var Vector,Position: TMultiVector; begin Vector := _GA.NewEuclideanVector(_V1); Position := _GA.GetAppliedRotor(Vector,_Versor,_Inverse); Result.U := Position.UnsafeData[1]; Result.V := Position.UnsafeData[2]; {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_ROTATION_TEST} Position.Debug(GlobalVars.OrigamiFile,'Triangle Positions'); {$endif} {$endif} Position.Free; Vector.Free; end; function CTextureAtlasExtractorOrigamiGA.IsValidUVPointGA(var _PGA,_EGA: TGeometricAlgebra; const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _FaceNormal: TVector3f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; var EdgeSizeInMesh,EdgeSizeInUV,Scale: single; i,v: integer; PEdge0,PEdge1,PTarget,PEdge0UV,PEdge1UV,PCenterTriangle,PCenterSegment,PCenterSegmentUV,PTemp,V0,V1,V2: TMultiVector; // Points LSEdge,LSEdgeUV,LSEdge0,LSEdge1,LSEdge2: TMultiVector; // Line segments. DirEdge,DirEdgeUV: TMultiVector; // Directions. PlaneRotation,SegmentRotation: TMultiVector; // Versors ColisionCheck : CColisionCheckGA; begin Result := false; ColisionCheck := CColisionCheckGA.Create(_PGA); // Get constants that will be required in our computation. // Bring our points to Geometric Algebra. PEdge0 := _PGA.NewHomogeneousFlat(_Vertices[_Edge0]); PEdge1 := _PGA.NewHomogeneousFlat(_Vertices[_Edge1]); PTarget := _PGA.NewHomogeneousFlat(_Vertices[_Target]); PCenterTriangle := _PGA.NewHomogeneousFlat(GetTriangleCenterPosition(_Vertices[_Edge0],_Vertices[_Edge1],_Vertices[_Target])); PEdge0UV := _PGA.NewHomogeneousFlat(_TexCoords[_Edge0]); PEdge1UV := _PGA.NewHomogeneousFlat(_TexCoords[_Edge1]); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget'); PCenterTriangle.Debug(GlobalVars.OrigamiFile,'PCenterTriangle'); PEdge0UV.Debug(GlobalVars.OrigamiFile,'PEdge0UV'); PEdge1UV.Debug(GlobalVars.OrigamiFile,'PEdge1UV'); {$endif} {$endif} // Do translation to get center in (0,0,0). _PGA.HomogeneousOppositeTranslation(PEdge0,PCenterTriangle); _PGA.HomogeneousOppositeTranslation(PEdge1,PCenterTriangle); _PGA.HomogeneousOppositeTranslation(PTarget,PCenterTriangle); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0 moved to the center of the triangle'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1 moved to the center of the triangle'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget moved to the center of the triangle'); {$endif} {$endif} // Get line segments. LSEdge := _PGA.GetOuterProduct(PEdge0,PEdge1); LSEdgeUV := _PGA.GetOuterProduct(PEdge0UV,PEdge1UV); // Get Directions. DirEdge := _PGA.GetFlatDirection(LSEdge); DirEdgeUV := _PGA.GetFlatDirection(LSEdgeUV); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} LSEdge.Debug(GlobalVars.OrigamiFile,'LSEdge'); LSEdgeUV.Debug(GlobalVars.OrigamiFile,'LSEdgeUV'); DirEdge.Debug(GlobalVars.OrigamiFile,'DirEdge'); DirEdgeUV.Debug(GlobalVars.OrigamiFile,'DirEdgeUV'); {$endif} {$endif} // Let's do the scale first. EdgeSizeInMesh := _PGA.GetLength(DirEdge); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} GlobalVars.OrigamiFile.Add('Norm of DirEdge is ' + FloatToStr(EdgeSizeInMesh) + '.'); {$endif} {$endif} if EdgeSizeInMesh = 0 then begin PEdge0.Free; PEdge1.Free; PTarget.Free; PEdge0UV.Free; PEdge1UV.Free; LSEdge.Free; LSEdgeUV.Free; DirEdge.Free; DirEdgeUV.Free; PCenterTriangle.Free; ColisionCheck.Free; exit; end; EdgeSizeInUV := _PGA.GetLength(DirEdgeUV); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} GlobalVars.OrigamiFile.Add('Norm of DirEdgeUV is ' + FloatToStr(EdgeSizeInUV) + '.'); {$endif} {$endif} Scale := EdgeSizeInUV / EdgeSizeInMesh; {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} GlobalVars.OrigamiFile.Add('Scale is ' + FloatToStr(Scale) + '.'); {$endif} {$endif} _PGA.ScaleEuclideanDataFromVector(PEdge0,Scale); _PGA.ScaleEuclideanDataFromVector(PEdge1,Scale); _PGA.ScaleEuclideanDataFromVector(PTarget,Scale); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0 after scale'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1 after scale'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget after scale'); {$endif} {$endif} // Project the triangle (Edge0,Edge1,Target) at the UV plane. PlaneRotation := GetVersorForTriangleProjectionGA(_EGA,_FaceNormal); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PlaneRotation.Debug(GlobalVars.OrigamiFile,'PlaneRotation'); {$endif} {$endif} // This part is not very practical, but it should avoid problems. PTemp := TMultiVector.Create(PEdge0); _PGA.ApplyRotor(PEdge0,PTemp,PlaneRotation); _PGA.BladeOfGradeFromVector(PEdge0,1); PTemp.Assign(PEdge1); _PGA.ApplyRotor(PEdge1,PTemp,PlaneRotation); _PGA.BladeOfGradeFromVector(PEdge1,1); PTemp.Assign(PTarget); _PGA.ApplyRotor(PTarget,PTemp,PlaneRotation); _PGA.BladeOfGradeFromVector(PTarget,1); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0 after plane projection'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1 after plane projection'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget after plane projection'); {$endif} {$endif} // Let's center our triangle at the center of the Edge0-Edge1 line segment. PCenterSegment := _PGA.NewEuclideanVector(SetVector((PEdge0.UnsafeData[1] + PEdge1.UnsafeData[1])*0.5,(PEdge0.UnsafeData[2] + PEdge1.UnsafeData[2])*0.5)); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PCenterSegment.Debug(GlobalVars.OrigamiFile,'PCenterSegment'); {$endif} {$endif} // Do translation to get center in (0,0,0). _PGA.HomogeneousOppositeTranslation(PEdge0,PCenterSegment); _PGA.HomogeneousOppositeTranslation(PEdge1,PCenterSegment); _PGA.HomogeneousOppositeTranslation(PTarget,PCenterSegment); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0 moved to the center of the segment'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1 moved to the center of the segment'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget moved to the center of the segment'); {$endif} {$endif} // Let's center our UV triangle at the center of the Edge0UV-Edge1UV line segment. PCenterSegmentUV := _PGA.NewEuclideanVector(SetVector((PEdge0UV.UnsafeData[1] + PEdge1UV.UnsafeData[1])*0.5,(PEdge0UV.UnsafeData[2] + PEdge1UV.UnsafeData[2])*0.5)); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PCenterSegmentUV.Debug(GlobalVars.OrigamiFile,'PCenterSegmentUV'); {$endif} {$endif} // Do translation to get center in (0,0,0). _PGA.HomogeneousOppositeTranslation(PEdge0UV,PCenterSegmentUV); _PGA.HomogeneousOppositeTranslation(PEdge1UV,PCenterSegmentUV); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0UV.Debug(GlobalVars.OrigamiFile,'PEdge0UV moved to the center of the UV segment'); PEdge1UV.Debug(GlobalVars.OrigamiFile,'PEdge1UV moved to the center of the UV segment'); {$endif} {$endif} // Now we have to recalculate the line segments and directions. // Get line segments. _PGA.OuterProduct(LSEdge,PEdge0,PEdge1); _PGA.OuterProduct(LSEdgeUV,PEdge0UV,PEdge1UV); // Get Directions. _PGA.FlatDirection(DirEdge,LSEdge); _PGA.FlatDirection(DirEdgeUV,LSEdgeUV); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} LSEdge.Debug(GlobalVars.OrigamiFile,'LSEdge'); LSEdgeUV.Debug(GlobalVars.OrigamiFile,'LSEdgeUV'); DirEdge.Debug(GlobalVars.OrigamiFile,'DirEdge'); DirEdgeUV.Debug(GlobalVars.OrigamiFile,'DirEdgeUV'); {$endif} {$endif} // Let's rotate our vectors. _PGA.GeometricProduct(PTemp,DirEdge,DirEdgeUV); // Rotate the triangle (Edge0,Edge1,Target) at the UV plane. SegmentRotation := _PGA.Euclidean3DLogarithm(PTemp); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} SegmentRotation.Debug(GlobalVars.OrigamiFile,'SegmentRotation'); {$endif} {$endif} // This part is not very practical, but it should avoid problems. PTemp.Assign(PEdge0); _PGA.ApplyRotor(PEdge0,PTemp,SegmentRotation); _PGA.BladeOfGradeFromVector(PEdge0,1); PTemp.Assign(PEdge1); _PGA.ApplyRotor(PEdge1,PTemp,SegmentRotation); _PGA.BladeOfGradeFromVector(PEdge1,1); PTemp.Assign(PTarget); _PGA.ApplyRotor(PTarget,PTemp,SegmentRotation); _PGA.BladeOfGradeFromVector(PTarget,1); {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_PROJECTION_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0 after rotation at the center of the segment'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1 after rotation at the center of the segment'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget after rotation at the center of the segment'); {$endif} {$endif} // Translate PCenterSegmentUV units. _PGA.HomogeneousTranslation(PEdge0,PCenterSegmentUV); _PGA.HomogeneousTranslation(PEdge1,PCenterSegmentUV); _PGA.HomogeneousTranslation(PTarget,PCenterSegmentUV); {$ifdef ORIGAMI_TEST} PEdge0.Debug(GlobalVars.OrigamiFile,'PEdge0 at its final position'); PEdge1.Debug(GlobalVars.OrigamiFile,'PEdge1 at its final position'); PTarget.Debug(GlobalVars.OrigamiFile,'PTarget at its final position'); {$endif} // Now we have the UV position (at PTarget) // Let's clear up some RAM before we continue. PTemp.Free; PEdge0UV.Free; PEdge1UV.Free; PCenterTriangle.Free; PCenterSegment.Free; PCenterSegmentUV.Free; LSEdge.Free; LSEdgeUV.Free; DirEdge.Free; DirEdgeUV.Free; PlaneRotation.Free; SegmentRotation.Free; // Get the line segments for colision detection. LSEdge0 := _PGA.GetOuterProduct(PEdge0,PEdge1); LSEdge1 := _PGA.GetOuterProduct(PEdge1,PTarget); LSEdge2 := _PGA.GetOuterProduct(PTarget,PEdge0); // Write UV coordinates. _UVPosition.U := PTarget.UnsafeData[1]; _UVPosition.V := PTarget.UnsafeData[2]; // Free more memory. PEdge0.Free; PEdge1.Free; PTarget.Free; // Let's check if this UV Position will hit another UV project face. Result := true; // the change in the _AddedFace temporary optimization for the upcoming loop. _CheckFace[_PreviousFace] := false; v := 0; V0 := TMultiVector.Create(_PGA.SystemDimension); V1 := TMultiVector.Create(_PGA.SystemDimension); V2 := TMultiVector.Create(_PGA.SystemDimension); for i := Low(_CheckFace) to High(_CheckFace) do begin // If the face was projected in the UV domain. if _CheckFace[i] then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(i) + ' has vertexes (' + FloatToStr(_TexCoords[_Faces[v]].U) + ', ' + FloatToStr(_TexCoords[_Faces[v]].V) + '), (' + FloatToStr(_TexCoords[_Faces[v+1]].U) + ', ' + FloatToStr(_TexCoords[_Faces[v+1]].V) + '), (' + FloatToStr(_TexCoords[_Faces[v+2]].U) + ', ' + FloatToStr(_TexCoords[_Faces[v+2]].V) + ').'); {$endif} {$endif} // Check if the candidate position is inside this triangle. // If it is inside the triangle, then point is not validated. Exit. _PGA.SetHomogeneousFlat(V0,_TexCoords[_Faces[v]]); _PGA.SetHomogeneousFlat(V1,_TexCoords[_Faces[v+1]]); _PGA.SetHomogeneousFlat(V2,_TexCoords[_Faces[v+2]]); if ColisionCheck.Are2DTrianglesColiding(_PGA,LSEdge0,LSEdge1,LSEdge2,V0,V1,V2) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex textured coordinate (' + FloatToStr(_UVPosition.U) + ', ' + FloatToStr(_UVPosition.V) + ') conflicts with face ' + IntToStr(i) + '.'); {$endif} Result := false; _CheckFace[_PreviousFace] := true; // Free RAM. LSEdge2.Free; LSEdge1.Free; LSEdge0.Free; V2.Free; V1.Free; V0.Free; ColisionCheck.Free; exit; end; end; inc(v,_VerticesPerFace); end; _CheckFace[_PreviousFace] := true; // Free RAM. V2.Free; V1.Free; V0.Free; LSEdge2.Free; LSEdge1.Free; LSEdge0.Free; ColisionCheck.Free; end; function CTextureAtlasExtractorOrigamiGA.MakeNewSeed(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; const _FaceNeighbors: TNeighborDetector; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace,_MaxVerts: integer; var _CheckFace: abool): TTextureSeed; var v,f,Value,vertex,FaceIndex,PreviousFace : integer; CurrentVertex,PreviousVertex,SharedEdge0,SharedEdge1: integer; FaceList,PreviousFaceList : CIntegerList; Angle: single; Position,TriangleCenter: TVector3f; CandidateUVPosition: TVector2f; AddedFace: abool; TriangleTransform,TriangleTransformInv: TMultiVector; EuclideanGA,ProjectiveGA: TGeometricAlgebra; FaceBackup: auint32; {$ifdef ORIGAMI_TEST} Temp: string; {$endif} begin EuclideanGA := TGeometricAlgebra.Create(3); ProjectiveGA := TGeometricAlgebra.CreateHomogeneous(3); SetLength(FaceBackup,_VerticesPerFace); // Setup neighbor detection list FaceList := CIntegerList.Create; FaceList.UseFixedRAM(High(_CheckFace)+1); PreviousFaceList := CIntegerList.Create; PreviousFaceList.UseFixedRAM(High(_CheckFace)+1); // Setup VertsLocation SetLength(FVertsLocation,High(_Vertices)+1); for v := Low(FVertsLocation) to High(FVertsLocation) do begin FVertsLocation[v] := -1; end; // Avoid unlimmited loop SetLength(AddedFace,High(_CheckFace)+1); for f := Low(_CheckFace) to High(_CheckFace) do begin AddedFace[f] := false; _CheckFace[f] := false; end; // Add starting face {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Starting Face of the seed is ' + IntToStr(_StartingFace)); {$endif} _FaceSeeds[_StartingFace] := _ID; _CheckFace[_StartingFace] := true; AddedFace[_StartingFace] := true; TriangleTransform := GetVersorForTriangleProjectionGA(EuclideanGA,_FaceNormals[_StartingFace]); TriangleTransformInv := EuclideanGA.GetInverse(TriangleTransform); {$ifdef ORIGAMI_TEST} TriangleTransform.Debug(GlobalVars.OrigamiFile,'TriangleTransform'); TriangleTransformInv.Debug(GlobalVars.OrigamiFile,'TriangleTransformInv'); {$endif} // Result.TransformMatrix := VertexUtil.GetTransformMatrixFromVector(_FaceNormals[_StartingFace]); Result.MinBounds.U := 999999; Result.MaxBounds.U := -999999; Result.MinBounds.V := 999999; Result.MaxBounds.V := -999999; Result.MeshID := _MeshID; // The first triangle is dealt in a different way. // We'll project it in the plane XY and the first vertex is on (0,0,0). {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Starting Face is ' + IntToStr(_StartingFace) + ' and it is being added now'); {$endif} FaceIndex := _StartingFace * _VerticesPerFace; TriangleCenter := GetTriangleCenterPosition(_Vertices[_Faces[FaceIndex]],_Vertices[_Faces[FaceIndex+1]],_Vertices[_Faces[FaceIndex+2]]); for v := 0 to _VerticesPerFace - 1 do begin vertex := _Faces[FaceIndex+v]; Position := SubtractVector(_Vertices[vertex],TriangleCenter); {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex is ' + IntToStr(vertex) + ' and Position is: [' + FloatToStr(Position.X) + ' ' + FloatToStr(Position.Y) + ' ' + FloatToStr(Position.Z) + ']'); {$endif} if _VertsSeed[vertex] <> -1 then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(_StartingFace) + ' is used and it is being cloned as ' + IntToStr(High(_Vertices)+2)); {$endif} // this vertex was used by a previous seed, therefore, we'll clone it SetLength(_Vertices,High(_Vertices)+2); SetLength(_VertsSeed,High(_Vertices)+1); _VertsSeed[High(_VertsSeed)] := _ID; SetLength(FVertsLocation,High(_Vertices)+1); FVertsLocation[High(_Vertices)] := vertex; // _VertsLocation works slightly different here than in the non-origami version. {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face item ' + IntToStr(FaceIndex+v) + ' has been changed to ' + IntToStr(High(_Vertices))); {$endif} _Faces[FaceIndex+v] := High(_Vertices); _Vertices[High(_Vertices)].X := _Vertices[vertex].X; _Vertices[High(_Vertices)].Y := _Vertices[vertex].Y; _Vertices[High(_Vertices)].Z := _Vertices[vertex].Z; SetLength(_VertsNormals,High(_Vertices)+1); _VertsNormals[High(_Vertices)].X := _VertsNormals[vertex].X; _VertsNormals[High(_Vertices)].Y := _VertsNormals[vertex].Y; _VertsNormals[High(_Vertices)].Z := _VertsNormals[vertex].Z; SetLength(_VertsColours,High(_Vertices)+1); _VertsColours[High(_Vertices)].X := _VertsColours[vertex].X; _VertsColours[High(_Vertices)].Y := _VertsColours[vertex].Y; _VertsColours[High(_Vertices)].Z := _VertsColours[vertex].Z; _VertsColours[High(_Vertices)].W := _VertsColours[vertex].W; // Get temporarily texture coordinates. SetLength(_TextCoords,High(_Vertices)+1); // _TextCoords[High(_Vertices)] := VertexUtil.GetUVCoordinates(Position,Result.TransformMatrix); _TextCoords[High(_Vertices)] := GetVertexPositionOnTriangleProjectionGA(EuclideanGA,Position,TriangleTransform,TriangleTransformInv); // Now update the bounds of the seed. if _TextCoords[High(_Vertices)].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[High(_Vertices)].V; if _TextCoords[High(_Vertices)].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[High(_Vertices)].V; end else begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(vertex) + ' is new.'); {$endif} // This seed is the first seed to use this vertex. _VertsSeed[vertex] := _ID; FVertsLocation[vertex] := vertex; // Get temporary texture coordinates. // _TextCoords[vertex] := VertexUtil.GetUVCoordinates(Position,Result.TransformMatrix); _TextCoords[vertex] := GetVertexPositionOnTriangleProjectionGA(EuclideanGA,Position,TriangleTransform,TriangleTransformInv); // Now update the bounds of the seed. if _TextCoords[vertex].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[vertex].U; if _TextCoords[vertex].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[vertex].U; if _TextCoords[vertex].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[vertex].V; if _TextCoords[vertex].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[vertex].V; end; end; // Add neighbour faces to the list. f := _FaceNeighbors.GetNeighborFromID(_StartingFace); while f <> -1 do begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(f) + ' is neighbour of ' + IntToStr(_StartingFace)); {$endif} // do some verification here if not AddedFace[f] then begin if (_FaceSeeds[f] = -1) then begin PreviousFaceList.Add(_StartingFace); FaceList.Add(f); {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(f) + ' has been added to the list'); {$endif} end; AddedFace[f] := true; end; f := _FaceNeighbors.GetNextNeighbor; end; // Neighbour Face Scanning starts here. // Wel'll check face by face and add the vertexes that were not added while FaceList.GetValue(Value) do begin PreviousFaceList.GetValue(PreviousFace); // Backup current face just in case the face gets rejected FaceIndex := Value * _VerticesPerFace; v := 0; while v < _VerticesPerFace do begin FaceBackup[v] := _Faces[FaceIndex + v]; inc(v); end; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Veryfing Face ' + IntToStr(Value) + ' that was added by previous face ' + IntToStr(PreviousFace)); {$endif} // The first idea is to get the vertex that wasn't added yet. ObtainCommonEdgeFromFaces(_Faces,_VerticesPerFace,Value,PreviousFace,CurrentVertex,PreviousVertex,SharedEdge0,SharedEdge1,v); {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Current Vertex = ' + IntToStr(CurrentVertex) + '; Previous Vertex = ' + IntToStr(PreviousVertex) + '; Share Edge = [' + IntToStr(SharedEdge0) + ', ' + IntToStr(SharedEdge1) + ']'); {$endif} // Find coordinates and check if we won't hit another face. if IsValidUVPointGA(ProjectiveGA,EuclideanGA,_Vertices,_Faces,_TextCoords,_FaceNormals[Value],CurrentVertex,SharedEdge0,SharedEdge1,PreviousVertex,_CheckFace,CandidateUVPosition,Value,PreviousFace,_VerticesPerFace) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been validated.'); {$endif} // Add the face and its vertexes _CheckFace[Value] := true; _FaceSeeds[Value] := _ID; // If the vertex wasn't used yet if _VertsSeed[CurrentVertex] = -1 then begin // This seed is the first seed to use this vertex. // Does this vertex has coordinates already? if FVertsLocation[CurrentVertex] <> -1 then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(CurrentVertex) + ' is being cloned as ' + IntToStr(High(_Vertices)+1)); {$endif} // Clone vertex SetLength(_Vertices,High(_Vertices)+2); SetLength(_VertsSeed,High(_Vertices)+1); _VertsSeed[High(_VertsSeed)] := _ID; SetLength(FVertsLocation,High(_Vertices)+1); FVertsLocation[High(_Vertices)] := CurrentVertex; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face item ' + IntToStr(FaceIndex+v) + ' has been changed from ' + IntToStr(CurrentVertex) + ' to ' + IntToStr(High(_Vertices))); {$endif} _Faces[FaceIndex+v] := High(_Vertices); _Vertices[High(_Vertices)].X := _Vertices[CurrentVertex].X; _Vertices[High(_Vertices)].Y := _Vertices[CurrentVertex].Y; _Vertices[High(_Vertices)].Z := _Vertices[CurrentVertex].Z; SetLength(_VertsNormals,High(_Vertices)+1); _VertsNormals[High(_Vertices)].X := _VertsNormals[CurrentVertex].X; _VertsNormals[High(_Vertices)].Y := _VertsNormals[CurrentVertex].Y; _VertsNormals[High(_Vertices)].Z := _VertsNormals[CurrentVertex].Z; SetLength(_VertsColours,High(_Vertices)+1); _VertsColours[High(_Vertices)].X := _VertsColours[CurrentVertex].X; _VertsColours[High(_Vertices)].Y := _VertsColours[CurrentVertex].Y; _VertsColours[High(_Vertices)].Z := _VertsColours[CurrentVertex].Z; _VertsColours[High(_Vertices)].W := _VertsColours[CurrentVertex].W; // Get temporary texture coordinates. SetLength(_TextCoords,High(_Vertices)+1); _TextCoords[High(_Vertices)].U := CandidateUVPosition.U; _TextCoords[High(_Vertices)].V := CandidateUVPosition.V; // Now update the bounds of the seed. if _TextCoords[High(_Vertices)].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[High(_Vertices)].V; if _TextCoords[High(_Vertices)].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[High(_Vertices)].V; end else begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(CurrentVertex) + ' is being used.'); {$endif} // Write the vertex coordinates. _VertsSeed[CurrentVertex] := _ID; FVertsLocation[CurrentVertex] := CurrentVertex; // Get temporary texture coordinates. _TextCoords[CurrentVertex].U := CandidateUVPosition.U; _TextCoords[CurrentVertex].V := CandidateUVPosition.V; // Now update the bounds of the seed. if _TextCoords[CurrentVertex].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[CurrentVertex].U; if _TextCoords[CurrentVertex].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[CurrentVertex].U; if _TextCoords[CurrentVertex].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[CurrentVertex].V; if _TextCoords[CurrentVertex].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[CurrentVertex].V; end; end else // if the vertex has been added previously. begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(CurrentVertex) + ' is being cloned as ' + IntToStr(High(_Vertices)+1) + ' due to another seed.'); {$endif} // Clone the vertex. SetLength(_Vertices,High(_Vertices)+2); SetLength(_VertsSeed,High(_Vertices)+1); _VertsSeed[High(_VertsSeed)] := _ID; SetLength(FVertsLocation,High(_Vertices)+1); FVertsLocation[High(_Vertices)] := CurrentVertex; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face item ' + IntToStr(FaceIndex+v) + ' has been changed from ' + IntToStr(CurrentVertex) + ' to ' + IntToStr(High(_Vertices))); {$endif} _Faces[FaceIndex+v] := High(_Vertices); _Vertices[High(_Vertices)].X := _Vertices[CurrentVertex].X; _Vertices[High(_Vertices)].Y := _Vertices[CurrentVertex].Y; _Vertices[High(_Vertices)].Z := _Vertices[CurrentVertex].Z; SetLength(_VertsNormals,High(_Vertices)+1); _VertsNormals[High(_Vertices)].X := _VertsNormals[CurrentVertex].X; _VertsNormals[High(_Vertices)].Y := _VertsNormals[CurrentVertex].Y; _VertsNormals[High(_Vertices)].Z := _VertsNormals[CurrentVertex].Z; SetLength(_VertsColours,High(_Vertices)+1); _VertsColours[High(_Vertices)].X := _VertsColours[CurrentVertex].X; _VertsColours[High(_Vertices)].Y := _VertsColours[CurrentVertex].Y; _VertsColours[High(_Vertices)].Z := _VertsColours[CurrentVertex].Z; _VertsColours[High(_Vertices)].W := _VertsColours[CurrentVertex].W; // Get temporary texture coordinates. SetLength(_TextCoords,High(_Vertices)+1); _TextCoords[High(_Vertices)].U := CandidateUVPosition.U; _TextCoords[High(_Vertices)].V := CandidateUVPosition.V; // Now update the bounds of the seed. if _TextCoords[High(_Vertices)].U < Result.MinBounds.U then Result.MinBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].U > Result.MaxBounds.U then Result.MaxBounds.U := _TextCoords[High(_Vertices)].U; if _TextCoords[High(_Vertices)].V < Result.MinBounds.V then Result.MinBounds.V := _TextCoords[High(_Vertices)].V; if _TextCoords[High(_Vertices)].V > Result.MaxBounds.V then Result.MaxBounds.V := _TextCoords[High(_Vertices)].V; end; // Check if other neighbors are elegible for this partition/seed. f := _FaceNeighbors.GetNeighborFromID(Value); while f <> -1 do begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(f) + ' is neighbour of ' + IntToStr(Value)); {$endif} // do some verification here if not AddedFace[f] then begin if (_FaceSeeds[f] = -1) then begin PreviousFaceList.Add(Value); FaceList.Add(f); {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(f) + ' has been added to the list'); {$endif} end; AddedFace[f] := true; end; f := _FaceNeighbors.GetNextNeighbor; end; end else // Face has been rejected. begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been rejected.'); {$endif} // Restore current face due to rejection v := 0; while v < _VerticesPerFace do begin _Faces[FaceIndex + v] := FaceBackup[v]; inc(v); end; end; end; if _NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(_NeighborhoodPlugin^).UpdateEquivalencesOrigami(FVertsLocation); end; SetLength(FVertsLocation,0); SetLength(AddedFace,0); SetLength(FaceBackup,0); TriangleTransform.Free; TriangleTransformInv.Free; FaceList.Free; PreviousFaceList.Free; EuclideanGA.Free; ProjectiveGA.Free; end; end.
{ *********************************************************************** } { } { GUI Hangman } { Version 1.0 - First release of program } { Last Revised: 27nd of July 2004 } { Copyright (c) 2004 Chris Alley } { } { *********************************************************************** } unit UDataModule; interface uses SysUtils, Classes, DB, ADODB, UConstantsAndTypes, Dialogs, Forms; type THangmanDataModule = class(TDataModule) HangmanADOConnection: TADOConnection; PlayersADOTable: TADOTable; GamesADOTable: TADOTable; PlayersDataSource: TDataSource; GamesDataSource: TDataSource; CalcPlayerGamesPlayed: TADOStoredProc; CalcPlayerGamesPlayedPlayerLogin: TWideStringField; CalcPlayerGamesPlayedGameDifficultyLevel: TWideStringField; CalcPlayerGamesPlayedCountOfGameDateTimeCompleted: TIntegerField; CalcPlayerAverageScore: TADOStoredProc; CalcPlayerBestScore: TADOStoredProc; CalcAllGamesPlayed: TADOStoredProc; CalcAllAverageScore: TADOStoredProc; CalcChampionDetails: TADOStoredProc; PlayersADOTablePlayerLogin: TWideStringField; PlayersADOTablePlayerFirstName: TWideStringField; PlayersADOTablePlayerLastName: TWideStringField; PlayersADOTablePlayerDateTimeRegistered: TDateTimeField; private { Private declarations } public function CheckIfLoginExistsInDatabase(ALogin: string): boolean; function AddNewPlayerToDatabase(ALogin, AFirstName, ALastName: string): boolean; function AddGameScoreToDatabase(ALogin, ADifficultyLevel: string; AScore: integer): boolean; function GetPlayerFirstAndLastNames(ALogin: string; var AFirstName, ALastName: string): boolean; function GetIndividualGameStatistics(ALogin, ADifficultyLevel: string; var AGamesPlayed, AAverageScore, ABestScore: integer): boolean; procedure GetGameStatistics(ADifficultyLevel: string; var AGamesPlayed, AAverageScore: integer; var ACurrentChampion: string; var AChampionScore: integer; var AChampionGameDateTime: string); procedure ConnectToDatabase; end; var HangmanDataModule: THangmanDataModule; implementation {$R *.dfm} { THangmanDataModule } function THangmanDataModule.CheckIfLoginExistsInDatabase(ALogin: string): boolean; { Returns true if the login exists in the database, otherwise it will return false. } begin Result := Self.PlayersADOTable.Locate('PlayerLogin', ALogin, [loCaseInsensitive]); end; function THangmanDataModule.AddNewPlayerToDatabase(ALogin, AFirstName, ALastName: string): boolean; { If the player doesn't already exist in the database, then the function will add the new player's details to the database and then return true. } begin if Self.PlayersADOTable.Locate('PlayerLogin', ALogin, [loCaseInsensitive]) = False then begin if (not(ALogin = '') and not(AFirstName = '') and not(ALastName = '')) then begin Self.PlayersADOTable.Insert; Self.PlayersADOTable.FieldByName('PlayerLogin').Value := ALogin; Self.PlayersADOTable.FieldByName('PlayerFirstName').Value := AFirstName; Self.PlayersADOTable.FieldByName('PlayerLastName').Value := ALastName; Self.PlayersADOTable.FieldByName('PlayerDateTimeRegistered').Value := Now; Self.PlayersADOTable.Post; Result := True; end else Result := False; end else Result := False; end; function THangmanDataModule.AddGameScoreToDatabase(ALogin, ADifficultyLevel: string; AScore: integer): boolean; { Adds the game's details to the database, depending on what Difficulty Level and Login were passed into the function. } begin if Self.PlayersADOTable.Locate('PlayerLogin', ALogin, [loCaseInsensitive]) = False then Result := False else begin if (not(ADifficultyLevel = Easy)) and (not(ADifficultyLevel = Normal)) and (not(ADifficultyLevel = Hard)) then Result := False else begin if (AScore < 0) or (AScore > 10) then Result := False else begin Self.GamesADOTable.Insert; Self.GamesADOTable.FieldByName('GamePlayerLogin').Value := ALogin; Self.GamesADOTable.FieldByName('GameDifficultyLevel').Value := ADifficultyLevel; Self.GamesADOTable.FieldByName('GameScore').Value := AScore; Self.GamesADOTable.FieldByName('GameDateTimeCompleted').Value := Now; Self.GamesADOTable.Post; Result := True; end; end; end; end; function THangmanDataModule.GetPlayerFirstAndLastNames(ALogin: string; var AFirstName, ALastName: string): boolean; { Grabs the player's first and last names out of the database. Returns false if the player's login cannot be found. } begin if Self.PlayersADOTable.Locate('PlayerLogin', ALogin, [loCaseInsensitive]) = False then begin AFirstName := 'Error'; ALastName := 'Error'; Result := False; end else begin AFirstName := Self.PlayersADOTable.FieldByName('PlayerFirstName').Value; ALastName := Self.PlayersADOTable.FieldByName('PlayerLastName').Value; Result := True; end; end; function THangmanDataModule.GetIndividualGameStatistics(ALogin, ADifficultyLevel: string; var AGamesPlayed, AAverageScore, ABestScore: integer): boolean; { Gets the number of games played, average score, and best score of the player whose login name was passed into the function, on the difficulty level passed into the function. } begin AGamesPlayed := 0; AAverageScore := 0; ABestScore := 0; if Self.PlayersADOTable.Locate('PlayerLogin', ALogin, [loCaseInsensitive]) = False then Result := False else begin // Get the number of games that the player has finished. Self.CalcPlayerGamesPlayed.Parameters.ParamValues['PlayerLogin'] := ALogin; Self.CalcPlayerGamesPlayed.Parameters.ParamValues['GameDifficultyLevel'] := ADifficultyLevel; Self.CalcPlayerGamesPlayed.Active := False; Self.CalcPlayerGamesPlayed.Active := True; if not(Self.CalcPlayerGamesPlayed.BOF and Self.CalcPlayerGamesPlayed.EOF) then AGamesPlayed := Self.CalcPlayerGamesPlayed.FieldValues['CountOfGameDateTimeCompleted']; // Get the average of the player's scores on ADifficultyLevel. Self.CalcPlayerAverageScore.Parameters.ParamValues['PlayerLogin'] := ALogin; Self.CalcPlayerAverageScore.Parameters.ParamValues['GameDifficultyLevel'] := ADifficultyLevel; Self.CalcPlayerAverageScore.Active := False; Self.CalcPlayerAverageScore.Active := True; if not(Self.CalcPlayerAverageScore.BOF and Self.CalcPlayerAverageScore.EOF) then AAverageScore := Self.CalcPlayerAverageScore.FieldValues['AvgOfGameScore']; // Get the best score that the player has made on ADifficultyLevel. Self.CalcPlayerBestScore.Parameters.ParamValues['PlayerLogin'] := ALogin; Self.CalcPlayerBestScore.Parameters.ParamValues['GameDifficultyLevel'] := ADifficultyLevel; Self.CalcPlayerBestScore.Active := False; Self.CalcPlayerBestScore.Active := True; if not(Self.CalcPlayerBestScore.BOF and Self.CalcPlayerBestScore.EOF) then ABestScore := Self.CalcPlayerBestScore.FieldValues['MaxOfGameScore']; Result := True; end; end; procedure THangmanDataModule.GetGameStatistics(ADifficultyLevel: string; var AGamesPlayed, AAverageScore: integer; var ACurrentChampion: string; var AChampionScore: integer; var AChampionGameDateTime: string); { Gets the numbers of games played, average score, current champion, champion's score, and the date and time that the champion made the score on the difficulty level passed into the procedure. } begin AGamesPlayed := 0; AAverageScore := 0; ACurrentChampion := ''; AChampionScore := 0; AChampionGameDateTime := ''; // Get the amount of games played on ADifficultyLevel. Self.CalcAllGamesPlayed.Parameters.ParamValues['GameDifficultyLevel'] := ADifficultyLevel; Self.CalcAllGamesPlayed.Active := False; Self.CalcAllGamesPlayed.Active := True; if not(Self.CalcAllGamesPlayed.BOF and Self.CalcAllGamesPlayed.EOF) then AGamesPlayed := Self.CalcAllGamesPlayed.FieldValues['CountOfGameDateTimeCompleted']; // Get the average score of all games played on ADifficultyLevel. Self.CalcAllAverageScore.Parameters.ParamValues['GameDifficultyLevel'] := ADifficultyLevel; Self.CalcAllAverageScore.Active := False; Self.CalcAllAverageScore.Active := True; if not(Self.CalcAllAverageScore.BOF and Self.CalcAllAverageScore.EOF) then AAverageScore := Self.CalcAllAverageScore.FieldValues['AvgOfGameScore']; // Get Champion details on ADifficultyLevel. Self.CalcChampionDetails.Parameters.ParamValues['GameDifficultyLevel'] := ADifficultyLevel; Self.CalcChampionDetails.Active := False; Self.CalcChampionDetails.Active := True; if not(Self.CalcChampionDetails.BOF and Self.CalcChampionDetails.EOF) then begin ACurrentChampion := Self.CalcChampionDetails.FieldValues['GamePlayerLogin']; AChampionScore := Self.CalcChampionDetails.FieldValues['GameScore']; AChampionGameDateTime := Self.CalcChampionDetails.FieldValues['MaxOfGameDateTimeCompleted']; end; end; procedure THangmanDataModule.ConnectToDatabase; { Connects to the game's database using a dynamically created connection string. It also makes the database's tables active. } const DatabaseFilePath = 'Database\HangmanDatabase.mdb'; var ApplicationFilePath: string; begin ApplicationFilePath := ExtractFilePath(Application.ExeName); Self.HangmanADOConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;' + 'Data Source=' + ApplicationFilePath + DatabaseFilePath + ';Mode=Share Deny None;Extended Properties="";' + 'Persist Security Info=False;Jet OLEDB:System database="";' + 'Jet OLEDB:Registry Path="";Jet OLEDB:Database Password="";' + 'Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;' + 'Jet OLEDB:Global Partial Bulk Ops=2;' + 'Jet OLEDB:Global Bulk Transactions=1;' + 'Jet OLEDB:New Database Password="";' + 'Jet OLEDB:Create System Database=False;' + 'Jet OLEDB:Encrypt Database=False;' + 'Jet OLEDB:Don''t Copy Locale on Compact=False;Jet OLEDB:' + 'Compact Without Replica Repair=False;Jet OLEDB:SFP=False'; Self.HangmanADOConnection.Connected := True; Self.PlayersADOTable.Active := True; Self.GamesADOTable.Active := True; end; end.
Unit AbstractRequest; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} Interface Uses IRPMonDll, RefObject, ProcessList; Type TGeneralRequest = Class (TRefObject) Private FDataBufferAllocated : Boolean; Protected FId : Cardinal; FDriverName : WideString; FDeviceName : WideString; FFileName : WideString; FProcessName : WideString; FDriverObject : Pointer; FDeviceObject : Pointer; FFileObject : Pointer; FRequestType : ERequestType; FResultType : ERequestResultType; FResultValue : NativeUInt; FTime : UInt64; FThreadId : THandle; FProcessId : THandle; FIRQL : Byte; FDataSize : NativeUInt; FData : Pointer; FRaw : PREQUEST_HEADER; FRawSize : Cardinal; FEmulated : Boolean; FDataPresent : Boolean; FDataStripped : Boolean; FAdmin : Boolean; FImpersonated : Boolean; FImpersonatedAdmin : Boolean; FIOSBStatus : Cardinal; FIOSBInformation : NativeUInt; FStackFrames : PPointer; FStackFrameCount : Cardinal; FProcess : TProcessEntry; Protected Function GetProcess:TProcessEntry; Procedure SetProcess(AProcess:TProcessEntry); Public Constructor Create(Var ARequest:REQUEST_HEADER); Overload; Destructor Destroy; Override; Function AssignData(AData:Pointer; ASize:NativeUInt; AWithinRequest:Boolean = True):Boolean; Procedure SetDriverName(AName:WideString); Procedure SetDeviceName(AName:WideString); Procedure SetFileName(AName:WideString); Procedure SetProcessName(AName:WideString); Procedure SetFileObject(AObject:Pointer); Class Function IOCTLToString(AControlCode:Cardinal):WideString; Class Function RequestTypeToString(ARequestType:ERequestType):WideString; Class Function RequestResultToString(AResult:NativeUInt; AResultType:ERequestResultType; AConstant:Boolean = False):WideString; Class Function NTSTATUSToString(AValue:Cardinal):WideString; Class Function AccessModeToString(AMode:Byte):WideString; Class Function IRQLToString(AValue:Byte):WideString; Class Function MajorFunctionToString(AMajor:Byte):WideString; Class Function MinorFunctionToString(AMajor:Byte; AMinor:Byte):WideString; Class Function ImageSignatureTypeToString(AType:EImageSignatureType):WideString; Class Function ImageSigningLevelToString(ALevel:EImageSigningLevel):WideString; Property Id : Cardinal Read FId; Property DriverName : WideString Read FDriverName Write SetDriverName; Property DeviceName : WideString Read FDeviceName Write SetDeviceName; Property FileName : WideString Read FFileName Write SetFileName; Property DriverObject : Pointer Read FDriverObject; Property DeviceObject : Pointer Read FDeviceObject; Property FileObject : Pointer Read FFileObject Write SetFileObject; Property RequestType : ERequestType Read FRequestType; Property ResultType : ERequestResultType Read FResultType; Property ResultValueRaw : NativeUInt Read FResultValue; Property TimeRaw : UInt64 Read FTime; Property ThreadId : THandle Read FThreadId; Property ProcessId : THandle Read FProcessId; Property IRQL : Byte Read FIRQL; Property DataSize : NativeUInt Read FDataSize; Property Data : Pointer Read FData; Property Raw : PREQUEST_HEADER Read FRaw; Property RawSize : Cardinal Read FRawSize; Property Emulated : Boolean Read FEmulated; Property Admin : Boolean Read FAdmin; Property Impersonated : Boolean Read FImpersonated; Property DataPresent : Boolean Read FDataPresent; Property DataStripped : Boolean Read FDataStripped; Property ProcessName : WideString Read FProcessName; Property ImpersonatedAdmin : Boolean Read FImpersonatedAdmin; Property IOSBStatus : Cardinal Read FIOSBStatus; Property IOSBInformation : NativeUInt Read FIOSBInformation; Property StackFrames : PPointer Read FStackFrames; Property StackFrameCount : Cardinal Read FStackFrameCount; Property Process : TProcessEntry Read GetProcess Write SetProcess; end; Implementation Uses SysUtils, NameTables; (** TGeneralRequest **) Constructor TGeneralRequest.Create(Var ARequest:REQUEST_HEADER); Var frame : Pointer; begin Inherited Create; FId := ARequest.Id; FDriverObject := ARequest.Driver; FDriverName := ''; FDeviceObject := ARequest.Device; FDeviceName := ''; FTime := ARequest.Time; FRequestType := ARequest.RequestType; FResultType := ARequest.ResultType; FResultValue := NativeUInt(ARequest.Other); FProcessId := ARequest.ProcessId; FThreadId := ARequest.ThreadId; FIRQL := ARequest.Irql; FIOSBStatus := ARequest.IOSBStatus; FIOSBInformation := ARequest.IOSBInformation; FData := Nil; FDataSize := 0; FRaw := RequestCopy(@ARequest); If Not Assigned(FRaw) THen Raise Exception.Create('Not enough memory'); FRawSize := RequestGetSize(FRaw); If FRawSize = 0 Then Raise Exception.Create('Request raw size is zero'); FRaw.Flags := (FRaw.Flags And Not (REQUEST_FLAG_NEXT_AVAILABLE)); FRaw.Next := Nil; FEmulated := (ARequest.Flags And REQUEST_FLAG_EMULATED) <> 0; FDataStripped := (ARequest.Flags And REQUEST_FLAG_DATA_STRIPPED) <> 0; FAdmin := (ARequest.Flags And REQUEST_FLAG_ADMIN) <> 0; FImpersonated := (ARequest.Flags And REQUEST_FLAG_IMPERSONATED) <> 0; FImpersonatedAdmin := (ARequest.Flags And REQUEST_FLAG_IMPERSONATED_ADMIN) <> 0; If (ARequest.Flags And REQUEST_FLAG_STACKTRACE) <> 0 Then begin FStackFrames := PPointer(PByte(FRaw) + FRawSize - SizeOf(Pointer)*REQUEST_STACKTRACE_SIZE); FStackFrameCount := REQUEST_STACKTRACE_SIZE; Repeat frame := PPointer(PByte(FStackFrames) + SizeOf(Pointer)*(FStackFrameCount - 1))^; If Not Assigned(frame) Then Dec(FStackFrameCount); Until (FStackFrameCount = 0) Or (Assigned(frame)); end; end; Destructor TGeneralRequest.Destroy; begin FProcess.Free; If Assigned(FRaw) Then RequestMemoryFree(FRaw); If FDataBufferAllocated Then FreeMem(FData); Inherited Destroy; end; Function TGeneralRequest.AssignData(AData:Pointer; ASize:NativeUInt; AWithinRequest:Boolean = True):Boolean; begin Result := True; If ASize > 0 Then begin FDataPresent := True; If Not AWithinRequest Then begin Result := Not Assigned(FData); If Result Then begin FData := AllocMem(ASize); Result := Assigned(FData); If Result Then begin Move(AData^, FData^, ASize); FDataSize := ASize; FDataBufferAllocated := True; end; end; end Else begin FDataSize := ASize; FData := PByte(FRaw) + FRawSize - FDataSize; If (FRaw.Flags And REQUEST_FLAG_STACKTRACE) <> 0 Then Dec(PByte(FData), REQUEST_STACKTRACE_SIZE*SizeOf(Pointer)); end; end; end; Procedure TGeneralRequest.SetDriverName(AName:WideString); begin FDriverName := AName; end; Procedure TGeneralRequest.SetDeviceName(AName:WideString); begin FDeviceName := AName; end; Procedure TGeneralRequest.SetFileName(AName:WideString); begin FFileName := AName; end; Procedure TGeneralRequest.SetProcessName(AName:WideString); begin FProcessName := AName; end; Procedure TGeneralRequest.SetFileObject(AObject:Pointer); begin FFileObject := AObject; end; Function TGeneralRequest.GetProcess:TProcessEntry; begin If Assigned(FProcess) Then FProcess.Reference; Result := FProcess; end; Procedure TGeneralRequest.SetProcess(AProcess:TProcessEntry); begin FProcess.Free; If Assigned(AProcess) Then AProcess.Reference; FProcess := AProcess; end; Class Function TGeneralRequest.IOCTLToString(AControlCode:Cardinal):WideString; begin Result := TablesIOCTLToString(AControlCode); end; Class Function TGeneralRequest.MajorFunctionToString(AMajor:Byte):WideString; begin Case AMajor Of 0 : Result := 'Create'; 1 : Result := 'CreateNamedPipe'; 2 : Result := 'Close'; 3 : Result := 'Read'; 4 : Result := 'Write'; 5 : Result := 'Query'; 6 : Result := 'Set'; 7 : Result := 'QueryEA'; 8 : Result := 'SetEA'; 9 : Result := 'Flush'; 10 : Result := 'QueryVolume'; 11 : Result := 'SetVolume'; 12 : Result := 'DirectoryControl'; 13 : Result := 'FSControl'; 14 : Result := 'DeviceControl'; 15 : Result := 'InternalDeviceControl'; 16 : Result := 'Shutdown'; 17 : Result := 'Lock'; 18 : Result := 'Cleanup'; 19 : Result := 'CreateMailslot'; 20 : Result := 'QuerySecurity'; 21 : Result := 'SetSecurity'; 22 : Result := 'Power'; 23 : Result := 'SystemControl'; 24 : Result := 'DeviceChange'; 25 : Result := 'QueryQuota'; 26 : Result := 'SetQuota'; 27 : Result := 'PnP'; Else Result := Format('0x%x>', [AMajor]); end; end; Class Function TGeneralRequest.MinorFunctionToString(AMajor:Byte; AMinor:Byte):WideString; begin Result := ''; Case AMajor Of 27 : begin Case AMinor Of 0 : Result := 'Start'; 1 : Result := 'QueryRemove'; 2 : Result := 'Remove'; 3 : Result := 'CancelRemove'; 4 : Result := 'Stop'; 5 : Result := 'QueryStop'; 6 : Result := 'CancelStop '; 7 : Result := 'QueryRelations'; 8 : Result := 'QueryInterface'; 9 : Result := 'QueryCapabilities'; 10 : Result := 'QueryResources'; 11 : Result := 'QueryResourceRequirements'; 12 : Result := 'QueryDeviceText'; 13 : Result := 'FilterResourceRequirements'; 15 : Result := 'ReadConfig'; 16 : Result := 'WriteConfig'; 17 : Result := 'Eject'; 18 : Result := 'SetLock'; 19 : Result := 'QueryId'; 20 : Result := 'QueryState'; 21 : Result := 'QueryBusInfo'; 22 : Result := 'UsageNotifications'; 23 : Result := 'SurpriseRemoval'; 25 : Result := 'Enumerated'; Else Result := Format('0x%x', [AMinor]); end; end; 22 : begin Case AMinor Of 0 : Result := 'WaitWake'; 1 : Result := 'PowerSequence'; 2 : Result := 'SetPower'; 3 : Result := 'QueryPower'; end; end; 23 : begin Case AMinor Of 0 : Result := 'QueryAllData'; 1 : Result := 'QuerySingleInstance'; 2 : Result := 'ChangeSingleInstance'; 3 : Result := 'ChangeSingleItem'; 4 : Result := 'EnableEvents'; 5 : Result := 'DisableEvents'; 6 : Result := 'EnableCollection'; 7 : Result := 'DisableCollection'; 8 : Result := 'RegInfo'; 9 : Result := 'Execute'; 11 : Result := 'RegInfoEx'; Else Result := Format('0x%x', [AMinor]); end; end; 12 : begin Case AMinor Of 1 : Result := 'QueryDirectory'; 2 : Result := 'ChangeNotify'; Else Result := Format('0x%x', [AMinor]); end; end; 13 : begin Case AMinor Of 0 : Result := 'UserRequest'; 1 : Result := 'MountVolume'; 2 : Result := 'VerifyVolume'; 3 : Result := 'LoadFS'; 4 : Result := 'KernelCall'; Else Result := Format('0x%x', [AMinor]); end; end; 17 : begin Case AMinor Of 1 : Result := 'Lock'; 2 : Result := 'UnlockSingle'; 3 : Result := 'UnlockAll'; 4 : Result := 'UnlockAllByKey'; Else Result := Format('0x%x', [AMinor]); end; end; 9 : begin Case AMinor Of 1 : Result := 'FlushAndPurge'; 2 : Result := 'DataOnly'; 3 : Result := 'NoSync'; Else Result := Format('0x%x', [AMinor]); end; end; 3, 4 : begin Case AMinor Of 0 : Result := 'Normal'; 1 : Result := 'Dpc'; 2 : Result := 'Mdl'; 3 : Result := 'Dpc,Mdl'; 4 : Result := 'Complete'; 5 : Result := 'Complete,Dpc'; 6 : Result := 'Complete,Mdl'; 7 : Result := 'Complete,Dpc,Mdl'; 8 : Result := 'Compressed'; 9 : Result := 'Compressed,Dpc'; 10 : Result := 'Compressed,Mdl'; 11 : Result := 'Compressed,Dpc,Mdl'; 12 : Result := 'Complete,Compressed'; 13 : Result := 'Complete,Compressed,Dpc'; 14 : Result := 'Complete,Compressed,Mdl'; 15 : Result := 'Complete,Compressed,Dpc,Mdl'; end; end; end; end; Class Function TGeneralRequest.RequestTypeToString(ARequestType:ERequestType):WideString; begin Case ARequestType Of ertIRP: Result := 'IRP'; ertIRPCompletion: Result := 'IRPComp'; ertAddDevice: Result := 'AddDevice'; ertDriverUnload: Result := 'Unload'; ertFastIo: Result := 'FastIo'; ertStartIo: Result := 'StartIo'; ertDriverDetected : Result := 'DriverDetected'; ertDeviceDetected : Result := 'DeviceDetected'; ertFileObjectNameAssigned : Result := 'FONameAssigned'; ertFileObjectNameDeleted : Result := 'FONameDeleted'; ertProcessCreated : Result := 'ProcessCreate'; ertProcessExitted : Result := 'ProcessExit'; ertImageLoad : Result := 'ImageLoad'; Else Result := Format('<unknown> (%u)', [Ord(ARequestType)]); end; end; Class Function TGeneralRequest.RequestResultToString(AResult:NativeUInt; AResultType:ERequestResultType; AConstant:Boolean = False):WideString; begin Case AResultType Of rrtUndefined: Result := 'None'; rrtNTSTATUS: begin If AConstant Then Result := Format('%s', [NTSTATUSToString(AResult)]) Else Result := Format('0x%x', [AResult]); end; rrtBOOLEAN: begin If AResult <> 0 Then Result := 'TRUE' Else Result := 'FALSE'; end; Else Result := ''; end; end; Class Function TGeneralRequest.NTSTATUSToString(AValue:Cardinal):WideString; begin Result := TablesNTSTATUSToString(AValue); end; Class Function TGeneralRequest.IRQLToString(AValue:Byte):WideString; begin Result := Format('%u', [AValue]); Case AValue Of 0 : Result := 'Passive'; 1 : Result := 'APC'; 2 : Result := 'Dispatch'; {$IFDEF WIN32} 27 : Result := 'Profile'; 28 : Result := 'Clock'; 29 : Result := 'IPI'; 30 : Result := 'Power'; 31 : Result := 'High'; {$ELSE} 13 : Result := 'Clock'; 14 : Result := 'Profile, IPI, Power'; 15 : Result := 'High'; {$ENDIF} Else Result := 'Interrupt'; end; end; Class Function TGeneralRequest.AccessModeToString(AMode:Byte):WideString; begin Case AMode Of 0 : Result := 'KernelMode'; 1 : Result := 'UserMode'; Else Result := Format('<unknown> (%u)', [AMode]); end; end; Class Function TGeneralRequest.ImageSignatureTypeToString(AType:EImageSignatureType):WideString; begin Result := ''; Case AType Of istNone: Result := 'None'; istEmbedded: Result := 'Embedded'; istCache: Result := 'Cached'; istCatalogCached: Result := 'Catalog cached'; istCatalogNotCached: Result := 'Catalog'; istCatalogHint: Result := 'Catalog hint'; istPackageCatalog: Result := 'Catalog package'; end; end; Class Function TGeneralRequest.ImageSigningLevelToString(ALevel:EImageSigningLevel):WideString; begin Result := ''; Case ALevel Of islUnchecked: Result := 'Unchecked'; islUnsigned: Result := 'Unsigned'; islEnterprise: Result := 'Enterprise'; islDeveloper: Result := 'Developer'; islAuthenticode: Result := 'Authenticode'; islCustom2: Result := 'Custom2'; islStore: Result := 'Store'; islAntiMalware: Result := 'Anti-malware'; islMicrosoft: Result := 'Microsoft'; islCustom4: Result := 'Custom4'; islCustom5: Result := 'Custom5'; islDynamicCode: Result := 'DynamicCode'; islWindows: Result := 'Windows'; islCustom7: Result := 'Custom7'; islWindowsTCB: Result := 'Windows TCB'; islCustom6: Result := 'Custom6'; end; end; End.
//--------------------------------------------------------------- // CharPrinter.pas - Tratamento de impressoras em modo caractere //--------------------------------------------------------------- // Autor : Fernando Allen Marques de Oliveira // Dezembro de 2000. // // TPrinterStream : classe derivada de TStream para enviar dados // diretamente para o spool da impressora sele- // cionada. // // TCharPrinter : Classe base para implementação de impressoras. // não inclui personalização para nenhuma impres- // sora específica, envia dados sem formatação. // // Modificado em 20/05/2003 - Compatibilização com diretivas padrão do Delphi 7 // Modificado em 21/07/2014 - Compatibilidade com ESC/POS Zyzmo[CODE] // Modifidado em 22/07/2014 - Compatibilidade com ESCBema (Bematech) unit CharPrinter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Printers, WinSpool; type { Stream para enviar caracteres à impressora atual } TPrinterStream = class (TStream) private fPrinter : TPrinter; fHandle : THandle; fTitle : String; procedure CreateHandle; procedure FreeHandle; public constructor Create (aPrinter: TPrinter; aTitle : String); destructor Destroy; override; function Write (const Buffer; Count : Longint): Longint; override; property Handle : THandle read fHandle; end; TCharPrinter = class(TObject) private { Private declarations } fStream : TStream; protected { Protected declarations } public { Public declarations } published { Published declarations } constructor Create; virtual; destructor Destroy; override; procedure OpenDoc (aTitle : String); virtual; procedure SendData (aData : String); procedure CloseDoc; virtual; property PrintStream : TStream read fStream; end; // Definições para TAdvancedPrinter // TprtLang = (lngEPFX,lngESCP2,lngHPPCL,lngESCPOS,lngESCBEMA); TprtFontSize = (pfs5cpi,pfs10cpi,pfs12cpi,pfs17cpi,pfs20cpi); TprtTextStyle = (psBold,psItalic,psUnderline); TprtTextStyles = set of TprtTextStyle; TAdvancedPrinter = class (TCharPrinter) private fLang : TprtLang; fFontSize : TprtFontSize; fTextStyle : TprtTextStyles; function GetLang : TprtLang; procedure SetFontSize (size : TprtFontSize); function GetFontSize : TprtFontSize; procedure SetTextStyle (styles : TprtTextStyles); function GetTextStyle : TprtTextStyles; procedure UpdateStyle; procedure Initialize; function Convert (s : string) : string; public procedure CR; procedure LF; overload; procedure LF (Lines : integer); overload; procedure CRLF; procedure FF; procedure Write (txt : string); procedure WriteLeft (txt, fill : string; size : integer); procedure WriteRight (txt, fill : string; size : integer); procedure WriteCenter(txt, fill : string; size : integer); procedure WriteRepeat(txt : string; quant : integer); procedure SetLang (lang : TprtLang); published constructor Create; override; procedure OpenDoc (aTitle : String); override; property Language : TprtLang read GetLang write SetLang; property FontSize : TprtFontSize read GetFontSize write SetFontSize; property TextStyle : TprtTextStyles read GetTextStyle write SetTextStyle; end; procedure Register; implementation procedure Register; begin { RegisterComponents(´AeF´, [TCharPrinter]);} end; { =================== } { = TPrinterStream = } { =================== } constructor TPrinterStream.Create (aPrinter : TPrinter; aTitle : String); begin inherited Create; fPrinter := aPrinter; fTitle := aTitle; CreateHandle; end; destructor TPrinterStream.Destroy; begin FreeHandle; inherited; end; procedure TPrinterStream.FreeHandle; begin if fHandle <> 0 then begin EndPagePrinter (fHandle); EndDocPrinter (fHandle); ClosePrinter (Handle); fHandle := 0; end; end; procedure TPrinterStream.CreateHandle; type DOC_INFO_1 = packed record pDocName : PChar; pOutputFile : PChar; pDataType : PChar; end; var aDevice, aDriver, aPort : array[0..255] of Char; aMode : Cardinal; DocInfo : DOC_INFO_1; begin DocInfo.pDocName := nil; DocInfo.pOutputFile := nil; DocInfo.pDataType := 'RAW'; FreeHandle; if fHandle = 0 then begin fPrinter.GetPrinter (aDevice, aDriver, aPort, aMode); if OpenPrinter (aDevice, fHandle, nil)then begin DocInfo.pDocName := PChar(fTitle); if StartDocPrinter (fHandle, 1, @DocInfo) = 0 then begin ClosePrinter (fHandle); fHandle := 0; end else if not StartPagePrinter (fHandle)then begin EndDocPrinter (fHandle); ClosePrinter (fHandle); fHandle := 0; end; end; end; end; function TPrinterStream.Write (const Buffer; Count : Longint) : Longint; var Bytes : Cardinal; begin WritePrinter (Handle, @Buffer, Count, Bytes); Result := Bytes; end; { ================= } { = TCharPrinter = } { ================= } constructor TCharPrinter.Create; begin inherited Create; fStream := nil; end; destructor TCharPrinter.Destroy; begin if fStream <> nil then fStream.Free; inherited; end; procedure TCharPrinter.OpenDoc (aTitle : String); begin if fStream = nil then begin fStream := TPrinterStream.Create (Printer, aTitle); end; end; procedure TCharPrinter.CloseDoc; begin if fStream <> nil then begin fStream.Free; fStream := nil; end; end; procedure TCharPrinter.SendData (aData : String); var Data : array[0..255] of char; cnt : integer; begin for cnt := 0 to length(aData) - 1 do Data[cnt] := aData[cnt+1]; fStream.Write (Data, length(aData)); end; { ===================== } { = TAdvancedPrinter = } { ===================== } procedure TAdvancedPrinter.SetLang (lang : TprtLang); begin fLang := lang; end; function TAdvancedPrinter.GetLang : TprtLang; begin result := fLang; end; procedure TAdvancedPrinter.SetFontSize (size : TprtFontSize); begin fFontSize := size; UpdateStyle; end; function TAdvancedPrinter.GetFontSize : TprtFontSize; begin result := fFontSize; UpdateStyle; end; procedure TAdvancedPrinter.SetTextStyle (styles : TprtTextStyles); begin fTextStyle := styles; UpdateStyle; end; function TAdvancedPrinter.GetTextStyle : TprtTextStyles; begin result := fTextStyle; UpdateStyle; end; procedure TAdvancedPrinter.UpdateStyle; var cmd : string; i : byte; begin cmd := ''; case fLang of lngESCP2, lngEPFX: begin i := 0; Case fFontSize of pfs5cpi : i := 32; pfs10cpi : i := 0; pfs12cpi : i := 1; pfs17cpi : i := 4; pfs20cpi : i := 5; end; if psBold in fTextStyle then i := i + 8; if psItalic in fTextStyle then i := i + 64; if psUnderline in fTextStyle then i := i + 128; cmd := #27'!'+chr(i); end; lngHPPCL : begin Case fFontSize of pfs5cpi : cmd := #27+'(s5H'; pfs10cpi : cmd := #27+'(s10H'; pfs12cpi : cmd := #27+'(s12H'; pfs17cpi : cmd := #27+'(s17H'; pfs20cpi : cmd := #27+'(s20H'; end; if psBold in fTextStyle then cmd := cmd + #27+'(s3B' else cmd := cmd + #27+'(s0B'; if psItalic in fTextStyle then cmd := cmd + #27+'(s1S' else cmd := cmd + #27+'(s0S'; if psUnderline in fTextStyle then cmd := cmd + #27+'&d0D' else cmd := cmd + #27+'&d@'; end; end; SendData(cmd); end; procedure TAdvancedPrinter.Initialize; begin case fLang of lngEPFX : SendData (#27+'@'+#27+'2'+#27+'P'+#18); lngESCP2 : SendData (#27+'@'+#27+'O'+#27+'2'+#27+'C0'+#11+#27+'!'+ #0); lngESCPOS : SendData (#27+ '@' (*+ #29 + #249 + #31 + #49*) ); lngHPPCL : SendData (#27+'E'+#27+'&l2A'+#27+'&l0O'+#27+'&l6D'+#27+'(s4099T'+#27+'(s0P'+#27+'&k0S'+#27+'(s0S'); lngESCBEMA: SendData (#27+ '@'+#29+#249+#32+#0+#27+#116+#8); end; end; function TAdvancedPrinter.Convert (s : string) : string; const accent : string = 'ãàáäâèéëêìíïîõòóöôùúüûçÃÀÁÄÂÈÉËÊÌÍÏÎÕÒÓÖÔÙÚÜÛÇ'; noaccent : string = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC'; var i : integer; begin for i := 1 to length(accent) do While Pos(accent[i],s) > 0 do s[Pos(accent[i],s)] := noaccent[i]; result := s; end; constructor TAdvancedPrinter.Create; begin inherited Create; fLang := lngESCPOS; fFontSize := pfs10cpi; fTextStyle := []; end; procedure TAdvancedPrinter.OpenDoc (aTitle : String); begin inherited OpenDoc (aTitle); Initialize; end; procedure TAdvancedPrinter.CR; begin SendData (#13); end; procedure TAdvancedPrinter.LF; begin SendData (#10); end; procedure TAdvancedPrinter.LF (Lines : integer); begin while lines > 0 do begin SendData(#10); dec(lines); end; end; procedure TAdvancedPrinter.CRLF; begin SendData (#13+#10); end; procedure TAdvancedPrinter.FF; begin SendData(#12); end; procedure TAdvancedPrinter.Write (txt : string); begin txt := Convert (txt); SendData (txt); end; procedure TAdvancedPrinter.WriteLeft (txt, fill : string; size : integer); begin txt := Convert(txt); while Length(txt) < size do txt := txt + fill; SendData (Copy(txt,1,size)); end; procedure TAdvancedPrinter.WriteRight (txt, fill : string; size : integer); begin txt := Convert(txt); while Length(txt) < size do txt := fill + txt; SendData (Copy(txt,Length(txt)-size+1,size)); end; procedure TAdvancedPrinter.WriteCenter(txt, fill : string; size : integer); begin txt := Convert(txt); while Length(txt) < size do txt := fill + txt + fill; SendData (Copy(txt,(Length(txt)-size) div 2 + 1,size)); end; procedure TAdvancedPrinter.WriteRepeat(txt : string; quant : integer); var s : string; begin s := ''; txt := Convert(txt); while quant > 0 do begin s := s + txt; dec(quant); end; SendData (s); end; end.
unit uFormBackgroundTaskStatus; interface uses Winapi.Windows, Winapi.Messages, System.Types, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Themes, Dmitry.Controls.Base, Dmitry.Controls.LoadingSign, uMemory, uFormUtils, uBitmapUtils, uThemesUtils, uDBForm, uFormInterfaces; type TFormBackgroundTaskStatus = class(TDBForm, IBackgroundTaskStatusForm) LbMessage: TLabel; LsMain: TLoadingSign; TmrRedraw: TTimer; procedure TmrRedrawTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Private declarations } FLoadingState: Extended; FText: string; FMouseCaptured: Boolean; FCapturedPosition: TPoint; FFormPosition: TPoint; FCanBeClosed: Boolean; procedure DrawForm; protected function GetFormID: string; override; procedure InterfaceDestroyed; override; function DisableMasking: Boolean; override; public { Public declarations } function ShowModal: Integer; override; procedure SetProgress(Max, Position: Int64); procedure SetText(Text: string); procedure CloseForm; end; implementation {$R *.dfm} procedure TFormBackgroundTaskStatus.CloseForm; begin FCanBeClosed := True; Close; end; function TFormBackgroundTaskStatus.DisableMasking: Boolean; begin Result := True; end; procedure TFormBackgroundTaskStatus.DrawForm; var Bitmap : TBitmap; R: TRect; begin Bitmap := TBitmap.Create; try Bitmap.Width := Width; Bitmap.Height := Height; FillTransparentColor(Bitmap, clBlack, 0); DrawRoundGradientVert(Bitmap, Rect(0, 0, Width, Height), Theme.GradientFromColor, Theme.GradientToColor, Theme.HighlightColor, 8, 240); DrawLoadingSignImage(LsMain.Left, LsMain.Top, Round((LsMain.Height div 2) * 70 / 100), LsMain.Height, Bitmap, clBlack, FLoadingState, 240); if StyleServices.Enabled and TStyleManager.IsCustomStyleActive then Font.Color := Theme.GradientText; R := Rect(LsMain.Left + LsMain.Width + 5, LsMain.Top, ClientWidth, ClientHeight); DrawText32Bit(Bitmap, LbMessage.Caption, Font, R, 0); RenderForm(Self.Handle, Bitmap, 220); finally F(Bitmap); end; end; procedure TFormBackgroundTaskStatus.SetProgress(Max, Position: Int64); begin LbMessage.Caption := StringReplace(FText, '%', IntToStr(Round(Position * 100 / Max)) + '%', []); DrawForm; end; procedure TFormBackgroundTaskStatus.SetText(Text: string); begin FText := Text; end; function TFormBackgroundTaskStatus.ShowModal: Integer; begin DrawForm; Result := inherited ShowModal; end; procedure TFormBackgroundTaskStatus.FormClose(Sender: TObject; var Action: TCloseAction); begin if FCanBeClosed then Action := caHide else Action := caNone; end; procedure TFormBackgroundTaskStatus.FormCreate(Sender: TObject); begin LbMessage.Caption := L('Please wait...'); FMouseCaptured := False; FCanBeClosed := False; end; procedure TFormBackgroundTaskStatus.FormDestroy(Sender: TObject); begin TmrRedraw.Enabled := False; end; procedure TFormBackgroundTaskStatus.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin FMouseCaptured := True; FCapturedPosition := Point(X, Y); FCapturedPosition := ClientToScreen(FCapturedPosition); FFormPosition := Point(Left, Top); end; end; procedure TFormBackgroundTaskStatus.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var P: TPoint; begin if FMouseCaptured then begin P := Point(X, Y); P := ClientToScreen(P); Left := FFormPosition.X + (P.X - FCapturedPosition.X); Top := FFormPosition.Y + (P.Y - FCapturedPosition.Y); end; end; procedure TFormBackgroundTaskStatus.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FMouseCaptured := False; end; function TFormBackgroundTaskStatus.GetFormID: string; begin Result := 'BackgroundTaskStatus'; end; procedure TFormBackgroundTaskStatus.InterfaceDestroyed; begin inherited; Release; end; procedure TFormBackgroundTaskStatus.TmrRedrawTimer(Sender: TObject); begin DrawForm; end; initialization FormInterfaces.RegisterFormInterface(IBackgroundTaskStatusForm, TFormBackgroundTaskStatus); end.
{ Zur VCL kompatible grafische Objekte, die keine Windows-Ressourcen brauchen und intern Vektorgrafiken anlegen, die man auch als Dateien speichern kann } unit Drawings; interface uses Classes, Graphics, SysUtils; type TVectorBrush = class(TPersistent) private FBitmap: TBitmap; FColor: TColor; FStyle: TBrushStyle; function GetBitmap: TBitmap; procedure SetBitmap(Value: TBitmap); protected procedure AssignTo(Dest: TPersistent); override; public destructor Destroy; override; property Bitmap: TBitmap read GetBitmap write SetBitmap; published property Color: TColor read FColor write FColor; property Style: TBrushStyle read FStyle write FStyle; end; TVectorCanvas = class(TPersistent) private FBrush: TVectorBrush; FOnChange, FOnChanging: TNotifyEvent; function GetBrush: TVectorBrush; procedure SetBrush(Value: TVectorBrush); protected procedure Changed; virtual; procedure Changing; virtual; public destructor Destroy; override; published property Brush: TVectorBrush read GetBrush write SetBrush; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; end; implementation function TVectorBrush.GetBitmap: TBitmap; begin if not Assigned(FBitmap) then FBitmap := TBitmap.Create; Result := FBitmap; end; procedure TVectorBrush.SetBitmap(Value: TBitmap); begin GetBitmap.Assign(Value) end; procedure TVectorBrush.AssignTo(Dest: TPersistent); begin try (Dest as TVectorBrush).Bitmap := Bitmap; (Dest as TVectorBrush).Color := Color; (Dest as TVectorBrush).Style := Style; except on EInvalidCast do try (Dest as TBrush).Bitmap := Bitmap; (Dest as TBrush).Color := Color; (Dest as TBrush).Style := Style; except on EInvalidCast do inherited AssignTo(Dest) end end end; destructor TVectorBrush.Destroy; begin FBitmap.Free; inherited Destroy end; function TVectorCanvas.GetBrush: TVectorBrush; begin if not Assigned(FBrush) then FBrush := TVectorBrush.Create; Result := FBrush; end; procedure TVectorCanvas.SetBrush(Value: TVectorBrush); begin GetBrush.Assign(Value) end; procedure TVectorCanvas.Changed; begin if Assigned(FOnChange) then FOnChange(Self) end; procedure TVectorCanvas.Changing; begin if Assigned(FOnChanging) then FOnChanging(Self) end; destructor TVectorCanvas.Destroy; begin FBrush.Free; inherited Destroy; end; end.
unit ufrmDialogMerchandise; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, Vcl.StdCtrls, uModBarang, uInterface, uModSuplier; type TfrmDialogMerchandise = class(TfrmMasterDialog, ICRUDAble) lbKode: TLabel; edtCode: TEdit; edtName: TEdit; lbNama: TLabel; procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private FModMerchandise: TModMerchandise; function GetModMerchandise: TModMerchandise; { Private declarations } public procedure LoadData(AID: String); function SaveData: Boolean; property ModMerchandise: TModMerchandise read GetModMerchandise write FModMerchandise; { Public declarations } end; var frmDialogMerchandise: TfrmDialogMerchandise; implementation uses uDMClient, uDXUtils, uApputils, uConstanta; {$R *.dfm} procedure TfrmDialogMerchandise.actDeleteExecute(Sender: TObject); begin inherited; if not TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then exit; Try DMCLient.CrudClient.DeleteFromDB(ModMerchandise); TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); Self.Close; except TAppUtils.Error(ER_DELETE_FAILED); raise; End; end; procedure TfrmDialogMerchandise.actSaveExecute(Sender: TObject); begin inherited; if SaveData then Self.ModalResult := mrOk; end; procedure TfrmDialogMerchandise.FormCreate(Sender: TObject); begin inherited; Self.AssignKeyDownEvent; end; function TfrmDialogMerchandise.GetModMerchandise: TModMerchandise; begin if not Assigned(FModMerchandise) then FModMerchandise := TModMerchandise.Create; Result := FModMerchandise; end; procedure TfrmDialogMerchandise.LoadData(AID: String); begin if Assigned(FModMerchandise) then FreeAndNil(FModMerchandise); FModMerchandise := DMClient.CrudClient.Retrieve(TModMerchandise.ClassName, aID) as TModMerchandise; edtCode.Text := ModMerchandise.MERCHAN_CODE; edtName.Text := ModMerchandise.MERCHAN_NAME; end; function TfrmDialogMerchandise.SaveData: Boolean; begin Result := False; if not ValidateEmptyCtrl then exit; ModMerchandise.MERCHAN_CODE := edtCode.Text; ModMerchandise.MERCHAN_NAME := edtName.Text; Try ModMerchandise.ID := DMClient.CrudClient.SaveToDBID(ModMerchandise); if ModMerchandise.ID <> '' then Result := True; TAppUtils.Information(CONF_ADD_SUCCESSFULLY); except // TAppUtils.Error(ER_INSERT_FAILED); raise; End; end; end.
unit wwStacks; { // // Simple stack classes to support the parsing of table filters // // Copyright (c) 1995 by Woll2Woll Software // } interface uses classes; type { TNode = Class; PTNode = ^TNode; } TStackStr = class private list: TStringList; public procedure push(s: string); function pop: string; constructor create; destructor destroy; override; function count: integer; end; TStackPtr = class private list: TList; public procedure push(s: Pointer); function pop: Pointer; constructor create; destructor destroy; override; function count: integer; end; implementation constructor TStackStr.create; begin list:= TStringList.create; list.sorted:= False; end; destructor TStackStr.destroy; begin list.free; list:= Nil; end; Function TStackStr.count: integer; begin result:= list.count; end; procedure TStackStr.push(s: string); begin list.add(s); end; function TStackStr.pop: string; begin if list.count=0 then result:= '' else begin result:= list[list.count-1]; list.delete(list.count-1); end end; constructor TStackPtr.create; begin list:= TList.create; end; Function TStackPtr.count: integer; begin result:= list.count; end; destructor TStackPtr.destroy; begin list.free; list:= Nil; end; procedure TStackPtr.push(s: Pointer); begin list.add(s); end; function TStackPtr.Pop: Pointer; begin if list.count=0 then result:= Nil else begin result:= list[list.count-1]; list.delete(list.count-1); end end; end.
PROGRAM quicksort; TYPE IntegerArray = array of integer; Procedure QuickSort(Var X : IntegerArray); Procedure Sort ( Left, Right : LongInt ); Var i, j : LongInt; tmp, pivot : LongInt; { tmp & pivot are the same type as the elements of array } Begin i:=Left; j:=Right; pivot := X[(Left + Right) shr 1]; // pivot := X[(Left + Rigth) div 2] Repeat While pivot > X[i] Do i:=i+1; While pivot < X[j] Do j:=j-1; If i<=j Then Begin tmp:=X[i]; X[i]:=X[j]; X[j]:=tmp; j:=j-1; i:=i+1; End; Until i>j; If Left<j Then Sort(Left,j); If i<Right Then Sort(i,Right); End; Begin Sort(0, Length(X) - 1); END; var data: IntegerArray; i: integer; begin { Dynamically initialize array } SetLength(data, 10); write('Creating ',10,' random numbers between 1 and 500000'); randomize; for i := 0 to 9 do data[i] := 1 + random(100); writeln('Sorting...'); writeln('Printing the last ',10,' numbers:'); for i in data do begin writeln(i); end; QuickSort(data); writeln('Printing the last ',10,' numbers:'); for i in data do begin writeln(i); end; end.
unit uEditoraModel; interface uses uGenericEntity; type TEditoraModel = class private FCodigo: Integer; FNome: String; procedure SetCodigo(const Value: Integer); procedure SetNome(const Value: String); public property Codigo: Integer read FCodigo write SetCodigo; property Nome: String read FNome write SetNome; constructor Create(ACodigo: Integer = 0; ANome: String = ''); end; implementation uses SysUtils; { TEditoraModel } constructor TEditoraModel.Create(ACodigo: Integer; ANome: String); begin FCodigo := ACodigo; FNome := ANome; end; procedure TEditoraModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TEditoraModel.SetNome(const Value: String); begin FNome := Value; end; end.
unit ASyncDB; //unit implementing a background thread. //may be usefull for applications that want to do background logging. //is not essential part of libsql. interface {$IFDEF FPC} {$MODE DELPHI} {$H+} {$ENDIF} uses {$IFNDEF LINUX} Windows, //sleep function {$ENDIF} SysUtils, Classes, syncobjs, pasmysql, passqlite, pasODBC, pasjansql, passql, sqlsupport; type //TDatabaseType = (dtSqlite, dtMySQL, dtODBC); TDBData = class SQL: String; Results: TResultSet; Handle: Integer; UserData: Integer; end; TDBThread = class; TOnDBData = procedure (Sender: TComponent; db: TSQLDB; Data: TDBData) of object; TASyncDB = class(TComponent) private { Private declarations } CS: TCriticalSection; Queue: TList; FHandleCount: Integer; FUser: String; FDatabase: String; FPass: String; FHost: String; FDBType: TDBMajorType; FActive: Boolean; FOnSuccess: TOnDBData; FOnFailure: TOnDBData; FMaxQueue: Integer; procedure SetDatabase(const Value: String); procedure SetDBType(const Value: TDBMajorType); procedure SetHost(const Value: String); procedure SetPass(const Value: String); procedure SetUser(const Value: String); procedure SetActive(const Value: Boolean); procedure SetOnFailure(const Value: TOnDBData); procedure SetOnSuccess(const Value: TOnDBData); procedure SetMaxQueue(const Value: Integer); protected { Protected declarations } FThread: TDBThread; db: TSqlDB; //used for format function public { Public declarations } constructor Create (AOwner: TComponent); override; destructor Destroy; override; function Query (SQL: String; UserData: Integer=0): Integer; function FormatQuery (SQL: String; const Args: array of const; UserData: Integer=0): Integer; published { Published declarations } property Active: Boolean read FActive write SetActive; property DBType: TDBMajorType read FDBType write SetDBType; property User: String read FUser write SetUser; property Pass: String read FPass write SetPass; property Host: String read FHost write SetHost; property Database: String read FDatabase write SetDatabase; property MaxQueue: Integer read FMaxQueue write SetMaxQueue; property OnSuccess: TOnDBData read FOnSuccess write SetOnSuccess; property OnFailure: TOnDBData read FOnFailure write SetOnFailure; end; TDBThread = class (TThread) Owner: TASyncDB; db: TSqlDB; error: String; data: TDBData; dbtype: TDBMajorType; procedure Execute; override; procedure SyncSuccess; procedure SyncFailure; { TASyncDB } end; procedure Register; implementation //{ $R *.dcr} constructor TASyncDB.Create(AOwner: TComponent); begin inherited Create (AOwner); Queue := TList.Create; CS := TCriticalSection.Create; FMaxQueue := 8192; //some arbitrary value //needed for formatquery thingy. //db := TSqlDB.Create (Self); end; destructor TASyncDB.Destroy; begin Active := False; CS.Free; Queue.Free; //db.Free; inherited Destroy; end; function TASyncDB.FormatQuery(SQL: String; const Args: array of const; UserData: Integer=0): Integer; var s: String; w: WideString; begin Result := -1; try if Assigned (FThread) and Assigned (FThread.db) then begin TSQLDB._FormatSql (s,w,SQL, Args, False, dbType); Result := Query (s, UserData); end; except end; end; function TASyncDB.Query(SQL: String; UserData: Integer=0): Integer; var data: TDBData; begin CS.Enter; if Queue.Count <= FMaxQueue then begin data := TDBData.Create; data.SQL := SQL; data.UserData := UserData; inc (FHandleCount); Result := FHandleCount; data.Handle := FHandleCount; Queue.Add (data); end else Result := -1; CS.Leave; end; procedure TASyncDB.SetActive(const Value: Boolean); begin if FActive and not Value then begin FThread.Terminate; FThread.WaitFor; FThread.Free; FThread := nil; end; if not FActive and Value then begin FThread := TDBThread.Create (True); FThread.Owner := Self; FThread.Resume; end; FActive := Value; end; procedure TASyncDB.SetDatabase(const Value: String); begin CS.Enter; FDatabase := Value; CS.Leave; end; procedure TASyncDB.SetDBType(const Value: TDBMajorType); begin CS.Enter; FDBType := Value; CS.Leave; end; procedure TASyncDB.SetHost(const Value: String); begin CS.Enter; FHost := Value; CS.Leave; end; procedure TASyncDB.SetMaxQueue(const Value: Integer); begin FMaxQueue := Value; end; procedure TASyncDB.SetOnFailure(const Value: TOnDBData); begin FOnFailure := Value; end; procedure TASyncDB.SetOnSuccess(const Value: TOnDBData); begin FOnSuccess := Value; end; procedure TASyncDB.SetPass(const Value: String); begin CS.Enter; FPass := Value; CS.Leave; end; procedure TASyncDB.SetUser(const Value: String); begin CS.Enter; FUser := Value; CS.Leave; end; { TDBThread } procedure TDBThread.Execute; var dbloaded: Boolean; begin //launch appropiate db type //and perform queries dbloaded := False; Owner.CS.Enter; case Owner.FDBType of dbMySQL: begin db := TMyDB.Create (nil); dbloaded := db.Connect (Owner.FHost, Owner.FUser, Owner.FPass, Owner.FDatabase); dbtype := dbMySQL; end; dbSqlite: begin db := TLiteDB.Create (nil); dbloaded := db.Use (Owner.FDatabase); dbtype := dbSqlite; end; dbODBC: begin db := TODBCDB.Create (nil); dbloaded := db.Connect (Owner.FHost, Owner.FUser, Owner.FPass, Owner.FDatabase); dbtype := dbODBC; end; dbJanSQL: begin db := TJanDB.Create(nil); dbloaded := db.Connect (Owner.FHost, Owner.FUser, Owner.FPass, Owner.FDatabase); dbType := dbJanSQL; end; end; Owner.CS.Leave; if not dbloaded then begin Owner.CS.Enter; Owner.FActive := False; FreeOnTerminate := True; Owner.CS.Leave; Terminate; end; while not Terminated do begin //see if there is anything in queue //if so, process. data := nil; Owner.CS.Enter; if Owner.Queue.Count > 0 then begin data := Owner.Queue[0]; Owner.Queue.Delete (0); end; Owner.CS.Leave; if Assigned (data) then begin db.Query (data.SQL); data.Results := db.CurrentResult; if db.LastError = 0 then SyncSuccess else SyncFailure; end else sleep (200); end; end; procedure TDBThread.SyncFailure; begin try if Assigned (Owner.OnFailure) then Owner.OnFailure (Owner, db, data); except end; end; procedure TDBThread.SyncSuccess; begin try if Assigned (Owner.OnSuccess) then Owner.OnSuccess (Owner, db, data); except end; end; procedure Register; begin RegisterComponents('libsql', [TASyncDB]); end; end.
unit KeyboardEntryDlg_U; // Description: "Secure Keyboard Entry" Dialog // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // This is a simple dialog that permits the user to easily add a slightly more // secure method of entering passwords and other sensitive data into a Delphi // application // // Features include: // The use of images, rather that text captions for the keytops to reduce the success rate of snooping software // "Speckled" images for buttons to reduce the effectiveness of "key" recognition software // Random "key" placement, again to reduce the success rate of snooping software // // Note: This component is not perfect; the RNG used is the standard Delphi // pseudorandom one, and the "speckling" of the keytops provides minimum // protection ("Speckling" was introduced to prevent an attacker from just // reading the text straight off the screen, and forces him/her to stick an // extra "despeckle" operation in there! ;) // // Attacking the protection that this dialog provides would be trivial; just // write a program that detects a window being displayed with a "Scramble // Keys" button on it. After that, hook the mouse messages, and every time the // left mousebutton is pressed, take a screenshot of the dialog, and with it // record the X & Y co-ords of the mouse within the dialog. // Later, recover the images and info, and just watch what "keys" are being // pressed on the dialog. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, SDUForms; const KEYS = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1!2"3£4$5%6^7&8*9(0)-_=+`¬[{]};:''@#~\|,<.>/? '; type TKeyboardEntryDlg = class(TSDUForm) pbScramble: TButton; edPassword: TEdit; pnlKey1: TPanel; pnlKey3: TPanel; pnlKey2: TPanel; pnlKey10: TPanel; pnlKey9: TPanel; pnlKey8: TPanel; pnlKey7: TPanel; pnlKey6: TPanel; pnlKey5: TPanel; pnlKey4: TPanel; pnlKey11: TPanel; pnlKey13: TPanel; pnlKey12: TPanel; pnlKey20: TPanel; pnlKey19: TPanel; pnlKey18: TPanel; pnlKey17: TPanel; pnlKey16: TPanel; pnlKey15: TPanel; pnlKey14: TPanel; pnlKey21: TPanel; pnlKey23: TPanel; pnlKey22: TPanel; pnlKey30: TPanel; pnlKey29: TPanel; pnlKey28: TPanel; pnlKey27: TPanel; pnlKey26: TPanel; pnlKey25: TPanel; pnlKey24: TPanel; pnlKey31: TPanel; pnlKey33: TPanel; pnlKey32: TPanel; pnlKey40: TPanel; pnlKey39: TPanel; pnlKey38: TPanel; pnlKey37: TPanel; pnlKey36: TPanel; pnlKey35: TPanel; pnlKey34: TPanel; pnlKey41: TPanel; pnlKey43: TPanel; pnlKey42: TPanel; pnlKey50: TPanel; pnlKey49: TPanel; pnlKey48: TPanel; pnlKey47: TPanel; pnlKey46: TPanel; pnlKey45: TPanel; pnlKey44: TPanel; ckShift: TCheckBox; pbCancel: TButton; Label1: TLabel; pbClear: TButton; igKey1: TImage; igKey2: TImage; igKey3: TImage; igKey4: TImage; igKey5: TImage; igKey6: TImage; igKey7: TImage; igKey8: TImage; igKey9: TImage; igKey10: TImage; igKey20: TImage; igKey19: TImage; igKey18: TImage; igKey17: TImage; igKey16: TImage; igKey15: TImage; igKey14: TImage; igKey13: TImage; igKey12: TImage; igKey11: TImage; igKey21: TImage; igKey22: TImage; igKey23: TImage; igKey24: TImage; igKey25: TImage; igKey26: TImage; igKey27: TImage; igKey28: TImage; igKey29: TImage; igKey30: TImage; igKey40: TImage; igKey39: TImage; igKey38: TImage; igKey37: TImage; igKey36: TImage; igKey35: TImage; igKey34: TImage; igKey33: TImage; igKey32: TImage; igKey31: TImage; igKey41: TImage; igKey42: TImage; igKey43: TImage; igKey44: TImage; igKey45: TImage; igKey46: TImage; igKey47: TImage; igKey48: TImage; igKey49: TImage; igKey50: TImage; pbOK: TButton; procedure pbScrambleClick(Sender: TObject); procedure ckShiftClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbClearClick(Sender: TObject); procedure igKeyClick(Sender: TObject); procedure igKeyDblClick(Sender: TObject); procedure FormShow(Sender: TObject); private KeysArray: array [1..100] of char; procedure DefaultKeys(); procedure PaintPanelBitmap(theString: string; thePicture: TPicture); procedure RandomizeCaption(); procedure RefreshKeyTops(); public Password: string; procedure BlankPassword(); end; implementation {$R *.DFM} procedure TKeyboardEntryDlg.pbScrambleClick(Sender: TObject); var i: integer; firstKey: integer; secondKey: integer; tempA: char; tempB: char; begin randomize; for i:=1 to 1000 do begin firstKey := (random(50)*2)+1; secondKey := (random(50)*2)+1; tempA := KeysArray[firstKey]; tempB := KeysArray[firstKey+1]; KeysArray[firstKey] := KeysArray[secondKey]; KeysArray[firstKey+1] := KeysArray[secondKey+1]; KeysArray[secondKey] := tempA; KeysArray[secondKey+1] := tempB; end; RefreshKeyTops(); end; procedure TKeyboardEntryDlg.DefaultKeys(); var i: integer; begin for i:=1 to 100 do begin KeysArray[i] := KEYS[i]; end; ckShiftClick(nil); end; procedure TKeyboardEntryDlg.ckShiftClick(Sender: TObject); begin RefreshKeyTops(); end; procedure TKeyboardEntryDlg.FormCreate(Sender: TObject); begin DefaultKeys(); RandomizeCaption(); end; procedure TKeyboardEntryDlg.pbClearClick(Sender: TObject); begin edPassword.text := ''; BlankPassword(); RefreshKeyTops(); end; procedure TKeyboardEntryDlg.PaintPanelBitmap(theString: string; thePicture: TPicture); var bitmap: TBitmap; P : PByteArray; rNum: integer; x, y: integer; begin if theString=' ' then begin theString:='<sp>'; end; bitmap := thePicture.bitmap; bitmap.width := 19; bitmap.height := 19; // Ensure that the background for the image is clBtnFace bitmap.canvas.brush.color := clBtnFace; bitmap.canvas.FloodFill(0, 0, clBtnFace, fsBorder); // Set the font colour to a random colour that looks like black bitmap.canvas.Font.Color := $00ffffff - (random($00101010) OR $00efefef); //clBlack; bitmap.canvas.Font.CharSet := ANSI_CHARSET; bitmap.PixelFormat := pf24bit; // Write the caption on to the bitmap x := (bitmap.width - bitmap.canvas.TextExtent(theString).cx) div 2; y := (bitmap.height - bitmap.canvas.TextExtent(theString).cy) div 2; bitmap.canvas.textout(x, y, theString); // Speckle the bitmap for y := 0 to bitmap.height -1 do begin P := bitmap.ScanLine[y]; for x := 0 to bitmap.width -1 do begin rNum :=random(200); if (rNum=0) then begin P[(x*3)] := random($10); // blue P[(x*3)+1] := random($10); //green P[(x*3)+2] := random($10); //red end; end; end; end; procedure TKeyboardEntryDlg.igKeyClick(Sender: TObject); var shifted: integer; number: integer; begin if ckShift.checked then begin shifted := 1; end else begin shifted := 0; end; number:= ((TImage(Sender).tag-1)*2) +1; edPassword.text := edPassword.text + '*'; Password := Password + KeysArray[number+shifted]; RefreshKeyTops(); end; procedure TKeyboardEntryDlg.BlankPassword(); var i: integer; begin randomize; for i:=1 to length(Password) do begin {$WARNINGS OFF} // Disable useless warning Password[i] := chr(random(255)); Password[i] := #0; {$WARNINGS ON} end; Password := ''; end; procedure TKeyboardEntryDlg.igKeyDblClick(Sender: TObject); begin // Doubleclicking should add two chars, the first is already added on the // first click, so just add a second for the second click igKeyClick(Sender); end; procedure TKeyboardEntryDlg.RandomizeCaption(); var i: integer; begin self.caption := ''; for i:=1 to random(50) do begin self.caption := self.caption + KEYS[random(length(keys))]; end; end; procedure TKeyboardEntryDlg.RefreshKeyTops(); var shifted: integer; begin if ckShift.checked then begin shifted := 1; end else begin shifted := 0; end; randomize(); PaintPanelBitmap(KeysArray[1+shifted], igKey1.picture); PaintPanelBitmap(KeysArray[3+shifted], igKey2.picture); PaintPanelBitmap(KeysArray[5+shifted], igKey3.picture); PaintPanelBitmap(KeysArray[7+shifted], igKey4.picture); PaintPanelBitmap(KeysArray[9+shifted], igKey5.picture); PaintPanelBitmap(KeysArray[11+shifted], igKey6.picture); PaintPanelBitmap(KeysArray[13+shifted], igKey7.picture); PaintPanelBitmap(KeysArray[15+shifted], igKey8.picture); PaintPanelBitmap(KeysArray[17+shifted], igKey9.picture); PaintPanelBitmap(KeysArray[19+shifted], igKey10.picture); PaintPanelBitmap(KeysArray[21+shifted], igKey11.picture); PaintPanelBitmap(KeysArray[23+shifted], igKey12.picture); PaintPanelBitmap(KeysArray[25+shifted], igKey13.picture); PaintPanelBitmap(KeysArray[27+shifted], igKey14.picture); PaintPanelBitmap(KeysArray[29+shifted], igKey15.picture); PaintPanelBitmap(KeysArray[31+shifted], igKey16.picture); PaintPanelBitmap(KeysArray[33+shifted], igKey17.picture); PaintPanelBitmap(KeysArray[35+shifted], igKey18.picture); PaintPanelBitmap(KeysArray[37+shifted], igKey19.picture); PaintPanelBitmap(KeysArray[39+shifted], igKey20.picture); PaintPanelBitmap(KeysArray[41+shifted], igKey21.picture); PaintPanelBitmap(KeysArray[43+shifted], igKey22.picture); PaintPanelBitmap(KeysArray[45+shifted], igKey23.picture); PaintPanelBitmap(KeysArray[47+shifted], igKey24.picture); PaintPanelBitmap(KeysArray[49+shifted], igKey25.picture); PaintPanelBitmap(KeysArray[51+shifted], igKey26.picture); PaintPanelBitmap(KeysArray[53+shifted], igKey27.picture); PaintPanelBitmap(KeysArray[55+shifted], igKey28.picture); PaintPanelBitmap(KeysArray[57+shifted], igKey29.picture); PaintPanelBitmap(KeysArray[59+shifted], igKey30.picture); PaintPanelBitmap(KeysArray[61+shifted], igKey31.picture); PaintPanelBitmap(KeysArray[63+shifted], igKey32.picture); PaintPanelBitmap(KeysArray[65+shifted], igKey33.picture); PaintPanelBitmap(KeysArray[67+shifted], igKey34.picture); PaintPanelBitmap(KeysArray[69+shifted], igKey35.picture); PaintPanelBitmap(KeysArray[71+shifted], igKey36.picture); PaintPanelBitmap(KeysArray[73+shifted], igKey37.picture); PaintPanelBitmap(KeysArray[75+shifted], igKey38.picture); PaintPanelBitmap(KeysArray[77+shifted], igKey39.picture); PaintPanelBitmap(KeysArray[79+shifted], igKey40.picture); PaintPanelBitmap(KeysArray[81+shifted], igKey41.picture); PaintPanelBitmap(KeysArray[83+shifted], igKey42.picture); PaintPanelBitmap(KeysArray[85+shifted], igKey43.picture); PaintPanelBitmap(KeysArray[87+shifted], igKey44.picture); PaintPanelBitmap(KeysArray[89+shifted], igKey45.picture); PaintPanelBitmap(KeysArray[91+shifted], igKey46.picture); PaintPanelBitmap(KeysArray[93+shifted], igKey47.picture); PaintPanelBitmap(KeysArray[95+shifted], igKey48.picture); PaintPanelBitmap(KeysArray[97+shifted], igKey49.picture); PaintPanelBitmap(KeysArray[99+shifted], igKey50.picture); end; procedure TKeyboardEntryDlg.FormShow(Sender: TObject); begin randomize; self.left := random(screen.width - self.width); self.top := random(screen.height - self.height); self.height := self.height + random(10); self.width := self.width + random(10); end; END.
unit Demo.PieChart.Rotating; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_PieChart_Rotating = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_PieChart_Rotating.GenerateChart; var // Defined as TInterfacedObject No need try..finally Data: IcfsGChartData; ChartNoRotation: IcfsGChartProducer; Chart100Rotation: IcfsGChartProducer; begin // Data Data := TcfsGChartData.Create; Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Language'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Speakers (in millions)') ]); Data.AddRow(['German', 5.85]); Data.AddRow(['French', 1.66]); Data.AddRow(['Italian', 0.316]); Data.AddRow(['Romansh', 0.0791]); // Chart No Rotation ChartNoRotation := TcfsGChartProducer.Create; ChartNoRotation.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; ChartNoRotation.Data.Assign(Data); ChartNoRotation.Options.Title('Swiss Language Use (no rotation)'); ChartNoRotation.Options.Legend('position', 'none'); ChartNoRotation.Options.PieSliceText('label'); // Chart 100 Rotation Chart100Rotation := TcfsGChartProducer.Create; Chart100Rotation.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; Chart100Rotation.Data.Assign(Data); Chart100Rotation.Options.Title('Swiss Language Use (100 degree rotation)'); Chart100Rotation.Options.Legend('position', 'none'); Chart100Rotation.Options.PieStartAngle(100); Chart100Rotation.Options.PieSliceText('label'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="display: flex; width: 100%; height: 100%;">' + '<div id="ChartNoRotation" style="width: 50%"></div>' + '<div id="Chart100Rotation" style="flex-grow: 1;">' + '</div></div>' ); GChartsFrame.DocumentGenerate('ChartNoRotation', ChartNoRotation); GChartsFrame.DocumentGenerate('Chart100Rotation', Chart100Rotation); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_PieChart_Rotating); end.
unit uLogin; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Imaging.pngimage, System.ImageList, Vcl.ImgList, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls; type TEstadoLogin = (elNormal, elEmail, elSenha); TStatusEmail = (seVazio, seMeio, seFinal); TFrmLogin = class(TForm) pnlMain: TPanel; imgAvatar: TImage; imgListAvatar: TImageList; timerAvatar: TTimer; lblEmail: TLabel; edtEmail: TEdit; lblSenha: TLabel; edtSenha: TEdit; btnEntrar: TButton; checkBoxMostrar: TCheckBox; procedure carregarImagemAvatar(index: Integer); procedure mudarEstadoLogin(novoEstado: TEstadoLogin); procedure validarAvatarPiscar(valor1, valor2: Integer); procedure validarStatusEmail; procedure timerAvatarTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edtEmailEnter(Sender: TObject); procedure edtEmailExit(Sender: TObject); procedure edtEmailChange(Sender: TObject); procedure edtSenhaEnter(Sender: TObject); procedure checkBoxMostrarClick(Sender: TObject); private FestadoLogin: TEstadoLogin; FpiscarAvatar: Boolean; FmostrarSenha: Boolean; FstatusEmail: TStatusEmail; public property estadoLogin: TEstadoLogin read FestadoLogin write FestadoLogin; property piscarAvatar: Boolean read FpiscarAvatar write FpiscarAvatar; property statusEmail: TStatusEmail read FstatusEmail write FstatusEmail; property mostrarSenha: Boolean read FmostrarSenha write FmostrarSenha; end; var FrmLogin: TFrmLogin; implementation {$R *.dfm} procedure TFrmLogin.carregarImagemAvatar(index: Integer); begin imgAvatar.Canvas.Pen.Style := psClear; imgAvatar.Canvas.Rectangle(0, 0, imgAvatar.Width + 1, imgAvatar.Height + 1); imgListAvatar.GetBitmap(index, imgAvatar.Picture.Bitmap); end; procedure TFrmLogin.checkBoxMostrarClick(Sender: TObject); var iPasswordChar: String; begin if not (checkBoxMostrar.Checked = mostrarSenha) then begin mostrarSenha := not mostrarSenha; timerAvatar.Interval := 1; if mostrarSenha then begin iPasswordChar := #0; end else begin iPasswordChar := '*'; end; edtSenha.PasswordChar := iPasswordChar[1]; end; end; procedure TFrmLogin.edtEmailChange(Sender: TObject); begin if estadoLogin = elEmail then begin validarStatusEmail; end; end; procedure TFrmLogin.edtEmailEnter(Sender: TObject); begin mudarEstadoLogin(elEmail); end; procedure TFrmLogin.edtEmailExit(Sender: TObject); begin mudarEstadoLogin(elNormal); end; procedure TFrmLogin.edtSenhaEnter(Sender: TObject); begin mudarEstadoLogin(elSenha); carregarImagemAvatar(10); timerAvatar.Interval := 35; end; procedure TFrmLogin.FormCreate(Sender: TObject); begin mudarEstadoLogin(elNormal); statusEmail := seVazio; mostrarSenha := checkBoxMostrar.Checked; end; procedure TFrmLogin.mudarEstadoLogin(novoEstado: TEstadoLogin); begin if novoEstado <> estadoLogin then begin estadoLogin := novoEstado; timerAvatar.Interval := 1; end; end; procedure TFrmLogin.timerAvatarTimer(Sender: TObject); begin if estadoLogin = elNormal then begin validarAvatarPiscar(1,0); end else if estadoLogin = elEmail then begin if Pos('@', edtEmail.Text) <> 0 then begin validarAvatarPiscar(6,5); statusEmail := seFinal; end else if edtEmail.Text <> EmptyStr then begin validarAvatarPiscar(4,3); statusEmail := seMeio; end else begin validarAvatarPiscar(1,2); statusEmail := seVazio; end; end else if estadoLogin = elSenha then begin if checkBoxMostrar.Checked then begin validarAvatarPiscar(9,8); mostrarSenha := True; end else begin validarAvatarPiscar(7,7); mostrarSenha := False; end; end; piscarAvatar := not piscarAvatar; end; procedure TFrmLogin.validarAvatarPiscar(valor1, valor2: Integer); begin if piscarAvatar then begin carregarImagemAvatar(valor1); timerAvatar.Interval := 150; end else begin carregarImagemAvatar(valor2); timerAvatar.Interval := 2000 + random(3000); end; end; procedure TFrmLogin.validarStatusEmail; begin case statusEmail of seFinal: begin if Pos('@', edtEmail.Text) = 0 then begin timerAvatar.Interval := 1; end; end; seMeio: begin if (Pos('@', edtEmail.Text) <> 0) or (edtEmail.Text = EmptyStr) then begin timerAvatar.Interval := 1; end; end; seVazio: begin if edtEmail.Text <> EmptyStr then begin timerAvatar.Interval := 1; end; end; end; end; end.
{ ======================================================================== Unit: HexEdits VCL: THexEdit Version: 1.0 Copyright (C) 1996, Immo Wache ========================================================================} unit HexEdits; interface uses WinTypes, WinProcs, Classes, StdCtrls, ExtCtrls, Controls, Messages, SysUtils, Forms, Graphics, Menus, Buttons, Clipbrd, Dialogs; type // TEditBase =(ebHex, ebDec, ebOct, ebBin); TEditBase = (ebDec, ebHex, ebBin, ebOct); THexEdit = class(TCustomEdit) private FMinValue, FMaxValue: Longint; FValidate: Boolean; FNumBase: TEditBase; procedure SetNumBase(NewValue: TEditBase); procedure SetValue(NewValue: Longint); function GetValue: Longint; function CheckValue(NewValue: Longint): Longint; procedure SetMaxValue(NewValue: Longint); procedure SetMinValue(NewValue: Longint); procedure SetValidate(B: Boolean); function SyntaxOk(const S: string): Boolean; procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; function BaseStrToInt(const S: string): Longint; function IntToBaseStr(Value: Longint): string; protected function IsValidChar(Key: Char): Boolean; virtual; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; function ValidCopy: Boolean; function ValidPaste: Boolean; function ValidCut: Boolean; function ValidDelete: Boolean; public constructor Create(AOwner: TComponent); override; published property AutoSelect; property AutoSize; property Anchors; property BorderStyle; property Color; property NumBase: TEditBase read FNumBase write SetNumBase; property Ctl3D; property DragCursor; property DragMode; property Enabled; property Font; property HideSelection; property MaxLength; property MaxValue: Longint read FMaxValue write SetMaxValue; property MinValue: Longint read FMinValue write SetMinValue; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Validate: Boolean read FValidate write SetValidate; property Value: Longint read GetValue write SetValue; property Visible; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; procedure Register; implementation const // Base: array[TEditBase] of Byte =(16, 10, 8, 2); Base: array[TEditBase] of Byte = (10, 16, 2, 8); constructor THexEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); {force Text to '0'} SetValue(0); end; function THexEdit.BaseStrToInt(const S: string): Longint; var Digit, I: Byte; begin Result := 0; for I := 1 to Length(S) do begin Digit := ord(S[I]) - ord('0'); if Digit > 10 then Dec(Digit, 7); Result := Result * Base[NumBase] + Digit; end; end; function THexEdit.IntToBaseStr(Value: Longint): string; var Ch: Char; begin Result := ''; repeat Ch := '0'; Inc(Ch, Value mod Base[NumBase]); if Ch > '9' then Inc(Ch, 7); Insert(Ch, Result, 1); Value := Value div Base[NumBase]; until Value = 0; end; function THexEdit.GetValue: Longint; begin Result := BaseStrToInt(Text); end; procedure THexEdit.SetValue(NewValue: Longint); begin Text := IntToBaseStr(CheckValue(NewValue)); end; procedure THexEdit.SetNumBase(NewValue: TEditBase); var TempValue: LongInt; begin TempValue := Value; FNumBase := NewValue; SetValue(TempValue); end; function THexEdit.CheckValue(NewValue: Longint): Longint; begin if NewValue < 0 then NewValue := 0; Result := NewValue; if FValidate then begin if NewValue < FMinValue then Result := FMinValue else if NewValue > FMaxValue then Result := FMaxValue; end; end; procedure THexEdit.SetMaxValue(NewValue: Longint); begin if NewValue < 0 then NewValue := 0; FMaxValue := NewValue; SetValue(Value); end; procedure THexEdit.SetMinValue(NewValue: Longint); begin if NewValue < 0 then NewValue := 0; FMinValue := NewValue; SetValue(Value); end; procedure THexEdit.SetValidate(B: Boolean); begin FValidate := B; SetValue(Value); end; function THexEdit.SyntaxOk(const S: string): Boolean; var I: Byte; NewValue: LongInt; begin { syntax correct if all chars are valid } Result := True; for I := 1 to Length(S) do begin if not CharInSet(S[I], ['0'..'9', 'A'..'F']) or (BaseStrToInt(S[I]) >= Base[NumBase]) then Result := False; end; { syntax correct if Value inside bounds } if Result and FValidate then begin NewValue := BaseStrToInt(S); if (NewValue < FMinValue) or (NewValue > FMaxValue) then Result := False; end; end; procedure THexEdit.CMEnter(var Message: TCMGotFocus); begin if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; inherited; end; procedure THexEdit.CMExit(var Message: TCMExit); begin inherited; SetValue(Value); end; function THexEdit.IsValidChar(Key: Char): Boolean; begin case Key of '0'..'9', 'A'..'F': Result := SyntaxOk(Copy(Text, 1, SelStart) + Key + Copy(Text, SelStart + 1 + SelLength, 255)); ^H: if SelLength = 0 then { ^H = Backspace } Result := SyntaxOk(Copy(Text, 1, SelStart - 1) + Copy(Text, SelStart + 1, 255)) else Result := SyntaxOk(Copy(Text, 1, SelStart) + Copy(Text, SelStart + 1 + SelLength, 255)); else Result := False; end; {case} end; function THexEdit.ValidCopy: Boolean; begin Result := True; end; function THexEdit.ValidPaste: Boolean; begin if Clipboard.HasFormat(CF_TEXT) then Result := SyntaxOk(Copy(Text, 1, SelStart) + Clipboard.AsText + Copy(Text, SelStart + 1, 255)) else result := FALSE; end; function THexEdit.ValidCut: Boolean; begin Result := SyntaxOk(Copy(Text, 1, SelStart) + Copy(Text, SelStart + 1 + SelLength, 255)); end; function THexEdit.ValidDelete: Boolean; var S: string; begin if SelLength = 0 then S := Copy(Text, 1, SelStart) + Copy(Text, SelStart + 2, 255) else S := Copy(Text, 1, SelStart) + Copy(Text, SelStart + 1 + SelLength, 255); Result := SyntaxOk(S); end; procedure THexEdit.KeyDown(var Key: Word; Shift: TShiftState); begin { handle Copy-, Paste-, Cut-, Delete-Keys} if ssShift in Shift then begin if Key = VK_INSERT then begin if not ValidPaste then Key := 0 end else if Key = VK_DELETE then begin if not ValidCut then Key := 0 end end else if ssCtrl in Shift then begin if Key = VK_INSERT then begin if not ValidCopy then Key := 0 end else if Key = VK_DELETE then begin if not ValidDelete then Key := 0 end end else if Key = VK_DELETE then begin if not ValidDelete then Key := 0 end; inherited KeyDown(Key, Shift); end; procedure THexEdit.KeyPress(var Key: Char); begin if FValidate then begin { handle Copy Paste Cut Keys} if Key = ^C then begin if not ValidCopy then Key := #0 end else if Key = ^V then begin if not ValidPaste then Key := #0 end else if Key = ^X then begin if not ValidCut then Key := #0 end else begin Key := UpCase(Key); {transform a..f to A..F} if not IsValidChar(Key) then Key := #0; end; if Key <> #0 then inherited KeyPress(Key); end; end; procedure Register; begin RegisterComponents('ConTEXT Components', [THexEdit]); end; end.
unit aaaliCrypt; interface uses sysutils; var DefaultKey : WideString = 'TK7IWlj1Ly+Y6DOe'; keyTototo : WideString = 'wsL3RStCVOgXh06x'; InternalPassword : string = 'haidarfaz'; function GenerateKey: string; function CreateRandomString(Chars: string; Count: Integer): string; function EncodeData(Data, Key: WideString; MinV: Word=0; MaxV: Word=5): WideString; function DecodeData(Data, Key: WideString): WideString; Function GenerateSerialNumber( AUserName: String ): String; implementation { --------------------------------------------------------------------- Password encryption ---------------------------------------------------------------------} { Based on code found on Torry's pages by Jurii Zhukow} const Codes64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/'; { Function to create an encryption key } function GenerateKey: string; var i, x: integer; s1, s2: string; begin s1:=Codes64; s2:=''; for i := 0 to 15 do begin x:=Random(Length(s1)); x:=Length(s1)-x; s2:=s2+s1[x]; s1:=Copy(s1,1,x-1)+Copy(s1,x+1,Length(s1)); end; Result:=s2; end; { Noise function } function CreateRandomString(Chars: string; Count: Integer): string; var i,X: integer; begin Result:=''; If Count>Length(Chars) then Count:=Length(Chars); for i:=1 to Count do begin X:=Length(Chars)-Random(Length(Chars)); Result:=Result+Chars[X]; Delete(Chars,X,1); end; end; { Encode Data } { "Key" _must_ be generated using above function. "Data" is data to be encoded. "MinV" - minimum quantity of "noise" chars before each encoded data char. "MaxV" - maximum quantity of "noise" chars before each encoded data char. } function EncodeData(Data, Key: WideString; MinV: Word=0; MaxV: Word=5): WideString; var i, x: integer; s1, s2, ss: string; begin if (MinV>MaxV) then begin i:=minv; minv:=maxv; maxv:=i; end; if (MaxV>100) then MaxV:=100; Result:=''; if Length(Key)<16 then Exit; for i:=1 to Length(Key) do begin s1:=Copy(Key,i+1,Length(Key)); if (Pos(Key[i],s1)>0) or (Pos(Key[i],Codes64)<=0) then Exit; end; s1:=Codes64; s2:=''; for i:=1 to Length(Key) do begin x:=Pos(Key[i],s1); if (x>0) then s1:=Copy(s1,1,x-1)+Copy(s1,x+1,Length(s1)); end; ss:=Key; for i:=1 to Length(Data) do begin s2:=s2+ss[Ord(Data[i]) mod 16 + 1]; ss:=Copy(ss,Length(ss),1)+Copy(ss,1,Length(ss)-1); s2:=s2+ss[Ord(Data[i]) div 16 + 1]; ss:=Copy(ss,Length(ss),1)+Copy(ss,1,Length(ss)-1); end; Result:=CreateRandomString(s1,Random(MaxV-MinV)+minV+1); for i:=1 to Length(s2) do Result:=Result+s2[i]+CreateRandomString(s1,Random(MaxV-MinV)+minV); end; { Decode data } { "Key" _must_ be same key as used to encrypt data. "Data" is encoded data } function DecodeData(Data, Key: WideString): WideString; var i, x, x2: integer; s1, s2, ss: string; begin Result := #1; if (Length(Key)<16) then Exit; for i := 1 to Length(Key) do begin s1 := Copy(Key, i + 1,Length(Key)); if (Pos(Key[i],s1)>0) or (Pos(Key[i],Codes64)<=0) then Exit; end; s1:=Codes64; s2:=''; ss:=Key; for i:=1 to Length(Data) do if (Pos(Data[i],ss)>0) then s2:=s2+Data[i]; Data:=s2; s2:=''; if ((Length(Data) mod 2)<>0) then Exit; for i := 0 to Length(Data) div 2 - 1 do begin x:=Pos(Data[i*2+1],ss)-1; if (x<0) then Exit; ss:=Copy(ss,Length(ss),1)+Copy(ss,1,Length(ss)-1); x2:=Pos(Data[i*2+2],ss)-1; if (x2<0) then Exit; x:=x+x2*16; s2:=s2+chr(x); ss:=Copy(ss,Length(ss),1)+Copy(ss,1,Length(ss)-1); end; Result:=s2; end; Function GenerateSerialNumber( AUserName: String ): String; Var I: Integer; Index: Integer; IntIndex: Integer; Serial: String; TempStr: String; TempStr1: String; Addon: Integer; Begin Result := ''; If AUserName = '' Then Begin //MessageDlg( 'User name is empty. Please set this propery before!', mtInformation, [ mbOK ], 0 ); Exit; End; AUserName := UpperCase( AUserName ); Index := 1; IntIndex := 1; Addon := 0; For I := 1 To Length( AUserName ) Do Begin Inc( AddOn, ( Ord( AUserName[ I ] ) * I ) ); End; For I := 1 To 12 Do Begin Serial := Serial + IntToHex( ( ( Ord( DefaultKey[ I * 2 ] ) Xor Ord( DefaultKey[ I ] ) ) Xor Ord( AUserName[ Index ] ) ) Xor ( ( Addon + I ) Mod 200 ) , 2 ); Inc( Addon, Ord( AUserName[ Index ] ) Xor I ); Inc( Index ); Inc( IntIndex ); If Index > Length( AUserName ) Then Index := 1; If IntIndex > Length( InternalPassword ) Then IntIndex := 1; End; If Length( Serial ) > 24 Then Serial := Copy( Serial, 1, 24 ); Result := Copy( Serial, 1, 8 ) + '-' + Copy( Serial, 9, 8 ) + '-' + Copy( Serial, 17, 8 ); End; end.
unit CustomEditHelper; interface uses Vcl.StdCtrls, System.SysUtils, Vcl.ExtCtrls, System.Classes; type TCustomEditHelper = class helper for TCustomEdit private procedure EditFloatText(Sender: TObject); procedure EditFloatKeyPress(Sender: TObject; var Key: Char); public procedure EditFloat; end; implementation { TCustomEditHelper } uses Biblioteca; procedure TCustomEditHelper.EditFloatKeyPress(Sender: TObject; var Key: Char); begin if not CharInSet(Key,['0'..'9',',','-',#8]) then Key:= #0; end; procedure TCustomEditHelper.EditFloatText(Sender: TObject); begin case Self.Tag of 0:begin if Trim((Sender as TCustomEdit).Text) = EmptyStr then (Sender as TCustomEdit).Text:= '0,00' else (Sender as TCustomEdit).Text:= FormataFloat('V',StrToFloatDef(Trim((Sender as TCustomEdit).Text),0)); end; 1:begin if Trim((Sender as TCustomEdit).Text) = EmptyStr then (Sender as TCustomEdit).Text:= '0,000' else (Sender as TCustomEdit).Text:= FormataFloat('Q',StrToFloatDef(Trim((Sender as TCustomEdit).Text),0)); end; end; end; procedure TCustomEditHelper.EditFloat; begin Self.Alignment:= taRightJustify; if (Self is TEdit) then begin (Self as TEdit).OnExit:= EditFloatText; (Self as TEdit).OnKeyPress:= EditFloatKeyPress; end else if (Self is TLabeledEdit) then begin (Self as TLabeledEdit).OnExit:= EditFloatText; (Self as TLabeledEdit).OnKeyPress:= EditFloatKeyPress; end; case self.Tag of 0:Self.Text:= '0,00'; 1:Self.Text:= '0,000'; end; end; end.
(* Category: SWAG Title: INPUT AND FIELD ENTRY ROUTINES Original name: 0002.PAS Description: General Input with Color Author: SWAG SUPPORT TEAM Date: 06-08-93 08:24 *) { General STRING input routine with Color prompt and input } USES DOS,Crt; TYPE CharSet = Set OF Char; VAR Name : STRING; procedure QWrite( Column, Line , Color : byte; S : STRING ); (* var VMode : BYTE ABSOLUTE $0040 : $0049; { Video mode: Mono=7, Color=0-3 } NumCol : WORD ABSOLUTE $0040 : $004A; { Number of CRT columns (1-based) } VSeg : WORD; OfsPos : integer; { offset position of the character in video RAM } vPos : integer; sLen : Byte ABSOLUTE S; *) Begin (* If VMode in [0,2,7] THEN VSeg := $B000 ELSE VSeg := $B800; OfsPos := (((pred(Line) * NumCol) + pred(Column)) * 2); FOR vPos := 0 to pred(sLen) do MemW[VSeg : (OfsPos + (vPos * 2))] := (Color shl 8) + byte(S[succ(vPos)]) *) GotoXY(column, line); TextAttr := color; Write(S); End; Function GetString(cx,cy,cc,pc : Byte; Default,Prompt : String; MaxLen : Integer;OKSet :charset):string; { cx = Input Column } { cy = Input Row } { cc = Input Color } { pc = Prompt Color } const BS = ^H; CR = ^M; iPutChar = '-'; ConSet : CharSet = [BS,CR]; var TStr : string; TLen,X,i : Integer; Ch : Char; begin {$I-} { turn off I/O checking } TStr := ''; TLen := 0; Qwrite(cx,cy,pc,Prompt); X := cx + Length(Prompt); For i := x to (x + Maxlen - 1) do Qwrite(i,cy,cc,iputChar); Qwrite(x,cy,cc,Default); OKSet := OKSet + ConSet; repeat Gotoxy(x,cy); repeat ch := readkey until Ch in OKSet; if Ch = BS then begin if TLen > 0 then begin TLen := TLen - 1; X := X - 1; QWrite(x,cy,cc,iPutChar); end end else if (Ch <> CR) and (TLen < MaxLen) then begin QWrite(x,cy,cc,Ch); TLen := TLen + 1; TStr[TLen] := Ch; X := X + 1; end until Ch = CR; If Tlen > 0 Then Begin TStr[0] := chr(Tlen); Getstring := TStr End Else Getstring := Default; {$I+} end; BEGIN ClrScr; Name := Getstring(16,5,79,31,'GOOD OLE BOY', 'Enter Name : ',25,['a'..'z','A'..'Z',' ']); GOTOXY(16,7); WriteLn('Name : ',Name); Readkey; END.
unit uniteProtocole; interface uses SysUtils, uniteReponse, uniteRequete, uniteConsigneur, uniteLecteurFichier, uniteLecteurFichierBinaire, uniteLecteurFichierTexte; //Traite les requêtes HTTP et fournit une réponse appropriée selon l'état du serveur type Protocole = class private //Le répertoire local qui contient tous les sites web de notre serveur repertoireDeBase:String; //Un consigneur permettant de consigner tous les messages leConsigneur:Consigneur; public //La methode traiterRequete analyse la requete et renvoie le code approprié au fureteur. //Elle reçoit la requete envoyée par le fureteur en paramètre et retourne un objet de type Reponse. // //@param uneRequete Reçoit la requête de l'utilisateur // //@return Reponse Traite la requête et retourne une réponse (Code d'erreur + message) // //@exception Exception Si la requête n'est pas une requête HTTP valide (si la 3ième partie n'est pas de la forme HTTP/x.y où x et y sont des entiers) function traiterRequete(uneRequete:Requete):Reponse; //Crée un objet Protocole qui traite les requêtes HTTP //et fournit une réponse appropriée selon l'état du serveur. // //@param unRepertoireDeBase le répertoire qui contient tous les sites web de notre serveur //@param unConsigneur sert à consigner des messages //@raises Exception exception de message 'Repertoire de Base inexistant' levée si le repertoireDeBase donné en paramètre n'existe pas constructor create(unRepertoireDeBase:String;unConsigneur:Consigneur); //Accesseur du répertoire de base // //@return String retourne le répertoire de base function getRepertoireDeBase:String; //Mutateur du répertoire de base // //@param unRepertoire le répertoire de base //@raises Exception exception de message 'Version HTTP incompatible' levée si la versionProtocole n'est pas du format HTTP/x.y où x et y sont entre 0 et 9. procedure setRepertoireDeBase(unRepertoireDeBase:String); end; implementation function Protocole.traiterRequete(uneRequete:Requete):Reponse; var uneReponse:Reponse; uneAdresseDemandeur:String; uneVersionProtocole:String; unCodeReponse:Word; unMessage:String; uneReponseHtml:String; stringTemporaire:String; //LecteurFichier que l'on pourra Transtyper unLecteurFichier:LecteurFichier; begin //write('[', formatDateTime('c',uneRequete.getDateReception), ']',' ', uneRequete.getAdresseDemandeur,' ', uneRequete.getMethode,' ', uneRequete.getUrl,' ', uneRequete.getVersionProtocole); leConsigneur.consigner('ProtocoleHTTP', uneRequete.getAdresseDemandeur+'-'+uneRequete.getMethode+' ( '+uneRequete.getVersionProtocole+' )'); //Initialisation des données pour l'objet Reponse qui retourne une erreur pour le moment. uneAdresseDemandeur:=uneRequete.getAdresseDemandeur; uneVersionProtocole:='HTTP/1.1'; //Vérification de la méthode //Reception de la requete if fileExists(repertoireDeBase+uneRequete.getUrl)then begin unCodeReponse:=200; unMessage:='OK'; if (AnsiUpperCase(extractFileExt(repertoireDeBase+uneRequete.getUrl)) = '.HTML') or (AnsiUpperCase(extractFileExt(repertoireDeBase+uneRequete.getUrl)) = '.XML') then unLecteurFichier:=lecteurFichierTexte.create(repertoireDeBase+uneRequete.getUrl) else unLecteurFichier:=lecteurFichierBinaire.create(repertoireDeBase+uneRequete.getUrl); try if unLecteurFichier is lecteurFichierTexte then uneReponseHtml:=unLecteurFichier.getEntete+#13+#13+lecteurFichierTexte(unLecteurFichier).lireContenu; if unLecteurFichier is lecteurFichierBinaire then uneReponseHtml:=unLecteurFichier.getEntete+#13+#13+lecteurFichierBinaire(unLecteurFichier).lireContenu; except on e:Exception do begin unCodeReponse:=500; unMessage:='erreur interne du serveur'; leConsigneur.consignerErreur('unProtocoleHTTP','impossible de lire la page demandée'); end; end; unLecteurFichier.destroy; end else begin unCodeReponse:=404; unMessage:='URL introuvable'; uneReponseHTML:='L''URL ('+uneRequete.getUrl+') n''existe pas sur le serveur, veuillez verifier l''orthographe et reessayer'; end; if (uneRequete.getMethode<>uppercase('GET')) then begin unCodeReponse:=501; unMessage:='Methode non implémentée'; uneReponseHTML:=('La methode '+uneRequete.getMethode+' n''est pas implémentée'); end; //Utilisation d'un subString pour vérifier HTTP/ seulement stringTemporaire:=copy(uneRequete.getVersionProtocole,1,5); //Vérification de x.y c'est à dire la 6e et 8e lettre du String pour qu'il soit bien entre 0 et 9 //Sinon, lève une exception if (stringTemporaire <> 'HTTP/') or ((uneRequete.getVersionProtocole[6] < '0')) or ((uneRequete.getVersionProtocole[6] > '9')) or ((uneRequete.getVersionProtocole[8] < '0')) or ((uneRequete.getVersionProtocole[8] > '9')) or (uneRequete.getVersionProtocole[7] <> '.') or (length(uneRequete.getVersionProtocole) <> 8) then begin raise Exception.create('Version HTTP incompatible'); end; //Vérifie le protocole HTTP if (uneRequete.getVersionProtocole <> 'HTTP/1.0') and (uneRequete.getVersionProtocole <> 'HTTP/1.1') then begin unCodeReponse:=505; unMessage:='Version HTTP' +uneRequete.getVersionProtocole +'non supportée'; uneReponseHtml:=('Protocole '+uneRequete.getVersionProtocole+' incompatble avec le serveur'); end; //Créer l'objet réponse avec tous les paramètres plus haut uneReponse:=Reponse.create(uneAdresseDemandeur,uneVersionProtocole,unCodeReponse,unMessage,uneReponseHtml); //Retourne l'objet réponse result:=uneReponse; //Case of pour ainsi consigner une seule fois dépendament de la variable unCodeReponse Case unCodeReponse of 200:leConsigneur.consigner('ProtocoleHTTP', uneReponse.getAdresseDemandeur+' – 200 : '+uneReponse.getMessage); 500:leConsigneur.consignerErreur('ProtocoleHTTP','impossible d''ouvrir la page demandée'); 501:leConsigneur.consigner('ProtocoleHTTP','La méthode '+uneRequete.getMethode+' n''est pas implémentée'); 505:leConsigneur.consigner('ProtocoleHTTP','Version HTTP'+uneRequete.getVersionProtocole+'incompatible avec le serveur'); 404:leConsigneur.consigner('ProtocoleHTTP',uneReponse.getAdresseDemandeur +' - 404 : '+uneReponse.getMessage); else leConsigneur.consignerErreur('ProtocoleHTTP','Erreur interne du serveur'); end; end; constructor Protocole.create(unRepertoireDeBase:String;unConsigneur:Consigneur); begin //Verifie si le repertoire existe et affecte a la variable code le numero de code si le repertoire existe ou pas if not directoryExists(unRepertoireDeBase)then raise Exception.create('Repertoire de Base inexistant'); setRepertoireDeBase(unRepertoireDeBase); leConsigneur:=unConsigneur; end; function Protocole.getRepertoireDeBase:String; begin result:=repertoireDeBase; end; procedure Protocole.setRepertoireDeBase(unRepertoireDeBase:String); begin repertoireDeBase:=unRepertoireDeBase; end; end.
unit ZipMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.ListBox; type TForm20 = class(TForm) lstFiles1: TListBox; edtPath: TEdit; Label1: TLabel; Button1: TButton; lblCompressed: TLabel; lblSize: TLabel; lblTempFile: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } var ZipFileName: String; public { Public declarations } end; var Form20: TForm20; implementation {$R *.fmx} uses IOUtils, System.Zip; procedure TForm20.Button1Click(Sender: TObject); begin lstFiles1.Clear; var files := TDirectory.GetFiles(edtPath.Text, '*.*', TSearchOption.soAllDirectories); var size: Integer := 0; if TFile.Exists(ZipFileName) then TFile.Delete(ZipFileName); lstFiles1.BeginUpdate; try for var i := 0 to pred(length(files)) do begin size := size + TFile.GetSize(files[i]); lstFiles1.Items.Add(TPath.GetFileName(files[i])); end; finally lstFiles1.EndUpdate; end; lblSize.Text := Format('%d bytes uncompressed', [size]); // Zips sub directories too TZipFile.ZipDirectoryContents( ZipFileName, edtPath.Text ); lblTempFile.Text := ZipFileName; var ZipSize := TFile.GetSize(ZipFileName); var ZipValid: String; // New in 11.0 TZipFile.IsValid if TZipFile.IsValid(ZipFileName) then ZipValid := 'Valid' else ZipValid := 'Invalid'; lblCompressed.Text := Format('%d bytes (%s) %f%%', [ZipSize, ZipValid, ZipSize/Size*100]); end; procedure TForm20.FormClose(Sender: TObject; var Action: TCloseAction); begin if TFile.Exists(ZipFileName) then TFile.Delete(ZipFileName); end; procedure TForm20.FormCreate(Sender: TObject); begin ZipFileName := TPath.Combine(TPath.GetTempPath, 'TestZip.zip'); end; end.
unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, cef, ceflib; const ID_URL = 0; ID_FALLBACK = 1; type TfrmSkypePopup = class(TForm) Button1: TButton; Button2: TButton; Chromium1: TChromium; tmrMousePos: TTimer; tmrCursorInWindowTracker: TTimer; tmrHide: TTimer; tmrShow: TTimer; procedure Button1Click(Sender: TObject); procedure Chromium1BeforePopup(const parentBrowser: ICefBrowser; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var url: ustring; var client: ICefBase; out Result: Boolean); procedure Chromium1LoadEnd(Sender: TCustomChromium; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer; out Result: Boolean); procedure Chromium1AfterCreated(Sender: TCustomChromium; const browser: ICefBrowser); procedure FormCreate(Sender: TObject); procedure Chromium1JsAlert(Sender: TCustomChromium; const browser: ICefBrowser; const frame: ICefFrame; const message: ustring; out Result: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tmrMousePosTimer(Sender: TObject); procedure tmrCursorInWindowTrackerTimer(Sender: TObject); procedure tmrShowTimer(Sender: TObject); procedure tmrHideTimer(Sender: TObject); private { Private declarations } mouse_pos: TPoint; last_url: String; procedure parseDimenstions(const s: String); procedure OnUrlFromSkype(var msg: TWMCopyData); message WM_COPYDATA; procedure OnException(Sender: TObject; E: Exception); public { Public declarations } bCapable: Boolean; browser: ICefBrowser; procedure loadImage(const url: string); procedure ShowImageAtPosition; procedure HideImage; function isMouseInForm: Boolean; procedure ShowAlphaAnim; procedure HideAlphaAnim; end; var frmSkypePopup: TfrmSkypePopup; sRootDir: String; sTemplateUrl: String; implementation {$R *.dfm} procedure initmon(b: boolean); stdcall; external 'skype_interc.dll'; procedure TfrmSkypePopup.Button1Click(Sender: TObject); var url: String; begin //Chromium1.Load(''); url := 'file://i:/src/skype_popup/test/gif01.gif'; //browser.GetMainFrame.ExecuteJavaScript('loadImage("' + url + '")', '', 0); loadImage(url); end; procedure TfrmSkypePopup.Chromium1BeforePopup(const parentBrowser: ICefBrowser; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var url: ustring; var client: ICefBase; out Result: Boolean); begin Result := False; end; procedure TfrmSkypePopup.Chromium1LoadEnd(Sender: TCustomChromium; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer; out Result: Boolean); begin bCapable := True; end; procedure TfrmSkypePopup.Chromium1AfterCreated(Sender: TCustomChromium; const browser: ICefBrowser); begin bCapable := False; browser.GetMainFrame.LoadUrl(sTemplateUrl); Self.browser := browser; end; procedure TfrmSkypePopup.FormCreate(Sender: TObject); begin sRootDir := ExtractFilePath(Application.ExeName); bCapable := False; sTemplateUrl := 'file://' + sRootDir + '/template/index.html'; initmon(true); Application.ShowMainForm := False; Application.OnException := OnException; end; procedure TfrmSkypePopup.Chromium1JsAlert(Sender: TCustomChromium; const browser: ICefBrowser; const frame: ICefFrame; const message: ustring; out Result: Boolean); var i: Integer; pref, body: String; begin //JS code may call alert to pass an event to application //should contain prefix and body Result := False; i := Pos(':', message); if i < 0 then Exit; //get prefix and boy of alert message pref := Copy(message, 1, i); body := Copy(message, i + 1, Length(message)); if pref = 'dims:' then begin //Caption := body; parseDimenstions(body); Result := True; end else if pref = 'error:' then begin //if body = 'image_failed' then Result := True; end else Result := False; end; procedure TfrmSkypePopup.parseDimenstions(const s: String); var w, h: Integer; i: Integer; begin i := Pos(',', s); if TryStrToInt(Copy(s, 1, i - 1), w) then if TryStrToInt(Copy(s, i + 1, Length(s)), h) then begin Chromium1.Width := w; Chromium1.Height := h; ClientWidth := w; ClientHeight := h; end; end; procedure TfrmSkypePopup.loadImage(const url: string); var ext: String; s: String; preload: String; begin s := url; ext := LowerCase(ExtractFileExt(url)); if (ext <> '.jpeg') AND (ext <> '.jpg') AND (ext <> '.png') AND (ext <> '.gif') then begin if Pos('imgur.com', LowerCase(s)) > 0 then s := s + '.jpg' else Exit; end; //don't preload gifs, can take long time if (ext = '.gif') then preload := 'false' else preload := 'true'; browser.GetMainFrame.ExecuteJavaScript(Format( 'loadImage("%s", %s);', [s, preload]), '', 0); ShowImageAtPosition; end; procedure TfrmSkypePopup.OnUrlFromSkype(var msg: TWMCopyData); var url: String; in_action: Boolean; begin //remember last url url := PChar(msg.CopyDataStruct.lpData); //look if one of our timers still working in sweat shop in_action := (tmrShow.Enabled OR tmrHide.Enabled OR tmrCursorInWindowTracker.Enabled); if (last_url = url) then begin if in_action then Exit; end else begin if in_action then begin { //shutdown... EVERYTHING tmrShow.Enabled := False; tmrHide.Enabled := False; tmrCursorInWindowTracker.Enabled := False; AlphaBlendValue := 255; Chromium1.ReCreateBrowser(sTemplateUrl);} end; end; last_url := url; if msg.CopyDataStruct.dwData = ID_URL then begin loadImage(url); end else if msg.CopyDataStruct.dwData = ID_FALLBACK then begin if isMouseInForm then begin tmrCursorInWindowTracker.Enabled := True; end else HideImage; end; end; procedure TfrmSkypePopup.FormClose(Sender: TObject; var Action: TCloseAction); begin initmon(false); end; procedure TfrmSkypePopup.OnException(Sender: TObject; E: Exception); begin // end; procedure TfrmSkypePopup.ShowImageAtPosition; var offsetX, offsetY: Integer; begin GetCursorPos(mouse_pos); Left := mouse_pos.X + 5; Top := mouse_pos.Y; with frmSkypePopup do begin offsetX := (Monitor.Left + Monitor.Width) - (mouse_pos.X + Width + 5); offsetY := (Monitor.Top + Monitor.Height) - (mouse_pos.Y + Height + 5); //ShowMessage(IntToStr(Monitor.width)); if offsetX < 0 then Left := mouse_pos.X + offsetX else Left := mouse_pos.X - 5; if offsetY < 0 then Top := mouse_pos.Y + offsetY else Top := mouse_pos.Y - 5; end; ShowWindow(Handle, SW_SHOWNA); //Visible := True; tmrMousePos.Enabled := True; ShowWindow(Application.Handle, SW_HIDE); ShowAlphaAnim; end; procedure TfrmSkypePopup.tmrMousePosTimer(Sender: TObject); var p: TPoint; begin GetCursorPos(p); if (Abs(p.X - mouse_pos.X) > 200) OR (Abs(p.Y - mouse_pos.Y) > 200) then begin HideImage; tmrMousePos.Enabled := False; end; end; procedure TfrmSkypePopup.HideImage; begin //ShowWindow(Handle, SW_HIDE); HideAlphaAnim; end; function TfrmSkypePopup.isMouseInForm: Boolean; var p: TPoint; r: TRect; begin GetCursorPos(p); GetWindowRect(Handle, r); Result := (p.X >= r.Left) AND (p.Y <= r.Right) AND (p.Y >= r.Top) AND (p.Y <= r.Bottom); end; procedure TfrmSkypePopup.tmrCursorInWindowTrackerTimer(Sender: TObject); begin if isMouseInForm then Exit; tmrCursorInWindowTracker.Enabled := False; HideImage; end; procedure TfrmSkypePopup.ShowAlphaAnim; var i: Integer; begin AlphaBlend := True; AlphaBlendValue := 0; ShowWindow(Handle, SW_SHOWNA); Visible := True; tmrHide.Enabled := False; tmrShow.Enabled := True; end; procedure TfrmSkypePopup.HideAlphaAnim; var i: Integer; begin AlphaBlend := True; AlphaBlendValue := 255; tmrShow.Enabled := False; tmrHide.Enabled := True; end; procedure TfrmSkypePopup.tmrShowTimer(Sender: TObject); begin AlphaBlendValue := AlphaBlendValue + 10; Update; if (AlphaBlendValue >= 250) then begin tmrShow.Enabled := False; AlphaBlendValue := 255; end; end; procedure TfrmSkypePopup.tmrHideTimer(Sender: TObject); begin AlphaBlendValue := AlphaBlendValue - 10; Update; if (AlphaBlendValue <= 10) then begin tmrHide.Enabled := False; Visible := False; AlphaBlendValue := 255; Chromium1.ReCreateBrowser(sTemplateUrl); end; end; end.
unit DFFiles; interface uses Wintypes,WinProcs,SysUtils; {$i gbtypes.inc} {$i types.inc} const fmOpenRead=0; fmShareDenyNone=$40; Type TBitmapInfo=record w,h:word; dx,dy:Integer; Transparent,animated:boolean; end; TShortFname=string[12]; TGOBFile=Class gh:TGOBHeader; Nfiles:TNEntries; Gobh:integer; hindex:Thandle; Pindex:^TGOBEntry; cfile:integer; cstart,csize:longint; Constructor OpenGob(GobName:TFileName); Function OpenInGob(name:TShortFname):integer; Function FRead(var b;size:integer):integer; Procedure Fseek(Pos:longint); Function Fsize:longint; Destructor Done; end; Type TDFFile=Class fh:Integer; Gob:TGobFile; GobName:TfileName; FileName:TShortFname; GobOpen:boolean; ExtFileOpen:boolean; InGob:boolean; Constructor Create; Function FOpen(Name:TFileName):integer; Function FRead(var b;size:integer):integer; Procedure Fseek(Pos:longint); Function Fsize:longint; Destructor done; end; TDFImage=Class(TDFFile) NImgs:integer; {BM data} bmh:BM_header; bmmh:BM_Mheader; bmm:BM_Multi; bm_multiple:boolean; {FME data} fh1:TFrame; fh2:TCell; bi:TBitmapInfo; {WAX Data} wh:wax_header; hwaxstruct:Thandle; Pws:pchar; Cwax,waxes,nviews,nframes:integer; Coding:(DF_RAW,DF_RLE0,DF_RLE); F_type:(DF_BM,DF_FME,DF_WAX); col_ofs:array[0..5999] of longint; cbuf:array[0..5999] of byte; flipit:boolean; Constructor Create; Function Fopen(Name:TfileName):integer; Function Nimages:integer; Procedure SetCurrentImage(n:integer); Procedure GetInfo(var b:TbitmapInfo); Procedure GetColumn(var b; n:integer); Function NWaxes:integer; Procedure SetWax(N:integer); Destructor done; Private Function HowManyWaxes:integer; Function BM_init:integer; Function FME_init:integer; Function WAX_init:integer; Function BM_Nimages:integer; Function WAX_Nimages:integer; Procedure BM_SetCI(n:integer); Procedure WAX_SetCI(n:integer); end; implementation function DFRLE0_uncompress(ibuf,obuf:pchar; size:word):word; var ip,op:pchar; c:integer; begin ip:=ibuf;op:=obuf; while ip<(ibuf+size) do begin c:=ord(ip^); inc(ip); if c<128 then begin Move(ip^,op^,c); inc(ip,c); inc(op,c); end else begin dec(c,128); Fillchar(op^,c,0); inc(op,c); end; end; result:=op-obuf; end; function DFRLE_uncompress (ibuf,obuf:pchar; size:word):word; var ip,op:pchar; c:byte; begin ip:=ibuf;op:=obuf; while ip<(ibuf+size) do begin c:=ord(ip^); inc(ip); if c<127 then begin Move(ip^,op^,c); inc(ip,c); inc(op,c); end else begin dec(c,128); Fillchar(op^,c,ip^); inc(op,c); inc(ip); end; end; result:=op-obuf; end; Constructor TGOBFile.OpenGob(GobName:TFileName); begin Gobh:=FileOpen(GobName,fmOpenRead or fmShareDenyNone); if gobh=-1 then begin fail; exit; end; FileRead(gobh,gh,sizeof(gh)); if gh.magic<>'GOB'#10 then begin FileClose(gobh); fail; exit; end; FileSeek(gobh,gh.index_ofs,0); FileRead(gobh,nfiles,sizeof(nfiles)); hindex:=GlobalAlloc(GMEM_MOVEABLE,nfiles*sizeof(TGOBEntry)); pindex:=GlobalLock(hindex); FileRead(gobh,pindex^,nfiles*sizeof(TGOBEntry)); GlobalUnlock(hindex); cfile:=0; end; Destructor TGOBFile.Done; begin FileClose(gobh); GlobalFree(hindex); end; Function TGOBFile.OpenInGob(name:TShortFname):integer; var i:integer; tmp:array[0..12] of char; begin OpenInGob:=-1; for i:=1 to length(name) do name[i]:=upcase(name[i]); Pindex:=GlobalLock(hindex); StrPcopy(tmp,name); for i:=0 to nfiles-1 do begin if StrComp(tmp,Pindex^.name)=0 then begin cfile:=i; csize:=Pindex^.size; cstart:=Pindex^.offs; FileSeek(gobh,cstart,0); OpenInGob:=0; break; end; Inc(Pindex); end; GlobalUnlock(hindex); end; Function TGOBFile.FRead(var b;size:integer):integer; begin Fread:=FileRead(gobh,b,size); end; Procedure TGOBFile.Fseek(Pos:longint); begin FileSeek(gobh,cstart+pos,0); end; Function TGOBFile.Fsize:longint; begin Fsize:=csize; end; Constructor TDFFile.Create; begin GobName:=''; GobOpen:=false; ExtFileOpen:=false; InGob:=false; end; Destructor TDFFile.done; begin if GobOpen then Gob.done; if ExtFileOpen then FileClose(fh); end; Function TDFFile.FOpen(Name:TFileName):integer; var NewGob:TFileName; NewFile:TShortFname; Function ParseName:boolean; var ps:integer; begin ParseName:=true; ps:=pos(']',Name); if ps=0 then ParseName:=false else begin NewGob:=Copy(Name,2,ps-2); NewFile:=Copy(Name,ps+1,length(Name)-ps); end; end; begin Fopen:=-1; if Name[1]='[' then begin If not ParseName then exit; if GobName<>NewGob then begin GobName:=NewGob; if GobOpen then begin GobOpen:=false; Gob.done; end; Gob:=TGOBFile.OpenGob(GobName); if Gob=Nil then exit; end; If Gob.OpenInGob(NewFile)=-1 then begin FileName:=NewFile; exit; end; GobOpen:=true; InGob:=true; Fopen:=0; end else begin if ExtFileOpen then begin FileClose(fh); ExtFileOpen:=false; end; Fh:=FileOpen(Name,fmOpenRead or fmShareDenyNone); if fh<0 then exit; FileName:=Name; ExtFileOpen:=true; InGob:=false; Fopen:=0; end; end; Function TDFFile.FRead(var b;size:integer):integer; begin if InGob then Fread:=Gob.Fread(b,size) else Fread:=FileRead(fh,b,size); end; Procedure TDFFile.Fseek(Pos:longint); begin if InGob then Gob.Fseek(pos) else FileSeek(fh,pos,0); end; Function TDFFile.Fsize:longint; var cpos:longint; begin if InGob then Fsize:=Gob.Fsize else begin cpos:=FileSeek(fh,1,0); Fsize:=FileSeek(fh,0,2); FileSeek(fh,cpos,0); end; end; Function TDFImage.Fopen(Name:TfileName):integer; var ext:string[4]; begin Result:=-1; if Inherited Fopen(Name)=-1 then exit; ext:=LowerCase(ExtractFileExt(Name)); if ext='.bm' then f_type:=DF_BM else if ext='.fme' then f_type:=DF_FME else if ext='.wax' then F_type:=DF_WAX else exit; Case F_type of df_bm: if BM_init=-1 then exit; df_fme: if FME_init=-1 then exit; df_wax: if WAX_init=-1 then exit; end; Result:=0; end; Function TDFImage.Nimages:integer; begin Result:=NImgs; end; Procedure TDFImage.SetCurrentImage(n:integer); begin Case f_type of df_bm: BM_SetCI(n); df_wax: WAX_SetCI(n); end; end; Procedure TDFImage.GetInfo(var b:TbitmapInfo); begin b:=bi; end; Procedure TDFImage.GetColumn(var b; n:integer); var i,ncol:integer; P1,p2:Pchar;c:char; size:integer; begin if flipit then ncol:=bi.w-n-1 else ncol:=n; FSeek(col_ofs[ncol]); case Coding of DF_RAW:Fread(b,bi.h); DF_RLE0:begin Fread(cbuf,col_ofs[ncol+1]-col_ofs[ncol]); DFRLE0_uncompress(@cbuf,@b,col_ofs[ncol+1]-col_ofs[ncol]); end; DF_RLE:begin Fread(cbuf,col_ofs[ncol+1]-col_ofs[ncol]); DFRLE_uncompress(@cbuf,@b,col_ofs[ncol+1]-col_ofs[ncol]); end; end; p1:=@b; p2:=p1+bi.h-1; for i:=0 to bi.h div 2-1 do begin c:=p1^; p1^:=p2^; P2^:=c; Inc(p1); dec(p2); end; end; {BM procedures} Function TDFImage.BM_init:integer; begin Result:=-1; Nimgs:=1; Fread(bmh,sizeof(bmh)); if bmh.magic<>'BM'#32#30 then exit; bm_multiple:=false; if (bmh.sizex=1) and (bmh.datasize<>1) then begin NImgs:=bmh.idemy; Fread(bmm,sizeof(bmm)); bm_multiple:=true; end; case bmh.compressed of 0: coding:=DF_RAW; 1: coding:=DF_RLE; 2: coding:=DF_RLE0; end; Result:=0; end; Function TDFImage.BM_Nimages:integer; begin Result:=1; end; Procedure TDFImage.BM_SetCI(n:integer); var i:word; l:longint; const BMM_Start=sizeof(BM_Header)+sizeof(bm_multi); begin if not bm_multiple then begin bi.w:=bmh.sizex; bi.h:=bmh.sizey; bi.dx:=-(bi.w div 2); bi.dy:=-bi.h; bi.transparent:=bmh.transparent and 8<>0; bi.animated:=false; if coding=DF_RAW then for i:=0 to bi.w-1 do col_ofs[i]:=longint(i)*bi.h+sizeof(bmh) else begin Fseek(bmh.datasize+sizeof(bmh)); FRead(col_ofs,bi.w*4); for i:=0 to bi.w-1 do inc(col_ofs[i],sizeof(bmh)); col_ofs[bi.w]:=bmh.datasize+sizeof(bmh); end; flipit:=false; exit; end; Fseek(BMM_Start+n*4); Fread(l,sizeof(l)); Fseek(l+BMM_Start); Fread(bmmh,sizeof(bmmh)); bi.w:=bmmh.sizex; bi.h:=bmmh.sizey; bi.dx:=-(bi.w div 2); bi.dy:=-bi.h; bi.transparent:=bmmh.transparent and 8<>0; bi.animated:=false; for i:=0 to bi.w-1 do col_ofs[i]:=longint(i)*bi.h+sizeof(bmmh)+BMM_Start+l; flipit:=false; end; {FME Procedure} Function TDFImage.FME_init:integer; var i:word; begin result:=-1; Fread(fh1,sizeof(fh1)); Fseek(fh1.Cell); Fread(fh2,sizeof(fh2)); with bi do begin w:=fh2.sizex; h:=fh2.sizey; dx:=fh1.xshift; dy:=fh1.yshift; transparent:=true; animated:=false; end; if fh2.compressed=0 then begin Coding:=DF_RAW; for i:=0 to bi.w-1 do col_ofs[i]:=longint(i)*bi.h+fh1.Cell+sizeof(fh2); end else begin Coding:=DF_RLE0; Fread(Col_ofs,bi.w*4); for i:=0 to bi.w-1 do inc(col_ofs[i],fh1.Cell); Col_ofs[bi.w]:=fh2.datasize+fh1.Cell; end; flipit:=fh1.flip<>0; Nimgs:=1; Result:=0; end; {WAX Procedures} Constructor TDFImage.Create; begin Inherited Create; HWaxStruct:=GlobalAlloc(GMEM_MOVEABLE,32000); if HWaxStruct=0 then fail; end; Destructor TDFImage.done; begin GlobalFree(HWaxStruct); Inherited Done; end; Function TDFImage.WAX_init:integer; var ws_size:integer; begin result:=-1; NImgs:=0; Fread(wh,sizeof(wh)); if (wh.version<>$11000) and (wh.version<>$10000) then exit; waxes:=HowManyWaxes; ws_size:=waxes*sizeof(twax)+sizeof(tseq)*wh.nseqs+sizeof(tframe)*wh.nframes; if ws_size>32000 then exit; Pws:=GlobalLock(HwaxStruct); Fread(PWS^,ws_size); GlobalUnlock(HwaxStruct); SetWax(0); Result:=0; end; Function TDFImage.NWaxes:integer; begin Result:=waxes; end; Function TDFImage.HowManyWaxes:integer; var N:integer; begin Result:=-1; if f_type<>DF_WAX then exit; N:=0; While (N<32) and (wh.waxes[n]<>0) do inc(N); if N=31 then exit; Result:=N; end; Procedure TDFImage.SetWax(N:integer); var pwax:^Twax; pseq:^Tseq; begin if f_type<>DF_WAX then exit; if N>waxes-1 then exit; Pws:=GlobalLock(HwaxStruct); Cwax:=N; pwax:=pointer(pws-sizeof(wh)+wh.waxes[cwax]); if pwax^.seqs[0]=pwax^.seqs[8] then nviews:=1 else nviews:=5; pseq:=pointer(pws-sizeof(wh)+pwax^.seqs[0]); nframes:=0; while (nframes<32) and (pseq^.frames[nframes]<>0) do inc(nframes); nImgs:=nviews*nframes; GlobalUnlock(HWaxStruct); end; Function TDFImage.WAX_Nimages:integer; begin Result:=nviews*nframes; end; Procedure TDFImage.WAX_SetCI(n:integer); var pwax:^twax; pseq:^tseq; pframe:^Tframe; cell:Tcell; cseq,cframe:integer; i:integer; l:longint; begin cseq:=(n mod nviews)*4; cframe:=n div nviews; PWS:=GlobalLock(HWaxStruct); pwax:=pointer(PWS-sizeof(wh)+wh.waxes[cwax]); pseq:=pointer(PWS-sizeof(wh)+pwax^.seqs[cseq]); pframe:=pointer(PWS-sizeof(wh)+pseq^.frames[cframe]); FSeek(pframe^.cell); Fread(cell,sizeof(cell)); with bi do begin w:=cell.sizex; h:=cell.sizey; dx:=pframe^.xshift; dy:=pframe^.yshift; transparent:=true; animated:=true; end; if cell.compressed=0 then begin Coding:=DF_RAW; for i:=0 to bi.w-1 do col_ofs[i]:=longint(i)*bi.h+Pframe^.Cell+sizeof(Tcell); end else begin Coding:=DF_RLE0; Fread(Col_ofs,bi.w*4); for i:=0 to bi.w-1 do inc(col_ofs[i],pframe^.Cell); Col_ofs[bi.w]:=cell.datasize+pframe^.cell; end; flipit:=pframe^.flip<>0; end; end.
unit VVS; { Voxel Viewer Scene Format Version: 1.0 Coded By: Stucuk Coded On: 17/05/04 } interface Uses VH_Types; Const VVSF_Ver = 1.0; // Only change if header changed or new arrays are added. Procedure SaveVVS(const Filename : string); Procedure LoadVVS(const Filename : string); implementation uses Windows,VH_Global,VH_Display; Var VVSFile : TVVSFile; Procedure AddToDataS(Id : Integer; Value : Single); begin inc(VVSFile.Header.DataS_No); SetLength(VVSFile.DataS,VVSFile.Header.DataS_No); VVSFile.DataS[VVSFile.Header.DataS_No-1].ID := ID; VVSFile.DataS[VVSFile.Header.DataS_No-1].Value := Value; end; Procedure AddToDataB(Id : Integer; Value : Boolean); begin inc(VVSFile.Header.DataB_No); SetLength(VVSFile.DataB,VVSFile.Header.DataB_No); VVSFile.DataB[VVSFile.Header.DataB_No-1].ID := ID; VVSFile.DataB[VVSFile.Header.DataB_No-1].Value := Value; end; Procedure BuildVVSFile; begin VVSFile.Header.DataB_No := 0; VVSFile.Header.DataS_No := 0; VVSFile.Header.Game := VoxelFile.Section[0].Tailer.Unknown; VVSFile.Header.GroundName := GroundTex_Textures[GroundTex.ID].Name; VVSFile.Header.SkyName := SkyTexList[SkyTex].Texture_Name; VVSFile.Version := VVSF_Ver; SetLength(VVSFile.DataS,0); SetLength(VVSFile.DataB,0); AddToDataS(Ord(DSRotX),XRot); AddToDataS(Ord(DSRotY),YRot); AddToDataS(Ord(DSDepth),Depth); AddToDataS(Ord(DSXShift),TexShiftX); AddToDataS(Ord(DSYShift),TexShiftY); AddToDataS(Ord(DSGroundSize),GSize); AddToDataS(Ord(DSGroundHeight),GroundHeightOffset); AddToDataS(Ord(DSSkyXPos),SkyPos.X); AddToDataS(Ord(DSSkyYPos),SkyPos.Y); AddToDataS(Ord(DSSkyZPos),SkyPos.Z); AddToDataS(Ord(DSSkyWidth),SkySize.X); AddToDataS(Ord(DSSkyHeight),SkySize.Y); AddToDataS(Ord(DSSkyLength),SkySize.Z); AddToDataS(Ord(DSFOV),FOV); AddToDataS(Ord(DSDistance),DEPTH_OF_VIEW); AddToDataS(Ord(DSUnitRot),UnitRot); AddToDataS(Ord(DSDiffuseX),LightDif.X); AddToDataS(Ord(DSDiffuseY),LightDif.Y); AddToDataS(Ord(DSDiffuseZ),LightDif.Z); AddToDataS(Ord(DSAmbientX),LightAmb.X); AddToDataS(Ord(DSAmbientY),LightAmb.Y); AddToDataS(Ord(DSAmbientZ),LightAmb.Z); AddToDataS(Ord(DSAmbientZ),LightAmb.Z); AddToDataS(Ord(DSTurretRotationX),VXLTurretRotation.X); AddToDataS(Ord(DSBackgroundColR),BGColor.X); AddToDataS(Ord(DSBackgroundColG),BGColor.Y); AddToDataS(Ord(DSBackgroundColB),BGColor.Z); AddToDataS(Ord(DSUnitCount),UnitCount); AddToDataS(Ord(DSUnitSpace),UnitSpace); AddToDataB(Ord(DBDrawBarrel),DrawBarrel); AddToDataB(Ord(DBDrawTurret),DrawTurret); AddToDataB(Ord(DBShowDebug),DebugMode); AddToDataB(Ord(DBShowVoxelCount),ShowVoxelCount); AddToDataB(Ord(DBDrawGround),Ground_Tex_Draw); AddToDataB(Ord(DBTileGround),TileGround); AddToDataB(Ord(DBDrawSky),DrawSky); AddToDataB(Ord(DBCullFace),CullFace); AddToDataB(Ord(DBLightGround),LightGround); end; Procedure GetFromDataS(const Id : Integer; var Value : single); var x : integer; begin for x := 0 to VVSFile.Header.DataS_No-1 do if VVSFile.DataS[x].ID = ID then begin Value := VVSFile.DataS[x].Value; Exit; end; end; Procedure GetFromDataB(const Id : Integer; var Value : Boolean); var x : integer; begin for x := 0 to VVSFile.Header.DataB_No-1 do if VVSFile.DataB[x].ID = ID then begin Value := VVSFile.DataB[x].Value; Exit; end; end; Procedure FindGround(Const Texture : string; var GroundTex : TGTI); var X : integer; begin for x := 0 to GroundTex_No-1 do if GroundTex_Textures[x].Name = Texture then begin GroundTex.Tex := GroundTex_Textures[x].Tex; GroundTex.ID := x; exit; end; end; Procedure FindSky(Const Texture : string); var X : integer; begin for x := 0 to SkyTexList_No-1 do if SkyTexList[x].Texture_Name = Texture then begin SkyTex := x; BuildSkyBox; exit; end; end; Procedure SetVVSFile; begin //if VoxelFile.Section[0].Tailer.Unknown = VVSFile.Header.Game then FindGround(VVSFile.Header.GroundName,GroundTex); FindSky(VVSFile.Header.SkyName); GetFromDataS(Ord(DSRotX),XRot); GetFromDataS(Ord(DSRotY),YRot); GetFromDataS(Ord(DSDepth),Depth); GetFromDataS(Ord(DSXShift),TexShiftX); GetFromDataS(Ord(DSYShift),TexShiftY); GetFromDataS(Ord(DSGroundSize),GSize); GetFromDataS(Ord(DSGroundHeight),GroundHeightOffset); GetFromDataS(Ord(DSSkyXPos),SkyPos.X); GetFromDataS(Ord(DSSkyYPos),SkyPos.Y); GetFromDataS(Ord(DSSkyZPos),SkyPos.Z); GetFromDataS(Ord(DSSkyWidth),SkySize.X); GetFromDataS(Ord(DSSkyHeight),SkySize.Y); GetFromDataS(Ord(DSSkyLength),SkySize.Z); GetFromDataS(Ord(DSFOV),FOV); GetFromDataS(Ord(DSDistance),DEPTH_OF_VIEW); GetFromDataS(Ord(DSUnitRot),UnitRot); GetFromDataS(Ord(DSDiffuseX),LightDif.X); GetFromDataS(Ord(DSDiffuseY),LightDif.Y); GetFromDataS(Ord(DSDiffuseZ),LightDif.Z); GetFromDataS(Ord(DSAmbientX),LightAmb.X); GetFromDataS(Ord(DSAmbientY),LightAmb.Y); GetFromDataS(Ord(DSAmbientZ),LightAmb.Z); GetFromDataS(Ord(DSTurretRotationX),VXLTurretRotation.X); GetFromDataS(Ord(DSBackgroundColR),BGColor.X); GetFromDataS(Ord(DSBackgroundColG),BGColor.Y); GetFromDataS(Ord(DSBackgroundColB),BGColor.Z); GetFromDataS(Ord(DSUnitCount),UnitCount); GetFromDataS(Ord(DSUnitSpace),UnitSpace); GetFromDataB(Ord(DBDrawBarrel),DrawBarrel); GetFromDataB(Ord(DBDrawTurret),DrawTurret); GetFromDataB(Ord(DBShowDebug),DebugMode); GetFromDataB(Ord(DBShowVoxelCount),ShowVoxelCount); GetFromDataB(Ord(DBDrawGround),Ground_Tex_Draw); GetFromDataB(Ord(DBTileGround),TileGround); GetFromDataB(Ord(DBDrawSky),DrawSky); GetFromDataB(Ord(DBCullFace),CullFace); GetFromDataB(Ord(DBLightGround),LightGround); end; Procedure SaveVVS(const Filename : string); var f : file; Written{,Writtent},x : integer; begin //Writtent := 0; BuildVVSFile; // Collect the data AssignFile(F,Filename); // Open file Rewrite(F,1); // Goto first byte? BlockWrite(F,VVSFile.Version,Sizeof(Single),Written); // Write Version BlockWrite(F,VVSFile.Header,Sizeof(TVVH),Written); // Write Header for x := 0 to VVSFile.Header.DataS_No-1 do BlockWrite(F,VVSFile.DataS[x],Sizeof(TVVD),Written); // Write DataS for x := 0 to VVSFile.Header.DataB_No-1 do BlockWrite(F,VVSFile.DataB[x],Sizeof(TVVDB),Written); // Write DataB CloseFile(F); // Close File end; Procedure LoadVVS(const Filename : string); var f : file; read,x : integer; begin AssignFile(F,Filename); // Open file Reset(F,1); // Goto first byte? BlockRead(F,VVSFile.Version,Sizeof(Single),read); // Read Header if VVSFile.Version <> VVSF_Ver then begin CloseFile(F); MessageBox(0,'Error: Wrong Version','Voxel Viewer Scene Error',0); Exit; end; BlockRead(F,VVSFile.Header,Sizeof(TVVH),read); // Read Header Setlength(VVSFile.DataS,VVSFile.Header.DataS_No); For x := 0 to VVSFile.Header.DataS_No-1 do BlockRead(F,VVSFile.DataS[x],Sizeof(TVVD),read); // Read DataS Setlength(VVSFile.DataB,VVSFile.Header.DataB_No); For x := 0 to VVSFile.Header.DataB_No-1 do BlockRead(F,VVSFile.DataB[x],Sizeof(TVVDB),read); // Read DataB CloseFile(F); SetVVSFile; end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_MODULE.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_MODULE; interface uses {$I uses.def} SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS; type TModuleState = (msNone, msCompiling, msCompiled); TModule = class private kernel: Pointer; UsedModules: TIntegerList; TempUsedModules: TIntegerList; public Name: String; LanguageName: String; FileName: String; Lines: TStringList; S1, S2, S3: Integer; P1, P2, P3: Integer; PInitBegin, PInitEnd: Integer; PFinBegin, PFinEnd: Integer; ModuleNumber: Integer; CancelPos: Integer; SkipParsing: Boolean; State: TModuleState; IsExtra: Boolean; IsPCU: Boolean; IncludedFiles: TStringList; constructor Create(i_kernel: Pointer); destructor Destroy; override; procedure Recalc; end; TModuleList = class(TTypedList) private kernel: Pointer; function GetModule(I: Integer): TModule; public LoadOrder: TIntegerList; constructor Create(i_kernel: Pointer); destructor Destroy; override; function AddModule(const ModuleName, LanguageName: String): TModule; function IndexOf(const ModuleName: String): Integer; function IndexOfModuleById(Id: Integer): Integer; function IsDefinedInPCU(Id: Integer): Boolean; function GetPos(const ModuleName: String; X, Y: Integer): Integer; procedure Recalc; procedure CreateLoadOrder; procedure SaveScript(const FileName: String); procedure CreateError(const Message: string; params: array of Const); procedure RaiseError(const Message: string; params: array of Const); procedure Delete(M: TModule); property Modules[I: Integer]: TModule read GetModule; default; end; implementation uses PAXCOMP_BYTECODE, PAXCOMP_SYMBOL_TABLE, PAXCOMP_KERNEL; constructor TModule.Create(i_kernel: Pointer); begin inherited Create; Self.kernel := i_kernel; Lines := TStringList.Create; UsedModules := TIntegerList.Create; TempUsedModules := TIntegerList.Create; IncludedFiles := TStringList.Create; S1 := 0; S2 := 0; S3 := 0; P1 := 0; P2 := 0; P3 := 0; PInitBegin := 0; PInitEnd := 0; PFinBegin := 0; PFinEnd := 0; CancelPos := -1; end; destructor TModule.Destroy; begin FreeAndNil(Lines); FreeAndNil(UsedModules); FreeAndNil(TempUsedModules); FreeAndNil(IncludedFiles); inherited; end; procedure TModule.Recalc; var I: Integer; begin for I:=1 to TKernel(kernel).Code.Card do with TKernel(kernel).Code[I] do if (Op = OP_BEGIN_MODULE) and (Arg1 = ModuleNumber) then P1 := I else if (Op = OP_END_INTERFACE_SECTION) and (Arg1 = ModuleNumber) then P2 := I else if (Op = OP_END_MODULE) and (Arg1 = ModuleNumber) then P3 := I else if (Op = OP_BEGIN_INITIALIZATION) and (Arg1 = ModuleNumber) then PInitBegin := I else if (Op = OP_END_INITIALIZATION) and (Arg1 = ModuleNumber) then PInitEnd := I else if (Op = OP_BEGIN_FINALIZATION) and (Arg1 = ModuleNumber) then PFinBegin := I else if (Op = OP_END_FINALIZATION) and (Arg1 = ModuleNumber) then PFinEnd := I; end; constructor TModuleList.Create(i_kernel: Pointer); begin inherited Create; Self.kernel := i_kernel; LoadOrder := TIntegerList.Create; end; destructor TModuleList.Destroy; begin FreeAndNil(LoadOrder); inherited; end; function TModuleList.AddModule(const ModuleName, LanguageName: String): TModule; begin result := TModule.Create(kernel); result.Name := ModuleName; result.LanguageName := LanguageName; L.Add(result); end; procedure TModuleList.Delete(M: TModule); var I: Integer; begin for I:=Count - 1 downto 0 do if Modules[I] = M then begin L.Delete(I); FreeAndNil(M); end; end; function TModuleList.GetPos(const ModuleName: String; X, Y: Integer): Integer; var S: String; I, L, CurrX, CurrY: Integer; ch: Char; begin TKernel(kernel).CompletionPrefix := ''; result := -1; I := IndexOf(ModuleName); if I = -1 then Exit; S := Modules[I].Lines.Text + #255; CurrX := -1; CurrY := 0; I := SLow(S) - 1; L := SHigh(S); while I < L do begin Inc(I); Inc(CurrX); if (CurrX = X) and (CurrY = Y) then begin if TKernel(kernel).FindDeclId < 0 then begin result := I; Exit; end; if ByteInSet(S[I], IdsSet + WhiteSpaces + [Ord('!'), Ord('.'), Ord('('), Ord(')'), Ord(';'), Ord(',')]) then begin if ByteInSet(S[I], WhiteSpaces + [Ord(';'), Ord(')'), Ord(',')]) and (ByteInSet(S[I - 1], IdsSet + [Ord('.')])) then begin Dec(i); end; if IsAlpha(S[I]) then begin while ByteInSet(S[I], IdsSet) do begin TKernel(kernel).CompletionPrefix := S[I] + TKernel(kernel).CompletionPrefix; Dec(I); if I = 0 then Exit; end; end; result := I; Exit; end; end; ch := S[I]; if ByteInSet(ch, [10, 13]) then begin Inc(CurrY); if S[I + 1] = #10 then Inc(I); CurrX := -1; end; if (CurrX = X) and (CurrY = Y) then begin if ByteInSet(S[I], IdsSet + WhiteSpaces + [Ord('.'), Ord('('), Ord(')'), Ord(';'), Ord(',')]) then begin if ByteInSet(S[I], WhiteSpaces + [Ord(';'), Ord(')'), Ord(',')]) and (ByteInSet(S[I - 1], IdsSet + [Ord('.')])) then begin Dec(i); end; if IsAlpha(S[I]) then begin while ByteInSet(S[I], IdsSet) do begin TKernel(kernel).CompletionPrefix := S[I] + TKernel(kernel).CompletionPrefix; Dec(I); if I = 0 then Exit; end; end; result := I; Exit; end; end; end; end; function TModuleList.IndexOf(const ModuleName: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if StrEql(Modules[I].Name, ModuleName) then begin result := I; Exit; end; end; function TModuleList.GetModule(I: Integer): TModule; begin result := TModule(L[I]); end; function TModuleList.IndexOfModuleById(Id: Integer): Integer; var I: Integer; M: TModule; begin for I:=0 to Count - 1 do begin M := Modules[I]; if (Id >= M.S1) and (Id <= M.S3) then begin result := I; Exit; end; end; result := -1; end; function TModuleList.IsDefinedInPCU(Id: Integer): Boolean; var I: Integer; begin result := false; I := IndexOfModuleById(Id); if I = -1 then Exit; result := Modules[I].IsPCU; end; procedure TModuleList.Recalc; var I: Integer; begin for I:=0 to Count - 1 do Modules[I].Recalc; end; procedure TModuleList.CreateLoadOrder; var I, J: Integer; M: TModule; Code: TCode; SymbolTable: TSymbolTable; Id: Integer; ModuleIndex: Integer; ok: Boolean; CurrModuleName: String; begin if TKernel(kernel).SignCodeCompletion then begin LoadOrder.Clear; LoadOrder.Add(0); Exit; end; Code := TKernel(kernel).Code; SymbolTable := TKernel(kernel).SymbolTable; Recalc; for I:=0 to Count - 1 do begin M := Modules[I]; M.UsedModules.Clear; M.TempUsedModules.Clear; CurrModuleName := M.Name; for J := M.P1 to M.P2 do begin if Code[J].Op = OP_END_IMPORT then break; if Code[J].Op = OP_BEGIN_USING then begin Id := Code[J].Arg1; if SymbolTable[Id].Host then continue; if Id = 0 then continue; if StrEql(ExtractName(SymbolTable[Id].Name), ExtractName(CurrModuleName)) then continue; ModuleIndex := IndexOfModuleById(Id); if ModuleIndex = -1 then RaiseError(errInternalError, []); M.UsedModules.Add(ModuleIndex); M.TempUsedModules.Add(ModuleIndex); end; end; end; LoadOrder.Clear; if Count = 0 then Exit; if Count = 1 then begin LoadOrder.Add(0); Exit; end; if TKernel(kernel).InterfaceOnly then begin for I:=0 to Count - 1 do LoadOrder.Add(I); Exit; end; repeat ok := false; for I:=0 to Count - 1 do begin if LoadOrder.IndexOf(I) >= 0 then continue; M := Modules[I]; if M.TempUsedModules.Count = 0 then begin ok := true; LoadOrder.Add(I); if LoadOrder.Count = Count then Exit; for J:=0 to Count - 1 do Modules[J].TempUsedModules.DeleteValue(I); break; end; end; if not ok then for I:=0 to Count - 1 do if LoadOrder.IndexOf(I) = -1 then begin CreateError(errCircularUnitReference, [Modules[I].Name]); Exit; end; until false; end; procedure TModuleList.CreateError(const Message: string; params: array of Const); begin TKernel(kernel).CreateError(Message, params); end; procedure TModuleList.RaiseError(const Message: string; params: array of Const); begin TKernel(kernel).RaiseError(Message, params); end; procedure TModuleList.SaveScript(const FileName: String); var I: Integer; S: String; Lst: TStringList; begin if not IsDump then Exit; S := ''; for I:=0 to Count - 1 do S := S + Modules[I].Lines.Text; Lst := TStringList.Create; try Lst.Text := S; Lst.SaveToFile(FileName); finally FreeAndNil(Lst); end; end; end.
// You are asked to write a program that can compute the pay for an employee, // assume that the name and Tax Registration Number (TRN), hours worked, and hourly rate are input. // The output will be the name, TRN, hours worked, and pay for the employee. // Regular pay will be computed as hours (up to 40) times rate, and overtime // will be computed attime and a half (1.5 times hours times rate) for all the hours worked over 40. Program calc_pay; var name, TRN : string; hrs_worked, hrly_rate :real; RegPay, OTP, Pay :real; BEGIN Writeln ('Please enter name'); Readln (name); Writeln ('Please enter Tax Registration Number'); Readln (TRN); Writeln ('Please enter hours worked'); Readln (hrs_worked); Writeln ('Please enter the hourly rate'); Readln (hrly_rate); IF hrs_worked >= 40 THEN Begin RegPay := hrly_rate * 40; OTP := (hrs_worked - 40) * 1.5 * hrly_rate; Pay := RegPay + OTP; END; IF hrs_worked < 40 THEN BEGIN Pay := hrs_worked * hrly_rate; END; Writeln ('The name is: ', name); Writeln ('The Tax Registration Number is: ', TRN); Writeln ('The hours worked is: ', hrs_worked:2:2); Writeln ('The pay is:$', pay:3:2); Readln (); END.
unit o_ObjOutlookDrop; interface uses System.SysUtils, Classes, MapiDefs, MapiUtil, MapiTags, o_ObjOutlookmsg, Activex, Winapi.ShellAPI, System.Win.ComObj, c_OutlookDropTypes, vcl.Dialogs, DragDrop, DropTarget, DragDropFile, Vcl.ComCtrls, Winapi.Windows, Vcl.Forms, o_Outlookdropmessages, o_Outlookdropmessage; type TObjOutlookDrop = class(TObject) private _CleanUpList: TStringList; _ChildForms: TList; _CurrentMessage: TObjOutlookMsg; _HasMessageSession: boolean; _DataFormatAdapterOutlook: TDataFormatAdapter; _OutlookDropMessages: TOutlookDropMessages; _CanUse: Boolean; procedure CleanUp; procedure Reset; procedure ResetView; function GetSender(const AMessage: IMessage): string; function GetSubject(const AMessage: IMessage): string; function ReadBodyText(const AMessage: IMessage): string; procedure SetToMessage(aOutlookMsg: TOutlookDropMessage); public //constructor Create(const AMessage: IMessage; const AStorage: IStorage); property OutlookDropMessages: TOutlookDropMessages read _OutlookDropMessages write _OutlookDropMessages; property DataFormatAdapterOutlook: TDataFormatAdapter read _DataFormatAdapterOutlook write _DataFormatAdapterOutlook; property CanUse: Boolean read _CanUse; procedure Dropped; constructor Create; destructor Destroy; override; end; implementation { TObjOutlookDrop } uses DragDropInternet, Contnrs; const // Attachment listview column indices ColType = 0; ColSize = 1; ColDisplay = 2; ColFile = 3; constructor TObjOutlookDrop.Create; begin _CanUse := true; try LoadMAPI32; OleCheck(MAPIInitialize(@MapiInit)); except _CanUse := false; end; { try OleCheck(MAPIInitialize(@MapiInit)); except on E: Exception do ShowMessage(Format('Failed to initialize MAPI: %s', [E.Message])); end; } _CleanUpList := TStringList.Create; _ChildForms := TObjectList.Create(True); _HasMessageSession := false; _OutlookDropMessages := TOutlookDropMessages.Create; end; destructor TObjOutlookDrop.Destroy; begin Reset; CleanUp; FreeAndNil(_CleanUpList); FreeAndNil(_ChildForms); FreeAndNil(_OutlookDropMessages); try MAPIUninitialize; except end; inherited; end; procedure TObjOutlookDrop.CleanUp; var i: integer; OutlookDataFormat: TOutlookDataFormat; begin _CurrentMessage := nil; for i := 0 to _CleanUpList.Count-1 do try System.SysUtils.DeleteFile(_CleanUpList[i]); except // Ignore errors - nothing we can do about it anyway. end; _CleanUpList.Clear; if (_HasMessageSession) then begin OutlookDataFormat := DataFormatAdapterOutlook.DataFormat as TOutlookDataFormat; OutlookDataFormat.Messages.UnlockSession; _HasMessageSession := False; end; _OutlookDropMessages.Clear; end; procedure TObjOutlookDrop.Reset; begin _ChildForms.Clear; ResetView; end; procedure TObjOutlookDrop.ResetView; begin _CurrentMessage := nil; end; function TObjOutlookDrop.GetSender(const AMessage: IMessage): string; var Prop: PSPropValue; begin if (Succeeded(HrGetOneProp(AMessage, PR_SENDER_NAME, Prop))) then try if (Prop.ulPropTag and PT_UNICODE = PT_UNICODE) then Result := String(PWideChar(Prop.Value.lpszW)) else Result := String(Prop.Value.lpszA); finally MAPIFreeBuffer(Prop); end else Result := ''; end; function TObjOutlookDrop.GetSubject(const AMessage: IMessage): string; var Prop: PSPropValue; begin if (Succeeded(HrGetOneProp(AMessage, PR_SUBJECT, Prop))) then try if (Prop.ulPropTag and PT_UNICODE = PT_UNICODE) then { TODO : TSPropValue.Value.lpszW is declared wrong } Result := String(PWideChar(Prop.Value.lpszW)) else Result := String(Prop.Value.lpszA); finally MAPIFreeBuffer(Prop); end else Result := ''; end; procedure TObjOutlookDrop.Dropped; var OutlookDataFormat: TOutlookDataFormat; i: integer; DropMessage: TOutlookDropMessage; AMessage: IMessage; begin if (_DataFormatAdapterOutlook.DataFormat <> nil) then begin OutlookDataFormat := _DataFormatAdapterOutlook.DataFormat as TOutlookDataFormat; Reset; CleanUp; OutlookDataFormat.Messages.LockSession; _HasMessageSession := True; for i := 0 to OutlookDataFormat.Messages.Count-1 do begin if (Supports(OutlookDataFormat.Messages[i], IMessage, AMessage)) then begin try DropMessage := _OutlookDropMessages.Add; DropMessage.Data := TObjOutlookMsg.Create(AMessage, OutlookDataFormat.Storages[i]); SetToMessage(DropMessage); finally AMessage := nil; end; end; end; end; end; procedure TObjOutlookDrop.SetToMessage(aOutlookMsg: TOutlookDropMessage); const AddressTags: packed record Values: ULONG; PropTags: array[0..1] of ULONG; end = (Values: 2; PropTags: (PR_DISPLAY_NAME, PR_EMAIL_ADDRESS_A)); var i, j: Integer; Table: IMAPITable; Rows: PSRowSet; Value: string; Prop: PSPropValue; Msg: TObjOutlookMsg; begin Msg := TObjOutlookMsg(aOutlookMsg.Data); if (Succeeded(Msg.Msg.GetRecipientTable(0, Table))) then begin if (Succeeded(HrQueryAllRows(Table, PSPropTagArray(@AddressTags), nil, nil, 0, Rows))) then try for i := 0 to integer(Rows.cRows)-1 do begin for j := 0 to Rows.aRow[i].cValues-1 do begin if (Rows.aRow[i].lpProps[j].ulPropTag and PT_UNICODE = PT_UNICODE) then { TODO : TSPropValue.Value.lpszW is declared wrong } Value := String(PWideChar(Rows.aRow[i].lpProps[j].Value.lpszW)) else Value := String(Rows.aRow[i].lpProps[j].Value.lpszA); if (j = 0) then aOutlookMsg.An := Value else begin if Pos('CN=', Value) = 0 then aOutlookMsg.An := aOutlookMsg.An + ';' + Value; end; end; end; finally FreePRows(Rows); end; Table := nil; end; if (Succeeded(HrGetOneProp(Msg.Msg, PR_SENDER_EMAIL_ADDRESS_A, Prop))) then try Value := String(Prop.Value.lpszA); finally MAPIFreeBuffer(Prop); end else Value := ''; aOutlookMsg.Von_eMail := Value; aOutlookMsg.Von := GetSender(Msg.Msg); aOutlookMsg.Betreff := GetSubject(Msg.Msg); aOutlookMsg.BodyText := ReadBodyText(Msg.Msg); end; function TObjOutlookDrop.ReadBodyText(const AMessage: IMessage): String; var Buffer: array of byte; Data: TMemoryStream; SourceStream: IStream; Size: integer; Dummy: Uint64; const BufferSize = 64*1024; // 64Kb MaxMessageSize = 256*1024; // 256 Kb begin Result := ''; if (Succeeded(AMessage.OpenProperty(PR_BODY, IStream, STGM_READ, 0, IUnknown(SourceStream)))) then begin SetLength(Buffer, BufferSize); Data := TMemoryStream.Create; try // Read up to 256Kb from stream SourceStream.Seek(0, STREAM_SEEK_SET, Dummy); while (Data.Size < MaxMessageSize) and (Succeeded(SourceStream.Read(@Buffer[0], Length(Buffer), @Size))) and (Size > 0) do begin Data.Write(Buffer[0], Size); end; Buffer[0] := 0; Data.Write(Buffer[0], 1); Data.Write(Buffer[0], 1); Result := PChar(Data.Memory); finally Data.Free; end; end; end; end.
UNIT nosogeneral; { nosogeneral 1.2 December 27th, 2022 Noso Unit for general functions Requires: Not dependencyes } {$mode ObjFPC}{$H+} INTERFACE uses Classes, SysUtils, Process, StrUtils, IdTCPClient, IdGlobal, fphttpclient, opensslsockets, fileutil; {Generic} Function Parameter(LineText:String;ParamNumber:int64;de_limit:string=' '):String; Function IsValidIP(IpString:String):boolean; Function GetSupply(block:integer):int64; Function Restar(number:int64):int64; Function HashrateToShow(speed:int64):String; Function Int2Curr(LValue: int64): string; Procedure RunExternalProgram(ProgramToRun:String); Function GetStackRequired(block:integer):int64; Function GetMNsPercentage(block:integer;MainnetMode:String='NORMAL'):integer; Function GetPoSPercentage(block:integer):integer; Function GetDevPercentage(block:integer):integer; Function GetMinimumFee(amount:int64):Int64; Function GetMaximunToSend(amount:int64):int64; {Network} Function RequestLineToPeer(host:String;port:integer;command:string):string; Function RequestToPeer(hostandPort,command:string):string; Function SendApiRequest(urltocheck:string):String; {File handling} function SaveTextToDisk(const aFileName: TFileName; const aText: String): Boolean; Function LoadTextFromDisk(const aFileName: TFileName): string; function TryCopyFile(Source, destination:string):boolean; function TryDeleteFile(filename:string):boolean; IMPLEMENTATION {$REGION Generic} {Returns a specific parameter number of text} Function Parameter(LineText:String;ParamNumber:int64;de_limit:string=' '):String; var Temp : String = ''; ThisChar : Char; Contador : int64 = 1; WhiteSpaces : int64 = 0; parentesis : boolean = false; Begin while contador <= Length(LineText) do begin ThisChar := Linetext[contador]; if ((thischar = '(') and (not parentesis)) then parentesis := true else if ((thischar = '(') and (parentesis)) then begin result := ''; exit; end else if ((ThisChar = ')') and (parentesis)) then begin if WhiteSpaces = ParamNumber then begin result := temp; exit; end else begin parentesis := false; temp := ''; end; end else if ((ThisChar = de_limit) and (not parentesis)) then begin WhiteSpaces := WhiteSpaces +1; if WhiteSpaces > Paramnumber then begin result := temp; exit; end; end else if ((ThisChar = de_limit) and (parentesis) and (WhiteSpaces = ParamNumber)) then begin temp := temp+ ThisChar; end else if WhiteSpaces = ParamNumber then temp := temp+ ThisChar; contador := contador+1; end; if temp = de_limit then temp := ''; Result := Temp; End; {Verify if a string is valid IPv4 address} Function IsValidIP(IpString:String):boolean; var valor1,valor2,valor3,valor4: integer; Begin result := true; //IPString := StringReplace(IPString,'.',' ',[rfReplaceAll, rfIgnoreCase]); valor1 := StrToIntDef(Parameter(IPString,0,'.'),-1); valor2 := StrToIntDef(Parameter(IPString,1,'.'),-1); valor3 := StrToIntDef(Parameter(IPString,2,'.'),-1); valor4 := StrToIntDef(Parameter(IPString,3,'.'),-1); if ((valor1 <0) or (valor1>255)) then result := false; if ((valor2 <0) or (valor2>255)) then result := false; if ((valor3 <0) or (valor3>255)) then result := false; if ((valor4 <0) or (valor4>255)) then result := false; if ((valor1=192) and (valor2=168)) then result := false; if ((valor1=127) and (valor2=0)) then result := false; End; {Returns the circulating supply on the specified block} Function GetSupply(block:integer):int64; Begin Result := 0; if block < 210000 then result := (block*5000000000)+1030390730000 else if ((block >= 210000) and (block < 420000)) then begin Inc(result,(209999*5000000000)+1030390730000); Inc(result,(block-209999)*5000000000); end; End; {Convert any positive integer in negative} Function Restar(number:int64):int64; Begin if number > 0 then Result := number-(Number*2) else Result := number; End; {Converts a integer in a human readeaeble format for hashrate} Function HashrateToShow(speed:int64):String; Begin if speed>1000000000 then result := FormatFloat('0.00',speed/1000000000)+' Gh/s' else if speed>1000000 then result := FormatFloat('0.00',speed/1000000)+' Mh/s' else if speed>1000 then result := FormatFloat('0.00',speed/1000)+' Kh/s' else result := speed.ToString+' h/s' End; {Converts a integer in a human readeaeble format for currency} Function Int2Curr(LValue: int64): string; Begin Result := IntTostr(Abs(LValue)); result := AddChar('0',Result, 9); Insert('.',Result, Length(Result)-7); If LValue <0 THen Result := '-'+Result; End; {Runs an external program} Procedure RunExternalProgram(ProgramToRun:String); var Process: TProcess; I: Integer; Begin Process := TProcess.Create(nil); TRY Process.InheritHandles := False; Process.Options := []; Process.ShowWindow := swoShow; for I := 1 to GetEnvironmentVariableCount do Process.Environment.Add(GetEnvironmentString(I)); {$IFDEF UNIX} process.Executable := 'bash'; process.Parameters.Add(ProgramToRun); {$ENDIF} {$IFDEF WINDOWS} Process.Executable := ProgramToRun; {$ENDIF} Process.Execute; EXCEPT ON E:Exception do END; {TRY} Process.Free; End; {Returns the required noso stack size} Function GetStackRequired(block:integer):int64; Begin result := (GetSupply(block)*20) div 10000; if result > 1100000000000 then result := 1100000000000; if block > 110000 then result := 1050000000000; End; {Returns the MNs percentage for the specified block (0 to 10000)} Function GetMNsPercentage(block:integer;MainnetMode:String='NORMAL'):integer; Begin result := 0; if block >= 48010{MNBlockStart} then begin result := 2000{MNsPercentage} + (((block-48010{MNBlockStart}) div 4000) * 100); if block >= 88400{PoSBlockEnd} then Inc(Result,1000); if result > 6000 then result := 6000; if AnsiContainsStr(MainnetMode,'MNSONLY') then result := 9000; end; End; {Returns the PoS percentage for the specified block (0 to 10000)} Function GetPoSPercentage(block:integer):integer; Begin result := 0; if ((block > 8424) and (block < 40000)) then result := 1000{PoSPercentage}; if block >= 40000 then begin result := 1000{PoSPercentage} + (((block-39000) div 1000) * 100); if result > 2000 then result := 2000; end; if block >= 88400{PoSBlockEnd} then result := 0; End; {Returns the Project percentage for the specified block} Function GetDevPercentage(block:integer):integer; Begin result := 0; if block >= 88400{PoSBlockEnd} then result := 1000; End; {Returns the minimum fee to be paid for the specified amount} Function GetMinimumFee(amount:int64):Int64; Begin Result := amount div 10000{Comisiontrfr}; if result < 1000000{MinimunFee} then result := 1000000{MinimunFee}; End; {Returns the maximum that can be sent from the specified amount} Function GetMaximunToSend(amount:int64):int64; var maximo : int64; comision : int64; Envio : int64; Diferencia : int64; Begin if amount < 1000000{MinimunFee} then exit(0); maximo := (amount * 10000{Comisiontrfr}) div (10000{Comisiontrfr}+1); comision := maximo div 10000{Comisiontrfr}; if Comision < 1000000{MinimunFee} then Comision := 1000000{MinimunFee}; Envio := maximo + comision; Diferencia := amount-envio; result := maximo+diferencia; End; {$ENDREGION} {$REGION Network} Function RequestLineToPeer(host:String;port:integer;command:string):string; var Client : TidTCPClient; Begin Result := ''; Client := TidTCPClient.Create(nil); Client.Host:=host; Client.Port:=Port; Client.ConnectTimeout:= 1000; Client.ReadTimeout:=1000; TRY Client.Connect; Client.IOHandler.WriteLn(Command); client.IOHandler.MaxLineLength:=Maxint; Result := Client.IOHandler.ReadLn(); EXCEPT on E:Exception do END;{Try} if client.Connected then Client.Disconnect(); client.Free; End; Function RequestToPeer(hostandPort,command:string):string; var Client : TidTCPClient; Begin Result := ''; Client := TidTCPClient.Create(nil); Client.Host:=Parameter(hostandPort,0); Client.Port:=StrToIntDef(Parameter(hostandPort,1),8080); Client.ConnectTimeout:= 1000; Client.ReadTimeout:=1000; TRY Client.Connect; Client.IOHandler.WriteLn(Command); client.IOHandler.MaxLineLength:=Maxint; Result := Client.IOHandler.ReadLn(); EXCEPT on E:Exception do END;{Try} if client.Connected then Client.Disconnect(); client.Free; End; Function SendApiRequest(urltocheck:string):String; var Conector : TFPHttpClient; Begin Result := ''; Conector := TFPHttpClient.Create(nil); conector.ConnectTimeout:=3000; conector.IOTimeout:=3000; TRY result := Trim(Conector.SimpleGet(urltocheck)); EXCEPT on E: Exception do END;//TRY Conector.Free; End; {$ENDREGION} {$REGION File handling} Function SaveTextToDisk(const aFileName: TFileName; const aText: String): Boolean; var LStream: TStringStream; Begin Result := true; LStream := TStringStream.Create(aText); TRY LStream.SaveToFile(aFileName); EXCEPT result := false; END;{Try} LStream.Free; End; Function LoadTextFromDisk(const aFileName: TFileName): string; var LStream: TStringStream; Begin Result := ''; LStream := TStringStream.Create; TRY LStream.LoadFromFile(aFileName); Result := LStream.DataString; EXCEPT result := ''; END;{Try} LStream.Free; End; function TryCopyFile(Source, destination:string):boolean; Begin result := true; TRY copyfile (source,destination,[cffOverwriteFile],true); EXCEPT on E:Exception do result := false; END; {TRY} End; {Try to delete a file safely} function TryDeleteFile(filename:string):boolean; Begin result := deletefile(filename); End; {$ENDREGION} END.{UNIT}
{@abstract(The main purpose @name is to define @link(TfrmPixelPoint) which allows the user to specify the real world coordinates of a pixel location on a bitmap.)} unit frmPixelPointUnit; interface uses SysUtils, Types, Classes, Variants, Graphics, Controls, Forms, Dialogs, StdCtrls, frmCustomGoPhastUnit, Buttons, GoPhastTypes, ArgusDataEntry; type {@abstract(@name is used to allow the user to specify the real world coordinates of a pixel location on a bitmap.)} TfrmPixelPoint = class(TfrmCustomGoPhast) // @name: TBitBtn; // Clicking @name closes @classname without doing anything. btnCancel: TBitBtn; // @name: TBitBtn; // Clicking @name displays help on @classname. btnHelp: TBitBtn; // @name: TBitBtn; // See @link(btnOKClick). btnOK: TBitBtn; // @name: TLabel; // @name displays "X". lblX: TLabel; // @name: TLabel; // @name displays "Y". lblY: TLabel; // @name: TRbwDataEntry; // The user specifies the real-world X-coordinate of the pixel in @name rdeX: TRbwDataEntry; // @name: TRbwDataEntry; // The user specifies the real-world Y-coordinate of the pixel in @name rdeY: TRbwDataEntry; // @name calls @link(SetData). procedure btnOKClick(Sender: TObject); private // @name: integer; // @name is the X-pixel coordinate in an image. FPixelX: integer; // @name is the Y-pixel coordinate in an image. FPixelY: integer; // @name specifies a new real-world location of a pixel and stores it //in TfrmImportBitmap.@link(TfrmImportBitmap.dgPoints). procedure SetData; { Private declarations } public // @name stores the x and y coordinates of a pixel. public procedure GetData(const AViewDirection: TViewDirection; const X, Y: integer); { Public declarations } end; implementation uses frmImportBitmapUnit; resourcestring StrZ = 'Z'; {$R *.dfm} { TfrmPixelPoint } procedure TfrmPixelPoint.GetData(const AViewDirection: TViewDirection; const X, Y: integer); begin case AViewDirection of vdTop: begin // do nothing/ end; vdFront: begin lblY.Caption := StrZ; end; vdSide: begin lblX.Caption := StrZ; end; else Assert(False); end; FPixelX := X; FPixelY := Y; end; procedure TfrmPixelPoint.btnOKClick(Sender: TObject); begin inherited; SetData; end; procedure TfrmPixelPoint.SetData; begin frmImportBitmap.AddPoint(FPixelX, FPixelY, StrToFloat(rdeX.Text), StrToFloat(rdeY.Text)); end; end.
unit UDSummaryFields; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32; type TCrpeSummaryFieldsDlg = class(TForm) pnlSummaryFields: TPanel; lblNumber: TLabel; lbNumbers: TListBox; editCount: TEdit; lblCount: TLabel; gbFormat: TGroupBox; editFieldName: TEdit; lblFieldName: TLabel; lblFieldType: TLabel; editFieldType: TEdit; lblFieldLength: TLabel; editFieldLength: TEdit; btnBorder: TButton; btnFont: TButton; btnFormat: TButton; editTop: TEdit; lblTop: TLabel; lblLeft: TLabel; editLeft: TEdit; lblSection: TLabel; editWidth: TEdit; lblWidth: TLabel; lblHeight: TLabel; editHeight: TEdit; cbSection: TComboBox; btnOk: TButton; btnClear: TButton; FontDialog1: TFontDialog; lblField: TLabel; lblSummarizedField: TLabel; lblSummaryType: TLabel; lblSummaryTypeN: TLabel; cbSummaryTypeField: TComboBox; editName: TEdit; cbSummaryType: TComboBox; editSummaryTypeN: TEdit; cbSummarizedField: TComboBox; lblHeaderAreaCode: TLabel; lblFooterAreaCode: TLabel; editHeaderAreaCode: TEdit; editFooterAreaCode: TEdit; rgUnits: TRadioGroup; btnHiliteConditions: TButton; procedure btnClearClick(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdateSummaryFields; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnFontClick(Sender: TObject); procedure EditSizeEnter(Sender: TObject); procedure EditSizeExit(Sender: TObject); procedure cbSectionChange(Sender: TObject); procedure btnBorderClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure rgUnitsClick(Sender: TObject); procedure btnFormatClick(Sender: TObject); procedure editNameChange(Sender: TObject); procedure cbSummarizedFieldChange(Sender: TObject); procedure cbSummaryTypeChange(Sender: TObject); procedure cbSummaryTypeFieldChange(Sender: TObject); procedure editSummaryTypeNChange(Sender: TObject); procedure btnHiliteConditionsClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; SFIndex : smallint; PrevSize : string; end; var CrpeSummaryFieldsDlg: TCrpeSummaryFieldsDlg; bSummaryFields : boolean; implementation {$R *.DFM} uses TypInfo, UCrpeUtl, UDBorder, UDFormat, UDHiliteConditions, UDFont, UCrpeClasses; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.FormCreate(Sender: TObject); begin bSummaryFields := True; LoadFormPos(Self); btnOk.Tag := 1; SFIndex := -1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.FormShow(Sender: TObject); begin UpdateSummaryFields; end; {------------------------------------------------------------------------------} { UpdateSummaryFields } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.UpdateSummaryFields; var OnOff : boolean; i : integer; begin SFIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then OnOff := False else begin OnOff := (Cr.SummaryFields.Count > 0); {Get SummaryFields Index} if OnOff then begin if Cr.SummaryFields.ItemIndex > -1 then SFIndex := Cr.SummaryFields.ItemIndex else SFIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff then begin {Fill Section ComboBox} cbSection.Clear; cbSection.Items.AddStrings(Cr.SectionFormat.Names); {Fill SummarizedField ComboBox} cbSummarizedField.Clear; cbSummarizedField.Items.AddStrings(Cr.Tables.FieldNames); {Fill SummaryType ComboBox} cbSummaryType.Clear; cbSummaryType.Items.Add('stSum'); cbSummaryType.Items.Add('stAverage'); cbSummaryType.Items.Add('stSampleVariance'); cbSummaryType.Items.Add('stSampleStdDev'); cbSummaryType.Items.Add('stMaximum'); cbSummaryType.Items.Add('stMinimum'); cbSummaryType.Items.Add('stCount'); cbSummaryType.Items.Add('stPopVariance'); cbSummaryType.Items.Add('stPopStdDev'); cbSummaryType.Items.Add('stDistinctCount'); cbSummaryType.Items.Add('stCorrelation'); cbSummaryType.Items.Add('stCoVariance'); cbSummaryType.Items.Add('stWeightedAvg'); cbSummaryType.Items.Add('stMedian'); cbSummaryType.Items.Add('stPercentile'); cbSummaryType.Items.Add('stNthLargest'); cbSummaryType.Items.Add('stNthSmallest'); cbSummaryType.Items.Add('stMode'); cbSummaryType.Items.Add('stNthMostFrequent'); cbSummaryType.Items.Add('stPercentage'); {Fill SummaryTypeField ComboBox} cbSummaryTypeField.Clear; cbSummaryTypeField.Items.AddStrings(Cr.Tables.FieldNames); {Fill Numbers ListBox} for i := 0 to Cr.SummaryFields.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.SummaryFields.Count); lbNumbers.ItemIndex := SFIndex; lbNumbersClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.lbNumbersClick(Sender: TObject); var OnOff : Boolean; i : integer; begin SFIndex := lbNumbers.ItemIndex; OnOff := (Cr.SummaryFields[SFIndex].Handle <> 0); btnBorder.Enabled := OnOff; btnFont.Enabled := OnOff; btnFormat.Enabled := OnOff; {Properties} editName.Text := Cr.SummaryFields.Item.Name; cbSummarizedField.ItemIndex := cbSummarizedField.Items.IndexOf(Cr.SummaryFields.Item.SummarizedField); cbSummaryType.ItemIndex := Ord(Cr.SummaryFields.Item.SummaryType); case Cr.SummaryFields.Item.SummaryType of stSum, stAverage, stSampleVariance, stSampleStdDev, stMaximum, stMinimum, stCount, stPopVariance, stPopStdDev, stDistinctCount, stMedian, stMode : begin lblSummaryTypeN.Visible := False; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := False; end; {Use SummaryTypeField} stCorrelation, stCoVariance, stWeightedAvg : begin lblSummaryTypeN.Visible := True; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := True; cbSummaryTypeField.ItemIndex := cbSummaryTypeField.Items.IndexOf(Cr.SummaryFields.Item.SummaryTypeField); end; {Use SummaryTypeN} stPercentile, stNthLargest, stNthSmallest, stNthMostFrequent : begin lblSummaryTypeN.Visible := True; cbSummaryTypeField.Visible := False; editSummaryTypeN.Visible := True; editSummaryTypeN.Text := IntToStr(Cr.SummaryFields.Item.SummaryTypeN); end; {Use SummaryTypeField with GrandTotal field} stPercentage : begin lblSummaryTypeN.Visible := True; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := True; i := cbSummaryTypeField.Items.IndexOf(Cr.SummaryFields.Item.SummaryTypeField); if i > -1 then cbSummaryTypeField.ItemIndex := i else cbSummaryTypeField.Text := Cr.SummaryFields.Item.SummaryTypeField; end; end; editHeaderAreaCode.Text := Cr.SummaryFields.Item.HeaderAreaCode; editFooterAreaCode.Text := Cr.SummaryFields.Item.FooterAreaCode; {Formatting} editFieldName.Text := Cr.SummaryFields.Item.FieldName; editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType), Ord(Cr.SummaryFields.Item.FieldType)); editFieldLength.Text := IntToStr(Cr.SummaryFields.Item.FieldLength); cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.SummaryFields.Item.Section); rgUnitsClick(Self); {Set HiliteConditions button} btnHiliteConditions.Enabled := (Cr.SummaryFields.Item.FieldType in [fvInt8s..fvCurrency]) and OnOff; end; {------------------------------------------------------------------------------} { editFieldChange } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.editNameChange(Sender: TObject); begin Cr.SummaryFields.Item.Name := editName.Text; end; {------------------------------------------------------------------------------} { cbSummarizedFieldChange } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.cbSummarizedFieldChange(Sender: TObject); begin Cr.SummaryFields.Item.SummarizedField := cbSummarizedField.Items[cbSummarizedField.ItemIndex]; UpdateSummaryFields; end; {------------------------------------------------------------------------------} { cbSummaryTypeChange } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.cbSummaryTypeChange(Sender: TObject); var i : integer; begin Cr.SummaryFields.Item.SummaryType := TCrSummaryType(cbSummaryType.ItemIndex); case Cr.SummaryFields.Item.SummaryType of stSum, stAverage, stSampleVariance, stSampleStdDev, stMaximum, stMinimum, stCount, stPopVariance, stPopStdDev, stDistinctCount, stMedian, stMode : begin lblSummaryTypeN.Visible := False; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := False; end; {Use SummaryTypeField} stCorrelation, stCoVariance, stWeightedAvg : begin lblSummaryTypeN.Visible := True; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := True; cbSummaryTypeField.ItemIndex := cbSummaryTypeField.Items.IndexOf(Cr.SummaryFields.Item.SummaryTypeField); end; {Use SummaryTypeN} stPercentile, stNthLargest, stNthSmallest, stNthMostFrequent : begin lblSummaryTypeN.Visible := True; cbSummaryTypeField.Visible := False; editSummaryTypeN.Visible := True; editSummaryTypeN.Text := IntToStr(Cr.SummaryFields.Item.SummaryTypeN); end; {Use SummaryTypeField with GrandTotal field} stPercentage : begin lblSummaryTypeN.Visible := True; editSummaryTypeN.Visible := False; cbSummaryTypeField.Visible := True; i := cbSummaryTypeField.Items.IndexOf(Cr.SummaryFields.Item.SummaryTypeField); if i > -1 then cbSummaryTypeField.ItemIndex := i else cbSummaryTypeField.Text := Cr.SummaryFields.Item.SummaryTypeField; end; end; UpdateSummaryFields; end; {------------------------------------------------------------------------------} { cbSummaryTypeFieldChange } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.cbSummaryTypeFieldChange(Sender: TObject); begin Cr.SummaryFields.Item.SummaryTypeField := cbSummaryTypeField.Items[cbSummaryTypeField.ItemIndex]; UpdateSummaryFields; end; {------------------------------------------------------------------------------} { editSummaryTypeNChange } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.editSummaryTypeNChange(Sender: TObject); begin if IsNumeric(editSummaryTypeN.Text) then Cr.SummaryFields.Item.SummaryTypeN := StrToInt(editSummaryTypeN.Text); UpdateSummaryFields; end; {------------------------------------------------------------------------------} { rgUnitsClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.rgUnitsClick(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin editTop.Text := TwipsToInchesStr(Cr.SummaryFields.Item.Top); editLeft.Text := TwipsToInchesStr(Cr.SummaryFields.Item.Left); editWidth.Text := TwipsToInchesStr(Cr.SummaryFields.Item.Width); editHeight.Text := TwipsToInchesStr(Cr.SummaryFields.Item.Height); end else {twips} begin editTop.Text := IntToStr(Cr.SummaryFields.Item.Top); editLeft.Text := IntToStr(Cr.SummaryFields.Item.Left); editWidth.Text := IntToStr(Cr.SummaryFields.Item.Width); editHeight.Text := IntToStr(Cr.SummaryFields.Item.Height); end; end; {------------------------------------------------------------------------------} { EditSizeEnter } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.EditSizeEnter(Sender: TObject); begin if Sender is TEdit then PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { EditSizeExit } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.EditSizeExit(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.SummaryFields.Item.Top := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.SummaryFields.Item.Left := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.SummaryFields.Item.Width := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.SummaryFields.Item.Height := InchesStrToTwips(TEdit(Sender).Text); UpdateSummaryFields; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.SummaryFields.Item.Top := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.SummaryFields.Item.Left := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.SummaryFields.Item.Width := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.SummaryFields.Item.Height := StrToInt(TEdit(Sender).Text); end; end; end; {------------------------------------------------------------------------------} { cbSectionChange } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.cbSectionChange(Sender: TObject); begin Cr.SummaryFields.Item.Section := cbSection.Items[cbSection.ItemIndex]; end; {------------------------------------------------------------------------------} { btnBorderClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.btnBorderClick(Sender: TObject); begin CrpeBorderDlg := TCrpeBorderDlg.Create(Application); CrpeBorderDlg.Border := Cr.SummaryFields.Item.Border; CrpeBorderDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnFontClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.btnFontClick(Sender: TObject); begin if Cr.Version.Crpe.Major > 7 then begin CrpeFontDlg := TCrpeFontDlg.Create(Application); CrpeFontDlg.Crf := Cr.SummaryFields.Item.Font; CrpeFontDlg.ShowModal; end else begin FontDialog1.Font.Assign(Cr.SummaryFields.Item.Font); if FontDialog1.Execute then Cr.SummaryFields.Item.Font.Assign(FontDialog1.Font); end; end; {------------------------------------------------------------------------------} { btnFormatClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.btnFormatClick(Sender: TObject); begin CrpeFormatDlg := TCrpeFormatDlg.Create(Application); CrpeFormatDlg.Format := Cr.SummaryFields.Item.Format; CrpeFormatDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnHiliteConditionsClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.btnHiliteConditionsClick(Sender: TObject); begin CrpeHiliteConditionsDlg := TCrpeHiliteConditionsDlg.Create(Application); CrpeHiliteConditionsDlg.Crh := Cr.SummaryFields.Item.HiliteConditions; CrpeHiliteConditionsDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.btnClearClick(Sender: TObject); begin Cr.SummaryFields.Clear; UpdateSummaryFields; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.btnOkClick(Sender: TObject); begin rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateSummaryFields call} if (not IsStrEmpty(Cr.ReportName)) and (SFIndex > -1) then begin editSizeExit(editTop); editSizeExit(editLeft); editSizeExit(editWidth); editSizeExit(editHeight); end; SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeSummaryFieldsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bSummaryFields := False; Release; end; end.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uSingleton; type TForm1 = class(TForm) btnCheckInstance: TButton; btnInstanceSingleton: TButton; btnClose: TButton; procedure btnCloseClick(Sender: TObject); procedure btnCheckInstanceClick(Sender: TObject); procedure btnInstanceSingletonClick(Sender: TObject); private FVariable: TSingleton; FPointerAlreadyInitiated: Boolean; procedure CheckInstance(aCheckOnly: boolean = False); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnCheckInstanceClick(Sender: TObject); begin CheckInstance; end; procedure TForm1.btnCloseClick(Sender: TObject); begin Application.Terminate; end; procedure TForm1.btnInstanceSingletonClick(Sender: TObject); begin FVariable := TSingleton.GetInstance; CheckInstance; FPointerAlreadyInitiated := Assigned(FVariable); end; procedure TForm1.CheckInstance(aCheckOnly: boolean); begin if TSingleton.InstanceNull(FVariable)then MessageBox(Handle, 'Null pointer', 'Information', MB_OK) else if FPointerAlreadyInitiated then MessageBox(Handle, 'Pointer Already Initiated', 'Information', MB_OK) else MessageBox(Handle, 'Pointer Initiated', 'Information', MB_OK) end; end.
unit CtkCore; { Catarinka Core Registration Library Copyright (c) 2013-2020 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} Winapi.Windows, System.Classes, System.SysUtils, Winapi.ShellAPI, System.TypInfo, CtkTimer, {$ELSE} Windows, Classes, SysUtils, ShellAPI, TypInfo, {$ENDIF} Lua, LuaObject; function RegisterCatarinka(L: plua_State): integer; cdecl; implementation uses pLua, pLuaTable, CtkFunctions, CtkStrList, CtkStrListParser, CtkHTMLParser, CtkJSON, CtkTarman, CatStrings; function pushctkmethod(L: plua_State; const name:string; func_table:array of luaL_Reg): integer; begin result := plua_pushcfunction_fromarray(L, name, func_table); // if name is the special _info, return table with number of functions and classes if (result = 0) and (name = '_info') then begin result := 1; lua_newtable(L); plua_SetFieldValue(L, 'methodcount', high(func_table)); plua_SetFieldValue(L, 'classcount', 0); end; end; function pushctkmethod_orobj(L: plua_State; const name:string; func_table:array of luaL_Reg; class_table:array of pluaObject_Reg): integer; begin // pushes Lua object if there is one with the given name result := plua_PushObjectFromArray(L, name,class_table); // if no object is found, check for function with given name if (result = 0) then result := plua_pushcfunction_fromarray(L, name, func_table); // if name is the special _info, return table with number of functions and classes if (result = 0) and (name = '_info') then begin result := 1; lua_newtable(L); plua_SetFieldValue(L, 'methodcount', high(func_table)); plua_SetFieldValue(L, 'classcount', high(class_table)+1); end; end; function get_string(L: plua_State): integer; cdecl; const string_table : array [1..27] of luaL_Reg = ( (name:'after';func:str_after), (name:'before';func:str_before), (name:'beginswith';func:str_beginswith), (name:'between';func:str_between), (name:'comparever';func:str_compareversion), (name:'decrease';func:str_decrease), (name:'endswith';func:str_endswith), (name:'gettoken';func:str_gettoken), (name:'increase';func:str_increase), (name:'ishex';func:str_ishex), (name:'isint';func:str_isint), (name:'lastchar';func:str_lastchar), (name:'match';func:str_wildmatch), (name:'matchx';func:str_wildmatchx), (name:'matchver';func:str_matchversion), (name:'matchverpat';func:str_matchversionex), (name:'maxlen';func:str_maxlen), (name:'occur';func:str_occur), (name:'random';func:str_random), (name:'replace';func:str_replace), (name:'replacefirst';func:str_replace_first), (name:'stripblanklines';func:str_stripblanklines), (name:'stripquotes';func:str_stripquotes), (name:'swapcase';func:str_swapcase), (name:'titlecase';func:str_titlecase), (name:'trim';func:str_trim), (name:nil;func:nil) ); const class_table: array [1..2] of pluaObject_Reg = ( (name:'list';proc:RegisterCatarinkaStrList), (name:'loop';proc:RegisterCatarinkaStrListParser) ); begin result := pushctkmethod_orobj(L, lua_tostring(L,2), string_table, class_table); end; function get_jsonfields(L: plua_State): integer; cdecl; const json_table : array [1..2] of luaL_Reg = ( (name:'escape';func:json_escape), (name:nil;func:nil) ); const class_table: array [1..1] of pluaObject_Reg = ( (name:'object';proc:RegisterCatarinkaJSON) ); begin result := pushctkmethod_orobj(L, lua_tostring(L,2), json_table, class_table); end; function get_htmlfields(L: plua_State): integer; cdecl; const html_table : array [1..7] of luaL_Reg = ( (name:'beautifycss';func:str_beautifycss), (name:'beautifyjs';func:str_beautifyjs), (name:'escape';func:html_escape), (name:'gettagcontents';func:str_extracttagcontent), (name:'striptags';func:html_striptags), (name:'unescape';func:html_unescape), (name:nil;func:nil) ); const class_table: array [1..1] of pluaObject_Reg = ( (name:'parser';proc:RegisterCatarinkaHTMLParser) ); begin result := pushctkmethod_orobj(L, lua_tostring(L,2), html_table, class_table); end; function get_base64fields(L: plua_State): integer; cdecl; const b64_table : array [1..3] of luaL_Reg = ( (name:'encode';func:str_base64enc), (name:'decode';func:str_base64dec), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), b64_table); end; function get_convertfields(L: plua_State): integer; cdecl; const conv_table : array [1..8] of luaL_Reg = ( (name:'commatostr';func:conv_commatexttostr), (name:'hextoint';func:conv_hextoint), (name:'hextostr';func:conv_hextostr), (name:'inttohex';func:conv_inttohex), (name:'strtoalphanum';func:str_toalphanum), (name:'strtohex';func:conv_strtohex), (name:'strtocomma';func:conv_strtocommatext), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), conv_table); end; function get_cryptofields(L: plua_State): integer; cdecl; const crypto_table : array [1..8] of luaL_Reg = ( (name:'md5';func:conv_strtomd5), (name:'randompwd';func:str_randompassword), (name:'randompwdadmin';func:str_randompasswordadmin), (name:'sha1';func:conv_strtosha1), (name:'sha256';func:conv_strtosha256), (name:'sha384';func:conv_strtosha384), (name:'sha512';func:conv_strtosha512), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), crypto_table); end; function get_dirfields(L: plua_State): integer; cdecl; const dir_table : array [1..8] of luaL_Reg = ( (name:'create';func:file_mkdir), (name:'delete';func:file_deldir), (name:'exists';func:file_direxists), (name:'getdirlist';func:file_getdirs), (name:'getfilelist';func:file_getdirfiles), (name:'packtotar';func:Lua_DirToTAR), (name:'unpackfromtar';func:Lua_TARToDir), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), dir_table); end; function get_filefields(L: plua_State): integer; cdecl; const file_table : array [1..14] of luaL_Reg = ( (name:'canopen';func:file_canopen), (name:'cleanname';func:file_cleanname), (name:'copy';func:file_copy), (name:'delete';func:file_delete), (name:'exec';func:file_exec), (name:'exechide';func:file_exechidden), (name:'exists';func:file_exists), (name:'getcontents';func:file_gettostr), (name:'getdir';func:file_extractdir), (name:'getname';func:file_extractname), (name:'getsize';func:file_getsize), (name:'getext';func:file_getext), (name:'getver';func:file_getversion), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), file_table); end; function get_httpfields(L: plua_State): integer; cdecl; const http_table : array [1..4] of luaL_Reg = ( (name:'crackrequest';func:http_crackrequest), (name:'getheader';func:http_gethdrfield), (name:'postdatatojson';func:http_postdatatojson), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), http_table); end; function get_netfields(L: plua_State): integer; cdecl; const net_table : array [1..3] of luaL_Reg = ( (name:'nametoip';func:net_nametoip), (name:'iptoname';func:net_iptoname), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), net_table); end; function get_taskfields(L: plua_State): integer; cdecl; const task_table : array [1..3] of luaL_Reg = ( (name:'isrunning';func:task_isrunning), (name:'kill';func:task_kill), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), task_table); end; function get_urlfields(L: plua_State): integer; cdecl; const url_table : array [1..12] of luaL_Reg = ( (name:'changepath';func:url_changepath), (name:'combine';func:url_combine), (name:'crack';func:url_crack), (name:'decode';func:url_decode), (name:'encode';func:url_encode), (name:'encodefull';func:url_encodefull), (name:'fileurltofilename';func:file_fileurltofilename), (name:'genfromhost';func:hostporttourl), (name:'getfileext';func:url_getfileext), (name:'getfilename';func:url_getfilename), (name:'gettiny';func:url_gettiny), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), url_table); end; function get_utilfields(L: plua_State): integer; cdecl; const utils_table : array [1..8] of luaL_Reg = ( (name:'delay';func:utils_delay), (name:'getarg';func:utils_getarg), (name:'hasarg';func:utils_hasarg), (name:'hassoftware';func:utils_hassoftwareinstalled), (name:'clipboard_gettext';func:utils_clipboard_gettext), (name:'clipboard_settext';func:utils_clipboard_settext), {$IFDEF DXE2_OR_UP} (name:'settimeout';func:utils_settimeout), {$ELSE} (name:'settimeout';func:utils_function_notavailable), {$ENDIF} (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), utils_table); end; function get_regexfields(L: plua_State): integer; cdecl; const re_table : array [1..4] of luaL_Reg = ( (name:'find';func:str_regexfind), (name:'match';func:str_regexmatch), (name:'replace';func:str_regexreplace), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), re_table); end; function get_consolefields(L: plua_State): integer; cdecl; const cs_table : array [1..6] of luaL_Reg = ( (name:'printgreen';func:console_printgreen), (name:'printred';func:console_printred), (name:'printwhite';func:console_printwhite), (name:'readln';func:console_readline), (name:'readpwd';func:console_readpassword), (name:nil;func:nil) ); begin result := pushctkmethod(L, lua_tostring(L,2), cs_table); end; function RegisterCatarinka(L: plua_State): integer; cdecl; begin lua_newtable(L); plua_SetFieldValueRW(L, 'base64', @get_base64fields, nil); plua_SetFieldValueRW(L, 'convert', @get_convertfields, nil); plua_SetFieldValueRW(L, 'crypto', @get_cryptofields, nil); plua_SetFieldValueRW(L, 'cs', @get_consolefields, nil); plua_SetFieldValueRW(L, 'dir', @get_dirfields, nil); plua_SetFieldValueRW(L, 'file', @get_filefields, nil); plua_SetFieldValueRW(L, 'html', @get_htmlfields, nil); plua_SetFieldValueRW(L, 'http', @get_httpfields, nil); plua_SetFieldValueRW(L, 'json', @get_jsonfields, nil); plua_SetFieldValueRW(L, 'net', @get_netfields, nil); plua_SetFieldValueRW(L, 'task', @get_taskfields, nil); plua_SetFieldValueRW(L, 'url', @get_urlfields, nil); plua_SetFieldValueRW(L, 'utils', @get_utilfields, nil); plua_SetFieldValueRW(L, 're', @get_regexfields, nil); plua_SetFieldValueRW(L, 'string', @get_string, nil); result := 1; end; end.