text
stringlengths
14
6.51M
{ Exercicio 26:Escreva um algoritmo que receba o nome e a idade de um atleta para uma competição. No final, exibir um boletim constando o nome do atleta e sua respectiva categoria, baseando-se na tabela abaixo: Idade Categoria Abaixo de 08 anos Não pode participar! Entre 08 e 10 anos Pré-Mirim Entre 11 e 13 anos Mirim Entre 14 e 16 anos Infantil Entre 17 e 19 anos Juvenil Acima de 19 anos Veterano } { Solução em Portugol Algoritmo Exercicio 26; Var idade: inteiro; nome: caracter; Inicio exiba("Programa que define a sua categoria no esporte."); exiba("Digite o seu nome: "); leia(nome); exiba("Digite a sua idade: "); leia(idade); se(idade < 8) então exiba(nome," : Não pode participar!"); fimse; se((idade >= 8) e (idade < 11)) então exiba(nome," : Pré-Mirim"); fimse; se((idade >= 11) e (idade < 14)) então exiba(nome," : Mirim"); fimse; se((idade >= 14) e (idade < 17)) então exiba(nome," : Infantil"); fimse; se((idade >= 17) e (idade <= 19)) então exiba(nome," : Juvenil"); fimse; se(idade > 19) então exiba(nome," : Veterano"); fimse; Fim. } // Solução em Pascal Program Exercicio26; uses crt; var idade: integer; nome: string; begin clrscr; writeln('Programa que define a sua categoria no esporte.'); writeln('Digite o seu nome: '); readln(nome); writeln('Digite a sua idade: '); readln(idade); if(idade < 8) then writeln(nome,' : Não pode participar!'); if((idade >= 8) and (idade < 11)) then writeln(nome,' : Pré-Mirim'); if((idade >= 11) and (idade < 14)) then writeln(nome,' : Mirim'); if((idade >= 14) and (idade < 17)) then writeln(nome,' : Infantil'); if((idade >= 17) and (idade <= 19)) then writeln(nome,' : Juvenil'); if(idade > 19) then writeln(nome,' : Veterano'); repeat until keypressed; end.
unit eInterestSimulator.Model.Interfaces; interface uses System.Generics.Collections; type TTypeSistema = (tpAlemao, tpAmericano, tpAmortizacaoConstante, tpAmortizacaoMisto, tpPagamentoUnico, tpPagamentoVariavel, tpPrice); iSimulador = interface ['{3A7BC019-4141-4BA4-A54B-816C49D8194D}'] function Capital(Value: Real): iSimulador; overload; function Capital: Real; overload; function TaxaJuros(Value: Real): iSimulador; overload; function TaxaJuros: Real; overload; function TotalParcelas(Value: Integer): iSimulador; overload; function TotalParcelas: Integer; overload; function TipoSistema(Value: TTypeSistema): iSimulador; overload; function TipoSistema: TTypeSistema; overload; end; iResultado = interface ['{E2D68003-B02B-47D9-99FC-EA394CBC64D1}'] function NumeroParcela(Value: Integer): iResultado; overload; function NumeroParcela: Integer; overload; function ValorJuros(Value: Real): iResultado; overload; function ValorJuros: Real; overload; function ValorAmortizacao(Value: Real): iResultado; overload; function ValorAmortizacao: Real; overload; function ValorSaldo(Value: Real): iResultado; overload; function ValorSaldo: Real; overload; function ValorPagamento(Value: Real): iResultado; overload; function ValorPagamento: Real; overload; end; iResultadoFactory = interface ['{992B706D-CC77-4905-8406-883CA7675274}'] function PagamentoUnico: iResultado; function PagamentoVariavel: iResultado; function Americano: iResultado; function AmortizacaoConstante: iResultado; function Price: iResultado; function AmortizacaoMisto: iResultado; function Alemao: iResultado; end; iSimuladorFactory = interface ['{8A0D8945-3F38-4477-B47B-7D2B30C654F9}'] function Simulador: iSimulador; end; iSistema = interface ['{E90B94AD-F472-497A-9034-6A354849313A}'] function Descricao(Value: String): iSistema; overload; function Descricao: String; overload; function Habilitado(Value: Boolean): iSistema; overload; function Habilitado: Boolean; overload; function TipoSistema(Value: TTypeSistema): iSistema; overload; function TipoSistema: TTypeSistema; overload; end; implementation end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clEncoder; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, SysUtils,{$IFDEF DEMO} Windows, Forms,{$ENDIF} {$ELSE} System.Classes, System.SysUtils,{$IFDEF DEMO} Winapi.Windows, Vcl.Forms,{$ENDIF} {$ENDIF} clStreams, clUtils, clTranslator, clWUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; const DefaultCharsPerLine = 76; type EclEncoderError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); property ErrorCode: Integer read FErrorCode; end; TclEncodeMethod = (cmNone, cmQuotedPrintable, cmBase64, cmUUEncode, cm8Bit); TclEncoder = class(TComponent) private FEncodeMethod: TclEncodeMethod; FCharsPerLine: Integer; FSuppressCrlf: Boolean; FBatchSize: Integer; FOnProgress: TclProgressEvent; FAllowESC: Boolean; function GetCorrectCharsPerLine: Integer; function ReadOneLine(AStream: TStream; var Eof: Boolean; var crlfSkipped: Integer): string; procedure EncodeUUE(ASource, ADestination: TStream); procedure DecodeUUE(ASource, ADestination: TStream); procedure EncodeBASE64(ASource, ADestination: TStream); procedure DecodeBASE64(ASource, ADestination: TStream); procedure EncodeQP(ASource, ADestination: TStream); procedure DecodeQP(ASource, ADestination: TStream); function DecodeBASE64Bytes(var Buffer; ACount: Integer; var ABase64Pos, ABase64Val: Byte): Integer; procedure CopyStreams(ASource, ADestination: TStream); protected procedure DoProgress(ABytesProceed, ATotalBytes: Int64); virtual; public constructor Create(AOwner: TComponent); override; function GetPreferredEncoding(ASource: TStream): TclEncodeMethod; overload; function GetPreferredEncoding(const ASource: string): TclEncodeMethod; overload; function GetPreferredEncoding(const ASource, ACharSet: string): TclEncodeMethod; overload; class procedure Encode(ASource, ADestination: TStream; AMethod: TclEncodeMethod); overload; class function Encode(ASource: TStream; AMethod: TclEncodeMethod): string; overload; class function Encode(const ASource: string; AMethod: TclEncodeMethod): string; overload; class function EncodeBytes(const ASource: TclByteArray; AMethod: TclEncodeMethod): string; overload; class function EncodeToString(const ASource: string; AMethod: TclEncodeMethod): string; overload; class function EncodeToString(ASource: TStream; AMethod: TclEncodeMethod): string; overload; class function EncodeBytesToString(const ASource: TclByteArray; AMethod: TclEncodeMethod): string; overload; class procedure Decode(ASource, ADestination: TStream; AMethod: TclEncodeMethod); overload; class procedure Decode(const ASource: string; ADestination: TStream; AMethod: TclEncodeMethod); overload; class function Decode(const ASource: string; AMethod: TclEncodeMethod): string; overload; class function DecodeBytes(const ASource: string; AMethod: TclEncodeMethod): TclByteArray; overload; procedure Encode(ASource, ADestination: TStream); overload; function Encode(ASource: TStream): string; overload; function Encode(ASource: TStream; const ACharSet: string): string; overload; function Encode(const ASource: string): string; overload; function Encode(const ASource, ACharSet: string): string; overload; function EncodeBytes(const ASource: TclByteArray): string; overload; function EncodeBytes(const ASource: TclByteArray; const ACharSet: string): string; overload; procedure Decode(ASource, ADestination: TStream); overload; procedure Decode(const ASource: string; ADestination: TStream); overload; procedure Decode(const ASource, ACharSet: string; ADestination: TStream); overload; function Decode(const ASource: string): string; overload; function Decode(const ASource, ACharSet: string): string; overload; function DecodeBytes(const ASource: string): TclByteArray; overload; function DecodeBytes(const ASource, ACharSet: string): TclByteArray; overload; published property CharsPerLine: Integer read FCharsPerLine write FCharsPerLine default DefaultCharsPerLine; property EncodeMethod: TclEncodeMethod read FEncodeMethod write FEncodeMethod default cmBase64; property SuppressCrlf: Boolean read FSuppressCrlf write FSuppressCrlf default False; property BatchSize: Integer read FBatchSize write FBatchSize default 8192; property AllowESC: Boolean read FAllowESC write FAllowESC default False; property OnProgress: TclProgressEvent read FOnProgress write FOnProgress; end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsEncoderDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} procedure RaiseEncoderError(const AErrorMessage: string; AErrorCode: Integer); resourcestring ErrorUnsupported = 'Unsupported format.'; ErrorWrongSymbols = 'Wrong symbols in source stream.'; const ErrorUnsupportedCode = -1; ErrorWrongSymbolsCode = -2; implementation const CR = #13; LF = #10; CRLF = CR + LF; MaxUUECharsPerLine = 132; MaxQPCharsPerLine = 132; MinBASE64CharsPerLine = 64; Base64CodeTable: TclString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64CodeTableEx: array[0..255] of Byte = ($00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$3f,$00,$00,$00,$40 ,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$00,$00,$00,$00,$00,$00,$00,$01,$02,$03,$04,$05,$06,$07 ,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$1a,$00,$00,$00,$00,$00 ,$00,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f,$30,$31 ,$32,$33,$34,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); procedure RaiseEncoderError(const AErrorMessage: string; AErrorCode: Integer); begin raise EclEncoderError.Create(AErrorMessage, AErrorCode); end; { TclEncoder } procedure TclEncoder.CopyStreams(ASource, ADestination: TStream); var sourceSize: Integer; begin sourceSize := ASource.Size - ASource.Position; DoProgress(0, sourceSize); ADestination.CopyFrom(ASource, sourceSize); DoProgress(sourceSize, sourceSize); end; constructor TclEncoder.Create(AOwner: TComponent); begin inherited Create(AOwner); FCharsPerLine := DefaultCharsPerLine; FSuppressCrlf := False; FEncodeMethod := cmBase64; FBatchSize := 8192; FAllowESC := False; end; function TclEncoder.Encode(ASource: TStream): string; begin Result := Encode(ASource, ''); end; procedure TclEncoder.Encode(ASource, ADestination: TStream); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsEncoderDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if ((ASource.Size - ASource.Position) <= 0) then Exit; case EncodeMethod of cmQuotedPrintable: EncodeQP(ASource, ADestination); cmBase64: EncodeBASE64(ASource, ADestination); cmUUEncode: EncodeUUE(ASource, ADestination); cmNone, cm8Bit: CopyStreams(ASource, ADestination); else RaiseEncoderError(ErrorUnsupported, ErrorUnsupportedCode); end; end; class function TclEncoder.Encode(const ASource: string; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; Result := encoder.Encode(ASource); finally encoder.Free(); end; end; class procedure TclEncoder.Encode(ASource, ADestination: TStream; AMethod: TclEncodeMethod); var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; encoder.Encode(ASource, ADestination); finally encoder.Free(); end; end; class function TclEncoder.Encode(ASource: TStream; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; Result := encoder.Encode(ASource, ''); finally encoder.Free(); end; end; function TclEncoder.Encode(const ASource: string): string; begin Result := Encode(ASource, ''); end; procedure TclEncoder.EncodeBASE64(ASource, ADestination: TStream); procedure ConvertToBase64(ASymbolsArray: PclChar; ACount, AProgressSize: Integer); const ProgressBlockCount = 1000; var Symb, i, j, cnt, progressStart, progressCur: Integer; begin cnt := (ACount div ProgressBlockCount); j := 0; progressStart := AProgressSize div 2; for i := 0 to ACount - 1 do begin if (cnt > 0) and (i > j * cnt) then begin progressCur := progressStart + j * progressStart div ProgressBlockCount + 1; if (progressCur < AProgressSize) then begin DoProgress(progressCur, AProgressSize); end; Inc(j); end; Symb := Integer(ASymbolsArray[i]); case Symb of 64: ASymbolsArray[i] := TclChar(13); 65: ASymbolsArray[i] := TclChar(10); 0..63: ASymbolsArray[i] := Base64CodeTable[Symb + 1]; else ASymbolsArray[i] := '='; end; end; end; var Buffer: PclChar; OutBuffer: PclChar; i, Completed, Length, LineLength, RestLength, InIndex, OutIndex, sourceSize: Integer; FirstPass: Boolean; begin sourceSize := ASource.Size - ASource.Position; DoProgress(0, sourceSize); Completed := sourceSize; if (Completed = 0) then Exit; FirstPass := True; if FSuppressCrlf then begin LineLength := sourceSize; end else begin LineLength := Trunc(GetCorrectCharsPerLine() * 3/4); end; Length := (((Completed div 3)*4) div LineLength) * (LineLength + 2); if (Length = 0) then Length := LineLength + 2; Length := (Length + ($2000 - 1)) and not ($2000 - 1); GetMem(Buffer, Completed + 1); GetMem(OutBuffer, Length); try ASource.Read(Buffer^, Completed); Buffer[Completed] := #0; OutIndex := 0; InIndex := 0; repeat if not (FSuppressCrlf or FirstPass) then begin OutBuffer[OutIndex] := TclChar(64); OutBuffer[OutIndex + 1] := TclChar(65); Inc(OutIndex, 2); end; FirstPass := False; RestLength := Completed - InIndex; if (RestLength > LineLength) then RestLength := LineLength; for i := 0 to (RestLength div 3) - 1 do begin {$IFDEF LOGGER} if (InIndex + 2 >= Completed) then begin clPutLogMessage(Self, edInside, 'EncodeBASE64, (InIndex + 2 >= Completed) inside a loop: %d %d', nil, [InIndex, Completed]); end; {$ENDIF} OutBuffer[OutIndex] := TclChar(Word(Buffer[InIndex]) shr 2); OutBuffer[OutIndex + 1] := TclChar(((Word(Buffer[InIndex]) shl 4) and 48) or ((Word(Buffer[InIndex + 1]) shr 4) and 15)); OutBuffer[OutIndex + 2] := TclChar(((Word(Buffer[InIndex + 1]) shl 2) and 60) or ((Word(Buffer[InIndex + 2]) shr 6) and 3)); OutBuffer[OutIndex + 3] := TclChar(Word(Buffer[InIndex + 2]) and 63); Inc(InIndex, 3); Inc(OutIndex, 4); end; if (RestLength mod 3) > 0 then begin {$IFDEF LOGGER} if (InIndex + 2 >= Completed) then begin clPutLogMessage(Self, edInside, 'EncodeBASE64, (InIndex + 2 >= Completed): %d %d', nil, [InIndex, Completed]); end; {$ENDIF} OutBuffer[OutIndex] := TclChar(Word(Buffer[InIndex]) shr 2); OutBuffer[OutIndex + 1] := TclChar(((Word(Buffer[InIndex]) shl 4) and 48) or ((Word(Buffer[InIndex + 1]) shr 4) and 15)); if((RestLength mod 3) = 1) then begin OutBuffer[OutIndex + 2] := TclChar(-1);//'='; OutBuffer[OutIndex + 3] := TclChar(-1);//'='; end else begin OutBuffer[OutIndex + 2] := TclChar(((Word(Buffer[InIndex + 1]) shl 2) and 60) or ((Word(Buffer[InIndex + 2]) shr 6) and 3)); OutBuffer[OutIndex + 3] := TclChar(-1);//'='; end; Inc(InIndex, 3); Inc(OutIndex, 4); end; //TODO DoProgress(InIndex div 2, sourceSize); until not(InIndex < Completed); ConvertToBase64(OutBuffer, OutIndex, sourceSize); ADestination.Write(OutBuffer^, OutIndex); DoProgress(sourceSize, sourceSize); finally FreeMem(OutBuffer); {$IFDEF LOGGER} try {$ENDIF} FreeMem(Buffer); {$IFDEF LOGGER} except on E: Exception do begin clPutLogMessage(Self, edInside, 'EncodeBASE64, FreeMem(Buffer);', E); raise; end; end; {$ENDIF} end; end; function TclEncoder.EncodeBytes(const ASource: TclByteArray; const ACharSet: string): string; var sourceStream: TStream; begin sourceStream := TMemoryStream.Create(); try if (ASource <> nil) and (Length(ASource) > 0) then begin sourceStream.WriteBuffer(ASource[0], Length(ASource)); sourceStream.Position := 0; end; Result := Encode(sourceStream, ACharSet); finally sourceStream.Free(); end; end; function TclEncoder.EncodeBytes(const ASource: TclByteArray): string; begin Result := EncodeBytes(ASource, ''); end; class function TclEncoder.EncodeBytesToString(const ASource: TclByteArray; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; encoder.SuppressCrlf := True; Result := encoder.EncodeBytes(ASource, ''); finally encoder.Free(); end; end; class function TclEncoder.EncodeBytes(const ASource: TclByteArray; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; Result := encoder.EncodeBytes(ASource, ''); finally encoder.Free(); end; end; class function TclEncoder.Decode(const ASource: string; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; Result := encoder.Decode(ASource); finally encoder.Free(); end; end; class procedure TclEncoder.Decode(const ASource: string; ADestination: TStream; AMethod: TclEncodeMethod); var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; encoder.Decode(ASource, ADestination); finally encoder.Free(); end; end; class procedure TclEncoder.Decode(ASource, ADestination: TStream; AMethod: TclEncodeMethod); var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; encoder.Decode(ASource, ADestination); finally encoder.Free(); end; end; function TclEncoder.Decode(const ASource: string): string; begin Result := Decode(ASource, ''); end; procedure TclEncoder.Decode(const ASource, ACharSet: string; ADestination: TStream); var sourceStream: TStream; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} sourceStream := TMemoryStream.Create(); try if (ASource <> '') then begin buffer := TclTranslator.GetBytes(ASource, ACharSet); sourceStream.WriteBuffer(buffer[0], Length(buffer)); sourceStream.Position := 0; end; Decode(sourceStream, ADestination); finally sourceStream.Free(); end; end; procedure TclEncoder.Decode(const ASource: string; ADestination: TStream); begin Decode(ASource, '', ADestination); end; procedure TclEncoder.Decode(ASource, ADestination: TStream); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsEncoderDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if ((ASource.Size - ASource.Position) <= 0) then Exit; case EncodeMethod of cmQuotedPrintable: DecodeQP(ASource, ADestination); cmBase64: DecodeBASE64(ASource, ADestination); cmUUEncode: DecodeUUE(ASource, ADestination); cmNone, cm8Bit: CopyStreams(ASource, ADestination); else RaiseEncoderError(ErrorUnsupported, ErrorUnsupportedCode); end; end; function TclEncoder.DecodeBASE64Bytes(var Buffer; ACount: Integer; var ABase64Pos, ABase64Val: Byte): Integer; var index, outIndex, charCode: Integer; buf: PclChar; begin index := 0; outIndex := 0; buf := PclChar(@Buffer); while (index < ACount) do begin if (buf[index] in ['=', CR, LF, ' ']) then begin Inc(index); Continue; end; charCode := Base64CodeTableEx[Byte(buf[index])] - 1; if (charCode < 0) then begin RaiseEncoderError(ErrorWrongSymbols, ErrorWrongSymbolsCode); end; case ABase64Pos of 0: begin ABase64Val := Byte(charCode shl 2); Inc(ABase64Pos); end; 1: begin buf[outIndex] := clChr(ABase64Val + (charCode shr 4)); ABase64Val := Byte(charCode shl 4); Inc(outIndex); Inc(ABase64Pos); end; 2: begin buf[outIndex] := clChr(ABase64Val + (charCode shr 2)); ABase64Val := Byte(charCode shl 6); Inc(outIndex); Inc(ABase64Pos); end; 3: begin buf[outIndex] := clChr(ABase64Val + charCode); Inc(outIndex); ABase64Pos := 0; end; end; Inc(index); end; Result := outIndex; end; function TclEncoder.DecodeBytes(const ASource, ACharSet: string): TclByteArray; var destinationStream: TStream; size: Integer; begin destinationStream := TMemoryStream.Create(); try Decode(ASource, ACharSet, destinationStream); destinationStream.Position := 0; size := destinationStream.Size - destinationStream.Position; if (size > 0) then begin SetLength(Result, size); destinationStream.Read(Result[0], size); end else begin Result := nil; end; finally destinationStream.Free(); end; end; function TclEncoder.DecodeBytes(const ASource: string): TclByteArray; begin Result := DecodeBytes(ASource, ''); end; class function TclEncoder.DecodeBytes(const ASource: string; AMethod: TclEncodeMethod): TclByteArray; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; Result := encoder.DecodeBytes(ASource); finally encoder.Free(); end; end; procedure TclEncoder.DecodeBASE64(ASource, ADestination: TStream); var sourceSize, sourceStart: Int64; bufSuze, cnt: Integer; Buffer: PclChar; base64Pos, base64Val: Byte; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(0, sourceSize); bufSuze := Integer(sourceSize); if (bufSuze > BatchSize) then begin bufSuze := BatchSize; end; base64Pos := 0; base64Val := 0; GetMem(Buffer, bufSuze); try cnt := ASource.Read(Buffer^, bufSuze); while (cnt > 0) do begin cnt := DecodeBASE64Bytes(Buffer^, cnt, base64Pos, base64Val); if (cnt > 0) then begin ADestination.Write(Buffer^, cnt); end; cnt := ASource.Read(Buffer^, bufSuze); DoProgress(ASource.Position - sourceStart, sourceSize); end; finally FreeMem(Buffer); end; end; procedure TclEncoder.EncodeQP(ASource, ADestination: TStream); procedure WriteStream(AStream: TStream; const AText: string); {$IFDEF DELPHI2009} var s: TclString; {$ENDIF} begin {$IFDEF DELPHI2009} s := TclString(AText); AStream.Write(PclChar(s)^, Length(s)); {$ELSE} AStream.Write(Pointer(AText)^, Length(AText)); {$ENDIF} end; var Symbol, Symbol1: TclChar; i, sourceSize, sourceStart: Integer; Code: Integer; SoftBreak, moreData: Boolean; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(0, sourceSize); repeat moreData := True; SoftBreak := True; i := 0; while(FSuppressCrlf or(i <= GetCorrectCharsPerLine() - 6)) do begin if (ASource.Read(Symbol, 1) = 1) then begin Code := Ord(Symbol); case Code of 32..60,62..126: ADestination.Write(Symbol, 1); 61: begin WriteStream(ADestination, Format('=%2.2X', [Code])); i := i + 2; end; 13: begin if (ASource.Read(Symbol, 1) = 1) then begin if (Symbol = LF) then begin Symbol1 := CR; ADestination.Write(Symbol1, 1); Symbol1 := LF; ADestination.Write(Symbol1, 1); SoftBreak := False; Break; end else begin WriteStream(ADestination, Format('=%2.2X', [Code])); i := i + 2; ASource.Seek(-1, soCurrent); end; end; end; else begin WriteStream(ADestination, Format('=%2.2X', [Code])); i := i + 2; end; end; end else begin SoftBreak := False; moreData := False; break; end; Inc(i); end; if SoftBreak then begin Symbol := '='; ADestination.Write(Symbol, 1); Symbol1 := CR; ADestination.Write(Symbol1, 1); Symbol1 := LF; ADestination.Write(Symbol1, 1); end; DoProgress(ASource.Position - sourceStart, sourceSize); until not moreData; end; class function TclEncoder.EncodeToString(ASource: TStream; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; encoder.SuppressCrlf := True; Result := encoder.Encode(ASource); finally encoder.Free(); end; end; class function TclEncoder.EncodeToString(const ASource: string; AMethod: TclEncodeMethod): string; var encoder: TclEncoder; begin encoder := TclEncoder.Create(nil); try encoder.EncodeMethod := AMethod; encoder.SuppressCrlf := True; Result := encoder.Encode(ASource); finally encoder.Free(); end; end; procedure TclEncoder.DecodeQP(ASource, ADestination: TStream); var Symbol: TclChar; Buffer: string; Eof: Boolean; i, sourceSize, sourceStart: Integer; HexNumber: Integer; CRLFSkipped: Integer; CodePresent: Boolean; DelimPresent: Boolean; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(0, sourceSize); HexNumber := 0; CRLFSkipped := 0; CodePresent := False; DelimPresent := False; repeat Buffer := ReadOneLine(ASource, Eof, CRLFSkipped); if DelimPresent then begin Dec(CRLFSkipped); end; DelimPresent := False; for i := 0 to CRLFSkipped - 1 do begin Symbol := #13; ADestination.Write(Symbol, 1); Symbol := #10; ADestination.Write(Symbol, 1); end; CRLFSkipped := 0; for i := 1 to Length(Buffer) do begin if (DelimPresent) then begin case Buffer[i] of 'A'..'F': begin HexNumber := HexNumber + (Ord(Buffer[i]) - 55); end; 'a'..'f': begin HexNumber := HexNumber + (Ord(Buffer[i]) - 87); end; '0'..'9': begin HexNumber := HexNumber + (Ord(Buffer[i]) - 48); end; else begin CodePresent := False; DelimPresent := False; HexNumber := 0; Symbol := '='; ADestination.Write(Symbol, 1); ADestination.Write(Buffer[i], 1); end; end; if not CodePresent then begin HexNumber := HexNumber*16; CodePresent := True; continue; end else begin Symbol := clChr(HexNumber); ADestination.Write(Symbol, 1); CodePresent := False; DelimPresent := False; HexNumber := 0; end; end else begin if Buffer[i] = '=' then begin DelimPresent := True; end else begin ADestination.Write(Buffer[i], 1); end; end; end; DoProgress(ASource.Position - sourceStart, sourceSize); until Eof; end; procedure TclEncoder.EncodeUUE(ASource, ADestination: TStream); procedure ConvertToUUE(ASymbolsArray: PclChar; ACount, ALineLength: Integer); var SymbCount, Symb, i: Integer; begin SymbCount := 0; for i := 0 to ACount - 1 do begin Inc(SymbCount); if (SymbCount > ALineLength) then begin if (SymbCount <= (ALineLength + 2)) then Continue; SymbCount := 1; end; Symb := Integer(ASymbolsArray[i]); if Symb = 0 then begin ASymbolsArray[i] := '`'; end else begin ASymbolsArray[i] := clChr((Symb and 63) + Ord(' ')); end; end; end; var Buffer: PclChar; OutBuffer: PclChar; LineLength, Length, OutLineLength, OutLen, i, k, Completed, Index, OutIndex, sourceSize: Integer; begin sourceSize := ASource.Size - ASource.Position; DoProgress(0, sourceSize); Completed := sourceSize; if (Completed = 0) then Exit; if FSuppressCrlf then begin Length:= Completed; end else begin Length:= Trunc(GetCorrectCharsPerLine() * 3/4); end; GetMem(Buffer, Completed); OutLen := ((Completed div Length) + 1) * (GetCorrectCharsPerLine() + 5); OutLen := (OutLen + ($2000 - 1)) and not ($2000 - 1); GetMem(OutBuffer, OutLen); try ASource.Read(Buffer^, Completed); Index := 0; OutIndex := 0; LineLength := 0; OutLineLength := 0; for i := 0 to (Completed div Length) do begin LineLength := Completed - Index; if (LineLength > Length) then LineLength := Length; OutBuffer[OutIndex] := TclChar(LineLength); Inc(OutIndex); for k := 0 to (LineLength div 3) - 1 do begin OutBuffer[OutIndex] := TclChar(Word(Buffer[Index]) shr 2); OutBuffer[OutIndex + 1] := TclChar(((Word(Buffer[Index]) shl 4) and 48) or ((Word(Buffer[Index + 1]) shr 4) and 15)); OutBuffer[OutIndex + 2] := TclChar(((Word(Buffer[Index + 1]) shl 2) and 60) or ((Word(Buffer[Index + 2]) shr 6) and 3)); OutBuffer[OutIndex + 3] := TclChar(Word(Buffer[Index + 2]) and 63); Inc(Index, 3); Inc(OutIndex, 4); end; if ((LineLength mod 3) > 0) then begin OutBuffer[OutIndex] := TclChar(Word(Buffer[Index]) shr 2); if ((LineLength mod 3) = 2) then begin OutBuffer[OutIndex + 1] := TclChar(((Word(Buffer[Index]) shl 4) and 48) or ((Word(Buffer[Index + 1]) shr 4) and 15)); OutBuffer[OutIndex + 2] := TclChar(((Word(Buffer[Index + 1]) shl 2) and 60)); end else begin OutBuffer[OutIndex + 1] := TclChar(((Word(Buffer[Index]) shl 4) and 48)); OutBuffer[OutIndex + 2] := #0; end; Inc(Index, LineLength mod 3); Inc(OutIndex, LineLength mod 3 + 1); end; if (OutLineLength = 0) then OutLineLength := OutIndex; if (not FSuppressCrlf) and (LineLength >= Length) then begin OutBuffer[OutIndex] := CR; OutBuffer[OutIndex + 1] := LF; Inc(OutIndex, 2); end; DoProgress(Index, sourceSize); end; ConvertToUUE(OutBuffer, OutIndex, OutLineLength); if not FSuppressCrlf then begin if (LineLength < Length) then begin OutBuffer[OutIndex] := CR; OutBuffer[OutIndex + 1] := LF; Inc(OutIndex, 2); end; OutBuffer[OutIndex] := '`'; Inc(OutIndex, 1); OutBuffer[OutIndex] := CR; OutBuffer[OutIndex + 1] := LF; Inc(OutIndex, 2); end; ADestination.Write(OutBuffer^, OutIndex); finally FreeMem(OutBuffer); FreeMem(Buffer); end; end; procedure TclEncoder.DecodeUUE(ASource, ADestination: TStream); var Buffer, DestBuffer: PclChar; curStrLength, Completed, i, Index, OutIndex, LineStartIndex, StrLength, sourceSize: Integer; SckipToLineEnd, HeaderSkipped, CRLFSkipped: Boolean; TmpStr: TclString; begin sourceSize := ASource.Size - ASource.Position; DoProgress(0, sourceSize); Completed := sourceSize; if (Completed = 0) then Exit; GetMem(Buffer, Completed); GetMem(DestBuffer, Completed); try ASource.Read(Buffer^, Completed); StrLength := 0; OutIndex := 0; curStrLength := 0; LineStartIndex := 0; CRLFSkipped := True; HeaderSkipped := False; SckipToLineEnd := False; for Index := 0 to Completed - 1 do begin if ((Buffer[Index] in [CR, LF]) or (Index = (Completed - 1))) then begin if (Index = (Completed - 1)) and (not SckipToLineEnd) and not (Buffer[Index] in [CR, LF]) then begin DestBuffer[OutIndex] := TclChar((Integer(Buffer[Index]) - $20) and 63); end; SckipToLineEnd := False; OutIndex := LineStartIndex; for i := 0 to (StrLength div 4) - 1 do begin DestBuffer[OutIndex] := clChr((Word(DestBuffer[LineStartIndex]) shl 2) or (Word(DestBuffer[LineStartIndex + 1]) shr 4)); DestBuffer[OutIndex + 1] := clChr((Word(DestBuffer[LineStartIndex + 1]) shl 4) or (Word(DestBuffer[LineStartIndex + 2]) shr 2)); DestBuffer[OutIndex + 2] := clChr((Word(DestBuffer[LineStartIndex + 2]) shl 6) or (Word(DestBuffer[LineStartIndex + 3]))); Inc(OutIndex, 3); Inc(LineStartIndex, 4); end; if ((StrLength mod 4) > 0) then begin DestBuffer[OutIndex] := clChr((Word(DestBuffer[LineStartIndex]) shl 2) or (Word(DestBuffer[LineStartIndex + 1]) shr 4)); DestBuffer[OutIndex + 1] := clChr((Word(DestBuffer[LineStartIndex + 1]) shl 4) or (Word(DestBuffer[LineStartIndex + 2]) shr 2)); Inc(OutIndex, StrLength mod 4); end; curStrLength := 0; StrLength := 0; CRLFSkipped := True; LineStartIndex := OutIndex; end else begin if SckipToLineEnd then begin DestBuffer[OutIndex] := #0; Inc(OutIndex); Continue; end; if CRLFSkipped then begin curStrLength := 0; if not HeaderSkipped then begin HeaderSkipped := True; TmpStr := 'begin'; if CompareMem(PclChar(Buffer + Index), PclChar(TmpStr), 5) then begin SckipToLineEnd := True; Continue; end; end; StrLength := (((Integer(Buffer[Index]) - $20) and 63)*4) div 3; CRLFSkipped := False; if StrLength = 0 then Break else Continue; end; DestBuffer[OutIndex] := TclChar((Integer(Buffer[Index]) - $20) and 63); Inc(OutIndex); Inc(curStrLength); if (curStrLength > StrLength) then begin SckipToLineEnd := True; end; end; DoProgress(Index, sourceSize); end; ADestination.Write(DestBuffer^, OutIndex); finally FreeMem(DestBuffer); FreeMem(Buffer); end; end; procedure TclEncoder.DoProgress(ABytesProceed, ATotalBytes: Int64); begin if Assigned(FOnProgress) then begin FOnProgress(Self, ABytesProceed, ATotalBytes); end; end; function TclEncoder.ReadOneLine(AStream: TStream; var Eof: Boolean; var crlfSkipped: Integer): string; var Symbol: Byte; PrevSymbol: Byte; Completed: Integer; StrLength: Integer; RollBackCnt: Integer; {$IFDEF DELPHI2009} s: TclString; {$ENDIF} begin Result := ''; Eof := False; crlfSkipped := 0; StrLength := 0; PrevSymbol := 0; {$IFNDEF WIN64} {$IFNDEF DELPHIX101} RollBackCnt := 0; {$ENDIF} {$ENDIF} while (True) do begin Completed := AStream.Read(Symbol, 1); if (Completed = 0) then begin Eof := True; RollBackCnt := StrLength; Break; end; if (Symbol in [13, 10]) then begin if (StrLength <> 0) then begin RollBackCnt := StrLength + 1; Break; end; if not ((PrevSymbol = 13) and (Symbol = 10)) then begin Inc(crlfSkipped); end; end else begin Inc(StrLength); end; PrevSymbol := Symbol; end; if (StrLength <> 0) then begin AStream.Seek(-RollBackCnt, soCurrent); {$IFDEF DELPHI2009} SetLength(s, StrLength); AStream.Read(PclChar(s)^, StrLength); Result := string(s); {$ELSE} SetLength(Result, StrLength); AStream.Read(Pointer(Result)^, StrLength); {$ENDIF} end; end; function TclEncoder.GetCorrectCharsPerLine: Integer; begin Result := CharsPerLine; if (Result < 1) then begin Result := DefaultCharsPerLine; end; case EncodeMethod of cmUUEncode: begin if (CharsPerLine < 3) then begin Result := 3; end else if (CharsPerLine > MaxUUECharsPerLine) then begin Result := MaxUUECharsPerLine; end; end; cmQuotedPrintable: begin if (CharsPerLine < 4) then begin Result := 4; end else if (CharsPerLine > MaxQPCharsPerLine) then begin Result := MaxQPCharsPerLine; end; end; cmBase64: begin if(MinBASE64CharsPerLine <= CharsPerLine) then begin Result := Round(CharsPerLine/4 + 0.25) * 4; end else begin Result := MinBASE64CharsPerLine; end; end; end; end; function TclEncoder.GetPreferredEncoding(const ASource: string): TclEncodeMethod; begin Result := GetPreferredEncoding(ASource, ''); end; function TclEncoder.GetPreferredEncoding(ASource: TStream): TclEncodeMethod; var NonTransportable, MaxNonTransportable: Integer; Symbol: TclChar; chPerLine: Integer; oldPos: Int64; begin Result := cmNone; oldPos := ASource.Position; try NonTransportable := 0; chPerLine := 0; MaxNonTransportable := (ASource.Size - ASource.Position) div 2; while(ASource.Read(Symbol, 1) = 1) do begin case Ord(Symbol) of 13,10: begin if(chPerLine > CharsPerLine) then Result := cmQuotedPrintable; chPerLine := 0; end; 27: begin if AllowESC then begin Inc(chPerLine); end else begin Result := cmBase64; chPerLine := 0; Break; end; end; 0..9,11..12,14..26,28..31: begin Result := cmBase64; chPerLine := 0; Break; end; 32..126: begin Inc(chPerLine); end; 127..255: begin Result := cmQuotedPrintable; Inc(NonTransportable); if (MaxNonTransportable < NonTransportable) then begin Result := cmBase64; Break; end; end; end; end; if(chPerLine > CharsPerLine) and (Result = cmNone) then begin Result := cmQuotedPrintable; end; finally ASource.Position := oldPos; end; end; function TclEncoder.GetPreferredEncoding(const ASource, ACharSet: string): TclEncodeMethod; var buffer: TclByteArray; stream: TStream; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} stream := TMemoryStream.Create(); try if (ASource <> '') then begin buffer := TclTranslator.GetBytes(ASource, ACharSet); stream.WriteBuffer(buffer[0], Length(buffer)); stream.Position := 0; end; Result := GetPreferredEncoding(stream); finally stream.Free(); end; end; function TclEncoder.Encode(const ASource, ACharSet: string): string; var sourceStream: TStream; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} sourceStream := TMemoryStream.Create(); try if (ASource <> '') then begin buffer := TclTranslator.GetBytes(ASource, ACharSet); sourceStream.WriteBuffer(buffer[0], Length(buffer)); sourceStream.Position := 0; end; Result := Encode(sourceStream, ACharSet); finally sourceStream.Free(); end; end; function TclEncoder.Encode(ASource: TStream; const ACharSet: string): string; var destinationStream: TStream; buffer: TclByteArray; size: Integer; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} destinationStream := TMemoryStream.Create(); try Encode(ASource, destinationStream); destinationStream.Position := 0; size := destinationStream.Size - destinationStream.Position; if (size > 0) then begin SetLength(buffer, size); destinationStream.Read(buffer[0], size); Result := TclTranslator.GetString(buffer, 0, size, ACharSet); end else begin Result := ''; end; finally destinationStream.Free(); end; end; function TclEncoder.Decode(const ASource, ACharSet: string): string; var destinationStream: TStream; buffer: TclByteArray; size: Integer; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} destinationStream := TMemoryStream.Create(); try Decode(ASource, ACharSet, destinationStream); destinationStream.Position := 0; size := destinationStream.Size - destinationStream.Position; if (size > 0) then begin SetLength(buffer, size); destinationStream.Read(buffer[0], size); Result := TclTranslator.GetString(buffer, 0, size, ACharSet); end else begin Result := ''; end; finally destinationStream.Free(); end; end; { EclEncoderError } constructor EclEncoderError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDsaKeyParameters; {$I ..\..\Include\CryptoLib.inc} interface uses ClpIDsaParameters, ClpIDsaKeyParameters, ClpAsymmetricKeyParameter; type TDsaKeyParameters = class abstract(TAsymmetricKeyParameter, IDsaKeyParameters) strict private var Fparameters: IDsaParameters; strict private function GetParameters: IDsaParameters; protected constructor Create(isPrivate: Boolean; parameters: IDsaParameters); public function Equals(const other: IDsaKeyParameters): Boolean; reintroduce; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI}override; property parameters: IDsaParameters read GetParameters; end; implementation { TDsaKeyParameters } constructor TDsaKeyParameters.Create(isPrivate: Boolean; parameters: IDsaParameters); begin Inherited Create(isPrivate); // Note: parameters may be Nil Fparameters := parameters; end; function TDsaKeyParameters.Equals(const other: IDsaKeyParameters): Boolean; begin if other = Nil then begin result := False; Exit; end; if ((Self as IDsaKeyParameters) = other) then begin result := True; Exit; end; result := (parameters as TObject).Equals(other.parameters as TObject) and (Inherited Equals(other)); end; function TDsaKeyParameters.GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} begin result := Inherited GetHashCode(); if (parameters <> Nil) then begin result := result xor parameters.GetHashCode(); end; end; function TDsaKeyParameters.GetParameters: IDsaParameters; begin result := Fparameters; end; end.
{$I ok_sklad.inc} unit EditDB; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, dxCntner, dxEditor, StdCtrls, ActnList, ssBaseTypes, ssFormStorage, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxLookAndFeelPainters, cxButtons, ssBaseDlg, ssBevel, ImgList, ssSpeedButton, ssPanel, ssGradientPanel, xButton, cxMaskEdit, cxButtonEdit, cxLabel, DB, DBClient, MConnect, SConnect, ssSocketConnection, ssLabel; type TDBInfo = record DBName, DBPath: String; DBID, Def: Integer; end; PDBInfo = ^TDBInfo; TfrmEditDB = class(TBaseDlg) bvlMain: TssBevel; edName: TcxTextEdit; lName: TLabel; edDBPath: TcxButtonEdit; chbDefault: TcxCheckBox; lDBText: TcxLabel; imgMain: TImage; bvlSep: TssBevel; btnTestConnect: TxButton; aTestConnect: TAction; lDBPath: TssLabel; lServer: TLabel; txtServer: TssBevel; imgHost: TImage; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure DataModified(Sender: TObject); procedure bvlMainMouseEnter(Sender: TObject); procedure bvlMainMouseLeave(Sender: TObject); procedure edDBPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure aTestConnectExecute(Sender: TObject); procedure FormCreate(Sender: TObject); protected procedure setid(const Value: integer); override; procedure SetParentName(const Value: string); override; public procedure SetCaptions; override; { Public declarations } end; var frmEditDB: TfrmEditDB; implementation uses ssBaseConst, prConst, ClientData, prFun, ssCallbackConst, ssClientDataSet, xLngManager, fMessageDlg, udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} //============================================================================================== procedure TfrmEditDB.setid(const Value: integer); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.setid') else _udebug := nil;{$ENDIF} if Value = 0 then begin FID := Value; Self.Caption := dmData.Lng.GetRS(ParentNameEx, 'TitleAdd'); //edDBPath.Text := dmData.SConnection.AppServer.GetDBFileName; end else with PDBInfo(Value)^ do begin FID := DBID; Self.Caption := dmData.Lng.GetRS(ParentNameEx, 'TitleEdit'); edName.Text := DBName; edDBPath.Text := DBPath; edDBPath.Enabled := False; lDBPath.Enabled := False; chbDefault.Checked := Def = 1; if not IsPattern then begin chbDefault.Enabled := not chbDefault.Checked; btnApply.Enabled := False; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var NewRecord: boolean; dbid: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.FormCloseQuery') else _udebug := nil;{$ENDIF} if ModalResult in [mrOK, mrYes] then begin CanClose := False; Screen.Cursor := crHourGlass; try NewRecord := FID = 0; if not dmData.Sconnection.Connected then dmData.SConnection.Open; if NewRecord then begin if dmData.SConnection.AppServer.NewDB(edDBPath.Text, '') = 0 then begin ssMessageDlg(rs(ParentNameEx, 'DBCreateError'), ssmtError, [ssmbOk]); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; dbid := dmData.SConnection.AppServer.AddDB(0, edName.Text, Integer(chbDefault.Checked), 1); if (dbid <= 0) or (dmData.SConnection.AppServer.AddDBParams(dbid, 'PROVIDER=LCPI.IBProvider.1;User ID=SYSDBA;Password=masterkey;Persist Security Info=True;ctype=WIN1251;auto_commit=True;Data Source=' + edDBPath.Text, 0) <> 0) then begin ssMessageDlg(rs(ParentNameEx, 'DBCreateError'), ssmtError, [ssmbOk]); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; end else begin if dmData.SConnection.AppServer.db_Update(FID, edName.Text, Integer(chbDefault.Checked), edDBPath.Text) <> 0 then begin ssMessageDlg(rs(ParentNameEx, 'DBUpdateError'), ssmtError, [ssmbOk]); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; end; SendMessage(MainHandle, WM_REFRESH, dbid, 0); if ModalResult = mrYes then begin if NewRecord then begin if not IsPattern then edName.Text := ''; edDBPath.Text := dmData.SConnection.AppServer.GetDBFileName; chbDefault.Enabled := True; chbDefault.Checked := False; edName.SetFocus; FID := 0; end end else CanClose := True; FModified := False; finally Screen.Cursor := crDefault; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.ActionListUpdate') else _udebug := nil;{$ENDIF} aOk.Enabled := (Trim(edName.Text)<>'') and (Trim(edDBPath.Text)<>''); aApply.Enabled := aOk.Enabled and FModified; aTestConnect.Enabled := Trim(edDBPath.Text) <> ''; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.DataModified(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.DataModified') else _udebug := nil;{$ENDIF} FModified := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.SetCaptions; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.SetCaptions') else _udebug := nil;{$ENDIF} inherited; with dmData.Lng do begin lName.Caption := GetRS(ParentNameEx, 'Name') + ':'; chbDefault.Properties.Caption := GetRS(ParentNameEx, 'Def'); lDBText.Caption := GetRS(ParentNameEx, 'DBWarning'); lDBPath.Caption := GetRS(ParentNameEx, 'Path') + ':'; aTestConnect.Caption := GetRS(ParentNameEx, 'TestConnect'); lServer.Caption := GetRS(ParentNameEx, 'Server') + ':'; txtServer.Caption := ' ' + dmData.SConnection.Host; aOK.Caption := GetRS('Common', 'OK'); aCancel.Caption := GetRS('Common', 'Cancel'); aApply.Caption := GetRS('Common', 'Apply'); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.SetParentName(const Value: string); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.SetParentName') else _udebug := nil;{$ENDIF} FParentName := Value; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.bvlMainMouseEnter(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.bvlMainMouseEnter') else _udebug := nil;{$ENDIF} with Sender as TssBevel do if HotTrack then bvlSep.ColorOuter := HotTrackColor; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmEditDB.bvlMainMouseLeave(Sender: TObject); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.bvlMainMouseLeave') else _udebug := nil;{$ENDIF} with Sender as TssBevel do if HotTrack then bvlSep.ColorOuter := clBtnShadow; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmEditDB.edDBPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.edDBPathPropertiesButtonClick') else _udebug := nil;{$ENDIF} with TSaveDialog.Create(nil) do try DefaultExt := 'gdb'; Filter := 'Interbase/Firebird Database (*.gdb)|*.gdb|All Files (*.*)|*.*'; if Execute then begin edDBPath.Text := FileName; end; finally Free; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.aTestConnectExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.aTestConnectExecute') else _udebug := nil;{$ENDIF} if dmData.SConnection.AppServer.db_TestConnect(edDBPath.Text) = 0 then ssMessageDlg(rs(ParentNameEx, 'ConnectSuccess'), ssmtInformation, [ssmbOk]) else ssMessageDlg(rs(ParentNameEx, 'ConnectError'), ssmtError, [ssmbOk]); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditDB.FormCreate(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditDB.FormCreate') else _udebug := nil;{$ENDIF} dmData.Images.GetBitmap(86, imgHost.Picture.Bitmap); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; initialization {$IFDEF UDEBUG}Debugging := False; DEBUG_unit_ID := debugRegisterUnit('EditDB', @Debugging, DEBUG_group_ID);{$ENDIF} finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit SetOpc; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, ExtCtrls, Grids, ValEdit, Menus, ActnMan, variants, AdoDb, Db; type TSetOpcDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; edOpera: TEdit; Datos: TValueListEditor; bLeer: TButton; PopupMenu1: TPopupMenu; Cargaracciones: TMenuItem; bAplica: TButton; procedure bLeerClick(Sender: TObject); procedure DatosGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure DatosValidate(Sender: TObject; ACol, ARow: Integer; const KeyName, KeyValue: String); procedure OKBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CargaraccionesClick(Sender: TObject); procedure bAplicaClick(Sender: TObject); private { Private declarations } FModulo, FUsuario: string; FListaopc: TStringList; FAction: TActionClients; procedure SetModulo(const Value: string); procedure SetearUsuario( const Usuario: string ); procedure GrabarCambios; function SiNo( Valor: boolean ):String; function StrToBool( const Valor: string ):boolean; function QuitarAmp( const Valor: string ):string; function UsuarioExiste( const valor: string ): boolean; procedure SetActionList(const Value: TActionClients); public { Public declarations } property Modulo: string read FModulo write SetModulo; property Action: TActionClients read FAction write SetActionList; end; var SetOpcDlg: TSetOpcDlg; implementation uses DataMod; {$R *.dfm} procedure TSetOpcDlg.SetearUsuario( const Usuario: string ); var Lista: TStringList; begin if UsuarioExiste( edOpera.Text ) then with DM do try CargarAcciones.Enabled := true; Lista := TStringlist.create; FListaOpc.Clear; FUsuario := Usuario; TDerechos.Open; TDerechos.Locate('CODIGO;MODULO', varArrayOf([FUsuario, FModulo ]), [locaseInsensitive]); while not (TDerechos.eof) and ( TDerechosCODIGO.Value = FUsuario) and (TDerechosMODULO.Value=FModulo) do begin Lista.Add( QuitarAmp( TDerechosNOMBRE.Value ) + '=' + Sino( TDerechosSINO.Value )); FListaOpc.Add( TDerechosOPCION.value ); TDerechos.next; end; Datos.Strings.Assign( Lista ); Datos.Enabled := true; finally Lista.free; TDerechos.Close; end else CargarAcciones.Enabled := false; end; procedure TSetOpcDlg.SetModulo(const Value: string); begin FModulo := Value; end; function TSetOpcDlg.SiNo(Valor: boolean): String; begin if Valor then Result := 'SI' else Result := 'NO'; end; procedure TSetOpcDlg.bLeerClick(Sender: TObject); begin try bLeer.Enabled := false; SetearUsuario( edopera.Text ); finally bLeer.Enabled := true; end; end; procedure TSetOpcDlg.DatosGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin Value := '>AA'; end; procedure TSetOpcDlg.DatosValidate(Sender: TObject; ACol, ARow: Integer; const KeyName, KeyValue: String); var Valor: string; begin Valor := Trim( KeyValue ); if ( ACol = 1 ) then if Valor = 'S' then Datos.cells[ ACol, ARow ] := 'SI' else if Valor = 'N' then Datos.cells[ ACol, ARow ] := 'NO' else if ( Valor <> 'SI' ) and ( Valor <> 'NO' ) then Raise exception.create( 'Valor debe ser SI/NO' ); end; procedure TSetOpcDlg.OKBtnClick(Sender: TObject); begin if FListaOpc.count > 1 then GrabarCambios; end; procedure TSetOpcDlg.GrabarCambios; var iContar: integer; begin with DM do begin TDerechos.open; for iContar := 1 to Datos.RowCount-1 do if TDerechos.Locate('CODIGO;MODULO;OPCION', varArrayOf([FUsuario, FModulo, FListaOpc[ iContar-1 ]]), [locaseInsensitive]) then begin TDerechos.edit; TDerechosSINO.Value := StrToBool( Datos.cells[ 1, iContar ]); TDerechos.post; end; TDerechos.Close; end; end; function TSetOpcDlg.StrToBool(const Valor: string): boolean; begin if Valor = 'SI' then Result := true else Result := false; end; procedure TSetOpcDlg.FormCreate(Sender: TObject); begin FListaOpc := TStringlist.create; end; procedure TSetOpcDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin FListaOpc.free; end; function TSetOpcDlg.QuitarAmp(const Valor: string): string; begin Result := Valor; Delete( Result, Pos( '&', Valor ), 1 ); end; function TSetOpcDlg.UsuarioExiste(const valor: string): boolean; begin with DM do try TClaves.Open; Result := TClaves.locate( 'NOMBRE', Valor, [loCaseInsensitive ]); finally Tclaves.close; end; end; procedure TSetOpcDlg.CargaraccionesClick(Sender: TObject); var i, z: integer; begin if FAction = nil then exit; with DM do try TDerechos.Open; for i :=0 to FAction.Count-1 do for z := 0 to FAction[ i ].Items.Count-1 do if not TDerechos.Locate('CODIGO;MODULO;OPCION', varArrayOf([FUsuario, FModulo, FAction[ i ].Items[ z ].Caption]), [locaseInsensitive]) then begin TDerechos.Append; TDerechosCODIGO.value := FUsuario; TDerechosMODULO.Value := FModulo; TDerechosOPCION.Value := FAction[ i ].Items[ z ].Caption; TDerechosNOMBRE.value := FAction[ i ].Items[ z ].DisplayName; TDerechosSINO.Value := false; TDerechos.post; end; finally TDerechos.close; SetearUsuario( FUsuario ); end; end; procedure TSetOpcDlg.SetActionList(const Value: TActionClients); begin FAction := Value; end; procedure TSetOpcDlg.bAplicaClick(Sender: TObject); begin if FListaOpc.count > 1 then GrabarCambios; end; end.
unit WindowsWlanGetter; interface uses nduWlanAPI, System.Types, System.SysUtils, System.Classes, nduWlanTypes, FIWClasses, System.Generics.Collections; type TWinNetworkInfo = class class function GetNetworkInfo: TObjectList<TWlanInfo>; end; implementation class function TWinNetworkInfo.GetNetworkInfo: TObjectList<TWlanInfo>; var Handle: DWORD; NegotiatedVersion: DWORD; //Version used in this session pAvailableNetworkList: Pndu_WLAN_AVAILABLE_NETWORK_LIST; //Interface to network list pWlanInterfaceInfo: Pndu_WLAN_INTERFACE_INFO_LIST; //Info about wireless interfaces i, j, z: integer; //Loop variables pInterfaceGUID: PGUID; //GUID buffer SDummy: string; //Buf string NewNetwork: TWlanInfo; begin SDummy:=''; Result:=TObjectList<TWlanInfo>.Create(true); {Get handle of wlan api} if not WlanOpenHandle(2,nil,@NegotiatedVersion,@Handle)=0 then raise Exception.Create('WinOpenHandle not succeded'); try try {Get wlan network interfaces} if not WlanEnumInterfaces(Handle,nil,@pWlanInterfaceInfo)=0 then raise Exception.Create('WlanEnumInterfaces not succeded'); for i:=0 to pWlanInterfaceInfo^.dwNumberOfItems-1 do begin {Get list of networks for every interface} pInterfaceGUID:=@pWlanInterfaceInfo^ .InterfaceInfo[pWlanInterfaceInfo^.dwIndex].InterfaceGuid; if not WlanGetAvailableNetworkList(Handle,pInterfaceGUID, WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES ,nil, pAvailableNetworkList) = 0 then raise Exception.Create('WlanGetAvailibleNetworkList not succeded'); {if network is open, save the information} for j:=0 to pAvailableNetworkList^.dwNumberOfItems - 1 do begin SDummy:=''; if not (pAvailableNetworkList^.Network[j].dot11DefaultAuthAlgorithm =DOT11_AUTH_ALGO_80211_OPEN) then continue; {If open network found, save ssid and name} //Become SSID for z:=0 to pAvailableNetworkList^.Network[j].dot11Ssid.uSSIDLength-1 do SDummy := SDummy + Chr(pAvailableNetworkList^.Network[j].dot11Ssid.ucSSID[z]); if SDummy.Trim='' then continue; NewNetwork:=TWlanInfo.Create; NewNetwork.Name:=SDummy.Trim; Result.Add(NewNetwork); end; end; except FreeAndNil(Result); end; finally WlanCloseHandle(Handle,nil); end; end; end.
unit adxolBDSFormCreator; {$I adxolDefs.inc} interface uses Windows, ToolsAPI; {$IFDEF DELPHI_9_UP} type TadxOlFormImplementationFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxXlFormImplementationFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxWdFormImplementationFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxPpFormImplementationFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxOlFormImplementationDfmFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxXlFormImplementationDfmFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxWdFormImplementationDfmFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxPpFormImplementationDfmFile = class(TInterfacedObject, IOTAFile) private fModuleName : String; fAncestorIdent: String; fAncestorClass: TClass; fFormIdent: String; public constructor Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); { Return the actual source code } function GetSource: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} { Return the age of the file. -1 if new } function GetAge: TDateTime; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property ModuleName : String read fModuleName write fModuleName; property FormIdent : String read fFormIdent write fFormIdent; property AncestorIdent: String read fAncestorIdent write fAncestorIdent; property AncestorClass: TClass read fAncestorClass write fAncestorClass; end; TadxOlFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator) private fNewUnitIdent : String; fNewClassname : String; fNewFilename : String; public constructor Create; function GetCreatorType: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetExisting: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFileSystem: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetOwner: IOTAModule; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetUnnamed: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetAncestorName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetImplFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetIntfFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFormName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetMainForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowSource: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} procedure FormCreated(const FormEditor: IOTAFormEditor); {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property NewUnitIdent : String read fNewUnitIdent write fNewUnitIdent; property NewClassName : String read fNewClassname write fNewClassname; property NewFilename : String read fNewFilename write fNewFilename; end; TadxXlFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator) private fNewUnitIdent : String; fNewClassname : String; fNewFilename : String; public constructor Create; function GetCreatorType: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetExisting: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFileSystem: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetOwner: IOTAModule; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetUnnamed: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetAncestorName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetImplFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetIntfFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFormName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetMainForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowSource: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} procedure FormCreated(const FormEditor: IOTAFormEditor); {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property NewUnitIdent : String read fNewUnitIdent write fNewUnitIdent; property NewClassName : String read fNewClassname write fNewClassname; property NewFilename : String read fNewFilename write fNewFilename; end; TadxWdFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator) private fNewUnitIdent : String; fNewClassname : String; fNewFilename : String; public constructor Create; function GetCreatorType: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetExisting: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFileSystem: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetOwner: IOTAModule; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetUnnamed: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetAncestorName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetImplFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetIntfFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFormName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetMainForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowSource: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} procedure FormCreated(const FormEditor: IOTAFormEditor); {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property NewUnitIdent : String read fNewUnitIdent write fNewUnitIdent; property NewClassName : String read fNewClassname write fNewClassname; property NewFilename : String read fNewFilename write fNewFilename; end; TadxPpFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator) private fNewUnitIdent : String; fNewClassname : String; fNewFilename : String; public constructor Create; function GetCreatorType: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetExisting: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFileSystem: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetOwner: IOTAModule; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetUnnamed: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetAncestorName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetImplFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetIntfFileName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetFormName: string; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetMainForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowForm: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function GetShowSource: Boolean; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} procedure FormCreated(const FormEditor: IOTAFormEditor); {$IFDEF BCBHEADER} virtual; abstract; {$ENDIF} property NewUnitIdent : String read fNewUnitIdent write fNewUnitIdent; property NewClassName : String read fNewClassname write fNewClassname; property NewFilename : String read fNewFilename write fNewFilename; end; {$ENDIF} implementation uses TypInfo, adxolFormsManager, adxwdFormsManager, adxppFormsManager, adxxlFormsManager; const CRLF = #13#10; function GetCurrentProjectGroup: IOTAProjectGroup; var IModuleServices: IOTAModuleServices; IModule: IOTAModule; IProjectGroup: IOTAProjectGroup; i: Integer; begin Result := nil; IModuleServices := BorlandIDEServices as IOTAModuleServices; for i := 0 to IModuleServices.ModuleCount - 1 do begin IModule := IModuleServices.Modules[i]; if IModule.QueryInterface(IOTAProjectGroup, IProjectGroup) = S_OK then begin Result := IProjectGroup; Break; end; end; end; function GetCurrentProject: IOTAProject; var ProjectGroup: IOTAProjectGroup; begin Result := nil; ProjectGroup := GetCurrentProjectGroup; if Assigned(ProjectGroup) then if ProjectGroup.ProjectCount > 0 then Result := ProjectGroup.ActiveProject end; {$IFDEF DELPHI_9_UP} function GetCustomFormUnit(const AClass: TClass): string; begin {$IFDEF UNICODE} Result := UTF8ToString(GetTypeData(PTypeInfo(AClass.ClassInfo))^.UnitName); {$ELSE} Result := GetTypeData(PTypeInfo(AClass.ClassInfo))^.UnitName; {$ENDIF} end; constructor TadxOlFormCreator.Create; var OTAModuleServices : IOTAModuleServices; begin inherited Create; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin OTAModuleServices.GetNewModuleAndClassName('Unit', fNewUnitIdent, fNewClassName, fNewFileName); end; end; function TadxOlFormCreator.GetCreatorType : String; begin result := sForm; end; function TadxOlFormCreator.GetExisting : Boolean; begin result := FALSE; end; function TadxOlFormCreator.GetFileSystem : String; var OTAModuleServices : IOTAModuleServices; begin result := ''; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin Result := OTAModuleServices.CurrentModule.GetFileSystem; end; end; function TadxOlFormCreator.GetOwner : IOTAModule; {var OTAModuleServices : IOTAModuleServices; begin result := nil; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin if OTAModuleServices.CurrentModule.GetOwnerCount > 0 then result := OTAModuleServices.CurrentModule.GetOwner(0); end; // if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK end; } begin Result := GetCurrentProjectGroup; if Assigned(Result) then Result := (Result as IOTAProjectGroup).ActiveProject else Result := GetCurrentProject; end; function TadxOlFormCreator.GetUnnamed : Boolean; begin result := TRUE; end; function TadxOlFormCreator.GetAncestorName: string; begin result := 'adxOlForm'; end; function TadxOlFormCreator.GetImplFileName: string; begin result := NewFilename; end; function TadxOlFormCreator.GetIntfFileName: string; begin result := NewFilename; end; function TadxOlFormCreator.GetFormName: string; begin result := NewClassName; end; function TadxOlFormCreator.GetShowSource: Boolean; begin result := false; end; function TadxOlFormCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxOlFormImplementationFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxOlForm); end; function TadxOlFormCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := nil; end; function TadxOlFormCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxOlFormImplementationDfmFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxOlForm); //result := nil; end; function TadxOlFormCreator.GetMainForm: Boolean; begin result := false; end; function TadxOlFormCreator.GetShowForm: Boolean; begin result := false; end; procedure TadxOlFormCreator.FormCreated(const FormEditor: IOTAFormEditor); begin // Do Nothing end; {-----------------------------------------------------------------------­------} constructor TadxXlFormCreator.Create; var OTAModuleServices : IOTAModuleServices; begin inherited Create; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin OTAModuleServices.GetNewModuleAndClassName('Unit', fNewUnitIdent, fNewClassName, fNewFileName); end; end; function TadxXlFormCreator.GetCreatorType : String; begin result := sForm; end; function TadxXlFormCreator.GetExisting : Boolean; begin result := FALSE; end; function TadxXlFormCreator.GetFileSystem : String; var OTAModuleServices : IOTAModuleServices; begin result := ''; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin Result := OTAModuleServices.CurrentModule.GetFileSystem; end; end; function TadxXlFormCreator.GetOwner : IOTAModule; {var OTAModuleServices : IOTAModuleServices; begin result := nil; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin if OTAModuleServices.CurrentModule.GetOwnerCount > 0 then result := OTAModuleServices.CurrentModule.GetOwner(0); end; // if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK end; } begin Result := GetCurrentProjectGroup; if Assigned(Result) then Result := (Result as IOTAProjectGroup).ActiveProject else Result := GetCurrentProject; end; function TadxXlFormCreator.GetUnnamed : Boolean; begin result := TRUE; end; function TadxXlFormCreator.GetAncestorName: string; begin result := 'adxXlForm'; end; function TadxXlFormCreator.GetImplFileName: string; begin result := NewFilename; end; function TadxXlFormCreator.GetIntfFileName: string; begin result := NewFilename; end; function TadxXlFormCreator.GetFormName: string; begin result := NewClassName; end; function TadxXlFormCreator.GetShowSource: Boolean; begin result := false; end; function TadxXlFormCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxXlFormImplementationFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxExcelTaskPane); end; function TadxXlFormCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := nil; end; function TadxXlFormCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxXlFormImplementationDfmFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxOlForm); //result := nil; end; function TadxXlFormCreator.GetMainForm: Boolean; begin result := false; end; function TadxXlFormCreator.GetShowForm: Boolean; begin result := false; end; procedure TadxXlFormCreator.FormCreated(const FormEditor: IOTAFormEditor); begin // Do Nothing end; {-----------------------------------------------------------------------­------} constructor TadxWdFormCreator.Create; var OTAModuleServices : IOTAModuleServices; begin inherited Create; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin OTAModuleServices.GetNewModuleAndClassName('Unit', fNewUnitIdent, fNewClassName, fNewFileName); end; end; function TadxWdFormCreator.GetCreatorType : String; begin result := sForm; end; function TadxWdFormCreator.GetExisting : Boolean; begin result := FALSE; end; function TadxWdFormCreator.GetFileSystem : String; var OTAModuleServices : IOTAModuleServices; begin result := ''; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin Result := OTAModuleServices.CurrentModule.GetFileSystem; end; end; function TadxWdFormCreator.GetOwner : IOTAModule; {var OTAModuleServices : IOTAModuleServices; begin result := nil; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin if OTAModuleServices.CurrentModule.GetOwnerCount > 0 then result := OTAModuleServices.CurrentModule.GetOwner(0); end; // if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK end; } begin Result := GetCurrentProjectGroup; if Assigned(Result) then Result := (Result as IOTAProjectGroup).ActiveProject else Result := GetCurrentProject; end; function TadxWdFormCreator.GetUnnamed : Boolean; begin result := TRUE; end; function TadxWdFormCreator.GetAncestorName: string; begin result := 'adxWdForm'; end; function TadxWdFormCreator.GetImplFileName: string; begin result := NewFilename; end; function TadxWdFormCreator.GetIntfFileName: string; begin result := NewFilename; end; function TadxWdFormCreator.GetFormName: string; begin result := NewClassName; end; function TadxWdFormCreator.GetShowSource: Boolean; begin result := false; end; function TadxWdFormCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxWdFormImplementationFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxWordTaskPane); end; function TadxWdFormCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := nil; end; function TadxWdFormCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxWdFormImplementationDfmFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxOlForm); //result := nil; end; function TadxWdFormCreator.GetMainForm: Boolean; begin result := false; end; function TadxWdFormCreator.GetShowForm: Boolean; begin result := false; end; procedure TadxWdFormCreator.FormCreated(const FormEditor: IOTAFormEditor); begin // Do Nothing end; {------------------------------------------------------------------------------} {-----------------------------------------------------------------------­------} constructor TadxPpFormCreator.Create; var OTAModuleServices : IOTAModuleServices; begin inherited Create; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin OTAModuleServices.GetNewModuleAndClassName('Unit', fNewUnitIdent, fNewClassName, fNewFileName); end; end; function TadxPpFormCreator.GetCreatorType : String; begin result := sForm; end; function TadxPpFormCreator.GetExisting : Boolean; begin result := FALSE; end; function TadxPpFormCreator.GetFileSystem : String; var OTAModuleServices : IOTAModuleServices; begin result := ''; if BorlandIDEServices.QueryInterface(IOTAModuleServices, OTAModuleServices) = S_OK then begin Result := OTAModuleServices.CurrentModule.GetFileSystem; end; end; function TadxPpFormCreator.GetOwner : IOTAModule; begin Result := GetCurrentProjectGroup; if Assigned(Result) then Result := (Result as IOTAProjectGroup).ActiveProject else Result := GetCurrentProject; end; function TadxPpFormCreator.GetUnnamed : Boolean; begin result := TRUE; end; function TadxPpFormCreator.GetAncestorName: string; begin result := 'adxPpForm'; end; function TadxPpFormCreator.GetImplFileName: string; begin result := NewFilename; end; function TadxPpFormCreator.GetIntfFileName: string; begin result := NewFilename; end; function TadxPpFormCreator.GetFormName: string; begin result := NewClassName; end; function TadxPpFormCreator.GetShowSource: Boolean; begin result := false; end; function TadxPpFormCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxPpFormImplementationFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxPowerPointTaskPane); end; function TadxPpFormCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin result := nil; end; function TadxPpFormCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin result := TadxPpFormImplementationDfmFile.Create(NewUnitIdent, NewClassName, AncestorIdent, TadxOlForm); //result := nil; end; function TadxPpFormCreator.GetMainForm: Boolean; begin result := false; end; function TadxPpFormCreator.GetShowForm: Boolean; begin result := false; end; procedure TadxPpFormCreator.FormCreated(const FormEditor: IOTAFormEditor); begin // Do Nothing end; {------------------------------------------------------------------------------} {------------------------------------------------------------------------------} constructor TadxOlFormImplementationFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxOlFormImplementationFile.GetSource: string; begin Result := 'unit ' + FModuleName + ';' + CRLF + CRLF + 'interface' + CRLF + CRLF + 'uses' + CRLF + ' Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs'; Result := Result + ',' + CRLF + ' Outlook2000, adxolFormsManager'; //+ GetCustomFormUnit(FAncestorClass); Result := Result + ';' + CRLF + CRLF + 'type' + CRLF + ' T' + fFormIdent + ' = class(' + FAncestorClass.ClassName + ')' + CRLF + // ' Label1: TLabel;' + //CRLF + ' private' + CRLF + ' { Private declarations }' + CRLF + ' protected' + CRLF + ' { Protected declarations }' + CRLF + ' public' + CRLF + ' { Public declarations }' + CRLF + ' published' + CRLF + ' { Published declarations }' + CRLF + ' end;' + CRLF + CRLF + '{NOTE: The ' + FFormIdent + ' variable is intended for the exclusive use' + CRLF + ' by the TadxOlFormsCollectionItem Designer.' + CRLF + ' NEVER use this variable for other purposes.}' + CRLF + 'var' + CRLF + ' ' + FFormIdent + ' : T' + FFormIdent + ';' + CRLF + CRLF + 'implementation' + CRLF + CRLF + '{$R *.DFM}' + CRLF + CRLF + 'initialization' + CRLF + ' RegisterClass(TPersistentClass(T' + FFormIdent + '));' + CRLF + CRLF + 'finalization' + CRLF + 'end.' + CRLF; end; { Return the age of the file. -1 if new } function TadxOlFormImplementationFile.GetAge: TDateTime; begin result := -1; end; {------------------------------------------------------------------------------} constructor TadxXlFormImplementationFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxXlFormImplementationFile.GetSource: string; begin Result := 'unit ' + FModuleName + ';' + CRLF + CRLF + 'interface' + CRLF + CRLF + 'uses' + CRLF + ' Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs'; Result := Result + ',' + CRLF + ' Outlook2000, adxxlFormsManager'; //+ GetCustomFormUnit(FAncestorClass); Result := Result + ';' + CRLF + CRLF + 'type' + CRLF + ' T' + fFormIdent + ' = class(' + FAncestorClass.ClassName + ')' + CRLF + // ' Label1: TLabel;' + //CRLF + ' private' + CRLF + ' { Private declarations }' + CRLF + ' protected' + CRLF + ' { Protected declarations }' + CRLF + ' public' + CRLF + ' { Public declarations }' + CRLF + ' published' + CRLF + ' { Published declarations }' + CRLF + ' end;' + CRLF + CRLF + '{NOTE: The ' + FFormIdent + ' variable is intended for the exclusive use' + CRLF + ' by the TadxXlFormsCollectionItem Designer.' + CRLF + ' NEVER use this variable for other purposes.}' + CRLF + 'var' + CRLF + ' ' + FFormIdent + ' : T' + FFormIdent + ';' + CRLF + CRLF + 'implementation' + CRLF + CRLF + '{$R *.DFM}' + CRLF + CRLF + 'initialization' + CRLF + ' RegisterClass(TPersistentClass(T' + FFormIdent + '));' + CRLF + CRLF + 'finalization' + CRLF + 'end.' + CRLF; end; { Return the age of the file. -1 if new } function TadxXlFormImplementationFile.GetAge: TDateTime; begin result := -1; end; {------------------------------------------------------------------------------} {------------------------------------------------------------------------------} constructor TadxWdFormImplementationFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxWdFormImplementationFile.GetSource: string; begin Result := 'unit ' + FModuleName + ';' + CRLF + CRLF + 'interface' + CRLF + CRLF + 'uses' + CRLF + ' Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs'; Result := Result + ',' + CRLF + ' Word2000, adxwdFormsManager'; //+ GetCustomFormUnit(FAncestorClass); Result := Result + ';' + CRLF + CRLF + 'type' + CRLF + ' T' + fFormIdent + ' = class(' + FAncestorClass.ClassName + ')' + CRLF + // ' Label1: TLabel;' + //CRLF + ' private' + CRLF + ' { Private declarations }' + CRLF + ' protected' + CRLF + ' { Protected declarations }' + CRLF + ' public' + CRLF + ' { Public declarations }' + CRLF + ' published' + CRLF + ' { Published declarations }' + CRLF + ' end;' + CRLF + CRLF + '{NOTE: The ' + FFormIdent + ' variable is intended for the exclusive use' + CRLF + ' by the TadxWordTaskPanesCollectionItem Designer.' + CRLF + ' NEVER use this variable for other purposes.}' + CRLF + 'var' + CRLF + ' ' + FFormIdent + ' : T' + FFormIdent + ';' + CRLF + CRLF + 'implementation' + CRLF + CRLF + '{$R *.DFM}' + CRLF + CRLF + 'initialization' + CRLF + ' RegisterClass(TPersistentClass(T' + FFormIdent + '));' + CRLF + CRLF + 'finalization' + CRLF + 'end.' + CRLF; end; { Return the age of the file. -1 if new } function TadxWdFormImplementationFile.GetAge: TDateTime; begin result := -1; end; {------------------------------------------------------------------------------} {------------------------------------------------------------------------------} constructor TadxPpFormImplementationFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxPpFormImplementationFile.GetSource: string; begin Result := 'unit ' + FModuleName + ';' + CRLF + CRLF + 'interface' + CRLF + CRLF + 'uses' + CRLF + ' Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs'; Result := Result + ',' + CRLF + ' MSPpt2000, adxppFormsManager'; //+ GetCustomFormUnit(FAncestorClass); Result := Result + ';' + CRLF + CRLF + 'type' + CRLF + ' T' + fFormIdent + ' = class(' + FAncestorClass.ClassName + ')' + CRLF + // ' Label1: TLabel;' + //CRLF + ' private' + CRLF + ' { Private declarations }' + CRLF + ' protected' + CRLF + ' { Protected declarations }' + CRLF + ' public' + CRLF + ' { Public declarations }' + CRLF + ' published' + CRLF + ' { Published declarations }' + CRLF + ' end;' + CRLF + CRLF + '{NOTE: The ' + FFormIdent + ' variable is intended for the exclusive use' + CRLF + ' by the TadxPowerPointTaskPanesCollectionItem Designer.' + CRLF + ' NEVER use this variable for other purposes.}' + CRLF + 'var' + CRLF + ' ' + FFormIdent + ' : T' + FFormIdent + ';' + CRLF + CRLF + 'implementation' + CRLF + CRLF + '{$R *.DFM}' + CRLF + CRLF + 'initialization' + CRLF + ' RegisterClass(TPersistentClass(T' + FFormIdent + '));' + CRLF + CRLF + 'finalization' + CRLF + 'end.' + CRLF; end; { Return the age of the file. -1 if new } function TadxPpFormImplementationFile.GetAge: TDateTime; begin result := -1; end; {------------------------------------------------------------------------------} { TadxOlFormImplementationDfmFile } constructor TadxOlFormImplementationDfmFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxOlFormImplementationDfmFile.GetSource: string; begin result := 'object ' + fFormIdent+':'+ 'T' + fFormIdent + CRLF + 'Left = 223' + CRLF + 'Top = 114' + CRLF + 'Width = 400' + CRLF + 'Height = 300' + CRLF + 'Caption = ''' + fFormIdent + '''' + CRLF + 'Color = clBtnFace' + CRLF + 'Font.Charset = DEFAULT_CHARSET' + CRLF + 'Font.Color = clWindowText' + CRLF + 'Font.Height = -11' + CRLF + 'Font.Name = ''MS Sans Serif''' + CRLF + 'Font.Style = []' + CRLF + 'OldCreateOrder = False' + CRLF + 'PixelsPerInch = 96' + CRLF + 'TextHeight = 13' + CRLF + 'end'; end; { Return the age of the file. -1 if new } function TadxOlFormImplementationDfmFile.GetAge: TDateTime; begin result := -1; end; { TadxXlFormImplementationDfmFile } constructor TadxXlFormImplementationDfmFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxXlFormImplementationDfmFile.GetSource: string; begin result := 'object ' + fFormIdent+':'+ 'T' + fFormIdent + CRLF + 'Left = 223' + CRLF + 'Top = 114' + CRLF + 'Width = 400' + CRLF + 'Height = 300' + CRLF + 'Caption = ''' + fFormIdent + '''' + CRLF + 'Color = clBtnFace' + CRLF + 'Font.Charset = DEFAULT_CHARSET' + CRLF + 'Font.Color = clWindowText' + CRLF + 'Font.Height = -11' + CRLF + 'Font.Name = ''MS Sans Serif''' + CRLF + 'Font.Style = []' + CRLF + 'OldCreateOrder = False' + CRLF + 'PixelsPerInch = 96' + CRLF + 'TextHeight = 13' + CRLF + 'end'; end; { Return the age of the file. -1 if new } function TadxXlFormImplementationDfmFile.GetAge: TDateTime; begin result := -1; end; { TadxWdFormImplementationDfmFile } constructor TadxWdFormImplementationDfmFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxWdFormImplementationDfmFile.GetSource: string; begin result := 'object ' + fFormIdent+':'+ 'T' + fFormIdent + CRLF + 'Left = 223' + CRLF + 'Top = 114' + CRLF + 'Width = 400' + CRLF + 'Height = 300' + CRLF + 'Caption = ''' + fFormIdent + '''' + CRLF + 'Color = clBtnFace' + CRLF + 'Font.Charset = DEFAULT_CHARSET' + CRLF + 'Font.Color = clWindowText' + CRLF + 'Font.Height = -11' + CRLF + 'Font.Name = ''MS Sans Serif''' + CRLF + 'Font.Style = []' + CRLF + 'OldCreateOrder = False' + CRLF + 'PixelsPerInch = 96' + CRLF + 'TextHeight = 13' + CRLF + 'end'; end; { Return the age of the file. -1 if new } function TadxWdFormImplementationDfmFile.GetAge: TDateTime; begin result := -1; end; { TadxPpFormImplementationDfmFile } constructor TadxPpFormImplementationDfmFile.Create(const AModuleName, AFormIdent, AAncestorIdent: String; AAncestorClass: TClass); begin inherited Create; fModuleName := AModuleName; fFormIdent := AFormIdent; fAncestorIdent := AAncestorIdent; fAncestorClass := AAncestorClass; end; { Return the actual source code } function TadxPpFormImplementationDfmFile.GetSource: string; begin result := 'object ' + fFormIdent+':'+ 'T' + fFormIdent + CRLF + 'Left = 223' + CRLF + 'Top = 114' + CRLF + 'Width = 400' + CRLF + 'Height = 300' + CRLF + 'Caption = ''' + fFormIdent + '''' + CRLF + 'Color = clBtnFace' + CRLF + 'Font.Charset = DEFAULT_CHARSET' + CRLF + 'Font.Color = clWindowText' + CRLF + 'Font.Height = -11' + CRLF + 'Font.Name = ''MS Sans Serif''' + CRLF + 'Font.Style = []' + CRLF + 'OldCreateOrder = False' + CRLF + 'PixelsPerInch = 96' + CRLF + 'TextHeight = 13' + CRLF + 'end'; end; { Return the age of the file. -1 if new } function TadxPpFormImplementationDfmFile.GetAge: TDateTime; begin result := -1; end; {$ENDIF} end.
unit MainWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DDraw, Menus, ExtDlgs; type TMainForm = class(TForm) OpenPictureDialog: TOpenPictureDialog; MainMenu: TMainMenu; File1: TMenuItem; Load: TMenuItem; procedure FormShow(Sender: TObject); procedure FormPaint(Sender: TObject); procedure LoadClick(Sender: TObject); private { Private declarations } fDirectDraw : IDirectDraw4; fPrimarySurface : IDirectDrawSurface4; fClipper : IDirectDrawClipper; fBitmap : TBitmap; fBitmapSurface : IDirectDrawSurface4; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.DFM} uses ComObj, LogFile; function CopyBitmapToSurface(Bitmap : TBitmap; const Surface : IDirectDrawSurface4; x, y : integer) : boolean; var dc : HDC; memdc : HDC; begin Result := false; if Surface.GetDC(dc) = DD_OK then try memdc := CreateCompatibleDC(dc); if memdc <> 0 then try SelectObject(memdc, Bitmap.Handle); if not BitBlt(dc, x, y, Bitmap.Width, Bitmap.Height, memdc, 0, 0, SRCCOPY) then LogThis('BitBlt FAILED') else Result := true; finally DeleteDC(memdc); end else LogThis('CreateCompatibleDC FAILED'); finally Surface.ReleaseDC(dc); end else LogThis('GetDC FAILED'); end; procedure TMainForm.FormShow(Sender: TObject); var ddsd : TDDSurfaceDesc2; //ddscaps : TDDSCAPS2; hRet : HRESULT; pDD : IDirectDraw; begin hRet := DirectDrawCreate(nil, pDD, nil); if hRet <> DD_OK then LogThis('DirectDrawCreate FAILED') else begin hRet := pDD.QueryInterface(IID_IDirectDraw4, fDirectDraw); if hRet <> DD_OK then LogThis('QueryInterface FAILED') else begin hRet := fDirectDraw.SetCooperativeLevel(Handle, DDSCL_NORMAL); if hRet <> DD_OK then LogThis('SetCooperativeLevel FAILED') else begin // Create the primary surface fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS; ddsd.ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE; hRet := fDirectDraw.CreateSurface(ddsd, fPrimarySurface, nil); if hRet <> DD_OK then LogThis('CreateSurface FAILED') else begin hRet := fDirectDraw.CreateClipper(0, fClipper, nil); if hRet <> DD_OK then LogThis('GetClipper FAILED') else begin hRet := fPrimarySurface.SetClipper(fClipper); if hRet <> DD_OK then LogThis('SetClipper FAILED'); end; end; end; end; end; end; procedure TMainForm.FormPaint(Sender: TObject); function DoBlit(const Src, Dest : IDirectDrawSurface4; x, y : integer) : boolean; var BltEfx : TDDBltFX; DestRect : TRect; SrcRect : TRect; begin fillchar(BltEfx, sizeof(BltEfx), 0); BltEfx.dwSize := sizeof(BltEfx); DestRect := Rect(x, y, pred(x + fBitmap.Width), pred(y + fBitmap.Height)); SrcRect := Rect(0, 0, pred(fBitmap.Width), pred(fBitmap.Height)); Result := Dest.Blt(@DestRect, Src, @SrcRect, DDBLT_WAIT, BltEfx) = DD_OK; end; var hRet : HRESULT; ScPt : TPoint; begin if (fBitmap <> nil) and (fClipper <> nil) then begin hRet := fClipper.SetHWnd(0, Handle); if hRet <> DD_OK then LogThis('SetHWnd FAILED') else begin ScPt := ClientToScreen(Point(0, 0)); DoBlit(fBitmapSurface, fPrimarySurface, ScPt.x, ScPt.y); end; end; end; procedure TMainForm.LoadClick(Sender: TObject); function CreateBitmapSurface(Width, Height : integer) : IDirectDrawSurface4; var hRet : HRESULT; ddsd : TDDSurfaceDesc2; begin fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS or DDSD_WIDTH or DDSD_HEIGHT; ddsd.ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth := Width; ddsd.dwHeight := Height; hRet := fDirectDraw.CreateSurface(ddsd, Result, nil); if hRet <> DD_OK then Result := nil; end; begin if OpenPictureDialog.Execute then begin fBitmapSurface := nil; fBitmap.Free; fBitmap := nil; fBitmap := TBitmap.Create; try fBitmap.LoadFromFile(OpenPictureDialog.FileName); fBitmapSurface := CreateBitmapSurface(fBitmap.Width, fBitmap.Height); if fBitmapSurface <> nil then CopyBitmapToSurface(fBitmap, fBitmapSurface, 0, 0) else begin fBitmap.Free; fBitmap := nil; end; Refresh; except fBitmap.Free; fBitmap := nil; end; end; end; initialization SetLogFile('C:\Tmp\Windowed.log'); end.
unit ServerHorse.Routers.Users; interface uses System.JSON, Horse, Horse.Jhonson, Horse.OctetStream, Horse.CORS, ServerHorse.Controller; procedure Registry; implementation uses System.Classes, ServerHorse.Controller.Interfaces, ServerHorse.Model.Entity.USERS, System.SysUtils, ServerHorse.Utils, Horse.Paginate, Vcl.Forms; procedure Registry; begin THorse .Use(Paginate) .Use(Jhonson) .Use(CORS) .Use(OctetStream) .Get('/users', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) var iController : iControllerEntity<TUSERS>; begin iController := TController.New.USERS; iController.This .DAO .SQL .Fields('USERS.*, ') .Fields('OCCUPATION.DESCRIPTION AS OCCUPATION ') .Where(TServerUtils.New.LikeFind(Req)) .Join('LEFT JOIN OCCUPATION ON OCCUPATION.GUUID = USERS.IDOCCUPATION') .OrderBy(TServerUtils.New.OrderByFind(Req)) .&End .Find(False); Res.Send<TJsonArray>(iController.This.DataSetAsJsonArray); end) .Get('/users/:ID', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) var iController : iControllerEntity<TUSERS>; begin iController := TController.New.USERS; iController.This .DAO .SQL .Where('GUUID = ' + QuotedStr(Req.Params['ID'])) .&End .Find; Res.Send<TJsonArray>(iController.This.DataSetAsJsonArray); end) .Post('/users/stream', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) var LStream: TMemoryStream; begin if not DirectoryExists((ExtractFilePath(application.exename))+'public\'+Req.Headers['Path']) then ForceDirectories((ExtractFilePath(application.exename))+'public\'+Req.Headers['Path']); LStream := Req.Body<TMemoryStream>; LStream.SaveToFile(extractfilepath(application.exename)+'public\'+Req.Headers['Path']+'\'+Req.Headers['FileName']); Res.Send('/'+stringreplace(Req.Headers['Path'],'\','/',[rfReplaceAll, rfIgnoreCase])+'/'+Req.Headers['FileName']).Status(201); end) .Post('/users', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) var vBody : TJsonObject; aGuuid: string; begin vBody := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject; try if not vBody.TryGetValue<String>('guuid', aGuuid) then vBody.AddPair('guuid', TServerUtils.New.AdjustGuuid(TGUID.NewGuid.ToString())); TController.New.USERS.This.Insert(vBody); Res.Status(200).Send<TJsonObject>(vBody); except Res.Status(500).Send(''); end; end) .Put('/users/:ID', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) var vBody : TJsonObject; aGuuid: string; begin vBody := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject; try if not vBody.TryGetValue<String>('guuid', aGuuid) then vBody.AddPair('guuid', Req.Params['ID'] ); TController.New.USERS.This.Update(vBody); Res.Status(200).Send<TJsonObject>(vBody); except Res.Status(500).Send(''); end; end) .Delete('/users/:id', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) var aTeste: string; begin try TController.New.USERS.This.Delete('guuid', QuotedStr(Req.Params['id'])); Res.Status(200).Send(''); except Res.Status(500).Send(''); end; end); end; end.
//Ghetto-sphere breach && cleanse the brains of war? unit socket; interface {$IFDEF FPC} {$PACKRECORDS C} {$ENDIF} //in.h const INADDR_ANY = $00000000; INADDR_BROADCAST = $FFFFFFFF; INADDR_NONE = $FFFFFFFF; INET_ADDRSTRLEN = 16; {#define IPPROTO_IP ??? } {#define IPPROTO_TCP ??? } {#define IPPROTO_UDP ??? } {#define SOL_TCP ??? } {#define TCP_NODELAY ??? } {#define TCP_NODELAY ??? } type in_port_t = uint16_t; in_addr_t = uint32_t; in_addr = record s_addr : in_addr_t; end; pin_addr: ^in_addr; sockaddr_in = record sin_family : sa_family_t; sin_port : in_port_t; sin_addr : in_addr; sin_zero : array[0..7] of byte; end; const SOL_SOCKET = $FFFF; PF_UNSPEC = 0; PF_INET = 2; PF_INET6 = 10; AF_UNSPEC = PF_UNSPEC; AF_INET = PF_INET; AF_INET6 = PF_INET6; SOCK_STREAM = 1; SOCK_DGRAM = 2; MSG_CTRUNC = $01000000; MSG_DONTROUTE = $02000000; MSG_EOR = $04000000; MSG_OOB = $08000000; MSG_PEEK = $10000000; MSG_TRUNC = $20000000; MSG_WAITALL = $40000000; SHUT_RD = 0; SHUT_WR = 1; SHUT_RDWR = 2; SO_DEBUG = $0001; SO_ACCEPTCONN = $0002; SO_REUSEADDR = $0004; SO_KEEPALIVE = $0008; SO_DONTROUTE = $0010; SO_BROADCAST = $0020; SO_USELOOPBACK = $0040; SO_LINGER = $0080; SO_OOBINLINE = $0100; SO_REUSEPORT = $0200; SO_SNDBUF = $1001; SO_RCVBUF = $1002; SO_SNDLOWAT = $1003; SO_RCVLOWAT = $1004; SO_SNDTIMEO = $1005; SO_RCVTIMEO = $1006; SO_ERROR = $1007; SO_TYPE = $1008; type socklen_t = uint32_t; Psocklen_t = ^socklen_t; sa_family_t = uint16_t; sockaddr = record sa_family : sa_family_t; sa_data : array of char; end; Psockaddr = ^sockaddr; sockaddr_storage = record ss_family : sa_family_t; __ss_padding : array[0..13] of char; end; linger = record l_onoff : longint; l_linger : longint; end; //netdb.h const HOST_NOT_FOUND = 1; NO_DATA = 2; NO_ADDRESS = NO_DATA; NO_RECOVERY = 3; TRY_AGAIN = 4; type hostent = record h_name : ^char; h_aliases : ^^char; h_addrtype : longint; h_length : longint; h_addr_list : ^^char; end; phostent = ^hostent; function h_errno: longint;cdecl;external; function gethostbyname(name: PChar):phostent; function accept(sockfd:longint; addr:psockaddr; addrlen:psocklen_t):longint;cdecl;external; function bind(sockfd:longint; addr:psockaddr; addrlen:socklen_t):longint;cdecl;external; function closesocket(sockfd:longint):longint;cdecl;external; function connect(sockfd:longint; addr:psockaddr; addrlen:socklen_t):longint;cdecl;external; function getpeername(sockfd:longint; addr:psockaddr; addrlen:psocklen_t):longint;cdecl;external; function getsockname(sockfd:longint; addr:psockaddr; addrlen:psocklen_t):longint;cdecl;external; function getsockopt(sockfd:longint; level:longint; optname:longint; optval:pointer; optlen:psocklen_t):longint;cdecl;external; function listen(sockfd:longint; backlog:longint):longint;cdecl;external; function recv(sockfd:longint; buf:pointer; len:size_t; flags:longint):ssize_t;cdecl;external; function recvfrom(sockfd:longint; buf:pointer; len:size_t; flags:longint; src_addr:psockaddr; addrlen:psocklen_t):ssize_t;cdecl;external; function send(sockfd:longint; buf:pointer; len:size_t; flags:longint):ssize_t;cdecl;external; function sendto(sockfd:longint; buf:pointer; len:size_t; flags:longint; dest_addr:psockaddr; addrlen:socklen_t):ssize_t;cdecl;external; function setsockopt(sockfd:longint; level:longint; optname:longint; optval:pointer; optlen:socklen_t):longint;cdecl;external; function shutdown(sockfd:longint; how:longint):longint;cdecl;external; function socket(domain:longint; _type:longint; protocol:longint):longint;cdecl;external; function sockatmark(sockfd:longint):longint;cdecl;external; //select.h Type Pfd_set = ^fd_set; Ptimeval = ^timeval; function select(nfds:longint; readfds:pfd_set; writefds:pfd_set; exceptfds:pfd_set; timeout:ptimeval):longint;cdecl;external; //ioctl.h const FIONBIO = 1; function ioctl(fd:longint; request:longint; args:array of const):longint;cdecl;external; function ioctl(fd:longint; request:longint):longint;cdecl;external; //inet.h function htonl(hostlong: uint32_t): uint32_t; inline; function htons(hostshort: uint16_t): uint16_t; inline; function ntohl(netlong: uint32_t): uint32_t; inline; function ntohs(netshort: uint16_t): uint16_t; inline; function inet_addr(cp:pchar):in_addr_t;cdecl;external; function inet_aton(cp:pchar; inp:pin_addr):longint;cdecl;external; function inet_ntoa(in:in_addr):pchar;cdecl;external; implementation Type array_word = array[0..1] of byte; Type array_dword = array[0..3] of byte; function wSwap(value:array_word):array_word; begin result[0]:=value[1]; result[1]:=value[0]; end; function dSwap(value: array_dword):array_dword; begin result[0]:=value[3]; result[1]:=value[2]; result[2]:=value[1]; result[3]:=value[0]; end; //or else we'll resort too function htonl(hostlong:uint32_t):uint32_t; inline; begin htonl:=SwapEndian(hostlong); end; function htons(hostshort:uint16_t):uint16_t; inline; begin htonl:=SwapEndian(hostlong); end; function ntohl(netlong:uint32_t):uint32_t; inline; begin htonl:=SwapEndian(hostlong); end; function ntohs(netshort:uint16_t):uint16_t; inline; begin htonl:=SwapEndian(hostlong); end; end. //again what are the command codes, too abandon stomack crapped-in?
unit EuroConvConst; interface uses ConvUtils; var // Euro Currency Conversion Units // basic unit of measurement is Euro cbEuroCurrency: TConvFamily; cuEUR: TConvType; cuDEM: TConvType; // Germany cuESP: TConvType; // Spain cuFRF: TConvType; // France cuIEP: TConvType; // Ireland cuITL: TConvType; // Italy cuBEF: TConvType; // Belgium cuNLG: TConvType; // Holland cuATS: TConvType; // Austria cuPTE: TConvType; // Portugal cuFIM: TConvType; // Finland cuGRD: TConvType; // Greece cuLUF: TConvType; // Luxembourg type TEuroDecimals = 3..6; function EuroConvert (const AValue: Double; const AFrom, ATo: TConvType; const Decimals: TEuroDecimals = 3): Double; implementation uses Math; const DEMPerEuros = 1.95583; ESPPerEuros = 166.386; FRFPerEuros = 6.55957; IEPPerEuros = 0.787564; ITLPerEuros = 1936.27; BEFPerEuros = 40.3399; NLGPerEuros = 2.20371; ATSPerEuros = 13.7603; PTEPerEuros = 200.482; FIMPerEuros = 5.94573; GRDPerEuros = 340.750; LUFPerEuros = 40.3399; function EuroConvert (const AValue: Double; const AFrom, ATo: TConvType; const Decimals: TEuroDecimals = 3): Double; begin // check special case: no conversion if AFrom = ATo then Result := AValue else begin // convert to Euro, than round Result := ConvertFrom (AFrom, AValue); Result := RoundTo (Result, -Decimals); // convert to currency than round again Result := ConvertTo (Result, ATo); Result := RoundTo (Result, -Decimals); end; end; initialization // Euro Currency's family type cbEuroCurrency := RegisterConversionFamily('EuroCurrency'); cuEUR := RegisterConversionType(cbEuroCurrency, 'Euro (€)', 1); cuDEM := RegisterConversionType(cbEuroCurrency, 'German Marks (DEM)', 1 / DEMPerEuros); cuESP := RegisterConversionType(cbEuroCurrency, 'Spanish Pesetas (ESP)', 1 / ESPPerEuros); cuFRF := RegisterConversionType(cbEuroCurrency, 'French Francs (FRF)', 1 / FRFPerEuros); cuIEP := RegisterConversionType(cbEuroCurrency, 'Irish Pounds (IEP)', 1 / IEPPerEuros); cuITL := RegisterConversionType(cbEuroCurrency, 'Italian Lire (ITL)', 1 / ITLPerEuros); cuBEF := RegisterConversionType(cbEuroCurrency, 'Belgian Francs (BEF)', 1 / BEFPerEuros); cuNLG := RegisterConversionType(cbEuroCurrency, 'Dutch Guilders (NLG)', 1 / NLGPerEuros); cuATS := RegisterConversionType(cbEuroCurrency, 'Austrian Schillings (ATS)', 1 / ATSPerEuros); cuPTE := RegisterConversionType(cbEuroCurrency, 'Portuguese Escudos (PTE)', 1 / PTEPerEuros); cuFIM := RegisterConversionType(cbEuroCurrency, 'Finnish Marks (FIM)', 1 / FIMPerEuros); cuGRD := RegisterConversionType(cbEuroCurrency, 'Greek Drachmas (GRD)', 1 / GRDPerEuros); cuLUF := RegisterConversionType(cbEuroCurrency, 'Luxembourg Francs (LUF)', 1 / LUFPerEuros); end.
unit HeapSort; interface uses StrategyInterface, ArraySubroutines; type THeapSort = class(TInterfacedObject, ISorter) procedure Sort(var A : Array of Integer); destructor Destroy; override; private procedure BuildHeap(var A : Array of Integer); procedure Heapify(var A : Array of Integer; i, size : Integer); end; implementation procedure THeapSort.Sort(var A: array of Integer); var len, cur : Integer; begin BuildHeap(A); len := Length(A); cur := len-1; while cur > 0 do begin Swap(A[0], A[cur]); Dec(cur); Heapify(A, 0, cur); end; end; procedure THeapSort.BuildHeap(var A: array of Integer); var i, len : Integer; begin len := Length(A); for i := len div 2 downto 0 do Heapify(A, i, len); end; procedure THeapSort.Heapify(var A: array of Integer; i, size: Integer); var left, right, largest : Integer; begin left := 2*i + 1; right := 2*i + 2; if (left < size) and (A[left] > A[i]) then begin largest := left; end else begin largest := i; end; if (right < size) and (A[largest] < A[right]) then largest := right; if largest <> i then begin Swap(A[largest], A[i]); Heapify(A, largest, size); end; end; destructor THeapSort.Destroy; begin WriteLn('Heap sort destr'); inherited; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSmtpFileHandler; interface {$I clVer.inc} {$IFDEF DELPHI6} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, Windows, SysUtils, SyncObjs, {$ELSE} System.Classes, Winapi.Windows, System.SysUtils, System.SyncObjs, {$ENDIF} clSmtpServer, clMailUserMgr; type TclSmtpFileHandler = class(TComponent) private FServer: TclSmtpServer; FAccessor: TCriticalSection; FMailBoxDir: string; FRelayDir: string; FCounter: Integer; procedure DoMessageRelayed(Sender: TObject; AConnection: TclSmtpCommandConnection; const AMailFrom: string; ARecipients: TStrings; AMessage: TStrings; var Action: TclSmtpMailDataAction); procedure DoMessageDelivered(Sender: TObject; AConnection: TclSmtpCommandConnection; const AMailFrom, ARecipient: string; Account: TclMailUserAccountItem; AMessage: TStrings; var Action: TclSmtpMailDataAction); function GenMessageFileName(const APath: string): string; function GetMailBoxPath(const AUserName: string): string; procedure SetServer(const Value: TclSmtpServer); procedure SetMailBoxDir(const Value: string); procedure SetRelayDir(const Value: string); procedure SetCounter(const Value: Integer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CleanEventHandlers; virtual; procedure InitEventHandlers; virtual; property Accessor: TCriticalSection read FAccessor; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Server: TclSmtpServer read FServer write SetServer; property MailBoxDir: string read FMailBoxDir write SetMailBoxDir; property RelayDir: string read FRelayDir write SetRelayDir; property Counter: Integer read FCounter write SetCounter default 1; end; var cMessageFileExt: string = '.MSG'; cEnvelopeFileExt: string = '.ENV'; implementation uses clUtils; { TclSmtpFileHandler } procedure TclSmtpFileHandler.CleanEventHandlers; begin Server.OnMessageRelayed := nil; Server.OnMessageDelivered := nil; end; constructor TclSmtpFileHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); FAccessor := TCriticalSection.Create(); FCounter := 1; end; destructor TclSmtpFileHandler.Destroy; begin FAccessor.Free(); inherited Destroy(); end; procedure TclSmtpFileHandler.DoMessageDelivered(Sender: TObject; AConnection: TclSmtpCommandConnection; const AMailFrom, ARecipient: string; Account: TclMailUserAccountItem; AMessage: TStrings; var Action: TclSmtpMailDataAction); var path: string; begin try Assert(Account <> nil); path := GetMailBoxPath(Account.UserName); FAccessor.Enter(); try ForceFileDirectories(path); TclStringsUtils.SaveStrings(AMessage, GenMessageFileName(path) + cMessageFileExt, ''); finally FAccessor.Leave(); end; Action := mdOk; except Action := mdProcessingError; end; end; procedure TclSmtpFileHandler.DoMessageRelayed(Sender: TObject; AConnection: TclSmtpCommandConnection; const AMailFrom: string; ARecipients: TStrings; AMessage: TStrings; var Action: TclSmtpMailDataAction); var path: string; envelope: TStrings; begin try path := AddTrailingBackSlash(RelayDir); FAccessor.Enter(); try ForceFileDirectories(path); path := GenMessageFileName(path); TclStringsUtils.SaveStrings(AMessage, path + cMessageFileExt, ''); envelope := nil; try envelope := TStringList.Create(); envelope.Add(AMailFrom); envelope.AddStrings(ARecipients); TclStringsUtils.SaveStrings(envelope, path + cEnvelopeFileExt, ''); finally envelope.Free(); end; finally FAccessor.Leave(); end; Action := mdOk; except Action := mdProcessingError; end; end; function TclSmtpFileHandler.GenMessageFileName(const APath: string): string; var i: Integer; begin FAccessor.Enter(); try Inc(FCounter); Result := APath + Format('MAIL%.8d', [Counter]); i := 0; while (FileExists(Result)) do begin Result := APath + Format('MAIL%.8d%d', [Counter, i]); Inc(i); end; finally FAccessor.Leave(); end; end; function TclSmtpFileHandler.GetMailBoxPath(const AUserName: string): string; begin Result := AddTrailingBackSlash(MailBoxDir) + AddTrailingBackSlash(AUserName); end; procedure TclSmtpFileHandler.InitEventHandlers; begin Server.OnMessageRelayed := DoMessageRelayed; Server.OnMessageDelivered := DoMessageDelivered; end; procedure TclSmtpFileHandler.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation <> opRemove) then Exit; if (AComponent = FServer) then begin CleanEventHandlers(); FServer := nil; end; end; procedure TclSmtpFileHandler.SetCounter(const Value: Integer); begin FAccessor.Enter(); try FCounter := Value; finally FAccessor.Leave(); end; end; procedure TclSmtpFileHandler.SetMailBoxDir(const Value: string); begin FAccessor.Enter(); try FMailBoxDir := Value; finally FAccessor.Leave(); end; end; procedure TclSmtpFileHandler.SetRelayDir(const Value: string); begin FAccessor.Enter(); try FRelayDir := Value; finally FAccessor.Leave(); end; end; procedure TclSmtpFileHandler.SetServer(const Value: TclSmtpServer); begin if (FServer <> Value) then begin if (FServer <> nil) then begin FServer.RemoveFreeNotification(Self); CleanEventHandlers(); end; FServer := Value; if (FServer <> nil) then begin FServer.FreeNotification(Self); InitEventHandlers(); end; end; end; end.
unit arSearch; {$Include l3Define.inc} { $Id: arSearch.pas,v 1.51 2016/10/17 10:58:22 lukyanets Exp $ } interface {$INCLUDE ProjectDefine.inc} uses WinTypes, Classes, l3RegEx, l3Types, l3Base, l3Interfaces, l3Variant, l3LongintList, k2Base, evTypes, evIntf, evSearch, evInternalInterfaces, nevTools, nevNavigation, DT_Types, DT_Hyper, DocIntf, EditWin; type TarMultiHyperlinkSearcher = class(TevCustomHyperlinkSearcher) { - для поиска ссылок вида DocID + SubID in SubIDList, используется для перехода из списка корреспондентов} private fDocID : TDocID; fSubIDList : Tl3LongintList; procedure SetSubIDList(aList : Tl3LongintList); protected procedure Cleanup; override; function DoHyperlinkSearch(const aHLink : IevHyperLink): Bool; override; public property HLDocID : TDocID read fDocID write fDocID; property HLSubIDList : Tl3LongintList read fSubIDList write SetSubIDList; end; TarHyperlinkSearcher = class(TevHyperlinkSearcher) private fCurrentDoc : TDocAddr; fSearchAddr : TDestHLinkRec; protected procedure DoSetText(const Value: AnsiString); override; public property CurrentDoc : TDocAddr read fCurrentDoc write fCurrentDoc; property SearchAddr : TDestHLinkRec read fSearchAddr write fSearchAddr; end; TarHyperLinkReplacer = class(TevHyperlinkReplacer) private fCurrentDoc : TDocAddr; fReplaceAddr : TDestHLinkRec; fAbsentDoc : Boolean; fEnableAbsentDoc : Boolean; protected procedure DoSetText(const Value: AnsiString); override; public property CurrentDoc : TDocAddr read fCurrentDoc write fCurrentDoc; property ReplaceAddr : TDestHLinkRec read fReplaceAddr write fReplaceAddr; property AbsentDoc : Boolean read fAbsentDoc; property EnableAbsentDoc : Boolean read fEnableAbsentDoc write fEnableAbsentDoc; end; TarSubReplacer = class(TevSubReplacer) protected function pm_GetDefaultText: AnsiString; override; {-} end;{TarSubReplacer} TarHLinkTNVEDSearcher = class(TevRegularExpressionSearcher) public constructor Create(aOwner: TComponent); override; end;{TarHLinkTNVEDSearcher} TarHLinkTNVEDReplacer = class(TevBaseReplacer) public function ReplaceFunc(const aView : InevView; const Container : InevOp; const aBlock : InevRange): Bool; override; end;{TevTextReplacer} TarAnyNonEmptyParagraphSearcher = class(TevAnyParagraphSearcher) protected function DoCheckText(aPara : Tl3Variant; aText : Tl3CustomString; const aSel : TevPair; out theSel : TevPair): Bool; override; end; implementation uses SysUtils, Controls, daTypes, DT_Const, DT_Serv, DT_Doc, dt_LinkServ, l3MinMax, l3String, StrShop, Dialogs, vtDialogs, AddrSup, arTypes, arConst, evParaTools, afwNavigation, PageBreak_Const, l3DataContainerWithoutIUnknownPrim; {TarMultiHyperlinkSearcher} procedure TarMultiHyperlinkSearcher.Cleanup; begin l3Free(fSubIDList); Inherited; end; procedure TarMultiHyperlinkSearcher.SetSubIDList(aList : Tl3LongintList); begin l3Free(fSubIDList); if aList <> nil then fSubIDList := aList.Use; end; function TarMultiHyperlinkSearcher.DoHyperlinkSearch(const aHLink : IevHyperLink): Bool; //override; {-} var lCurAddr : TevAddress; l_Index : Integer; begin Result := false; if (aHLink.AddressList.Count = 0) then Exit; for l_Index := 0 to Pred(aHLink.AddressList.Count) do begin lCurAddr := aHLink.AddressList[l_Index]; if ((lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.DocID = fDocID) or (fDocID < 0)) and ((fSubIDList = nil) or (fSubIDList.IndexOf(lCurAddr{$IfDef XE4}.rTafwAddress{$EndIf}.SubID) >= 0)) then begin Result := true; Break; end;//(lCurAddr.DocID = DocID) or (DocID < 0) end;//for I end; {TarHyperlinkSearcher} procedure TarHyperlinkSearcher.DoSetText(const Value: AnsiString); function lp_FindSubOnly: Boolean; begin Result := (fSearchAddr.Doc = -1) and (fSearchAddr.Sub <> -1); end; begin if not StrToHlinkSpecValue(Value, fSearchAddr.Doc, fSearchAddr.Sub) then begin StrToDocAddr(Value, fSearchAddr.Doc, fSearchAddr.Sub); if fSearchAddr.Doc = 0 then fSearchAddr.Doc := fCurrentDoc.DocID else begin fSearchAddr.Doc := LinkServer(fCurrentDoc.FamID).Renum.ConvertToRealNumber(fSearchAddr.Doc); if not lp_FindSubOnly then if (fSearchAddr.Doc <= 0) then raise Exception.Create(Format(sidNoDocPresent, [fSearchAddr.Doc])); end; end; // if not StrToHlinkSpecValue(Value, fSearchAddr.Doc, fSearchAddr.Sub) then inherited DoSetText(Value); end; {TarHyperLinkReplacer} procedure TarHyperLinkReplacer.DoSetText(const Value: AnsiString); var lRelFlag : Boolean; lDocID : TDocID; lDocIsPresent : Boolean; begin fAbsentDoc := false; StrToDocAddr(Value, fReplaceAddr.Doc, fReplaceAddr.Sub); if fReplaceAddr.Doc = -1 then begin if fReplaceAddr.Sub = -1 then raise Exception.Create(sidEmptyHyperAddress); end // if fReplaceAddr.Doc = -1 then else if fReplaceAddr.Doc = 0 then fReplaceAddr.Doc := fCurrentDoc.DocID else begin lDocID := LinkServer(fCurrentDoc.FamID).Renum.ConvertToRealNumber(fReplaceAddr.Doc); if (lDocID = 0) then begin fReplaceAddr.Doc := 0; raise Exception.Create(Format(sidWrongDocID, [lDocID])); end; // if (lDocID = 0) then lDocIsPresent := (lDocID > -1) and DocumentServer(fCurrentDoc.FamID).CheckDoc(lDocID, True, lRelFlag); if lDocIsPresent or (EnableAbsentDoc and (vtMessageDlg(l3Fmt(sidNoDocPresent + ^M + sidQstContinue, [fReplaceAddr.Doc]), mtWarning, [mbYes, mbNo]) = mrYes)) then begin fAbsentDoc := not lDocIsPresent; if (lDocID = -1) then begin lDocID := fReplaceAddr.Doc; LinkServer(fCurrentDoc.FamID).Renum.GetRNumber(lDocID); end; // if (lDocID = -1) then end // if lDocIsPresent or (EnableAbsentDoc and else begin fReplaceAddr.Doc := 0; if EnableAbsentDoc then raise EarSilent.Create(Format(sidNoDocPresent,[fReplaceAddr.Doc])) else raise Exception.Create(Format(sidNoDocPresent,[fReplaceAddr.Doc])); end; fReplaceAddr.Doc := lDocID; end; inherited DoSetText(Value); end; {TarSubReplacer} function TarSubReplacer.pm_GetDefaultText: AnsiString; begin Result := ''; end; {TarHLinkTNVEDSearcher} constructor TarHLinkTNVEDSearcher.Create(aOwner: TComponent); begin inherited Create(aOwner); Text := '\d\d(\d\d(( )?\d\d([^0-9]\d\d\d)?)?)?'; end; {TarHLinkTNVEDReplacer} function TarHLinkTNVEDReplacer.ReplaceFunc(const aView : InevView; const Container : InevOp; const aBlock : InevRange): Bool; var FndLen : Integer; HLId : Long; S : AnsiString; HL : IevHyperlink; l_Doc: TdaDocID; l_Sub: TSubID; begin Result := True; S := l3Str(evAsString(aBlock.Data, cf_Text)); FndLen := Length(S); l_Doc := 650000 + StrToInt(Copy(S, 1, 2)); l_Doc := LinkServer(TDocEditorWindow(Owner).DocFamily).Renum.ConvertToRealNumber(l_Doc); if l_Doc = -1 then begin Result := False; Exit; end; if FndLen >= 4 then l_Sub := StrToInt(Copy(S, 3, 2)) else l_Sub := 0; try if Supports(aBlock, IevHyperlink, HL) then try if not HL.Exists then HL.Insert; HL.AddressList.Add(TevAddress_C(l_Doc, l_Sub)); finally HL := nil; end//try..finally else raise Exception.Create(''); except Result := False; end; end; function TarAnyNonEmptyParagraphSearcher.DoCheckText(aPara : Tl3Variant; aText : Tl3CustomString; const aSel : TevPair; out theSel : TevPair): Bool; begin Result := not (aPara.IsKindOf(k2_typPageBreak) or aText.Empty); if Result then Result := inherited DoCheckText(aPara, aText, aSel, theSel); end; end.
//Exercício 5: Escreva um algoritmo que receba o salário de um funcionário, calcule e exiba o quanto ele ganha por dia. { Solução em Portugol Algoritmo Exercicio; Var salario: inteiro; salario_diario: real; Inicio exiba("Programa que calcula o salário diário de um funcionário."); exiba("Digite o salário do funcionário: "); leia(salario); salario_diario <- salario/30; // Calculo do salário de 1 dia de trabalho em um mês com 30 dias. exiba("O salário diário do funcionário é: ", salario_diario); Fim. } // Solução em Pascal Program Exercicio; uses crt; var salario: integer; salario_diario: real; begin clrscr; writeln('Programa que calcula o salário diário de um funcionário.'); writeln('Digite o salário do funcionário: '); readln(salario); salario_diario := salario/30; // Calculo do salário de 1 dia de trabalho em um mês com 30 dias. writeln('O salário diário do funcionário é: ',salario_diario:0:2);//OBS: leia o final do programa. repeat until keypressed; end. // OBS:Comando para representar reais de maneira mais fácil de ler: // variavel:espaços_antes_da_variavel:casas_depois_virgula
{ Date Created: 5/25/00 5:01:02 PM } unit InfoSETTCODETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoSETTCODERecord = record PCode: String[4]; PDescription: String[30]; PActive: Boolean; End; TInfoSETTCODEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoSETTCODERecord end; TEIInfoSETTCODE = (InfoSETTCODEPrimaryKey); TInfoSETTCODETable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFActive: TBooleanField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetEnumIndex(Value: TEIInfoSETTCODE); function GetEnumIndex: TEIInfoSETTCODE; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoSETTCODERecord; procedure StoreDataBuffer(ABuffer:TInfoSETTCODERecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFActive: TBooleanField read FDFActive; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PActive: Boolean read GetPActive write SetPActive; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoSETTCODE read GetEnumIndex write SetEnumIndex; end; { TInfoSETTCODETable } procedure Register; implementation procedure TInfoSETTCODETable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFActive := CreateField( 'Active' ) as TBooleanField; end; { TInfoSETTCODETable.CreateFields } procedure TInfoSETTCODETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoSETTCODETable.SetActive } procedure TInfoSETTCODETable.Validate; begin { Enter Validation Code Here } end; { TInfoSETTCODETable.Validate } procedure TInfoSETTCODETable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoSETTCODETable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoSETTCODETable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoSETTCODETable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoSETTCODETable.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoSETTCODETable.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoSETTCODETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 4, N'); Add('Description, String, 30, N'); Add('Active, Boolean, 0, N'); end; end; procedure TInfoSETTCODETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoSETTCODETable.SetEnumIndex(Value: TEIInfoSETTCODE); begin case Value of InfoSETTCODEPrimaryKey : IndexName := ''; end; end; function TInfoSETTCODETable.GetDataBuffer:TInfoSETTCODERecord; var buf: TInfoSETTCODERecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PActive := DFActive.Value; result := buf; end; procedure TInfoSETTCODETable.StoreDataBuffer(ABuffer:TInfoSETTCODERecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFActive.Value := ABuffer.PActive; end; function TInfoSETTCODETable.GetEnumIndex: TEIInfoSETTCODE; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoSETTCODEPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoSETTCODETable, TInfoSETTCODEBuffer ] ); end; { Register } function TInfoSETTCODEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PActive; end; end; end. { InfoSETTCODETable }
unit IdDsnPropEdBindingNET; interface uses Classes, System.Drawing, System.Collections, System.ComponentModel, System.Windows.Forms, System.Data, IdSocketHandle; type TIdDsnPropEdBindingNET = class(System.Windows.Forms.Form) {$REGION 'Designer Managed Code'} strict private /// <summary> /// Required designer variable. /// </summary> Components: System.ComponentModel.Container; btnOk: System.Windows.Forms.Button; btnCancel: System.Windows.Forms.Button; lblBindings: System.Windows.Forms.Label; lbBindings: System.Windows.Forms.ListBox; btnNew: System.Windows.Forms.Button; btnDelete: System.Windows.Forms.Button; lblIPAddress: System.Windows.Forms.Label; edtIPAddress: System.Windows.Forms.ComboBox; lblPort: System.Windows.Forms.Label; edtPort: System.Windows.Forms.NumericUpDown; cboIPVersion: System.Windows.Forms.ComboBox; lblIPVersion: System.Windows.Forms.Label; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> procedure InitializeComponent; procedure btnNew_Click(sender: System.Object; e: System.EventArgs); procedure btnDelete_Click(sender: System.Object; e: System.EventArgs); procedure edtPort_ValueChanged(sender: System.Object; e: System.EventArgs); procedure edtIPAddress_SelectedValueChanged(sender: System.Object; e: System.EventArgs); procedure cboIPVersion_SelectedValueChanged(sender: System.Object; e: System.EventArgs); procedure lbBindings_SelectedValueChanged(sender: System.Object; e: System.EventArgs); {$ENDREGION} strict protected /// <summary> /// Clean up any resources being used. /// </summary> procedure Dispose(Disposing: Boolean); override; private FHandles : TIdSocketHandles; FDefaultPort : Integer; FIPv4Addresses : TStrings; FIPv6Addresses : TStrings; FCurrentHandle : TIdSocketHandle; { Private Declarations } procedure SetHandles(const Value: TIdSocketHandles); procedure SetIPv4Addresses(const Value: TStrings); procedure SetIPv6Addresses(const Value: TStrings); procedure UpdateBindingList; procedure UpdateEditControls; procedure FillComboBox(ACombo : System.Windows.Forms.ComboBox; AStrings :TStrings); procedure SetCaption(const AValue : String); function GetCaption : String; public constructor Create; function Execute : Boolean; function GetList: string; procedure SetList(const AList: string); property Handles : TIdSocketHandles read FHandles write SetHandles; property DefaultPort : Integer read FDefaultPort write FDefaultPort; property IPv4Addresses : TStrings read FIPv4Addresses write SetIPv4Addresses; property IPv6Addresses : TStrings read FIPv6Addresses write SetIPv6Addresses; property Caption : String read GetCaption write SetCaption; end; [assembly: RuntimeRequiredAttribute(TypeOf(TIdDsnPropEdBindingNET))] procedure FillHandleList(const AList: string; ADest: TIdSocketHandles); function GetListValues(const ASocketHandles : TIdSocketHandles) : String; implementation uses IdGlobal, IdIPAddress, IdDsnCoreResourceStrings, IdStack, SysUtils; const IPv6Wildcard1 = '::'; {do not localize} IPv6Wildcard2 = '0:0:0:0:0:0:0:0'; {do not localize} IPv6Loopback = '::1'; {do not localize} IPv4Wildcard = '0.0.0.0'; {do not localize} IPv4Loopback = '127.0.0.1'; {do not localize} function IsValidIP(const AAddr : String): Boolean; var LIP: TIdIPAddress; begin LIP := TIdIPAddress.MakeAddressObject(AAddr); Result := Assigned(LIP); if Result then begin FreeAndNil(LIP); end; end; function StripAndSymbol(s : String) : String; begin Result := ''; repeat if s='' then begin Break; end; Result := Result + Fetch(s,'&'); until False; end; procedure FillHandleList(const AList: string; ADest: TIdSocketHandles); var LItems: TStringList; i: integer; LIPVersion: TIdIPVersion; LAddr, LText: string; LPort: integer; begin ADest.Clear; LItems := TStringList.Create; try LItems.CommaText := AList; for i := 0 to LItems.Count-1 do begin if Length(LItems[i]) > 0 then begin if LItems[i][1] = '[' then begin // ipv6 LIPVersion := Id_IPv6; LText := Copy(LItems[i], 2, MaxInt); LAddr := Fetch(LText, ']:'); LPort := IndyStrToInt(LText, -1); end else begin // ipv4 LIPVersion := Id_IPv4; LText := LItems[i]; LAddr := Fetch(LText, ':'); LPort := IndyStrToInt(LText, -1); //Note that 0 is legal and indicates the server binds to a random port end; if IsValidIP(LAddr) and (LPort > -1) and (LPort < 65536) then begin with ADest.Add do begin IPVersion := LIPVersion; IP := LAddr; Port := LPort; end; end; end; end; finally LItems.Free; end; end; function NumericOnly(const AText : String) : String; var i: Integer; begin Result := ''; for i := 1 to Length(AText) do begin if IsNumeric(AText[i]) then begin Result := Result + AText[i]; end else begin Break; end; end; if (Length(Result) = 0) then begin Result := '0'; end; end; function IndexOfNo(const ANo : Integer; AItems : System.Windows.Forms.ComboBox.ObjectCollection) : Integer; begin for Result := 0 to AItems.Count -1 do begin if ANo = IndyStrToInt( NumericOnly(AItems[Result].ToString )) then begin Exit; end; end; Result := -1; end; function GetDisplayString(ASocketHandle: TIdSocketHandle): string; begin Result := ''; case ASocketHandle.IPVersion of Id_IPv4 : Result := IndyFormat('%s:%d', [ASocketHandle.IP, ASocketHandle.Port]); Id_IPv6 : Result := IndyFormat('[%s]:%d', [ASocketHandle.IP, ASocketHandle.Port]); end; end; function GetListValues(const ASocketHandles : TIdSocketHandles) : String; var i: Integer; begin Result := ''; for i := 0 to ASocketHandles.Count -1 do begin Result := Result + ',' + GetDisplayString(ASocketHandles[i]); end; Delete(Result,1,1); end; {$AUTOBOX ON} {$REGION 'Windows Form Designer generated code'} /// <summary> /// Required method for Designer support -- do not modify /// the contents of this method with the code editor. /// </summary> procedure TIdDsnPropEdBindingNET.InitializeComponent; type TArrayOfInteger = array of Integer; begin Self.btnOk := System.Windows.Forms.Button.Create; Self.btnCancel := System.Windows.Forms.Button.Create; Self.lblBindings := System.Windows.Forms.Label.Create; Self.lbBindings := System.Windows.Forms.ListBox.Create; Self.btnNew := System.Windows.Forms.Button.Create; Self.btnDelete := System.Windows.Forms.Button.Create; Self.lblIPAddress := System.Windows.Forms.Label.Create; Self.edtIPAddress := System.Windows.Forms.ComboBox.Create; Self.lblPort := System.Windows.Forms.Label.Create; Self.edtPort := System.Windows.Forms.NumericUpDown.Create; Self.cboIPVersion := System.Windows.Forms.ComboBox.Create; Self.lblIPVersion := System.Windows.Forms.Label.Create; (System.ComponentModel.ISupportInitialize(Self.edtPort)).BeginInit; Self.SuspendLayout; // // btnOk // Self.btnOk.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom or System.Windows.Forms.AnchorStyles.Right))); Self.btnOk.DialogResult := System.Windows.Forms.DialogResult.OK; Self.btnOk.Location := System.Drawing.Point.Create(312, 160); Self.btnOk.Name := 'btnOk'; Self.btnOk.TabIndex := 0; // // btnCancel // Self.btnCancel.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom or System.Windows.Forms.AnchorStyles.Right))); Self.btnCancel.DialogResult := System.Windows.Forms.DialogResult.Cancel; Self.btnCancel.Location := System.Drawing.Point.Create(392, 160); Self.btnCancel.Name := 'btnCancel'; Self.btnCancel.TabIndex := 1; // // lblBindings // Self.lblBindings.AutoSize := True; Self.lblBindings.Location := System.Drawing.Point.Create(8, 8); Self.lblBindings.Name := 'lblBindings'; Self.lblBindings.Size := System.Drawing.Size.Create(42, 16); Self.lblBindings.TabIndex := 2; Self.lblBindings.Text := '&Binding'; // // lbBindings // Self.lbBindings.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Bottom) or System.Windows.Forms.AnchorStyles.Left))); Self.lbBindings.Location := System.Drawing.Point.Create(8, 24); Self.lbBindings.Name := 'lbBindings'; Self.lbBindings.Size := System.Drawing.Size.Create(137, 121); Self.lbBindings.TabIndex := 3; Include(Self.lbBindings.SelectedValueChanged, Self.lbBindings_SelectedValueChanged); // // btnNew // Self.btnNew.Location := System.Drawing.Point.Create(152, 56); Self.btnNew.Name := 'btnNew'; Self.btnNew.TabIndex := 4; Include(Self.btnNew.Click, Self.btnNew_Click); // // btnDelete // Self.btnDelete.Location := System.Drawing.Point.Create(152, 88); Self.btnDelete.Name := 'btnDelete'; Self.btnDelete.TabIndex := 5; Include(Self.btnDelete.Click, Self.btnDelete_Click); // // lblIPAddress // Self.lblIPAddress.Location := System.Drawing.Point.Create(240, 8); Self.lblIPAddress.Name := 'lblIPAddress'; Self.lblIPAddress.Size := System.Drawing.Size.Create(100, 16); Self.lblIPAddress.TabIndex := 6; Self.lblIPAddress.Text := 'Label1'; // // edtIPAddress // Self.edtIPAddress.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right))); Self.edtIPAddress.Location := System.Drawing.Point.Create(240, 24); Self.edtIPAddress.Name := 'edtIPAddress'; Self.edtIPAddress.Size := System.Drawing.Size.Create(224, 21); Self.edtIPAddress.TabIndex := 7; Include(Self.edtIPAddress.SelectedValueChanged, Self.edtIPAddress_SelectedValueChanged); // // lblPort // Self.lblPort.Location := System.Drawing.Point.Create(240, 58); Self.lblPort.Name := 'lblPort'; Self.lblPort.Size := System.Drawing.Size.Create(100, 16); Self.lblPort.TabIndex := 8; Self.lblPort.Text := 'Label1'; // // edtPort // Self.edtPort.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right))); Self.edtPort.Location := System.Drawing.Point.Create(240, 74); Self.edtPort.Maximum := System.Decimal.Create(TArrayOfInteger.Create(65535, 0, 0, 0)); Self.edtPort.Name := 'edtPort'; Self.edtPort.Size := System.Drawing.Size.Create(224, 20); Self.edtPort.TabIndex := 9; Include(Self.edtPort.ValueChanged, Self.edtPort_ValueChanged); // // cboIPVersion // Self.cboIPVersion.DropDownStyle := System.Windows.Forms.ComboBoxStyle.DropDownList; Self.cboIPVersion.Location := System.Drawing.Point.Create(240, 124); Self.cboIPVersion.Name := 'cboIPVersion'; Self.cboIPVersion.Size := System.Drawing.Size.Create(224, 21); Self.cboIPVersion.TabIndex := 10; Include(Self.cboIPVersion.SelectedValueChanged, Self.cboIPVersion_SelectedValueChanged); // // lblIPVersion // Self.lblIPVersion.Location := System.Drawing.Point.Create(240, 108); Self.lblIPVersion.Name := 'lblIPVersion'; Self.lblIPVersion.Size := System.Drawing.Size.Create(100, 16); Self.lblIPVersion.TabIndex := 11; Self.lblIPVersion.Text := 'Label1'; // // TIdDsnPropEdBindingNET // Self.AcceptButton := Self.btnOk; Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13); Self.CancelButton := Self.btnCancel; Self.ClientSize := System.Drawing.Size.Create(470, 189); Self.Controls.Add(Self.lblIPVersion); Self.Controls.Add(Self.cboIPVersion); Self.Controls.Add(Self.edtPort); Self.Controls.Add(Self.lblPort); Self.Controls.Add(Self.edtIPAddress); Self.Controls.Add(Self.lblIPAddress); Self.Controls.Add(Self.btnDelete); Self.Controls.Add(Self.btnNew); Self.Controls.Add(Self.lbBindings); Self.Controls.Add(Self.lblBindings); Self.Controls.Add(Self.btnCancel); Self.Controls.Add(Self.btnOk); Self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog; Self.MaximizeBox := False; Self.MaximumSize := System.Drawing.Size.Create(480, 225); Self.MinimizeBox := False; Self.MinimumSize := System.Drawing.Size.Create(480, 225); Self.Name := 'TIdDsnPropEdBindingNET'; Self.ShowInTaskbar := False; Self.StartPosition := System.Windows.Forms.FormStartPosition.CenterScreen; Self.Text := 'WinForm'; (System.ComponentModel.ISupportInitialize(Self.edtPort)).EndInit; Self.ResumeLayout(False); end; {$ENDREGION} procedure TIdDsnPropEdBindingNET.Dispose(Disposing: Boolean); begin if Disposing then begin if Components <> nil then begin Components.Dispose(); FreeAndNil(FHandles); FreeAndNil(FIPv4Addresses); FreeAndNil(FIPv6Addresses); //don't free FCurrentHandle; - it's in the handles collection TIdStack.DecUsage; end; end; inherited Dispose(Disposing); end; constructor TIdDsnPropEdBindingNET.Create; begin inherited Create; // // Required for Windows Form Designer support // InitializeComponent; // // TODO: Add any constructor code after InitializeComponent call // FHandles := TIdSocketHandles.Create(nil); FIPv4Addresses := TStringList.Create; FIPv6Addresses := TStringList.Create; SetIPv4Addresses(nil); SetIPv6Addresses(nil); TIdStack.IncUsage; try GStack.AddLocalAddressesToList(FIPv4Addresses); finally TIdStack.DecUsage; end; UpdateEditControls; //captions btnNew.Text := RSBindingNewCaption; btnDelete.Text := RSBindingDeleteCaption; lblIPAddress.Text := RSBindingHostnameLabel; lblPort.Text := RSBindingPortLabel; lblIPVersion.Text := RSBindingIPVerLabel; btnOk.Text := RSOk; btnCancel.Text := RSCancel; //IPVersion choices //we yhave to strip out the & symbol. In Win32, we use this //in a radio-box so a user could select by pressingg the 4 or 6 //key. For this, we don't have a radio box and I'm too lazy //to use two Radio Buttons. cboIPVersion.Items.Add(StripAndSymbol(RSBindingIPV4Item)); cboIPVersion.Items.Add(StripAndSymbol(RSBindingIPV6Item)); end; procedure TIdDsnPropEdBindingNET.SetHandles(const Value: TIdSocketHandles); begin FHandles.Assign(Value); UpdateBindingList; end; function TIdDsnPropEdBindingNET.GetList: string; begin Result := GetListValues(Handles); end; procedure TIdDsnPropEdBindingNET.SetIPv6Addresses(const Value: TStrings); begin if Assigned(Value) then begin FIPv6Addresses.Assign(Value); end; // Ensure that these two are always present if FIPv6Addresses.IndexOf(IPv6Loopback) = -1 then begin FIPv6Addresses.Insert(0, IPv6Loopback); end; if FIPv6Addresses.IndexOf(IPv6Wildcard1) = -1 then begin FIPv6Addresses.Insert(0, IPv6Wildcard1); end; end; procedure TIdDsnPropEdBindingNET.SetIPv4Addresses(const Value: TStrings); begin if Assigned(Value) then begin FIPv4Addresses.Assign(Value); end; // Ensure that these two are always present if FIPv4Addresses.IndexOf(IPv6Loopback) = -1 then begin FIPv4Addresses.Insert(0, IPv4Loopback); end; if FIPv4Addresses.IndexOf(IPv4Wildcard) = -1 then begin FIPv4Addresses.Insert(0, IPv4Wildcard); end; end; procedure TIdDsnPropEdBindingNET.SetList(const AList: string); begin FCurrentHandle := nil; FillHandleList(AList, Handles); UpdateBindingList; UpdateEditControls; end; procedure TIdDsnPropEdBindingNET.lbBindings_SelectedValueChanged(sender: System.Object; e: System.EventArgs); begin if lbBindings.SelectedIndex >= 0 then begin btnDelete.Enabled := True; FCurrentHandle := FHandles[lbBindings.SelectedIndex]; end else begin btnDelete.Enabled := False; FCurrentHandle := nil; end; UpdateEditControls; end; procedure TIdDsnPropEdBindingNET.cboIPVersion_SelectedValueChanged(sender: System.Object; e: System.EventArgs); begin case cboIPVersion.SelectedIndex of 0 : begin if FCurrentHandle.IPVersion <> Id_IPv4 then begin FCurrentHandle.IPVersion := Id_IPv4; FillComboBox(edtIPAddress,FIPv4Addresses); FCurrentHandle.IP := IPv4Wildcard; end; end; 1 : begin if FCurrentHandle.IPVersion <> Id_IPv6 then begin FCurrentHandle.IPVersion := Id_IPv6; FillComboBox(edtIPAddress,FIPv6Addresses); FCurrentHandle.IP := IPv6Wildcard1; end; end; end; UpdateEditControls; UpdateBindingList; end; procedure TIdDsnPropEdBindingNET.edtIPAddress_SelectedValueChanged(sender: System.Object; e: System.EventArgs); begin FCurrentHandle.IP := edtIPAddress.SelectedItem.ToString; UpdateBindingList; end; procedure TIdDsnPropEdBindingNET.edtPort_ValueChanged(sender: System.Object; e: System.EventArgs); begin if Assigned(FCurrentHandle) then begin FCurrentHandle.Port := edtPort.Value.ToInt16(edtPort.Value); end; UpdateBindingList; end; procedure TIdDsnPropEdBindingNET.btnDelete_Click(sender: System.Object; e: System.EventArgs); var LSH : TIdSocketHandle; i : Integer; begin if lbBindings.SelectedIndex >= 0 then begin // Delete is not available in D4's collection classes // This should work just as well. i := lbBindings.get_SelectedIndex; LSH := Handles[i]; FreeAndNil(LSH); lbBindings.Items.Remove(i); FCurrentHandle := nil; UpdateBindingList; end; lbBindings_SelectedValueChanged(nil, nil); UpdateEditControls; end; procedure TIdDsnPropEdBindingNET.btnNew_Click(sender: System.Object; e: System.EventArgs); begin FCurrentHandle := FHandles.Add; FCurrentHandle.IP := IPv4Wildcard; FCurrentHandle.Port := FDefaultPort; UpdateBindingList; FillComboBox(edtIPAddress, FIPv4Addresses); UpdateEditControls; end; procedure TIdDsnPropEdBindingNET.UpdateBindingList; var i: integer; selected: integer; s: string; begin selected := lbBindings.SelectedIndex; lbBindings.BeginUpdate; try if lbBindings.Items.Count = FHandles.Count then begin for i := 0 to FHandles.Count - 1 do begin s := GetDisplayString(FHandles[i]); if s <> lbBindings.Items[i].ToString then begin lbBindings.Items[i] := s; end; end; end else begin lbBindings.Items.Clear; for i := 0 to FHandles.Count-1 do begin lbBindings.Items.Add(GetDisplayString(FHandles[i])); end; end; finally lbBindings.EndUpdate; if Assigned(FCurrentHandle) then begin lbBindings.SelectedIndex := FCurrentHandle.Index; end else begin lbBindings.SelectedIndex := IndyMin(selected, lbBindings.Items.Count-1); end; end; { selected := lbBindings.SelectedItem; lbBindings.Items.BeginUpdate; try if lbBindings.Items.Count = FHandles.Count then begin for i := 0 to FHandles.Count - 1 do begin s := GetDisplayString(FHandles[i]); if s <> lbBindings.Items[i] then begin lbBindings.Items[i] := s; end; end; end else begin lbBindings.Items.Clear; for i := 0 to FHandles.Count-1 do begin lbBindings.Items.Add(GetDisplayString(FHandles[i])); end; end; finally lbBindings.Items.EndUpdate; if Assigned(FCurrentHandle) then begin lbBindings.ItemIndex := FCurrentHandle.Index; end else begin lbBindings.ItemIndex := IndyMin(selected, lbBindings.Items.Count-1); end; end; } end; procedure TIdDsnPropEdBindingNET.UpdateEditControls; begin if Assigned(FCurrentHandle) then begin edtPort.Text := ''; edtPort.Value := FCurrentHandle.Port; case FCurrentHandle.IPVersion of Id_IPv4 : begin FillComboBox(edtIPAddress, FIPv4Addresses); edtIPAddress.SelectedItem := edtIPAddress.Items[0]; cboIPVersion.SelectedItem := cboIPVersion.Items[0]; end; Id_IPv6 : begin FillComboBox(edtIPAddress, FIPv6Addresses); edtIPAddress.SelectedItem := edtIPAddress.Items[0]; cboIPVersion.SelectedItem := cboIPVersion.Items[1]; end; end; if edtIPAddress.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown then begin edtIPAddress.Text := FCurrentHandle.IP; end else begin edtIPAddress.SelectedIndex := edtIPAddress.Items.IndexOf(FCurrentHandle.IP); end; end; lblIPAddress.Enabled := Assigned(FCurrentHandle); edtIPAddress.Enabled := Assigned(FCurrentHandle); lblPort.Enabled := Assigned(FCurrentHandle); edtPort.Enabled := Assigned(FCurrentHandle); lblIPVersion.Enabled := Assigned(FCurrentHandle); cboIPVersion.Enabled := Assigned(FCurrentHandle); end; procedure TIdDsnPropEdBindingNET.FillComboBox( ACombo: System.Windows.Forms.ComboBox; AStrings: TStrings); var i : Integer; begin ACombo.Items.Clear; for i := 0 to AStrings.Count-1 do begin ACombo.Items.Add(AStrings[i]); end; end; function TIdDsnPropEdBindingNET.Execute: Boolean; begin Result := Self.ShowDialog = System.Windows.Forms.DialogResult.OK; end; function TIdDsnPropEdBindingNET.GetCaption: String; begin Result := Text; end; procedure TIdDsnPropEdBindingNET.SetCaption(const AValue: String); begin Text := AValue; end; end.
unit Customer; interface uses ObjectsMappers; type TBaseBO = class private FID: Integer; procedure SetID(const Value: Integer); public procedure CheckInsert; virtual; procedure CheckUpdate; virtual; procedure CheckDelete; virtual; property ID: Integer read FID write SetID; end; [MapperJSONNaming(JSONNameLowerCase)] TCustomer = class(TBaseBO) private FFirst_Name: string; FLast_Name: string; FAge: integer; procedure SetFirst_name(const Value: string); procedure SetLast_name(const Value: string); procedure SetAge(const Value:integer); public procedure CheckInsert; override; procedure CheckUpdate; override; procedure CheckDelete; override; [MapperColumn('First_Name')] property First_Name: string read FFirst_Name write SetFirst_Name; [MapperColumn('Last_Name')] property Last_Name: string read FLast_Name write SetLast_Name; [MapperColumn('Age')] property Age: integer read FAge write SetAge; end; implementation uses System.SysUtils; { TBaseBO } procedure TBaseBO.CheckDelete; begin end; procedure TBaseBO.CheckInsert; begin end; procedure TBaseBO.CheckUpdate; begin end; procedure TBaseBO.SetID(const Value: Integer); begin FID := Value; end; { TCustomer } procedure TCustomer.CheckDelete; begin inherited; if age > 50 then raise Exception.Create('Cannot delete an customer with a age greater than 50 years (yes, it is a silly check)'); end; procedure TCustomer.CheckInsert; begin inherited; if length(First_Name) < 3 then raise Exception.Create('First Name cannot be less than 3 chars'); end; procedure TCustomer.CheckUpdate; begin inherited; if length(First_Name) < 3 then raise Exception.Create('First Name cannot be less than 3 chars'); end; procedure TCustomer.SetFirst_Name(const Value: string); begin FFirst_Name := Value; end; procedure TCustomer.SetLast_Name(const Value: string); begin FLast_Name := Value; end; procedure TCustomer.SetAge(const Value: integer); begin FAge := Value; end; end.
{!DOCTOPIC}{ Numeric functions } {!DOCREF} { @method: function se.SumTBA(const Arr: TByteArray): Int64; @desc: Returns the total sum of the array } function SimbaExt.SumTBA(const Arr: TByteArray): Int64; begin Result := exp_SumTBA(Arr); end; {!DOCREF} { @method: function se.SumTIA(const Arr: TIntArray): Int64; @desc: Returns the total sum of the array } function SimbaExt.SumTIA(const Arr: TIntArray): Int64; begin Result := exp_SumTIA(Arr); end; {!DOCREF} { @method: function se.SumTEA(const Arr: TExtArray): Extended; @desc: Returns the total sum of the array } function SimbaExt.SumTEA(const Arr: TExtArray): Extended; begin Result := exp_SumTEA(Arr); end; {!DOCREF} { @method: function se.TIACombinations(const Arr: TIntArray; Seq:Integer): T2DIntegerArray; @desc: Returns all the possible combinations in the array } function SimbaExt.TIACombinations(const Arr: TIntArray; Seq:Integer): T2DIntegerArray; begin Result := exp_TIACombinations(Arr, Seq); end; {!DOCREF} { @method: function se.TEACombinations(const Arr: TExtArray; Seq:Integer): T2DExtendedArray; @desc: Returns all the possible combinations in the array } function SimbaExt.TEACombinations(const Arr: TExtArray; Seq:Integer): T2DExtendedArray; begin Result := exp_TEACombinations(Arr, Seq); end; {!DOCREF} { @method: procedure se.MinMaxTBA(const Arr: TByteArray; var Min:Byte; var Max:Byte); @desc: Returns the lower and upper value in the array } procedure SimbaExt.MinMaxTBA(const Arr: TByteArray; var Min:Byte; var Max:Byte); begin exp_MinMaxTBA(Arr, Min,Max); end; {!DOCREF} { @method: procedure se.MinMaxTIA(const Arr: TIntArray; var Min:Integer; var Max: Integer); @desc: Returns the lower and upper value in the array } procedure SimbaExt.MinMaxTIA(const Arr: TIntArray; var Min:Integer; var Max: Integer); begin exp_MinMaxTIA(Arr, Min,Max); end; {!DOCREF} { @method: procedure se.MinMaxTEA(const Arr: TExtArray; var Min:Extended; var Max: Extended); @desc: Returns the lower and upper value in the array } procedure SimbaExt.MinMaxTEA(const Arr: TExtArray; var Min:Extended; var Max: Extended); begin exp_MinMaxTEA(Arr, Min,Max); end;
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 11/27/2004 8:27:14 PM JPMugaas Fix for compiler errors. Rev 1.4 11/27/04 2:56:40 AM RLebeau Added support for overloaded version of LoginSASL(). Added GetDisplayName() method to TIdSASLListEntry, and FindSASL() method to TIdSASLEntries. Rev 1.3 10/26/2004 10:55:32 PM JPMugaas Updated refs. Rev 1.2 6/11/2004 9:38:38 AM DSiders Added "Do not Localize" comments. Rev 1.1 2004.02.03 5:45:50 PM czhower Name changes Rev 1.0 1/25/2004 3:09:54 PM JPMugaas New collection class for SASL mechanism processing. } unit IdSASLCollection; interface {$i IdCompilerDefines.inc} uses Classes, IdBaseComponent, IdCoder, IdException, IdSASL, IdTCPConnection; type TIdSASLEntries = class; TIdSASLListEntry = class(TCollectionItem) protected FSASL : TIdSASL; function GetDisplayName: String; override; function GetOwnerComponent: TComponent; function GetSASLEntries: TIdSASLEntries; procedure SetSASL(AValue : TIdSASL); public procedure Assign(Source: TPersistent); override; property OwnerComponent: TComponent read GetOwnerComponent; property SASLEntries: TIdSASLEntries read GetSASLEntries; published property SASL : TIdSASL read FSASL write SetSASL; end; TIdSASLEntries = class ( TOwnedCollection ) protected procedure CheckIfEmpty; function GetItem(Index: Integer) : TIdSASLListEntry; function GetOwnerComponent: TComponent; procedure SetItem(Index: Integer; const Value: TIdSASLListEntry); public constructor Create ( AOwner : TPersistent ); reintroduce; function Add: TIdSASLListEntry; procedure LoginSASL(const ACmd, AHost, AProtocolName: String; const AOkReplies, AContinueReplies: array of string; AClient : TIdTCPConnection; ACapaReply : TStrings; const AAuthString : String = 'AUTH'); overload; {Do not Localize} procedure LoginSASL(const ACmd, AHost, AProtocolName: String; const AServiceName: String; const AOkReplies, AContinueReplies: array of string; AClient : TIdTCPConnection; ACapaReply : TStrings; const AAuthString : String = 'AUTH'); overload; {Do not Localize} function ParseCapaReply(ACapaReply: TStrings; const AAuthString: String = 'AUTH') : TStrings; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use ParseCapaReplyToList()'{$ENDIF};{$ENDIF} {do not localize} procedure ParseCapaReplyToList(ACapaReply, ADestList: TStrings; const AAuthString: String = 'AUTH'); {do not localize} function FindSASL(const AServiceName: String): TIdSASL; function Insert(Index: Integer): TIdSASLListEntry; procedure RemoveByComp(AComponent : TComponent); function IndexOfComp(AItem : TIdSASL): Integer; property Items[Index: Integer] : TIdSASLListEntry read GetItem write SetItem; default; property OwnerComponent: TComponent read GetOwnerComponent; end; EIdSASLException = class(EIdException); EIdSASLNotSupported = class(EIdSASLException); EIdSASLNotReady = class(EIdSASLException); EIdSASLMechNeeded = class(EIdSASLException); implementation uses IdCoderMIME, IdGlobal, IdGlobalProtocols, IdReply, IdResourceStringsProtocols, SysUtils; { TIdSASLListEntry } procedure TIdSASLListEntry.Assign(Source: TPersistent); begin if Source is TIdSASLListEntry then begin SASL := TIdSASLListEntry(Source).SASL; end else begin inherited Assign(Source); end; end; function TIdSASLListEntry.GetDisplayName: String; begin if FSASL <> nil then begin Result := String(FSASL.ServiceName); end else begin Result := inherited GetDisplayName; end; end; function TIdSASLListEntry.GetOwnerComponent: TComponent; var LEntries: TIdSASLEntries; begin LEntries := SASLEntries; if Assigned(LEntries) then begin Result := LEntries.OwnerComponent; end else begin Result := nil; end; end; function TIdSASLListEntry.GetSASLEntries: TIdSASLEntries; begin if Collection is TIdSASLEntries then begin Result := TIdSASLEntries(Collection); end else begin Result := nil; end; end; procedure TIdSASLListEntry.SetSASL(AValue : TIdSASL); var LOwnerComp: TComponent; begin if FSASL <> AValue then begin LOwnerComp := OwnerComponent; if (FSASL <> nil) and (LOwnerComp <> nil) then begin FSASL.RemoveFreeNotification(LOwnerComp); end; FSASL := AValue; if (FSASL <> nil) and (LOwnerComp <> nil) then begin FSASL.FreeNotification(LOwnerComp); end; end; end; { TIdSASLEntries } function CheckStrFail(const AStr : String; const AOk, ACont: array of string) : Boolean; begin Result := (PosInStrArray(AStr, AOk) = -1) and (PosInStrArray(AStr, ACont) = -1); end; function PerformSASLLogin(const ACmd, AHost, AProtocolName: String; ASASL: TIdSASL; AEncoder: TIdEncoder; ADecoder: TIdDecoder; const AOkReplies, AContinueReplies: array of string; AClient : TIdTCPConnection): Boolean; var S: String; begin Result := False; AClient.SendCmd(ACmd + ' ' + String(ASASL.ServiceName), []);//[334, 504]); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin Exit; // this mechanism is not supported end; if (PosInStrArray(AClient.LastCmdResult.Code, AOkReplies) > -1) then begin Result := True; Exit; // we've authenticated successfully :) end; S := ADecoder.DecodeString(TrimRight(AClient.LastCmdResult.Text.Text)); S := ASASL.StartAuthenticate(S, AHost, AProtocolName); AClient.SendCmd(AEncoder.Encode(S)); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin ASASL.FinishAuthenticate; Exit; end; while PosInStrArray(AClient.LastCmdResult.Code, AContinueReplies) > -1 do begin S := ADecoder.DecodeString(TrimRight(AClient.LastCmdResult.Text.Text)); S := ASASL.ContinueAuthenticate(S, AHost, AProtocolName); AClient.SendCmd(AEncoder.Encode(S)); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin ASASL.FinishAuthenticate; Exit; end; end; Result := (PosInStrArray(AClient.LastCmdResult.Code, AOkReplies) > -1); ASASL.FinishAuthenticate; end; function TIdSASLEntries.Add: TIdSASLListEntry; begin Result := TIdSASLListEntry(inherited Add); end; constructor TIdSASLEntries.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdSASLListEntry); end; procedure TIdSASLEntries.CheckIfEmpty; var I: Integer; begin for I := 0 to Count-1 do begin if Items[I].SASL <> nil then begin Exit; end; end; EIdSASLMechNeeded.Toss(RSSASLRequired); end; function TIdSASLEntries.GetItem(Index: Integer): TIdSASLListEntry; begin Result := TIdSASLListEntry(inherited Items[Index]); end; function TIdSASLEntries.GetOwnerComponent: TComponent; var LOwner: TPersistent; begin LOwner := inherited GetOwner; if LOwner is TComponent then begin Result := TComponent(LOwner); end else begin Result := nil; end; end; function TIdSASLEntries.IndexOfComp(AItem: TIdSASL): Integer; begin for Result := 0 to Count -1 do begin if Items[Result].SASL = AItem then begin Exit; end; end; Result := -1; end; function TIdSASLEntries.Insert(Index: Integer): TIdSASLListEntry; begin Result := TIdSASLListEntry( inherited Insert(Index) ); end; procedure TIdSASLEntries.LoginSASL(const ACmd, AHost, AProtocolName: String; const AOkReplies, AContinueReplies: array of string; AClient: TIdTCPConnection; ACapaReply: TStrings; const AAuthString: String); var i : Integer; LE : TIdEncoderMIME; LD : TIdDecoderMIME; LSupportedSASL : TStrings; LSASLList: TList; LSASL : TIdSASL; LError : TIdReply; function SetupErrorReply: TIdReply; begin Result := TIdReplyClass(AClient.LastCmdResult.ClassType).Create(nil); Result.Assign(AClient.LastCmdResult); end; begin // make sure the collection is not empty CheckIfEmpty; //create a list of mechanisms that both parties support LSASLList := TList.Create; try LSupportedSASL := TStringList.Create; try ParseCapaReplyToList(ACapaReply, LSupportedSASL, AAuthString); for i := Count-1 downto 0 do begin LSASL := Items[i].SASL; if LSASL <> nil then begin if not LSASL.IsAuthProtocolAvailable(LSupportedSASL) then begin Continue; end; if LSASLList.IndexOf(LSASL) = -1 then begin LSASLList.Add(LSASL); end; end; end; finally FreeAndNil(LSupportedSASL); end; if LSASLList.Count = 0 then begin EIdSASLNotSupported.Toss(RSSASLNotSupported); end; //now do it LE := nil; try LD := nil; try LError := nil; try for i := 0 to LSASLList.Count-1 do begin LSASL := TIdSASL(LSASLList.Items[i]); if not LSASL.IsReadyToStart then begin Continue; end; if not Assigned(LE) then begin LE := TIdEncoderMIME.Create(nil); end; if not Assigned(LD) then begin LD := TIdDecoderMIME.Create(nil); end; if PerformSASLLogin(ACmd, AHost, AProtocolName, LSASL, LE, LD, AOkReplies, AContinueReplies, AClient) then begin Exit; end; if not Assigned(LError) then begin LError := SetupErrorReply; end; end; if Assigned(LError) then begin LError.RaiseReplyError; end else begin EIdSASLNotReady.Toss(RSSASLNotReady); end; finally FreeAndNil(LError); end; finally FreeAndNil(LD); end; finally FreeAndNil(LE); end; finally FreeAndNil(LSASLList); end; end; procedure TIdSASLEntries.LoginSASL(const ACmd, AHost, AProtocolName: String; const AServiceName: String; const AOkReplies, AContinueReplies: array of string; AClient: TIdTCPConnection; ACapaReply: TStrings; const AAuthString: String); var LE : TIdEncoderMIME; LD : TIdDecoderMIME; LSupportedSASL : TStrings; LSASL : TIdSASL; begin LSASL := nil; // make sure the collection is not empty CheckIfEmpty; //determine if both parties support the same mechanism LSupportedSASL := TStringList.Create; try ParseCapaReplyToList(ACapaReply, LSupportedSASL, AAuthString); if LSupportedSASL.IndexOf(AServiceName) <> -1 then begin LSASL := FindSASL(AServiceName); end; finally FreeAndNil(LSupportedSASL); end; if LSASL = nil then begin EIdSASLNotSupported.Toss(RSSASLNotSupported); end else if not LSASL.IsReadyToStart then begin EIdSASLNotReady.Toss(RSSASLNotReady); end; //now do it LE := TIdEncoderMIME.Create(nil); try LD := TIdDecoderMIME.Create(nil); try if not PerformSASLLogin(ACmd, AHost, AProtocolName, LSASL, LE, LD, AOkReplies, AContinueReplies, AClient) then begin AClient.RaiseExceptionForLastCmdResult; end; finally FreeAndNil(LD); end; finally FreeAndNil(LE); end; end; function TIdSASLEntries.ParseCapaReply(ACapaReply: TStrings; const AAuthString: String): TStrings; begin Result := TStringList.Create; try ParseCapaReplyToList(ACapaReply, Result, AAuthString); except FreeAndNil(Result); raise; end; end; procedure TIdSASLEntries.ParseCapaReplyToList(ACapaReply, ADestList: TStrings; const AAuthString: String = 'AUTH'); {do not localize} const VALIDDELIMS: String = ' ='; {Do not Localize} var i: Integer; s: string; LEntry : String; begin if ACapaReply = nil then begin Exit; end; ADestList.BeginUpdate; try for i := 0 to ACapaReply.Count - 1 do begin s := ACapaReply[i]; if TextStartsWith(s, AAuthString) and CharIsInSet(s, Length(AAuthString)+1, VALIDDELIMS) then begin s := UpperCase(Copy(s, Length(AAuthString)+1, MaxInt)); s := StringReplace(s, '=', ' ', [rfReplaceAll]); {Do not Localize} while Length(s) > 0 do begin LEntry := Fetch(s, ' '); {Do not Localize} if LEntry <> '' then begin if ADestList.IndexOf(LEntry) = -1 then begin ADestList.Add(LEntry); end; end; end; end; end; finally ADestList.EndUpdate; end; end; function TIdSASLEntries.FindSASL(const AServiceName: String): TIdSASL; var i: Integer; LEntry: TIdSASLListEntry; begin Result := nil; For i := 0 to Count-1 do begin LEntry := Items[i]; if LEntry.SASL <> nil then begin if TextIsSame(String(LEntry.SASL.ServiceName), AServiceName) then begin Result := LEntry.SASL; Exit; end; end; end; end; procedure TIdSASLEntries.RemoveByComp(AComponent: TComponent); var i : Integer; begin for i := Count-1 downto 0 do begin if Items[i].SASL = AComponent then begin Delete(i); end; end; end; procedure TIdSASLEntries.SetItem(Index: Integer; const Value: TIdSASLListEntry); begin inherited SetItem(Index, Value); end; end.
unit uExportaExcel; interface uses DB, ComObj, Graphics, Variants; type TExportaExcel = class private fArquivoExcel: string; fNomeArquivo: string; fDirArquivo: string; fDataset: TDataSet; FNomePlanilha: string; procedure SetDirArquivo(const Value: string); public property Dataset: TDataSet read fDataset write fDataset; property DirArquivo: string read FDirArquivo write SetDirArquivo; property NomeArquivo: string read FNomeArquivo write FNomeArquivo; property NomePlanilha: string read FNomePlanilha write FNomePlanilha; function GerarExcel: Boolean; end; implementation uses SysUtils; { TExportaExcel } function TExportaExcel.GerarExcel: Boolean; var Excel, Sheet: OleVariant; Nome: string; i, Linha: Integer; begin Result := False; fArquivoExcel := fDirArquivo + ExtractFileName(fNomeArquivo); fArquivoExcel := ChangeFileExt(fArquivoExcel, '.XLSX'); //nome da planílha if FNomePlanilha <> EmptyStr then Nome := FNomePlanilha else Nome := 'Plan1'; try //Desabilitando os controles fDataset.DisableControls; //cria a aplicação Excel := CreateOleObject('Excel.Application'); //Oculta a tabela Excel.Visible := False; //adiciona pasta de trabalho Excel.WorkBooks.Add; //deleta as planilhas que sobraram Excel.WorkBooks[1].Sheets[2].Delete; Excel.WorkBooks[1].Sheets[2].Delete; //planilha recebendo variável nome Excel.WorkBooks[1].WorkSheets[1].Name := Nome; //Repassando variável Sheet := Excel.WorkBooks[1].WorkSheets[Nome]; Linha := 1; //Escreve o cabeçalho for i := 0 to Pred(fDataset.FieldCount) do begin if fDataset.Fields[i].Tag > 0 then begin Sheet.Cells[Linha, fDataset.Fields[i].Tag] := fDataset.Fields[i].DisplayLabel; //Formatando a celula Sheet.Cells[Linha, fDataset.Fields[i].Tag].Font.Name := 'Segoe UI'; Sheet.Cells[Linha, fDataset.Fields[i].Tag].Font.Bold := True; Sheet.Cells[linha, fDataset.Fields[i].Tag].Font.Size := 9; //Alinhando horizontalmente ao centro Sheet.Cells[linha, fDataset.Fields[i].Tag].HorizontalAlignment := 3; Sheet.Cells[linha, fDataset.Fields[i].Tag].Font.Color := clWhite; // Cor da Fonte Sheet.Cells[linha, fDataset.Fields[i].Tag].Interior.Color := clBlack; // Cor da Célula end; end; fDataset.First; Linha := Linha + 1; while not fDataset.Eof do begin for i := 0 to Pred(fDataset.FieldCount) do begin if fDataset.Fields[i].Tag > 0 then begin //Verifica o tipo de campo para formatação case fDataset.Fields[i].DataType of ftInteger, ftSmallint, ftWord, ftLargeint: begin Sheet.Cells[Linha, fDataset.Fields[i].Tag] := fDataset.Fields[i].AsInteger; end; ftDate, ftDateTime: begin Sheet.Cells[Linha, fDataset.Fields[i].Tag] := fDataset.Fields[i].AsDateTime; Sheet.Cells[Linha, fDataset.Fields[i].Tag].NumberFormat := 'dd/mm/aa'; //Alinhando horizontalmente ao centro Sheet.Cells[linha, fDataset.Fields[i].Tag].HorizontalAlignment := 3; end; ftFloat, ftCurrency: begin Sheet.Cells[Linha, fDataset.Fields[i].Tag] := fDataset.Fields[i].AsFloat; if (fDataset.Fields[i] as TFloatField).currency then Sheet.Cells[Linha, fDataset.Fields[i].Tag].NumberFormat := 'R$ #.##0,00_);[Vermelho](R$ #.##0,00)' else Sheet.Cells[Linha, fDataset.Fields[i].Tag].NumberFormat := '#.##0,00_);[Vermelho](#.##0,00)'; end; ftString: begin Sheet.Cells[Linha, fDataset.Fields[i].Tag] := fDataset.Fields[i].AsString; Sheet.Cells[Linha, fDataset.Fields[i].Tag].NumberFormat := '@'; end; else Sheet.Cells[Linha, fDataset.Fields[i].Tag] := fDataset.Fields[i].AsString; end; //Formatando a celula Sheet.Cells[Linha, fDataset.Fields[i].Tag].Font.Name := 'Segoe UI'; Sheet.Cells[Linha, fDataset.Fields[i].Tag].Font.Size := 9; end; end; Inc(Linha); fDataset.Next; end; Excel.DisplayAlerts := False; // Discard unsaved files.... Excel.Columns.AutoFit; if ForceDirectories(ExtractFilePath(fArquivoExcel)) then Excel.WorkBooks[1].SaveAs(fArquivoExcel); finally //Sair do Excel if not VarIsEmpty(Excel) then begin Excel.Workbooks[1].Close; Excel.Quit; Excel := Unassigned; Sheet := Unassigned; fDataset.First; //Habilitando os controles fDataset.EnableControls; Result := FileExists(fArquivoExcel); end; end; end; procedure TExportaExcel.SetDirArquivo(const Value: string); begin FDirArquivo := IncludeTrailingPathDelimiter(Value); end; end.
/// Utilities to load or save text delimited files. unit tmsUTextDelim; {$INCLUDE ..\FLXCOMPILER.INC} interface uses Classes, SysUtils, tmsUExcelAdapter, tmsUFlxNumberFormat, tmsUFlxMessages; type /// <summary> /// Handles how to convert a column from text when importing a text file. /// </summary> XLSColumnImportTypes=( /// <summary> /// Try to convert it to a number, a date, etc. /// </summary> xct_general, /// <summary> /// Keep the column as text, even if it can be converted to a number or other things. /// </summary> xct_text, /// <summary> /// Do not import this column. /// </summary> xct_skip); //*********************************************************************************** /// <summary> /// Saves the Active sheet of an Excel file as a text delimited file. /// </summary> /// <remarks> /// You will normally want to use <see cref="TFlexCelImport.SaveAsText@TFileName@Char" text="TFlexCelImport.SaveAsText" /> /// instead of this method to save whole files, or SaveRangeAsTextDelim to save a range of the active /// sheet. /// </remarks> /// <param name="OutStream">Stream where we are going to save the file.</param> /// <param name="Workbook">Workbook we want to save.</param> /// <param name="Delim">Delimiter used in the file (&quot;,&quot; or &quot;;&quot; for csv, #9 /// for tab delimited)</param> procedure SaveAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char); {$IFDEF DELPHI2008UP}overload;{$ENDIF} /// <summary> /// Saves a range of cells in a text delimited file. /// </summary> /// <remarks> /// To save the full sheet use SaveAsTextDelim or <see cref="TFlexCelImport.SaveAsText@TFileName@Char" text="TFlexCelImport.SaveAsText" />. /// </remarks> /// <param name="OutStream">Stream where we are going to save the file.</param> /// <param name="Workbook">Workbook we want to save.</param> /// <param name="Delim">Delimiter used in the file (&quot;,&quot; or &quot;;&quot; for csv, #9 /// for tab delimited)</param> /// <param name="Range">Encoding for the generated file.</param> procedure SaveRangeAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char; const Range: TXlsCellRange); {$IFDEF DELPHI2008UP}overload;{$ENDIF} /// <summary> /// Imports a text file into an Excel file. /// </summary> /// <remarks> /// Normally you can just use <see cref="TFlexCelImport.OpenText@TFileName@Char@array of XLSColumnImportTypes" text="TFlexCelImport.OpenFile Method" /> /// to import csv files, but this method gives you a little more control, like the row and column where /// to import the data.<para></para> /// Actually OpenText internally calls this method. /// </remarks> /// <param name="InStream">Stream with the text delimited file you want to import.</param> /// <param name="Workbook">Excel file where there data will be imported.</param> /// <param name="aDelim">Delimiter used in the file. This is normally &quot;,&quot;, &quot;;&quot; /// in csv files or #9 (tab) in tab delimited files.</param> /// <param name="FirstRow">First row where the data will be imported. (1 based)</param> /// <param name="FirstCol">First column where the data will be imported (1 based)</param> /// <param name="ColumnFormats">Array of import types specifying how to import each column.</param> procedure LoadFromTextDelim(const InStream: TStream; const Workbook: TExcelFile; const aDelim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes); {$IFDEF DELPHI2008UP}overload;{$ENDIF} {$IFDEF DELPHI2008UP} /// <summary> /// Saves the Active sheet of an Excel file as a text delimited file. /// </summary> /// <remarks> /// You will normally want to use <see cref="TFlexCelImport.SaveAsText@TFileName@Char" text="TFlexCelImport.SaveAsText" /> /// instead of this method to save whole files, or SaveRangeAsTextDelim to save a range of the active /// sheet.<para></para> /// <para></para> /// <b>This method only works in Delphi 2009 or newer.</b> /// </remarks> /// <param name="OutStream">Stream where we are going to save the file.</param> /// <param name="Workbook">Workbook we want to save.</param> /// <param name="Delim">Delimiter used in the file (&quot;,&quot; or &quot;;&quot; for csv, #9 /// for tab delimited)</param> /// <param name="Encoding">Encoding for the saved file.</param> procedure SaveAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char; const Encoding: TEncoding); overload; /// <summary> /// Saves a range of cells in a text delimited file. /// </summary> /// <remarks> /// To save the full sheet use SaveAsTextDelim or <see cref="TFlexCelImport.SaveAsText@TFileName@Char" text="TFlexCelImport.SaveAsText" />.<para></para> /// <para></para> /// <b>This method only works in Delphi 2009 or newer.</b> /// </remarks> /// <param name="OutStream">Stream where we are going to save the file.</param> /// <param name="Workbook">Workbook we want to save.</param> /// <param name="Delim">Delimiter used in the file (&quot;,&quot; or &quot;;&quot; for csv, #9 /// for tab delimited)</param> /// <param name="Range">Range of cells we want to export.</param> /// <param name="Encoding">Encoding for the generated file.</param> procedure SaveRangeAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char; const Range: TXlsCellRange; const Encoding: TEncoding); overload; /// <summary> /// Imports a text file into an Excel file. /// </summary> /// <remarks> /// Normally you can just use <see cref="TFlexCelImport.OpenText@TFileName@Char@array of XLSColumnImportTypes" text="TFlexCelImport.OpenFile Method" /> /// to import csv files, but this method gives you a little more control, like the row and column where /// to import the data.<para></para> /// <para></para> /// <b>This overload of the method is only available in Delphi 2009 or newer.</b> /// </remarks> /// <param name="InStream">Stream with the text delimited file you want to import.</param> /// <param name="Workbook">Excel file where there data will be imported.</param> /// <param name="Delim">Delimiter used in the file. This is normally &quot;,&quot;, &quot;;&quot; /// in csv files or #9 (tab) in tab delimited files.</param> /// <param name="FirstRow">First row where the data will be imported. (1 based)</param> /// <param name="FirstCol">First column where the data will be imported (1 based)</param> /// <param name="ColumnFormats">Array of import types specifying how to import each column.</param> /// <param name="Encoding">Encoding used in the text file. (UTF8, Unicode, etc).</param> /// <param name="DetectBOM">If true, FlexCel will try to detect the encoding from the BOM (Byte /// order mark) in the file. Set it to true if the files have BOM.</param> procedure LoadFromTextDelim(const InStream: TStream; const Workbook: TExcelFile; const Delim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes; const Encoding: TEncoding; const DetectBOM: Boolean = false); overload; /// <summary> /// Imports a text file into an Excel file. /// </summary> /// <remarks> /// Normally you can just use <see cref="TFlexCelImport.OpenText@TFileName@Char@array of XLSColumnImportTypes" text="TFlexCelImport.OpenFile Method" /> /// to import csv files, but this method gives you a little more control, like the row and column where /// to import the data.<para></para> /// <para></para> /// <b>This overload of the method is only available in Delphi 2009 or newer.</b> /// </remarks> /// <param name="Sr">StreamReader with the text delimited file you want to import.</param> /// <param name="Workbook">Excel file where there data will be imported.</param> /// <param name="Delim">Delimiter used in the file. This is normally &quot;,&quot;, &quot;;&quot; /// in csv files or #9 (tab) in tab delimited files.</param> /// <param name="FirstRow">First row where the data will be imported. (1 based)</param> /// <param name="FirstCol">First column where the data will be imported (1 based)</param> /// <param name="ColumnFormats">Array of import types specifying how to import each column.</param> procedure LoadFromTextDelim(const Sr: TStreamReader; const Workbook: TExcelFile; const Delim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes); overload; {$ENDIF} //*********************************************************************************** implementation function FlxQuotedStr(const S: string): string; var I: Integer; begin Result := S; for I := Length(Result) downto 1 do if Result[I] = '"' then Insert('"', Result, I); Result := '"' + Result + '"'; end; procedure SaveRangeAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char; const Range: TXlsCellRange {$IFDEF DELPHI2008UP}; const Encoding: TEncoding {$ENDIF}); var r,c: integer; s: String; //UTF16 in D2009, AnsiString otherwise. Color: integer; {$IFDEF DELPHI2008UP} Buff : TBytes; {$ENDIF} begin for r:=Range.Top to Range.Bottom do begin for c:=Range.Left to Range.Right do begin Color := -1; s:=XlsFormatValue1904(Workbook.CellValue[r,c],Workbook.FormatList[Workbook.CellFormat[r,c]].Format, Workbook.Options1904Dates, Color); if (pos(Delim, s)>0) or (pos('"', s)>0) or (pos(#10,s)>0) or (pos(#13,s)>0) then begin s:=FlxQuotedStr(s); end; if c<Range.Right then s:=s+Delim else s:=s+#13#10; {$IFDEF DELPHI2008UP} Buff := Encoding.GetBytes(s); OutStream.Write(Buff[0], Length(Buff)); {$ELSE} OutStream.Write(s[1], Length(s)); {$ENDIF} end; end; end; procedure SaveAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char {$IFDEF DELPHI2008UP}; const Encoding: TEncoding {$ENDIF}); var Range:TXlsCellRange; begin Range.Left:=1; Range.Top:=1; Range.Right:=Workbook.MaxCol; Range.Bottom:=Workbook.MaxRow; {$IFDEF DELPHI2008UP} SaveRangeAsTextDelim(OutStream, Workbook, Delim, Range, Encoding); {$ELSE} SaveRangeAsTextDelim(OutStream, Workbook, Delim, Range); {$ENDIF} end; {$IFDEF DELPHI2008UP} procedure ReadQString(const InStream: TStreamReader; var S: TStringBuilder; var ch: integer); var InQuote: boolean; begin InQuote:=false; S.Length := 0; while ch >= 0 do begin ch := InStream.Read; if (ch<> Ord('"')) and InQuote then begin exit; end; if InQuote or (ch<> Ord('"')) then s.Append(char(ch)); InQuote:=(ch= Ord('"')) and not InQuote; end; end; procedure ReadNString(const InStream: TStreamReader; const Delim: Integer; var S: TStringBuilder; var ch: integer); begin s.Length := 0; s.Append(char(ch)); while Ch >= 0 do begin ch := InStream.Read; if (ch=Delim)or (ch=13)or (ch=10) or (ch < 0) then exit; s.Append(char(ch)); end; //while end; procedure LoadFromTextDelim(const InStream: TStream; const Workbook: TExcelFile; const Delim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes; const Encoding: TEncoding; const DetectBOM: Boolean = false); var Sr: TStreamReader; Enc: TEncoding; begin Enc := Encoding; if Enc = nil then Enc := TEncoding.ASCII; Sr := TStreamReader.Create(InStream, Enc, DetectBOM); //OwnsStream is false, so it won't free the stream. try LoadFromTextDelim(Sr, Workbook, Delim, FirstRow, FirstCol, ColumnFormats); finally FreeAndNil(Sr); end; end; procedure LoadFromTextDelim(const Sr: TStreamReader; const Workbook: TExcelFile; const Delim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes); var r,c: integer; s: TStringBuilder; ch: integer; bDelim : integer; begin bDelim := ord(Delim); r:=FirstRow; c:=FirstCol; s := TStringBuilder.Create; try ch := Sr.Read; while ch >= 0 do begin if (ch= Ord('"')) then ReadQString(Sr, s, ch) else if (ch=bDelim) then begin inc(c); Ch := Sr.Read; continue; end else if (ch=10) then begin c:=FirstCol; inc(r); ch := Sr.Read; continue; end else if (ch=13) then begin ch := Sr.Read; continue; end else ReadNString(Sr, bDelim, s, ch); if c-FirstCol< Length(ColumnFormats) then case ColumnFormats[c-FirstCol] of xct_text: Workbook.CellValue[r, c]:=s.ToString; xct_skip: begin end; else WorkBook.SetCellString(r,c,s.ToString); end //case else WorkBook.SetCellString(r,c,s.ToString); end; finally FreeAndNil(s); end; end; {$ELSE} procedure ReadQString(const InStream: TStream; out S: String; var ch: Char); var InQuote: boolean; begin InQuote:=false; s:=''; while InStream.Position<InStream.Size do begin InStream.ReadBuffer(ch, SizeOf(ch)); if (ch<>'"') and InQuote then begin exit; end; if InQuote or (ch<>'"') then s:=s+ch; InQuote:=(ch='"') and not InQuote; end; end; procedure ReadNString(const InStream: TStream; const Delim: Char; var S: String; var ch: Char); begin s:=ch; while InStream.Position<InStream.Size do begin InStream.ReadBuffer(ch, SizeOf(ch)); if (ch=Delim)or (ch=#13)or (ch=#10) then exit; s:=s+ch; end; //while end; procedure LoadFromTextDelim(const InStream: TStream; const Workbook: TExcelFile; const aDelim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes); var r,c: integer; s: String; ch: Char; Delim: Char; begin Delim := Char(aDelim); r:=FirstRow; c:=FirstCol; if InStream.Position<InStream.Size then InStream.ReadBuffer(ch, SizeOf(ch)); while InStream.Position<InStream.Size do begin if (ch='"') then ReadQString(InStream, s, ch) else if (ch=Delim) then begin inc(c); InStream.ReadBuffer(ch, SizeOf(ch)); continue; end else if (ch=#10) then begin c:=FirstCol; inc(r); InStream.ReadBuffer(ch, SizeOf(ch)); continue; end else if (ch=#13) then begin InStream.ReadBuffer(ch, SizeOf(ch)); continue; end else ReadNString(InStream, Delim, s, ch); if c-FirstCol< Length(ColumnFormats) then case ColumnFormats[c-FirstCol] of xct_text: Workbook.CellValue[r, c]:=s; xct_skip: begin end; else WorkBook.SetCellString(r,c,s); end //case else WorkBook.SetCellString(r,c,s); end; end; {$ENDIF} {$IFDEF DELPHI2008UP} procedure SaveAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char); begin SaveAsTextDelim(OutStream, Workbook, Delim, TEncoding.ASCII); end; procedure SaveRangeAsTextDelim(const OutStream: TStream; const Workbook: TExcelFile; const Delim: Char; const Range: TXlsCellRange); begin SaveRangeAsTextDelim(OutStream, Workbook, Delim, Range, TEncoding.ASCII); end; procedure LoadFromTextDelim(const InStream: TStream; const Workbook: TExcelFile; const aDelim: Char; const FirstRow, FirstCol: integer; const ColumnFormats: array of XLSColumnImportTypes); begin LoadFromTextDelim(InStream, Workbook, aDelim, FirstRow, FirstCol, ColumnFormats, nil); end; {$ENDIF} end.
{ *************************************************************************** } { } { NLDPicture - www.nldelphi.com Open Source designtime component } { } { Initiator: Albert de Weerd (aka NGLN) } { License: Free to use, free to modify } { SVN path: http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDPicture } { } { *************************************************************************** } { } { Edit by: Albert de Weerd } { Date: December 13, 2008 } { Version: 2.0.0.3 } { } { *************************************************************************** } unit NLDPicture; interface uses Classes, Graphics, Forms, SysUtils, Dialogs, Jpeg; type TCustomNLDPicture = class(TComponent) private FAutoSize: Boolean; FBitmap: TBitmap; FBitmapResName: String; FFileName: TFileName; FHeight: Integer; FJpegResName: String; FInternalLoading: Boolean; FOnChanged: TNotifyEvent; FPicture: TPicture; FStretched: Boolean; FWidth: Integer; function IsPictureStored: Boolean; function IsSizeStored: Boolean; procedure PictureChanged(Sender: TObject); procedure SetAutoSize(const Value: Boolean); procedure SetBitmapResName(const Value: String); procedure SetFileName(const Value: TFileName); procedure SetHeight(const Value: Integer); procedure SetJpegResName(const Value: String); procedure SetPicture(const Value: TPicture); procedure SetStretched(const Value: Boolean); procedure SetWidth(const Value: Integer); protected procedure Changed; procedure RefreshBitmap; virtual; property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property BitmapResName: String read FBitmapResName write SetBitmapResName; property FileName: TFileName read FFileName write SetFileName; property Height: Integer read FHeight write SetHeight stored IsSizeStored; property JpegResName: String read FJpegResName write SetJpegResName; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property Picture: TPicture read FPicture write SetPicture stored IsPictureStored; property Stretched: Boolean read FStretched write SetStretched default False; property Width: Integer read FWidth write SetWidth stored IsSizeStored; public procedure Assign(Source: TPersistent); override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; public function Empty: Boolean; procedure SetSize(const AWidth, AHeight: Integer; const NotifyChange: Boolean); property Bitmap: TBitmap read FBitmap; end; TNLDPicture = class(TCustomNLDPicture) published property AutoSize; property BitmapResName; property OnChanged; property FileName; property Height; property JpegResName; property Picture; property Stretched; property Width; end; implementation { TCustomNLDPicture } resourcestring SFileNotFound = 'File not found: %s'; SJpegResType = 'JPEG'; procedure TCustomNLDPicture.Assign(Source: TPersistent); begin if Source is TCustomNLDPicture then begin FAutoSize := TCustomNLDPicture(Source).FAutoSize; FBitmapResName := TCustomNLDPicture(Source).FBitmapResName; FFileName := TCustomNLDPicture(Source).FFileName; FHeight := TCustomNLDPicture(Source).FHeight; FJpegResName := TCustomNLDPicture(Source).FJpegResName; FOnChanged := TCustomNLDPicture(Source).FOnChanged; FPicture.Assign(TCustomNLDPicture(Source).FPicture); FStretched := TCustomNLDPicture(Source).FStretched; FWidth := TCustomNLDPicture(Source).FWidth; RefreshBitmap; Changed; end else inherited Assign(Source); end; procedure TCustomNLDPicture.Changed; begin if Assigned(FOnChanged) then FOnChanged(Self); end; constructor TCustomNLDPicture.Create(AOwner: TComponent); begin inherited Create(AOwner); FBitmap := TBitmap.Create; FPicture := TPicture.Create; FPicture.OnChange := PictureChanged; if not ((AOwner is TCustomForm) or (AOwner is TDataModule)) then SetSubcomponent(True); end; destructor TCustomNLDPicture.Destroy; begin FPicture.Free; FBitmap.Free; inherited Destroy; end; function TCustomNLDPicture.Empty: Boolean; begin Result := not Assigned(FPicture.Graphic); if not Result then Result := FPicture.Graphic.Empty; end; function TCustomNLDPicture.IsPictureStored: Boolean; begin Result := (FFileName = '') and (FBitmapResName = '') and (FJpegResName = '') and (not Empty); end; function TCustomNLDPicture.IsSizeStored: Boolean; begin Result := not FAutoSize; end; procedure TCustomNLDPicture.PictureChanged(Sender: TObject); begin if not FInternalLoading then begin FBitmapResName := ''; FFileName := ''; FJpegResName := ''; end; if FAutoSize then begin FWidth := FPicture.Width; FHeight := FPicture.Height; end; RefreshBitmap; Changed; end; procedure TCustomNLDPicture.RefreshBitmap; begin if Empty then begin FBitmap.Width := 0; FBitmap.Height := 0; end else begin FBitmap.Width := FWidth; FBitmap.Height := FHeight; if FStretched then FBitmap.Canvas.StretchDraw(Rect(0, 0, FWidth, FHeight), FPicture.Graphic) else FBitmap.Canvas.Draw(0, 0, FPicture.Graphic); end; end; procedure TCustomNLDPicture.SetAutoSize(const Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; if FAutoSize then begin FStretched := False; FWidth := FPicture.Width; FHeight := FPicture.Height; RefreshBitmap; end; Changed; end; end; procedure TCustomNLDPicture.SetBitmapResName(const Value: String); begin if FBitmapResName <> Value then try FInternalLoading := True; FBitmapResName := Value; FFileName := ''; FJpegResName := ''; if FBitmapResName = '' then FPicture.Graphic := nil else try FPicture.Bitmap.LoadFromResourceName(HInstance, FBitmapResName); except on E: EResNotFound do begin FPicture.Graphic := nil; if not (csDesigning in ComponentState) then raise; end else raise; end; finally FInternalLoading := False; end; end; procedure TCustomNLDPicture.SetFileName(const Value: TFileName); begin if FFileName <> Value then try FInternalLoading := True; FFileName := Value; FBitmapResName := ''; FJpegResName := ''; if FFileName = '' then FPicture.Graphic := nil else try if FileExists(FFileName) then FPicture.LoadFromFile(FFileName) else raise EInvalidGraphic.CreateFmt(SFileNotFound, [FFileName]); except on E: EInvalidGraphic do begin FPicture.Graphic := nil; if csDesigning in ComponentState then ShowMessage(E.Message) else raise; end; else raise; end; finally FInternalLoading := False; end; end; procedure TCustomNLDPicture.SetHeight(const Value: Integer); begin if FHeight <> Value then if (not FAutoSize) and (Value >= 0) then begin FHeight := Value; RefreshBitmap; Changed; end; end; procedure TCustomNLDPicture.SetJpegResName(const Value: String); var Stream: TStream; Jpg: TJPEGImage; begin if FJpegResName <> Value then try FInternalLoading := True; FJpegResName := Value; FBitmapResName := ''; FFileName := ''; if FJpegResName = '' then FPicture.Graphic := nil else try Stream := TResourceStream.Create(HInstance, FJpegResName, PChar(SJpegResType)); Jpg := TJPEGImage.Create; try Jpg.LoadFromStream(Stream); FPicture.Graphic := Jpg; finally Jpg.Free; Stream.Free; end; except on E: EResNotFound do begin FPicture.Graphic := nil; if not (csDesigning in ComponentState) then raise; end else raise; end; finally FInternalLoading := False; end; end; procedure TCustomNLDPicture.SetPicture(const Value: TPicture); begin FPicture.Assign(Value); end; procedure TCustomNLDPicture.SetSize(const AWidth, AHeight: Integer; const NotifyChange: Boolean); begin if (FWidth <> AWidth) or (FHeight <> AHeight) then if not FAutoSize then begin if AWidth >= 0 then FWidth := AWidth; if AHeight >= 0 then FHeight := AHeight; RefreshBitmap; if NotifyChange then Changed; end; end; procedure TCustomNLDPicture.SetStretched(const Value: Boolean); begin if FStretched <> Value then if not FAutoSize then begin FStretched := Value; RefreshBitmap; Changed; end; end; procedure TCustomNLDPicture.SetWidth(const Value: Integer); begin if FWidth <> Value then if (not FAutoSize) and (Value >= 0) then begin FWidth := Value; RefreshBitmap; Changed; end; end; end.
unit LoanView; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Readhtml, FramView, FramBrwz, Htmlview, Buttons, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDCustomParentPanel, LMDBackPanel, FFSDataBackground, ComCtrls, ToolWin, PreviewForm, sDialogs, sSpeedButton, sToolBar; type TfrmLoanView = class(TForm) FFSDataBackground1: TFFSDataBackground; PrintDialog: TPrintDialog; PrinterSetupDlg: TPrinterSetupDialog; FindDialog: TFindDialog; ToolBar1: TsToolBar; ToolButton1: TToolButton; btnPageSetup: TsSpeedButton; btnPrint: TsSpeedButton; ToolButton2: TToolButton; btnPreview: TsSpeedButton; ToolButton3: TToolButton; btnFirst: TsSpeedButton; btnPrior: TsSpeedButton; btnNext: TsSpeedButton; btnLast: TsSpeedButton; ToolButton4: TToolButton; btnFind: TsSpeedButton; ToolButton5: TToolButton; btnEmail: TsSpeedButton; ToolButton6: TToolButton; btnSave: TsSpeedButton; btnLoad: TsSpeedButton; OpenDlg: TsOpenDialog; SaveDlg: TsSaveDialog; ReportViewer: THTMLViewer; procedure btnPrintClick(Sender: TObject); procedure btnPageSetupClick(Sender: TObject); procedure btnPreviewClick(Sender: TObject); procedure btnFindClick(Sender: TObject); procedure FindDialogFind(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.DFM} procedure TfrmLoanView.btnPrintClick(Sender: TObject); begin if printdialog.Execute then ReportViewer.Print(1, 9999); end; procedure TfrmLoanView.btnPageSetupClick(Sender: TObject); begin if PrinterSetupDlg.Execute then begin // if PrintRange = prAllPages then ReportViewer.Print(1, 9999) // else ReportViewer.Print(FromPage, ToPage); end; end; procedure TfrmLoanView.btnPreviewClick(Sender: TObject); var pf: TPreviewForm; Abort: boolean; begin pf := TPreviewForm.CreateIt(Self,ReportViewer, Abort); try if not Abort then pf.ShowModal; finally pf.Free; end; end; procedure TfrmLoanView.btnFindClick(Sender: TObject); begin FindDialog.Execute; end; procedure TfrmLoanView.FindDialogFind(Sender: TObject); begin with FindDialog do if not ReportViewer.Find(FindText, frMatchCase in Options) then MessageDlg('No further occurances of "'+FindText+'"', mtInformation, [mbOK], 0); end; procedure TfrmLoanView.btnSaveClick(Sender: TObject); begin with SaveDlg do if Execute then begin // Broke... // CopyFile(PChar(Viewer.CurrentFile),PChar(SaveDlg.FileName),True); end; end; procedure TfrmLoanView.btnLoadClick(Sender: TObject); begin with OpenDlg do if Execute then begin // Broke... // Viewer.LoadFromFile(OpenDlg.FileName); end; end; end.
{VESA.PAS - version 4.0 (beta)} {XMS} {$A+,B-,D+,E+,F+,G-,I+,L+,N-,O-,P+,Q-,R-,S+,T-,V+,X+} {$M 16384,0,655360} Unit VESA; Interface Const {Графические режимы} M640x400=$100; M640x480=$101; M800x600=$103; M1024x768=$105; M1280x1024=$107; {Режимы вывода изображения} NormalPut=0; AndPut=2; XorPut=4; OrPut=6; ShadowPut=8; {Режимы вывода тени} LightShadow=3; MediumShadow=4; DarkShadow=5; {Mouse buttons} NoButton=0; LeftButton=1; RightButton=2; BothButtons=3; {Active font} afRaster = true; afStroked = false; {структура, содержащая информацию о графическом режиме} type TModeInfoRec = record Mode: word; SizeX, SizeY: word; BitsPerPixel: byte; end; function SupportedModesCount: word; procedure GetSupportedModesInfo(var Buf); Procedure InitAll(Mode: word); Procedure DoneAll; Function LoadSpr(FileName:string):pointer; Function LoadSpr1(Var f:file):pointer; Procedure GetSpriteParameters(Var x,y,Size:word); procedure PictureToFile(x1, y1, x2, y2: integer; FileName: string); procedure PictureFromFile(x, y: integer; FileName: string); Procedure InitHiMem; Procedure DoneHiMem; Procedure FreeHiMem(Var _pp:pointer); Procedure GetHiMem(Var _pp:pointer;Size:longint); procedure WriteToHiMem(p: pointer; var Buf; Size: longint); procedure ReadFromHiMem(p: pointer; var Buf; Size: longint); Procedure VESADone; Procedure VESAInit(Mode:word); Procedure PutPixel(x,y:integer;Color:byte);Far; Procedure PutSprite(x,y:integer;p:pointer); Procedure PutImage(x,y:integer;p:pointer;Reg:integer); Procedure SetVisualPage(Page:word);Far; Procedure SetActivePage(Page:word);Far; Procedure SetWSize(x1,y1,x2,y2:integer);Far; procedure GetWSize(var x1, y1, x2, y2: integer); far; Procedure Line(x1,y1,x2,y2:integer); Procedure Circle(x,y,Radius:integer); procedure Ellipse(x, y, RadiusX, RadiusY: integer); Procedure SetColor(NewColor:byte);Far; Function GetColor:byte;Far; Procedure Bar(x1,y1,x2,y2:integer);Far; Procedure SetPalette(Var Palette);Far; procedure GetPalette(Var Palette); Procedure SetStandartPalette;Far; Procedure WaitVBL;Far; Function GetMaxX:integer;Far; Function GetMaxY:integer;Far; Function ImageSize(x1,y1,x2,y2:integer):longint; Procedure Rectangle(x1,y1,x2,y2:integer;Color1,Color2:byte); Procedure GetImage(x1,y1,x2,y2:integer;p:pointer); Function GetPixel(x,y:integer):byte;Far; Procedure OutTextXY(x,y:integer;Message:string);Far; function TextWidth(s:string): integer; function TextHeight(s:string): integer; Procedure SetUserCursor(p:pointer);Far; Procedure SetStandartCursor;Far; Procedure SetShadowMode(SM:byte);Far; procedure FloodFill(x, y: integer; BorderColor: byte); far; function Inside(x, y, x1, y1, x2, y2: integer): boolean; far; procedure LoadStrokedFont(FontFile: string); function StrokedFontName: string; function StrokedFontInfo: string; procedure SetActiveFont(AFont: boolean); {afRaster or afStroked} procedure SetStrokedFontScale(ScaleX, ScaleY: real); procedure SetUserRasterFont(var Font); far; procedure SetStandartRasterFont; far; Procedure ShowMouse;Far; Procedure HideMouse;Far; Procedure InitMouse;Far; Procedure DoneMouse;Far; Function MouseX:integer;Far; Function MouseY:integer;Far; Function MouseButton:integer;Far; procedure SetMousePosition(x, y: word); far; procedure SetMouseArea(x1, y1, x2, y2: word); far; Implementation uses XMS; Type pSpriteHeader=^SpriteHeader; SpriteHeader=Record Size: longint; Free: boolean; End; TFontCharacter = record Width: byte; Offs: word end; TCharacters = array [char] of TFontCharacter; TFontData = array [0 .. 60000] of shortint; PFontData = ^TFontData; TStrokedFont = record Height, Upper: byte; Count: word; First: byte; Name: string[4]; Info: string; Characters: TCharacters; Data: PFontData end; var Mem, VESAFlag, MouseFlag: boolean; HeaderSize: word; GraphMode: word; OldMode: byte; ModeAttrs: array [0..255] of byte; MyName, TempName: string[8]; CurSFont: TStrokedFont; ActiveFont, StrokedFontLoaded: boolean; FontScaleX, FontScaleY: real; SpriteX, SpriteY, SpriteSize: word; OldExitProc: pointer; {XMS variables} XMSBuffer: pointer; XMSBufferOffs, XMSBufferSize: word; Base: word; XMSSize, XMSOffset: longint; Header: SpriteHeader; { не } Reserve: byte; { разделять } {$L VESA.OBJ} Procedure PutPixel(x,y:integer;Color:byte);External; Procedure PutImage_(x,y:integer;p:pointer;Reg:integer);far;External; Procedure PutImage__(x,y:integer;p:pointer;Reg:integer; Offset: longint; BufSize, BufOffs: word);far;External; procedure PutSprite_(x, y: integer; p: pointer); far; external; procedure PutSprite__(x, y: integer; p: pointer; Offset: longint; BufSize, BufOffs: word); far; external; Procedure SetVisualPage(Page:word);External; Procedure SetActivePage(Page:word);External; Procedure VESAInit_;External; Procedure Line(x1,y1,x2,y2:integer);External; Procedure SetWSize(x1,y1,x2,y2:integer);External; procedure GetWSize(var x1, y1, x2, y2: integer); external; Procedure SetColor(NewColor:byte);External; Function GetColor:byte;External; Procedure Bar(x1,y1,x2,y2:integer);External; Procedure SetPalette(Var Palette);External; procedure GetPalette(var Palette); external; Procedure SetStandartPalette;External; Procedure GetImage_(x1,y1,x2,y2:integer;p:pointer); far; External; Procedure GetImage__(x1,y1,x2,y2:integer;p:pointer; Offset: longint; BufSize, BufOffs: word); far; External; Function GetPixel(x,y:integer):byte;External; Procedure OutText(x,y:integer;Message:string);Far;External; Procedure InitMouse;External; Procedure DoneMouse;External; Procedure ShowMouse;External; Procedure HideMouse;External; Function MouseX:integer;External; Function MouseY:integer;External; Function MouseButton:integer;External; procedure SetMousePosition(x, y: word); external; procedure SetMouseArea(x1, y1, x2, y2: word); external; Procedure WaitVBL;External; Function GetMaxX:integer;External; Function GetMaxY:integer;External; Procedure SetUserCursor(p:pointer);External; Procedure SetStandartCursor;External; Procedure SetShadowMode(SM:byte);External; procedure SetUserRasterFont(var Font); external; procedure SetStandartRasterFont; external; Procedure DoneHiMem; Begin FreeMem(XMSBuffer, $8001); DoneXMS; Mem := false End; Procedure Error(Message:string); Begin WriteLn('Ошибка: ',Message); If Mem Then DoneHiMem; Halt(1) End; function GetXMSOffset(p: pointer): longint; begin asm and word ptr p+2,0FFFh end; GetXMSOffset := longint(p); end; procedure FreeHiMem(var _pp: pointer); var p: pointer; Offset: longint; Offs: longint; Size, NewSize: longint; begin CopyEMBRev(XMSOffset); p := _pp; asm and word ptr p+2,0FFFh end; Offset := longint(p); Offset := Offset - HeaderSize; CopyHeader(Offset); NewSize := Header.Size; if Offset > 0 then begin Offs := 0; while (Offs <> Offset) and (Offs <> XMSSize) do begin CopyHeader(Offs); Offs := Offs + Header.Size; end; if Offs <> Offset then Error('VESA.FreeHiMem'); CopyHeader(Offs); if Header.Free then begin Offset := Offs; NewSize := NewSize + Header.Size; end; end; if Offset + NewSize < XMSSize then begin CopyHeader(Offset + NewSize); if Header.Free then NewSize := NewSize + Header.Size; end; Header.Size := NewSize; Header.Free := true; CopyHeaderRev(Offset); _pp := nil; CopyEMB(XMSOffset); end; procedure GetHiMem(var _pp:pointer; Size: longint); var Offset, Ost: longint; f: boolean; p: pointer; begin CopyEMBRev(XMSOffset); Offset := 0; f := false; repeat CopyHeader(Offset); if (Header.Size - HeaderSize >= Size) and Header.Free then f := true else Offset := Offset + Header.Size; until (Offset = XMSSize) or f; if not f then _pp := nil else begin p := pointer(Offset); asm or word ptr p+2,0F000h mov ax,HeaderSize add word ptr p,ax adc word ptr p+2,0 end; _pp := p; if Header.Size - HeaderSize - Size <= HeaderSize then begin Header.Free := false; CopyHeaderRev(Offset); end else begin Ost := Header.Size - Size - HeaderSize; Header.Size := Size + HeaderSize; Header.Free := false; CopyHeaderRev(Offset); Offset := Offset + Size + HeaderSize; Header.Size := Ost; Header.Free := true; CopyHeaderRev(Offset); end; end; CopyEMB(XMSOffset); end; procedure GetArea(Offset, Size: longint; var p: pointer; var RealSize: longint); begin if (Offset >= XMSOffset) and (Offset < XMSOffset + XMSBufferSize) then begin p := Ptr(Base, XMSBufferOffs + (Offset - XMSOffset)); RealSize := XMSOffset + XMSBufferSize - Offset; end else begin CopyEMBRev(XMSOffset); XMSOffset := Offset; CopyEMB(XMSOffset); p := Ptr(Base, XMSBufferOffs); RealSize := XMSBufferSize; end; if Size < RealSize then RealSize := Size; end; function LoadSprite(var f: file; RealSize: longint): pointer; var p1, p: pointer; Offset, Size: longint; x, s: word; begin GetHiMem(p, RealSize); if p = nil then LoadSprite := nil else begin LoadSprite := p; Offset := GetXMSOffset(p); while RealSize > 0 do begin GetArea(Offset, RealSize, p1, Size); BlockRead(f, p1^, Size); RealSize := RealSize - Size; Offset := Offset + Size; end; end; end; Procedure InitHiMem; var x: word; Offs: word; p: pointer; Begin InitXMS; GetMem(XMSBuffer, $8001); Mem := true; asm mov ax,word ptr XMSBuffer mov Offs,ax mov ax,word ptr XMSBuffer+2 mov Base,ax end; Base := Base + Offs div 16; XMSBufferOffs := Offs mod 16; x := $8000 - XMSBufferOffs; XMSBufferSize := $8000 - XMSBufferOffs; if x mod 2 = 1 then Inc(x); SetCopyParams(XMSBuffer, x); XMSSize := EMBSize; XMSSize := XMSSize * 1024; XMSOffset := 0; if HeaderSize mod 2 = 1 then SetHeaderParams(Addr(Header), HeaderSize + 1) else SetHeaderParams(Addr(Header), HeaderSize); CopyHeader(0); Header.Size := XMSSize; Header.Free := true; CopyHeaderRev(0); CopyEMB(XMSOffset); End; Procedure VESAInit(Mode:word); Begin New(CurSFont.Data); GraphMode:=Mode; Asm mov ah,0Fh int 10h mov byte ptr OldMode,al mov ax,ds mov es,ax mov di,offset ModeAttrs mov ax,4F01h mov cx,word ptr GraphMode int 10h mov ax,4F02h mov bx,word ptr GraphMode int 10h call far ptr VESAInit_ End; VESAFlag := true End; Procedure VESADone; Begin Asm mov ah,00h mov al,byte ptr OldMode int 10h End; Dispose(CurSFont.Data); VESAFlag := false End; Function ImageSize(x1,y1,x2,y2:integer): longint; Begin ImageSize:=Abs(longint(x2-x1+1)*longint(y2-y1+1))+4 End; Procedure Rectangle(x1,y1,x2,y2:integer;Color1,Color2:byte); Var c:byte; Begin c:=GetColor; SetColor(Color2); Line(x1,y2,x2,y2); Line(x2,y1,x2,y2); SetColor(Color1); Line(x1,y1,x1,y2); Line(x1,y1,x2,y1); SetColor(c) End; Procedure Circle(x,y,Radius:integer); Var CurX,CurY,Delta,q:integer; Color:byte; Begin Color:=GetColor; CurX:=0; CurY:=Radius; Delta:=1+Sqr(CurY-1)-Sqr(Radius); Repeat PutPixel(X-CurX,Y-CurY,Color); PutPixel(X+CurX,Y-CurY,Color); PutPixel(X-CurX,Y+CurY,Color); PutPixel(X+CurX,Y+CurY,Color); If Delta<0 Then Begin q:=((Delta+CurY) shl 1)-1; If q<=0 Then Begin Inc(CurX); Delta:=Delta+(CurX shl 1)+1 End Else Begin Inc(CurX); Dec(CurY); Delta:=Delta+(CurX shl 1)-(CurY shl 1)+2 End End Else If Delta>0 Then Begin q:=((Delta-CurX) shl 1)-1; If q<=0 Then Begin Inc(CurX); Dec(CurY); Delta:=Delta+(CurX shl 1)-(CurY shl 1)+2 End Else Begin Dec(CurY); Delta:=Delta-(CurY shl 1)+1 End End Else If Delta=0 Then Begin Inc(CurX); Dec(CurY); Delta:=Delta+(CurX shl 1)-(CurY shl 1)+2 End Until CurY<0 End; procedure Ellipse(x, y, RadiusX, RadiusY: integer); var i, j, r1, r2, t, Step:real; x1, x2, y1, y2: integer; c: byte; begin c := GetColor; x1 := x; x2 := x + RadiusX; y1 := y; y2 := y + RadiusY; if (x1 <> x2) and (y1 <> y2) then begin i := x2; j := y2; r1 := Abs(x1 - i); r2 := Abs(y1 - j); t := 0.0; if RadiusX > RadiusY then Step := 1 / RadiusX else Step := 1 / RadiusY; while t <= 2 * Pi do begin i := r1 * Cos(t) + x1; j := r2 * Sin(t) + y1; PutPixel(Round(i), Round(j), c); t := t + Step; end end else Line(x2, y2, x2 + 2 * (x1 - x2), y2 + 2 * (y1 - y2)); end; procedure StrokedOutText(x, y: integer; s: string); var CurX, CurY, OldX, OldY, i, xx, a, b: integer; Sm: word; cx, cy: shortint; begin OldX := x; OldY := y + Round(CurSFont.Upper * FontScaleY); CurX := OldX; CurY := OldY; for i := 1 to Length(s) do begin xx := Ord(s[i]); if (xx >= CurSFont.First) and (xx <= CurSFont.First + CurSFont.Count - 1) then begin Sm := CurSFont.Characters[s[i]].Offs; cx := CurSFont.Data^[Sm]; Inc(Sm); while cx and $80 <> 0 do begin cy := CurSFont.Data^[Sm]; Inc(Sm); if cy and $80 <> 0 then begin cx := cx and $7F; cy := cy and $7F; if cx and $40 <> 0 then cx := cx or $80; if cy and $40 <> 0 then cy := cy or $80; a := Round(cx * FontScaleX); b := Round(cy * FontScaleY); Line(OldX, OldY, CurX + a, CurY - b); end else begin cx := cx and $7F; cy := cy and $7F; if cx and $40 <> 0 then cx := cx or $80; if cy and $40 <> 0 then cy := cy or $80; a := Round(cx * FontScaleX); b := Round(cy * FontScaleY); end; OldX := CurX + a; OldY := CurY - b; cx := CurSFont.Data^[Sm]; Inc(Sm); end; CurX := OldX; CurY := OldY end end end; Procedure OutTextXY(x,y:integer;Message:string); Begin If Message<>'' Then begin if ActiveFont = afRaster then OutText(x,y,Message) else StrokedOutText(x, y, Message) end End; Function TextHeight(s: string): integer; begin if ActiveFont = afRaster then TextHeight := 16 else TextHeight := Round(CurSFont.Height * FontScaleY) end; function TextWidth(s: string): integer; var i: integer; Width: integer; begin if ActiveFont = afRaster then TextWidth := Length(s) * 8 else begin Width := 0; for i := 1 to Length(s) do if (Ord(s[i]) >= CurSFont.First) and (Ord(s[i]) <= CurSFont.First + CurSFont.Count - 1) then Width := Width + Round(CurSFont.Characters[s[i]].Width * FontScaleX); TextWidth := Width end end; function PointerToXMS(p: pointer): boolean; var HighByte: byte; pp: pointer; begin pp := p; asm mov ax,word ptr pp+2 mov cl,4 shr ah,cl mov HighByte,ah end; PointerToXMS := HighByte = $0F; end; procedure PutSprite(x, y: integer; p: pointer); var pp: pointer; Offset, s: longint; begin if PointerToXMS(p) then begin Offset := GetXMSOffset(p); GetArea(Offset, XMSBufferSize, pp, s); PutSprite__(x, y, pp, Offset, XMSBufferSize, XMSBufferOffs); end else PutSprite_(x, y, p); end; procedure WriteToHiMem(p: pointer; var Buf; Size: longint); var pp, b: pointer; s, Offset: longint; SaveSI: word; begin b := Addr(Buf); Offset := GetXMSOffset(p); SaveSI := word(b); while Size > 0 do begin GetArea(Offset, Size, pp, s); Size := Size - s; Offset := Offset + s; asm push cx push si push di push ds push es mov cx,word ptr s les di,pp lds si,b mov si,SaveSI cld rep movsb mov SaveSI,si pop es pop ds pop di pop si pop cx end; end; end; procedure ReadFromHiMem(p: pointer; var Buf; Size: longint); var pp, b: pointer; s, Offset: longint; SaveDI: word; begin b := Addr(Buf); Offset := GetXMSOffset(p); SaveDI := word(b); while Size > 0 do begin GetArea(Offset, Size, pp, s); Size := Size - s; Offset := Offset + s; asm push cx push si push di push ds push es mov cx,word ptr s les di,b mov di,SaveDI lds si,pp cld rep movsb mov SaveDI,di pop es pop ds pop di pop si pop cx end; end; end; Procedure PutImage(x,y:integer;p:pointer;Reg:integer); var Offset, s: longint; pp: pointer; Begin if PointerToXMS(p) then begin Offset := GetXMSOffset(p); GetArea(Offset, XMSBufferSize, pp, s); PutImage__(x, y, pp, Reg, Offset, XMSBufferSize, XMSBufferOffs); end else PutImage_(x, y, p, Reg); End; Procedure GetImage(x1,y1,x2,y2:integer;p:pointer); Var Offset, s: longint; pp: pointer; Begin if PointerToXMS(p) then begin Offset := GetXMSOffset(p); GetArea(Offset, XMSBufferSize, pp, s); GetImage__(x1, y1, x2, y2, pp, Offset, XMSBufferSize, XMSBufferOffs); end else GetImage_(x1, y1, x2, y2, p); End; {Borland stroked fonts} procedure LoadStrokedFont(FontFile: string); var f: file; c: char; x: byte; y, Table, CWidth, CPointer, i, Result: word; z: shortint; begin Assign(f, FontFile); Reset(f, 1); Seek(f, $04); x := 0; repeat BlockRead(f, c, 1); if c <> #26 then begin Inc(x); CurSFont.Info[x] := c end; until c = #26; CurSFont.Info[0] := Chr(x); BlockRead(f, y, 2); CurSFont.Name[0] := #04; BlockRead(f, CurSFont.Name[1], 4); Seek(f, $81); CurSFont.Count := 0; BlockRead(f, CurSFont.Count, 1); if CurSFont.Count = 0 then CurSFont.Count := 256; Seek(f, $84); BlockRead(f, CurSFont.First, 1); BlockRead(f, Table, 2); Table := Table + $80; Seek(f, $88); BlockRead(f, CurSFont.Upper, 1); Seek(f, $8A); BlockRead(f, z, 1); CurSFont.Height := CurSFont.Upper - z; CPointer := $90; CWidth := CPointer + CurSFont.Count * 2; c := Chr(CurSFont.First); for i := 1 to CurSFont.Count do begin Seek(f, CWidth); BlockRead(f, CurSFont.Characters[c].Width, 1); Seek(f, CPointer); BlockRead(f, CurSFont.Characters[c].Offs, 2); Inc(CWidth); CPointer := CPointer + 2; if c <> #255 then c := Succ(c) end; Seek(f, Table); BlockRead(f, CurSFont.Data^, 60000, Result); Close(f); StrokedFontLoaded := true end; function StrokedFontName: string; begin if StrokedFontLoaded then StrokedFontName := CurSFont.Name end; function StrokedFontInfo: string; begin if StrokedFontLoaded then StrokedFontInfo := CurSFont.Info end; procedure SetActiveFont(AFont: boolean); begin if not ((AFont = afStroked) and not StrokedFontLoaded) then ActiveFont := AFont end; procedure SetStrokedFontScale(ScaleX, ScaleY: real); begin FontScaleX := ScaleX; FontScaleY := ScaleY end; Procedure InitAll(Mode: word); Begin VESAInit(Mode); InitHiMem; InitMouse End; Procedure DoneAll; Begin DoneMouse; DoneHiMem; VESADone End; Function LoadSpr(FileName:string):pointer; Var f:file; RealSize: longint; Begin Assign(f,FileName); {$I-} Reset(f,1); If IOResult=0 Then Begin LoadSpr := LoadSpr1(f); Close(f) End; {$I+} End; Function LoadSpr1(Var f:file):pointer; Var RealSize: longint; Begin BlockRead(f,SpriteX,2); BlockRead(f,SpriteY,2); BlockRead(f,SpriteSize,2); RealSize := SpriteX; RealSize := RealSize * SpriteY + 4; LoadSpr1 := LoadSprite(f, RealSize); End; Procedure GetSpriteParameters(Var x,y,Size:word); Begin x:=SpriteX; y:=SpriteY; Size:=SpriteSize End; procedure PictureToFile(x1, y1, x2, y2: integer; FileName: string); var f: file; p: pointer; x: word; i: integer; begin Assign(f, FileName); Rewrite(f, 1); x := x2 - x1 + 1; BlockWrite(f, x, 2); x := y2 - y1 + 1; BlockWrite(f, x, 2); GetMem(p, ImageSize(x1, 0, x2, 0)); for i := y1 to y2 do begin GetImage(x1, i, x2, i, p); BlockWrite(f, p^, ImageSize(x1, 0, x2, 0)) end; FreeMem(p, ImageSize(x1, 0, x2, 0)); Close(f) end; procedure PictureFromFile(x, y: integer; FileName: string); var p: pointer; f: file; i: integer; sx, sy: word; begin Assign(f, FileName); Reset(f, 1); BlockRead(f, sx, 2); BlockRead(f, sy, 2); GetMem(p, ImageSize(1, 0, sx, 0)); for i := y to y + sy - 1 do begin BlockRead(f, p^, ImageSize(1, 0, sx, 0)); PutSprite(x, i, p) end; FreeMem(p, ImageSize(1, 0, sx, 0)); Close(f) end; procedure Exchange(var x, y: integer); var z: integer; begin if x > y then begin z := x; x := y; y := z; end; end; function Inside(x, y, x1, y1, x2, y2: integer): boolean; begin Exchange(x1, x2); Exchange(y1, y2); Inside := (x >= x1) and (x <= x2) and (y >= y1) and (y <= y2); end; procedure FloodFill(x, y: integer; BorderColor: byte); type TStack = array [1 .. 1000] of integer; var Top: integer; StackX, StackY: TStack; xx, yy, xm, xr, xl, j: integer; c, cc: byte; f: boolean; begin c := GetColor; Top := 1; StackX[Top] := x; StackY[Top] := y; while Top <> 0 do begin xx := StackX[Top]; yy := StackY[Top]; Dec(Top); PutPixel(xx, yy, c); xm := xx; while (GetPixel(xx, yy) <> BorderColor) and (xx <= GetMaxX) do begin PutPixel(xx, yy, c); Inc(xx); end; xr := xx - 1; xx := xm; while (GetPixel(xx, yy) <> BorderColor) and (xx >= 0) do begin PutPixel(xx, yy, c); Dec(xx); end; xl := xx + 1; j := 1; repeat yy := yy + j; if (yy >= 0) and (yy <= GetMaxY) then begin xx := xl; while xx <= xr do begin f := false; cc := GetPixel(xx, yy); while (cc <> BorderColor) and (cc <> c) and (xx < xr) do begin f := true; Inc(xx); cc := GetPixel(xx, yy); end; if f then begin Inc(Top); StackX[Top] := xx - 1; StackY[Top] := yy; end; repeat Inc(xx); cc := GetPixel(xx, yy); until not ((cc = BorderColor) or (cc = c) and (xx < xr)); end; end; j := j - 3; until not (j >= -2); end; end; procedure ExitProcedure; far; begin ExitProc := OldExitProc; if MouseFlag then DoneMouse; if Mem then DoneHiMem; if VESAFlag then VESADone end; function SupportedModesCount: word; var p, p1: pointer; Count: word; begin GetMem(p, 1024); GetMem(p1, 512); Count := 0; asm les di,dword ptr p mov ax,4F00h int 10h les di,dword ptr es:[di+0Eh] @NextMode: cmp word ptr es:[di],0FFFFh jz @EndOfList push es push di mov ax,4F01h mov cx,es:[di] les di,dword ptr p1 int 10h cmp ax,004Fh jnz @NotSupported mov al,es:[di] test al,01h jz @NotSupported test al,10h jz @NotSupported cmp byte ptr es:[di+19h],8 jnz @NotSupported inc word ptr Count @NotSupported: pop di pop es add di,2 jmp @NextMode @EndOfList: end; FreeMem(p, 1024); FreeMem(p1, 512); SupportedModesCount := Count; end; procedure GetSupportedModesInfo(var Buf); var p, p1, _p: pointer; begin GetMem(p, 1024); GetMem(p1, 512); _p := Addr(Buf); asm les di,dword ptr p mov ax,4F00h int 10h les di,dword ptr es:[di+0Eh] @NextMode: cmp word ptr es:[di],0FFFFh jz @EndOfList push es push di mov ax,4F01h mov cx,es:[di] les di,dword ptr p1 int 10h cmp ax,004Fh jnz @NotSupported mov al,es:[di] test al,01h jz @NotSupported test al,10h jz @NotSupported cmp byte ptr es:[di+19h],8 jnz @NotSupported push ds lds si,dword ptr _p mov [si],cx mov ax,es:[di+12h] mov [si+2],ax mov ax,es:[di+14h] mov [si+4],ax mov al,es:[di+19h] mov [si+6],al pop ds add word ptr _p,7 @NotSupported: pop di pop es add di,2 jmp @NextMode @EndOfList: end; FreeMem(p, 1024); FreeMem(p1, 512); end; Begin OldExitProc := ExitProc; ExitProc := Addr(ExitProcedure); HeaderSize:=SizeOf(SpriteHeader); Mem:=False; VESAFlag := false; MouseFlag := false; MyName:='VESAMode'; TempName:=' '; ActiveFont := afRaster; StrokedFontLoaded := false; FontScaleX := 1; FontScaleY := 1; End.
unit K332563400; {* [RequestLink:332563400] } // Модуль: "w:\common\components\rtl\Garant\Daily\K332563400.pas" // Стереотип: "TestCase" // Элемент модели: "K332563400" MUID: (4F2694F901CD) // Имя типа: "TK332563400" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoEVDWriterTest ; type TK332563400 = class(TEVDtoEVDWriterTest) {* [RequestLink:332563400] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK332563400 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *4F2694F901CDimpl_uses* //#UC END# *4F2694F901CDimpl_uses* ; function TK332563400.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'NSRC 7.7'; end;//TK332563400.GetFolder function TK332563400.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4F2694F901CD'; end;//TK332563400.GetModelElementGUID initialization TestFramework.RegisterTest(TK332563400.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit Service; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Vcl.ExtCtrls, XSuperObject, IdGlobal, System.DateUtils, Forms, IniFiles, Constants, IdStack; type TRCore = class(TDataModule) TimerWDog: TTimer; TimerStart: TTimer; procedure DataModuleCreate(Sender: TObject); procedure TimerStartTimer(Sender: TObject); procedure TimerWDogTimer(Sender: TObject); private function ReadIniFile: boolean; procedure CheckTests; public Host : string; DevID : integer; DevUID : string; Name : string; DevClass : word; SessionID : string; LogFileName : string; TextEncode : IIdTextEncoding; DataLoaded : boolean; ControlPCN : boolean; // контролировать или нет распределение по пультам CheckClientTime : TDateTime; CheckTestTime : TDateTime; SetFlagTime : TDateTime; NextPingTime : TDateTime; DeltaTime : integer; // разница во времени с ядром (в секундах) SlotDmgDelay : integer; // задержка перевода слота в аварию, сек ESetUpdateState : TEventSet; // набор событий, которые изменяют статус объекта ESetDeleteAlarm : TEventSet; // набор событий, которые удаляют тревогу ESetAddAlarm : TEventSet; // набор событий, которые создают тревогу LocalAddresses : TStrings; // список IP адресов const PING_PERIOD = 1000; //милисекунды CHECK_CLIENT_PERIOD = 2900; //милисекунды CHECK_TESTS_PERIOD = 10; // секунды CHECK_PREALARMS_PERIOD = 3; // секунды SET_FLAG_PERIOD = 2000; ///милисекунды EVENT_FILE_NAME = 'REvents.txt'; procedure StopWork; end; const AppVersion = 2022; var RCore: TRCore; procedure LogOut(LogStr:string); procedure StopService; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses FormMain, Global, PCN, EventUnit, DataUnit, HTTP_Client; {$R *.dfm} procedure LogOut(LogStr:string); var F: TextFile; DT: TDateTime; begin DT := IncSecond(Now, RCore.DeltaTime); LogStr := DateTimeToStr(DT) + ' ' + LogStr; fmMain.Memo1.Lines.Add(LogStr); AssignFile(F, RCore.LogFileName); {$I-} Append(F); {$I+} if IOResult <> 0 then begin LogOut('Ошибка доступа к файлу ' + RCore.LogFileName); Exit; end; Writeln(F, LogStr); CloseFile(F); end; procedure StopService; begin LogOut('Служба остановлена'); fmMain.Close; end; procedure TRCore.DataModuleCreate(Sender: TObject); var F: TextFile; i: integer; begin ESetUpdateState := [EvTypeArm, EvTypeDisArm, EvTypeAlarm, EvTypeFire, EvTypeHiJack, EvTypePreAlarm, EvTypeDamageDevice, EvTypeDamageLink, EvTypeDamagePower, EvTypeRepairDevice, EvTypeRepairLink, EvTypeRepairPower, EvTypeDropAlarm, EvTypeDropDamageDevice, EvTypeDropDamageLink, EvTypeDropDamagePower, EvTypeTestUp, EvTypeTestDown]; ESetDeleteAlarm := [EvTypeArm, EvTypeDisArm, EvTypeRepairDevice, EvTypeRepairLink, EvTypeRepairPower, EvTypeTestUp, EvTypeDropAlarm, EvTypeDropDamageDevice, EvTypeDropDamageLink, EvTypeDropDamagePower, EvTypeDropAlarm]; ESetAddAlarm := [EvTypeAlarm, EvTypeFire, EvTypeHiJack, EvTypeDamageDevice, EvTypeDamageLink, EvTypeDamagePower, EvTypeTestDown, EvTypePreAlarm]; if not DirectoryExists(ExtractFilePath(Application.ExeName) + 'Logs\Radio') then CreateDir(ExtractFilePath(Application.ExeName) + 'Logs\Radio'); if not DirectoryExists(ExtractFilePath(Application.ExeName) + 'Data') then CreateDir(ExtractFilePath(Application.ExeName) + 'Data'); LogFileName := ExtractFilePath(Application.ExeName) + 'Logs\Radio\' + 'Radio_' + FormatDateTime('yyyy-mm-dd hh-mm-ss', Now) + '.log'; if not FileExists(LogFileName) then begin AssignFile(F, LogFileName); Rewrite(F); CloseFile(F); end; HttpLink := THttpLink.Create; NextPingTime := IncMilliSecond(Now, PING_PERIOD); DataLoaded := False; CoreServer := TFriServer.Create; DataServer := TFriServer.Create; DevClass := Byte(DevClassDriverRadio); end; function TRCore.ReadIniFile: boolean; var IniFile : TIniFile; FileName:string; F:TextFile; FormatStr:string; begin Result := True; FileName := ExtractFilePath(Application.ExeName) + 'Config.ini'; if FileExists(FileName) then begin IniFile := TIniFile.Create(FileName); // DevID := IniFile.ReadInteger('RadioDriver', 'ID', 0); // DevUID := IniFile.ReadString('RadioDriver', 'UID', ''); // // SlotDmgDelay := IniFile.ReadInteger('RadioServer','SlotDmgDelay', 600); CoreServer.DevId := IniFile.ReadInteger('MainCore','ID',0); CoreServer.Port := IniFile.ReadInteger('MainCore','Port',0); CoreServer.Host := IniFile.ReadString('MainCore','Host',''); CoreServer.DevUID := IniFile.ReadString('MainCore','UID',''); DataServer.DevId := IniFile.ReadInteger('DataDriver','ID',0); DataServer.Port := IniFile.ReadInteger('DataDriver','Port',0); DataServer.Host := IniFile.ReadString('DataDriver','Host',''); DataServer.DevUID := IniFile.ReadString('DataDriver','UID',''); IniFile.Free; // if DevID = 0 then // begin // LogOut('Не заполнен параметр - ИД радио драйвера'); // Result := False; // end; // if DevUID = '' then // begin // LogOut('Не заполнен параметр - УИД радио драйвера'); // Result := False; // end; if CoreServer.Port = 0 then begin LogOut('Не заполнен параметр - HTTP порт ядра'); Result := False; end; if CoreServer.Host = '' then begin LogOut('Не заполнен параметр - адрес ядра'); Result := False; end; if CoreServer.DevId = 0 then begin LogOut('Не заполнен параметр - ИД ядра'); Result := False; end; if CoreServer.DevUID = '' then begin LogOut('Не заполнен параметр - УИД ядра'); Result := False; end; if DataServer.Port = 0 then begin LogOut('Не заполнен параметр - HTTP порт драйвера данных'); Result := False; end; if DataServer.Host = '' then begin LogOut('Не заполнен параметр - адрес драйвера данных'); Result := False; end; if DataServer.DevId = 0 then begin LogOut('Не заполнен параметр - ИД драйвера данных'); Result := False; end; if DataServer.DevUID = '' then begin LogOut('Не заполнен параметр - УИД драйвера данных'); Result := False; end; LogOut('HTTP порт ядро = ' + IntToStr(CoreServer.Port)); LogOut('Хост ядро = ' + CoreServer.Host); end else begin LogOut('Не найден файл config.ini'); Result := False; end; end; procedure TRCore.TimerStartTimer(Sender: TObject); begin LocalAddresses := GStack.LocalAddresses; LocalAddresses.Add('127.0.0.1'); LocalAddresses.Add('localhost'); TimerStart.Enabled := False; if not ReadIniFile then begin LogOut('Ошибка чтения ini файла'); StopService; Exit; end; CheckClientTime := IncMilliSecond(Now, CHECK_CLIENT_PERIOD); CheckTestTime := IncSecond(Now, CHECK_TESTS_PERIOD); RCore.TimerWDog.Enabled := True; end; procedure TRCore.TimerWDogTimer(Sender: TObject); var i, j: integer; RX, AddInfo: string; Event : TPcnEvent; EventsBuf : ISuperArray; RadioPCN: TPultHolder; begin if Now > NextPingTime then begin NextPingTime := IncMilliSecond(Now, PING_PERIOD); if not DataLoaded then begin HttpLink.RequestData; Exit; end; if RCore.SessionID = '' then begin if not HttpLink.StartSession then Exit; end; HttpLink.Ping(CoreServer); end; if not HttpLink.OnLink then Exit; if not DataLoaded then Exit; if Now > CheckTestTime then begin TimerWDog.Enabled := False; try CheckTestTime := IncSecond(Now, CHECK_TESTS_PERIOD); CheckTests; finally TimerWDog.Enabled := True; end; end; for i := 0 to High(PHolders) do begin RadioPCN := PHolders[i]; if RadioPCN.CommHandle = InvalidID then begin if not RadioPCN.OpenComPort then begin if RadioPCN.Control.State <> PcnStateDown then begin AddInfo := 'Ошибка открытия ком. порта ' + RadioPCN.Control.ComPortName; with RadioPCN do GenEvent(PultID, Control.PULT_CLASS, Byte(EventTypeDamageDevice), AddInfo); RadioPCN.Control.State := PcnStateDown; LogOut(AddInfo); Continue; end; end; end; if PHolders[i].Control.PULT_CLASS = Byte(DevClassRadioPcnProton) then begin Event := PHolders[i].ReadAsProton; PHolders[i].WorkMessage(Event); end; if (SecondsBetween(Now, PHolders[i].Control.LastEvent) > 4) and (PHolders[i].Control.State <> PcnStateDown) then begin PHolders[i].Control.State := PcnStateDown; with PHolders[i] do GenEvent(PultID, Control.PULT_CLASS, Byte(EventTypeDamageDevice), 'Таймаут событий. Ком. порт - ' + Control.ComPortName); for j := 0 to High(PHolders[i].Childs) do begin with PHolders[i] do GenEvent(Childs[j].ID, Childs[j].PULT_CLASS, Byte(EventTypeDamageDevice), 'При аварии ПЦН'); PHolders[i].Childs[j].State := PcnStateDown; end; end; for j := 0 to High(PHolders[i].Childs) do begin if (MinutesBetween(Now, PHolders[i].Childs[j].LastEvent) > PHolders[i].Childs[j].PrmTimout) and (PHolders[i].Childs[j].State <> PcnStateDown) then begin with PHolders[i] do GenEvent(Childs[j].ID, Childs[j].PULT_CLASS, Byte(EventTypeDamageDevice), 'Таймаут событий'); PHolders[i].Childs[j].State := PcnStateDown; end; end; end; end; procedure TRCore.CheckTests; var i, j: integer; Test: TTest; Prd: TPrd; begin // LogOut('Check tests +++++++++'); for i := 0 to High(Prds) do begin if Prds[i] = nil then begin Continue; end; Prd := Prds[i]; if not Prd.IS_ACTIVE then Continue; Test := AData.GetTest(Prd); if Now > Test.NEXT_TEST then begin GenEvent(Prd.ID, Byte(DevClassPrd), Byte(EventTypeTestLoss), 'Таймаут ожидания теста', Prd.CUST); Test.NEXT_TEST := IncMinute(Now, Prd.TEST_PER); end; end; end; procedure TRCore.StopWork; var i: integer; Buf: ISuperArray; begin for i := 0 to High(PHolders) do begin if PHolders[i].CommHandle <> InvalidID then PHolders[i].CloseComPort; end; // HttpLink.Client.ClientBuf.SaveTo('Events.txt'); // HttpLink.Client.Clear; end; end.
unit RetroClock; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, DrawnControl; type TClockScaleLineIndex = 0..59; { TClockScaleLines } TClockScaleLines = class(TDrawing) private FCenter: TPoint; FBaseLineLength: Integer; FRadius: Integer; function GetShiftFromCenter(Index: TClockScaleLineIndex): TPoint; function GetLineAngle(Index: TClockScaleLineIndex): Extended; function GetLineLength(Index: TClockScaleLineIndex): Integer; function GetLines(Index: TClockScaleLineIndex): TLine; procedure SetBaseLineLength(AValue: Integer); procedure SetCenter(AValue: TPoint); procedure SetRadius(AValue: Integer); protected procedure Resize; override; procedure Zoom(CP: TPoint; Factor: Extended); override; public constructor Create(AOwner: TComponent); override; property Center: TPoint read FCenter write SetCenter; property Lines[Index: TClockScaleLineIndex]: TLine read GetLines; property Radius: Integer read FRadius write SetRadius; published property BaseLineLength: Integer read FBaseLineLength write SetBaseLineLength; end; { TClockScale } TClockScale = class(TDrawing) private FCenter: TPoint; FClockScaleLines: TClockScaleLines; FRadius: Integer; function GetLines(Index: TClockScaleLineIndex): TLine; procedure SetCenter(AValue: TPoint); procedure SetRadius(AValue: Integer); property ClockScaleLines: TClockScaleLines read FClockScaleLines write FClockScaleLines; protected procedure Resize; override; procedure Shift(V: TPoint); override; public constructor Create(AOwner: TComponent); override; property Center: TPoint read FCenter write SetCenter; property Radius: Integer read FRadius write SetRadius; end; { TClock } TClock = class(TDrawing) private FFrame: TWSRectangle; FCenter: TPoint; FDiameter: Integer; FHourPtr, FMinPtr, FSecPtr: TRotativePointer; FScale: TClockScale; FTime: TDateTime; function GetHourPtr: TRotativePointer; function GetMinPtr: TRotativePointer; function GetRadius: Integer; function GetScale: TClockScale; function GetSecPtr: TRotativePointer; procedure SetCenter(AValue: TPoint); procedure SetDiameter(AValue: Integer); procedure SetRadius(AValue: Integer); protected procedure Draw; override; procedure Resize; override; public constructor Create(AOwner: TComponent); override; property Center: TPoint read FCenter write SetCenter; property Frame: TWSRectangle read FFrame write FFrame; property Scale: TClockScale read FScale write FScale; property HourPtr: TRotativePointer read FHourPtr write FHourPtr; property MinPtr: TRotativePointer read FMinPtr write FMinPtr; property SecPtr: TRotativePointer read FSecPtr write FSecPtr; property Time: TDateTime read FTime; published property Diameter: Integer read FDiameter write SetDiameter; property Radius: Integer read GetRadius write SetRadius; end; type { TRetroClock } TRetroClock = class(TDrawnControl) private function GetClock: TClock; protected class function GetDrawingClass: TDrawingClass; override; public constructor Create(AOwner: TComponent); override; property Clock: TClock read GetClock; published property Align; property Anchors; end; procedure Register; implementation procedure Register; begin RegisterComponents('HMI',[TRetroClock]); end; function Min(x, y: Integer): Integer; overload; begin if x < y then Result := x else Result := y end; { TClockScaleLines } function TClockScaleLines.GetShiftFromCenter(Index: TClockScaleLineIndex): TPoint; var Length, Angle: Extended; begin Length := GetLineLength(Index); Angle := GetLineAngle(Index); Result.X := Round((Radius - Length) * Cos(Angle)); Result.Y := Round((Radius - Length) * Sin(Angle)); end; function TClockScaleLines.GetLineAngle(Index: TClockScaleLineIndex): Extended; begin Result := Index / 30 * Pi - Pi / 2 end; function TClockScaleLines.GetLineLength(Index: TClockScaleLineIndex): Integer; begin Result := BaseLineLength; if Index mod 5 = 0 then Result := Result * 2; if Index mod 15 = 0 then Result := Result * 2 end; function TClockScaleLines.GetLines(Index: TClockScaleLineIndex): TLine; begin Result := Elements[Index] as TLine end; procedure TClockScaleLines.SetBaseLineLength(AValue: Integer); var i: Integer; EP: TPoint; begin if FBaseLineLength = AValue then Exit; FBaseLineLength := AValue; for i := Low(TClockScaleLineIndex) to Min(High(TClockScaleLineIndex), ElementCount - 1) do begin EP := Lines[i].EP; Lines[i].Length := GetLineLength(i); Lines[i].SP := Lines[i].SP + EP - Lines[i].EP; end; end; procedure TClockScaleLines.SetCenter(AValue: TPoint); var V: TPoint; begin if AValue = FCenter then Exit; V := AValue - FCenter; FCenter := AValue; Shift(V) end; procedure TClockScaleLines.SetRadius(AValue: Integer); begin if FRadius=AValue then Exit; FRadius:=AValue; end; procedure TClockScaleLines.Resize; var i: TClockScaleLineIndex; begin for i := Low(TClockScaleLineIndex) to High(TClockScaleLineIndex) do begin Lines[i].SP := Center + GetShiftFromCenter(i); Lines[i].Angle:= GetLineAngle(i); Lines[i].Length := GetLineLength(i); end; {inherited Resize; the Elements have no own Resize procedure} end; procedure TClockScaleLines.Zoom(CP: TPoint; Factor: Extended); var V: TPoint; begin V := Center - CP; VectorZoom(V, Factor); Center := Center + V; Radius := Round(Radius * Factor); BaseLineLength := Round(BaseLineLength * Factor); Radius := Round(Radius * Factor); inherited Zoom(CP, Factor); end; constructor TClockScaleLines.Create(AOwner: TComponent); var i: Integer; Line: TLine; begin inherited Create(AOwner); BaseLineLength := 32; for i := Low(TClockScaleLineIndex) to High(TClockScaleLineIndex) do begin Line := TLine.Create(Self); Line.SP := Center + GetShiftFromCenter(i); Line.Angle:= -Pi / 2 + i / 30 * Pi; Line.Length := GetLineLength(i); Line.Pen.Color := clBlack; AddElement(Line); end; end; { TClockScale } procedure TClockScale.SetCenter(AValue: TPoint); begin if FCenter=AValue then Exit; FCenter:=AValue; end; function TClockScale.GetLines(Index: TClockScaleLineIndex): TLine; begin Result := Elements[Index] as TLine end; procedure TClockScale.SetRadius(AValue: Integer); begin if FRadius=AValue then Exit; FRadius:=AValue; end; procedure TClockScale.Resize; begin ClockScaleLines.Center := Center; ClockScaleLines.Radius := Radius; ClockScaleLines.BaseLineLength := Round(0.1 * Radius); inherited Resize; end; procedure TClockScale.Shift(V: TPoint); begin Center := Center + V; inherited Shift(V); end; constructor TClockScale.Create(AOwner: TComponent); begin inherited Create(AOwner); ClockScaleLines := TClockScaleLines.Create(Self); ClockScaleLines.Center := Center; ClockScaleLines.Radius := Radius; ClockScaleLines.BaseLineLength := Round(0.1 * Radius); AddElement(ClockScaleLines); end; { TClock } procedure TClock.Draw; var h, min, s, ms: Word; begin FTime := Now; DecodeTime(Time, h, min, s, ms); if h > 12 then h := h - 12; HourPtr.Angle := (h + min / 60) / 6 * Pi; MinPtr.Angle := min / 30 * Pi; SecPtr.Angle := s / 30 * Pi; inherited Draw; end; function TClock.GetHourPtr: TRotativePointer; begin if not Assigned(FHourPtr) then begin FHourPtr := TRotativePointer.Create(Self); FHourPtr.Offset := -Pi / 2; AddElement(FHourPtr); {Resize} end; Result := FHourPtr; end; function TClock.GetMinPtr: TRotativePointer; begin if not Assigned(FMinPtr) then begin FMinPtr := TRotativePointer.Create(Self); FMinPtr.Pen.Color := clOlive; FMinPtr.Offset := -Pi / 2; AddElement(FMinPtr); {Resize} end; Result := FMinPtr; end; function TClock.GetRadius: Integer; begin Result := Diameter div 2 end; function TClock.GetScale: TClockScale; begin if not Assigned(FScale) then begin FScale := TClockScale.Create(Self); AddElement(FScale); {Resize;} end; Result := FScale; end; function TClock.GetSecPtr: TRotativePointer; begin if not Assigned(FSecPtr) then begin FSecPtr := TRotativePointer.Create(Self); FSecPtr.Pen.Color := clRed; FSecPtr.Offset := -Pi / 2; AddElement(FSecPtr); {Resize} end; Result := FSecPtr end; procedure TClock.SetCenter(AValue: TPoint); begin if FCenter = AValue then Exit; FCenter := AValue; end; procedure TClock.SetDiameter(AValue: Integer); begin if FDiameter = AValue then Exit; Zoom(Center, AValue / FDiameter); FDiameter := AValue; end; procedure TClock.SetRadius(AValue: Integer); begin SetDiameter(AValue * 2); end; procedure TClock.Resize; begin Frame.Left := 0; Frame.Top := 0; Frame.Height := Control.Height; Frame.Width := Control.Width; Center := Point(Control.Width div 2, Control.Height div 2); Diameter := Round(0.9 * Min(Control.Width, Control.Height)); Scale.Radius := Radius; Scale.Center := Center; HourPtr.Center := Center; HourPtr.Radius := Round(0.67 * 0.9 * Radius); MinPtr.Center := Center; MinPtr.Radius := Round(0.9 * Radius); SecPtr.Center := Center; SecPtr.Radius := MinPtr.Radius; SecPtr.Angle := 0; inherited Resize; end; constructor TClock.Create(AOwner: TComponent); var MinPtrRadius, i: Integer; begin inherited Create(AOwner); Frame := TWSRectangle.Create(Self); Frame.Brush.Color := clOlive; Frame.Pen.Color := $2080E0; Frame.Pen.Width := 8; AddElement(Frame); Scale := TClockScale.Create(Self); Scale.Center := Center; Scale.Radius := Radius; for i := Low(TClockScaleLineIndex) to High(TClockScaleLineIndex) do Scale.ClockScaleLines.Lines[i].Pen.Color := clWhite; AddElement(Scale); MinPtrRadius := Scale.ClockScaleLines.Radius - Scale.ClockScaleLines.BaseLineLength; HourPtr := TRotativePointer.Create(Self); HourPtr.Center := Scale.Center; HourPtr.Radius := MinPtrRadius * 3 div 3; HourPtr.Offset := -Pi / 2; HourPtr.Pen.Color := clWhite; HourPtr.Pen.Width := 4; AddElement(HourPtr); MinPtr := TRotativePointer.Create(Self); MinPtr.Center := Scale.Center; MinPtr.Radius := MinPtrRadius; MinPtr.Offset := -Pi / 2; MinPtr.Pen.Color := clYellow; MinPtr.Pen.Width := 4; AddElement(MinPtr); SecPtr := TRotativePointer.Create(Self); SecPtr.Center := Scale.Center; SecPtr.Radius := MinPtrRadius; SecPtr.Offset := -Pi / 2; SecPtr.Pen.Color := clRed; SecPtr.Pen.Width := 4; AddElement(SecPtr); end; { TRetroClock } function TRetroClock.GetClock: TClock; begin Result := Drawing as TClock end; class function TRetroClock.GetDrawingClass: TDrawingClass; begin Result := TClock; end; constructor TRetroClock.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 200; Height := 200; end; end.
{ Date Created: 5/30/00 3:28:18 PM } unit InfoGRUPEVNTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoGRUPEVNTRecord = record PGroup: String[6]; PEventCode: String[6]; End; TInfoGRUPEVNTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoGRUPEVNTRecord end; TEIInfoGRUPEVNT = (InfoGRUPEVNTPrimaryKey); TInfoGRUPEVNTTable = class( TDBISAMTableAU ) private FDFGroup: TStringField; FDFEventCode: TStringField; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPEventCode(const Value: String); function GetPEventCode:String; procedure SetEnumIndex(Value: TEIInfoGRUPEVNT); function GetEnumIndex: TEIInfoGRUPEVNT; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoGRUPEVNTRecord; procedure StoreDataBuffer(ABuffer:TInfoGRUPEVNTRecord); property DFGroup: TStringField read FDFGroup; property DFEventCode: TStringField read FDFEventCode; property PGroup: String read GetPGroup write SetPGroup; property PEventCode: String read GetPEventCode write SetPEventCode; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoGRUPEVNT read GetEnumIndex write SetEnumIndex; end; { TInfoGRUPEVNTTable } procedure Register; implementation procedure TInfoGRUPEVNTTable.CreateFields; begin FDFGroup := CreateField( 'Group' ) as TStringField; FDFEventCode := CreateField( 'EventCode' ) as TStringField; end; { TInfoGRUPEVNTTable.CreateFields } procedure TInfoGRUPEVNTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoGRUPEVNTTable.SetActive } procedure TInfoGRUPEVNTTable.Validate; begin { Enter Validation Code Here } end; { TInfoGRUPEVNTTable.Validate } procedure TInfoGRUPEVNTTable.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoGRUPEVNTTable.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoGRUPEVNTTable.SetPEventCode(const Value: String); begin DFEventCode.Value := Value; end; function TInfoGRUPEVNTTable.GetPEventCode:String; begin result := DFEventCode.Value; end; procedure TInfoGRUPEVNTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Group, String, 6, N'); Add('EventCode, String, 6, N'); end; end; procedure TInfoGRUPEVNTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Group, Y, Y, N, N'); end; end; procedure TInfoGRUPEVNTTable.SetEnumIndex(Value: TEIInfoGRUPEVNT); begin case Value of InfoGRUPEVNTPrimaryKey : IndexName := ''; end; end; function TInfoGRUPEVNTTable.GetDataBuffer:TInfoGRUPEVNTRecord; var buf: TInfoGRUPEVNTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PGroup := DFGroup.Value; buf.PEventCode := DFEventCode.Value; result := buf; end; procedure TInfoGRUPEVNTTable.StoreDataBuffer(ABuffer:TInfoGRUPEVNTRecord); begin DFGroup.Value := ABuffer.PGroup; DFEventCode.Value := ABuffer.PEventCode; end; function TInfoGRUPEVNTTable.GetEnumIndex: TEIInfoGRUPEVNT; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoGRUPEVNTPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoGRUPEVNTTable, TInfoGRUPEVNTBuffer ] ); end; { Register } function TInfoGRUPEVNTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PGroup; 2 : result := @Data.PEventCode; end; end; end. { InfoGRUPEVNTTable }
unit FrameDataViewer; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, BaseApp, BaseForm, VirtualTrees, ExtCtrls, define_dealItem, define_price, define_datasrc, db_dealItem, BaseRule, Rule_CYHT, Rule_BDZX, Rule_Boll, Rule_Std, Rule_MA, StockDayDataAccess, UIDealItemNode, StockDetailDataAccess, StdCtrls; type TDataViewerData = record DayDataAccess: StockDayDataAccess.TStockDayDataAccess; DetailDataAccess: StockDetailDataAccess.TStockDetailDataAccess; WeightMode: TRT_WeightMode; Rule_BDZX_Price: TRule_BDZX_Price; Rule_CYHT_Price: TRule_CYHT_Price; DayDataSrc: TDealDataSource; DetailDataSrc: TDealDataSource; end; TfmeDataViewer = class(TfrmBase) pnMain: TPanel; pnTop: TPanel; pnData: TPanel; pnDataTop: TPanel; pnlDatas: TPanel; spl1: TSplitter; pnlDetail: TPanel; vtDetailDatas: TVirtualStringTree; pnlDetailTop: TPanel; pnlDayData: TPanel; vtDayDatas: TVirtualStringTree; pnlDayDataTop: TPanel; edtDetailDataSrc: TComboBox; procedure vtDetailDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure vtDayDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure vtDayDatasChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure edtDetailDataSrcChange(Sender: TObject); protected fDataViewerData: TDataViewerData; procedure LoadDetailTreeView; procedure LoadDayDataTreeView(AStockItem: PStockItemNode); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize(App: TBaseApp); override; procedure SetData(ADataType: integer; AData: Pointer); override; procedure SetStockItem(AStockItem: PStockItemNode); end; implementation {$R *.dfm} uses BaseStockApp, define_datetime, define_stock_quotes, define_dealstore_file, StockDayData_Load, StockDetailData_Load, db_DealItem_Load; type TDayColumns = ( colIndex, colDate, colOpen, colClose, colHigh, colLow, colDayVolume, colDayAmount, colWeight //, colBoll, colBollUP, colBollLP //, colCYHT_SK, colCYHT_SD , colBDZX_AK, colBDZX_AD1, colBDZX_AJ ); TDetailColumns = ( colTime, colPrice, colDetailVolume, colDetailAmount, colType //, colBoll, colBollUP, colBollLP //, colCYHT_SK, colCYHT_SD //, colBDZX_AK, colBDZX_AD1, colBDZX_AJ ); PStockDayDataNode = ^TStockDayDataNode; TStockDayDataNode = record DayIndex: integer; QuoteData: PRT_Quote_Day; end; PStockDetailDataNode = ^TStockDetailDataNode; TStockDetailDataNode = record QuoteData: PRT_Quote_Detail; end; const DayColumnsText: array[TDayColumns] of String = ( 'Index', '日期', '开盘', '收盘', '最高', '最低', '成交量', '成交金额', '权重' //, 'BOLL', 'UP', 'LP' //, 'SK', 'SD' , 'AK', 'AD1', 'AJ' ); DayColumnsWidth: array[TDayColumns] of integer = ( 60, 0, 0, 0, 0, 0, 0, 0, 0 //, 'BOLL', 'UP', 'LP' //, 'SK', 'SD' , 0, 0, 0 ); DetailColumnsText: array[TDetailColumns] of String = ( '时间', '价格', '成交量', '成交金额', '性质' //, 'BOLL', 'UP', 'LP' //, 'SK', 'SD' //, 'AK', 'AD1', 'AJ' ); { TfrmDetailDataViewer } constructor TfmeDataViewer.Create(AOwner: TComponent); begin inherited; //fStockDetailDataAccess := nil; FillChar(fDataViewerData, SizeOf(fDataViewerData), 0); fDataViewerData.DayDataSrc := Src_163; fDataViewerData.DetailDataSrc := Src_Sina; edtDetailDataSrc.Items.Clear; edtDetailDataSrc.Items.AddObject('Sina', TObject(DataSrc_Sina)); edtDetailDataSrc.Items.AddObject('163', TObject(DataSrc_163)); edtDetailDataSrc.ItemIndex := 0; edtDetailDataSrc.OnChange := edtDetailDataSrcChange; //fRule_Boll_Price := nil; //fRule_CYHT_Price := nil; //fRule_BDZX_Price := nil; end; destructor TfmeDataViewer.Destroy; begin inherited; end; procedure TfmeDataViewer.edtDetailDataSrcChange(Sender: TObject); begin inherited; fDataViewerData.DetailDataSrc := GetDealDataSource(Integer(edtDetailDataSrc.Items.Objects[edtDetailDataSrc.ItemIndex])); end; procedure TfmeDataViewer.SetData(ADataType: integer; AData: Pointer); begin SetStockItem(AData); end; procedure TfmeDataViewer.SetStockItem(AStockItem: PStockItemNode); begin LoadDayDataTreeView(AStockItem); end; procedure TfmeDataViewer.LoadDetailTreeView; var i: integer; tmpNodeData: PStockDetailDataNode; tmpDetailData: PRT_Quote_Detail; tmpNode: PVirtualNode; begin vtDetailDatas.Clear; vtDetailDatas.BeginUpdate; try if nil <> fDataViewerData.DetailDataAccess then begin for i := 0 to fDataViewerData.DetailDataAccess.RecordCount - 1 do begin tmpDetailData := fDataViewerData.DetailDataAccess.RecordItem[i]; tmpNode := vtDetailDatas.AddChild(nil); tmpNodeData := vtDetailDatas.GetNodeData(tmpNode); tmpNodeData.QuoteData := tmpDetailData; end; end; finally vtDetailDatas.EndUpdate; end; end; procedure TfmeDataViewer.LoadDayDataTreeView(AStockItem: PStockItemNode); var i: integer; tmpStockDataNode: PStockDayDataNode; tmpStockData: PRT_Quote_Day; tmpNode: PVirtualNode; begin vtDayDatas.BeginUpdate; try vtDayDatas.Clear; if nil = AStockItem then exit; fDataViewerData.DayDataAccess := AStockItem.StockDayDataAccess; if nil = fDataViewerData.DayDataAccess then fDataViewerData.DayDataAccess := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem.StockItem, fDataViewerData.DayDataSrc, fDataViewerData.WeightMode); fDataViewerData.Rule_BDZX_Price := AStockItem.Rule_BDZX_Price; fDataViewerData.Rule_CYHT_Price := AStockItem.Rule_CYHT_Price; for i := fDataViewerData.DayDataAccess.RecordCount - 1 downto 0 do begin tmpStockData := fDataViewerData.DayDataAccess.RecordItem[i]; tmpNode := vtDayDatas.AddChild(nil); tmpStockDataNode := vtDayDatas.GetNodeData(tmpNode); tmpStockDataNode.QuoteData := tmpStockData; tmpStockDataNode.DayIndex := i; end; finally vtDayDatas.EndUpdate; end; //StockDetailData_Load.LoadStockDetailData(App, fStockDetailDataAccess, 'E:\StockApp\sdata\sdetsina\600000\600000_20151125.sdet'); (*// if nil <> fRule_Boll_Price then begin FreeAndNil(fRule_Boll_Price); end; fRule_Boll_Price := TRule_Boll_Price.Create(); fRule_Boll_Price.OnGetDataLength := DoGetStockDealDays; fRule_Boll_Price.OnGetDataF := DoGetStockClosePrice; fRule_Boll_Price.Execute; //*) (*// if nil <> fRule_CYHT_Price then begin FreeAndNil(fRule_CYHT_Price); end; fRule_CYHT_Price := TRule_CYHT_Price.Create(); fRule_CYHT_Price.OnGetDataLength := DoGetStockDealDays; fRule_CYHT_Price.OnGetPriceOpen := DoGetStockOpenPrice; fRule_CYHT_Price.OnGetPriceClose := DoGetStockClosePrice; fRule_CYHT_Price.OnGetPriceHigh := DoGetStockHighPrice; fRule_CYHT_Price.OnGetPriceLow := DoGetStockLowPrice; fRule_CYHT_Price.Execute; //*) (*// if nil <> fRule_BDZX_Price then begin FreeAndNil(fRule_BDZX_Price); end; fRule_BDZX_Price := TRule_BDZX_Price.Create(); fRule_BDZX_Price.OnGetDataLength := DoGetStockDealDays; fRule_BDZX_Price.OnGetPriceOpen := DoGetStockOpenPrice; fRule_BDZX_Price.OnGetPriceClose := DoGetStockClosePrice; fRule_BDZX_Price.OnGetPriceHigh := DoGetStockHighPrice; fRule_BDZX_Price.OnGetPriceLow := DoGetStockLowPrice; fRule_BDZX_Price.Execute; //*) (*// for i := 0 to fStockDetailDataAccess.RecordCount - 1 do begin tmpStockData := fStockDetailDataAccess.RecordItem[i]; tmpNode := vtDatas.AddChild(nil); tmpStockDataNode := vtDatas.GetNodeData(tmpNode); tmpStockDataNode.QuoteData := tmpStockData; tmpStockDataNode.DayIndex := i; end; //*) end; procedure TfmeDataViewer.Initialize(App: TBaseApp); var col_day: TDayColumns; col_detail: TDetailColumns; tmpCol: TVirtualTreeColumn; begin inherited; vtDayDatas.NodeDataSize := SizeOf(TStockDayDataNode); vtDayDatas.Header.Options := [hoColumnResize, hoVisible]; vtDayDatas.Header.Columns.Clear; vtDayDatas.TreeOptions.SelectionOptions := [toFullRowSelect]; vtDayDatas.TreeOptions.AnimationOptions := []; vtDayDatas.TreeOptions.MiscOptions := [toAcceptOLEDrop,toFullRepaintOnResize,toInitOnSave,toToggleOnDblClick,toWheelPanning,toEditOnClick]; vtDayDatas.TreeOptions.PaintOptions := [toShowButtons,toShowDropmark,{toShowRoot} toShowTreeLines,toThemeAware,toUseBlendedImages]; vtDayDatas.TreeOptions.StringOptions := [toSaveCaptions,toAutoAcceptEditChange]; for col_day := low(TDayColumns) to high(TDayColumns) do begin tmpCol := vtDayDatas.Header.Columns.Add; tmpCol.Text := DayColumnsText[col_day]; if 0 = DayColumnsWidth[col_day] then begin tmpCol.Width := 120; end else begin tmpCol.Width := DayColumnsWidth[col_day]; end; end; vtDetailDatas.NodeDataSize := SizeOf(TStockDetailDataNode); vtDetailDatas.OnGetText := vtDetailDatasGetText; vtDetailDatas.Header.Options := [hoColumnResize, hoVisible]; vtDetailDatas.Header.Columns.Clear; for col_detail := low(TDetailColumns) to high(TDetailColumns) do begin tmpCol := vtDetailDatas.Header.Columns.Add; tmpCol.Text := DetailColumnsText[col_detail]; tmpCol.Width := 120; end; vtDayDatas.OnGetText := vtDayDatasGetText; vtDayDatas.OnChange := vtDayDatasChange; fDataViewerData.DayDataSrc := Src_163; end; procedure TfmeDataViewer.vtDayDatasChange(Sender: TBaseVirtualTree; Node: PVirtualNode); var tmpNodeData: PStockDayDataNode; tmpFileUrl: string; begin inherited; if nil = Node then exit; tmpNodeData := Sender.GetNodeData(Node); if nil = tmpNodeData then exit; if nil = tmpNodeData.QuoteData then exit; if nil = fDataViewerData.DetailDataAccess then begin fDataViewerData.DetailDataAccess := TStockDetailDataAccess.Create(FilePath_DBType_Item, fDataViewerData.DayDataAccess.StockItem, fDataViewerData.DetailDataSrc); end; fDataViewerData.DetailDataAccess.Clear; fDataViewerData.DetailDataAccess.StockItem := fDataViewerData.DayDataAccess.StockItem; fDataViewerData.DetailDataAccess.FirstDealDate := tmpNodeData.QuoteData.DealDate.Value; tmpFileUrl := TBaseStockApp(App).StockAppPath.GetFileUrl( fDataViewerData.DetailDataAccess.DBType, fDataViewerData.DetailDataAccess.DataType, GetDealDataSourceCode(fDataViewerData.DetailDataSrc), tmpNodeData.QuoteData.DealDate.Value, fDataViewerData.DayDataAccess.StockItem); if not FileExists(tmpFileUrl) then begin tmpFileUrl := ChangeFileExt(tmpFileUrl, '.sdet'); end; //tmpFileUrl := 'E:\StockApp\sdata\sdetsina\600000\600000_20151125.sdet'; if FileExists(tmpFileUrl) then begin LoadStockDetailData( App, fDataViewerData.DetailDataAccess, tmpFileUrl); end; LoadDetailTreeView; end; procedure TfmeDataViewer.vtDayDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpNodeData: PStockDayDataNode; begin CellText := ''; tmpNodeData := Sender.GetNodeData(Node); if nil <> tmpNodeData then begin if nil <> tmpNodeData.QuoteData then begin if Integer(colIndex) = Column then begin CellText := IntToStr(Node.Index); exit; end; if Integer(colDate) = Column then begin CellText := FormatDateTime('yyyymmdd', tmpNodeData.QuoteData.DealDate.Value); exit; end; if Integer(colOpen) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceOpen.Value); exit; end; if Integer(colClose) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceClose.Value); exit; end; if Integer(colHigh) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceHigh.Value); exit; end; if Integer(colLow) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceLow.Value); exit; end; if Integer(colDayVolume) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealVolume); exit; end; if Integer(colDayAmount) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealAmount); exit; end; if Integer(colWeight) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.Weight.Value); exit; end; if Integer(colBDZX_AK) = Column then begin if nil <> fDataViewerData.Rule_BDZX_Price then begin if nil <> fDataViewerData.Rule_BDZX_Price.Ret_AK_Float then begin CellText := FormatFloat('0.00', fDataViewerData.Rule_BDZX_Price.Ret_AK_Float.value[tmpNodeData.DayIndex]); end; end; exit; end; if Integer(colBDZX_AD1) = Column then begin if nil <> fDataViewerData.Rule_BDZX_Price then begin if nil <> fDataViewerData.Rule_BDZX_Price.Ret_AD1_EMA then begin CellText := FormatFloat('0.00', fDataViewerData.Rule_BDZX_Price.Ret_AD1_EMA.ValueF[tmpNodeData.DayIndex]); end; end; exit; end; if Integer(colBDZX_AJ) = Column then begin if nil <> fDataViewerData.Rule_BDZX_Price then begin if nil <> fDataViewerData.Rule_BDZX_Price.Ret_AJ then begin CellText := FormatFloat('0.00', fDataViewerData.Rule_BDZX_Price.Ret_AJ.value[tmpNodeData.DayIndex]); end; end; exit; end; (*// if Integer(colCYHT_SK) = Column then begin CellText := FormatFloat('0.00', fRule_Cyht_Price.SK[tmpNodeData.DayIndex]); exit; end; if Integer(colCYHT_SD) = Column then begin CellText := FormatFloat('0.00', fRule_Cyht_Price.SD[tmpNodeData.DayIndex]); exit; end; //*) (*// if Integer(colBoll) = Column then begin CellText := FormatFloat('0.00', fRule_Boll_Price.Boll[tmpNodeData.DayIndex]); exit; end; if Integer(colBollUP) = Column then begin CellText := FormatFloat('0.00', fRule_Boll_Price.UB[tmpNodeData.DayIndex]); exit; end; if Integer(colBollLP) = Column then begin CellText := FormatFloat('0.00', fRule_Boll_Price.LB[tmpNodeData.DayIndex]); exit; end; //*) end; end; end; procedure TfmeDataViewer.vtDetailDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpNodeData: PStockDetailDataNode; begin CellText := ''; tmpNodeData := Sender.GetNodeData(Node); if nil <> tmpNodeData then begin if nil <> tmpNodeData.QuoteData then begin if Integer(colTime) = Column then begin CellText := GetTimeText(@tmpNodeData.QuoteData.DealDateTime.Time); exit; end; if Integer(colPrice) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.Price.Value); exit; end; if Integer(colDetailVolume) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealVolume); exit; end; if Integer(colDetailAmount) = Column then begin CellText := IntToStr(tmpNodeData.QuoteData.DealAmount); exit; end; if Integer(colType) = Column then begin CellText := 'U'; if DealType_Buy = tmpNodeData.QuoteData.DealType then begin CellText := '买'; end; if DealType_Sale = tmpNodeData.QuoteData.DealType then begin CellText := '卖'; end; if DealType_Neutral = tmpNodeData.QuoteData.DealType then begin CellText := '中'; end; exit; end; (*// if Integer(colCYHT_SK) = Column then begin CellText := FormatFloat('0.00', fRule_Cyht_Price.SK[tmpNodeData.DayIndex]); exit; end; if Integer(colCYHT_SD) = Column then begin CellText := FormatFloat('0.00', fRule_Cyht_Price.SD[tmpNodeData.DayIndex]); exit; end; //*) (*// if Integer(colBoll) = Column then begin CellText := FormatFloat('0.00', fRule_Boll_Price.Boll[tmpNodeData.DayIndex]); exit; end; if Integer(colBollUP) = Column then begin CellText := FormatFloat('0.00', fRule_Boll_Price.UB[tmpNodeData.DayIndex]); exit; end; if Integer(colBollLP) = Column then begin CellText := FormatFloat('0.00', fRule_Boll_Price.LB[tmpNodeData.DayIndex]); exit; end; //*) end; end; end; end.
unit CapitolTownsSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, ComCtrls, InternationalizerComponent, ImgList; const tidTownName = 'Town'; tidTownRating = 'TownRating'; tidTownTax = 'TownTax'; tidTownPopulation = 'TownPopulation'; tidTownQOL = 'TownQOL'; tidTownQOS = 'TownQOS'; tidTownWealth = 'TownWealth'; tidTownCount = 'TownCount'; tidTownHasMayor = 'HasMayor'; tidActualRuler = 'ActualRuler'; tidCurrBlock = 'CurrBlock'; type TCapitolTownsSheetHandler = class; TCapitolTownsSheetViewer = class(TVisualControl) lvTowns: TListView; pnTax: TPanel; lbTax: TLabel; pbTax: TPercentEdit; btnElect: TFramedButton; edMayor: TEdit; lbMayor: TLabel; ImageList1: TImageList; InternationalizerComponent1: TInternationalizerComponent; procedure pbTaxMoveBar(Sender: TObject); procedure pbTaxChange(Sender: TObject); procedure lvTownsChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure btnElectClick(Sender: TObject); public { Public declarations } private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TCapitolTownsSheetHandler; fProperties : TStringList; protected procedure SetParent(which : TWinControl); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; end; TCapitolTownsSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TCapitolTownsSheetViewer; fHasAccess : boolean; fCurrBlock : integer; public function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedSetTownTax( const parms : array of const ); procedure threadedSitMayor(const parms : array of const); end; function CapitolTownsHandlerCreator : IPropertySheetHandler; stdcall; implementation {$R *.DFM} uses Threads, SheetHandlerRegistry, FiveViewUtils, Protocol, SheetUtils, MathUtils, {$IFDEF VER140} Variants, {$ENDIF} Literals, CoolSB; // TCapitolTownsSheetHandler function TCapitolTownsSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TCapitolTownsSheetViewer.Create(Owner); fControl.fProperties := TStringList.Create; fControl.fHandler := self; result := fControl; end; function TCapitolTownsSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TCapitolTownsSheetHandler.RenderProperties(Properties : TStringList); var cnt : integer; i : integer; iStr : string; Item : TListItem; begin try fControl.fProperties.Assign( Properties ); SheetUtils.ClearListView(fControl.lvTowns); fControl.lvTowns.Items.BeginUpdate; try fHasAccess := GrantAccess(fContainer.GetClientView.getSecurityId, Properties.Values['SecurityId']) or (uppercase(Properties.Values[tidActualRuler]) = uppercase(fContainer.GetClientView.getUserName)); cnt := StrToInt(Properties.Values[tidTownCount]); for i := 0 to pred(cnt) do begin iStr := IntToStr(i); Item := fControl.lvTowns.Items.Add; Item.Caption := Properties.Values[tidTownName + iStr]; Item.SubItems.Add(Properties.Values[tidTownPopulation + iStr]); Item.SubItems.Add(Properties.Values[tidTownQOL + iStr] + '%'); Item.SubItems.Add(Properties.Values[tidTownQOS + iStr] + '%'); Item.SubItems.Add(Properties.Values[tidTownWealth + iStr] + '%'); Item.SubItems.Add(Properties.Values[tidTownTax + iStr] + '%'); if Properties.Values[tidTownHasMayor + iStr] <> '1' then Item.ImageIndex := 0 else Item.ImageIndex := 1; end; finally fControl.lvTowns.Items.EndUpdate; fControl.SetBounds(fControl.Left,fControl.Top,fControl.Width,fControl.Height); end; if cnt = 0 then SheetUtils.AddItem(fControl.lvTowns, [GetLiteral('Literal192')]); fControl.pnTax.Visible := fHasAccess; except fControl.pnTax.Visible := false; end; end; procedure TCapitolTownsSheetHandler.SetFocus; begin if not fLoaded then begin inherited; SheetUtils.AddItem(fControl.lvTowns, [GetLiteral('Literal193')]); Threads.Fork( threadedGetProperties, priHigher, [fLastUpdate] ); end; end; procedure TCapitolTownsSheetHandler.Clear; begin inherited; fControl.lvTowns.Items.BeginUpdate; try fControl.lvTowns.Items.Clear; fControl.lbMayor.Visible := false; fControl.edMayor.Visible := false; fControl.btnElect.Visible := false; finally fControl.lvTowns.Items.EndUpdate; end; end; procedure TCapitolTownsSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList; Update : integer; Prop : TStringList; Proxy : OleVariant; aux : string; i : integer; iStr : string; begin Update := parms[0].vInteger; try Lock; try Proxy := fContainer.GetCacheObjectProxy; if (Update = fLastUpdate) and not VarIsEmpty(Proxy) then begin aux := Proxy.Properties(tidTownCount); if (Update = fLastUpdate) and (aux <> '') then begin Names := TStringList.Create; Prop := TStringList.Create; Prop.Values[tidTownCount] := aux; try Names.Add('SecurityId'); for i := 0 to pred(StrToInt(aux)) do begin iStr := IntToStr(i); Names.Add(tidTownName + iStr); Names.Add(tidTownRating + iStr); Names.Add(tidTownTax + iStr); Names.Add(tidTownPopulation + iStr); Names.Add(tidTownQOL + iStr); Names.Add(tidTownQOS + iStr); Names.Add(tidTownWealth + iStr); Names.Add(tidTownHasMayor + iStr); end; Names.Add( tidActualRuler ); Names.Add( tidCurrBlock ); if Update = fLastUpdate then fContainer.GetPropertyList(Proxy, Names, Prop); finally Names.Free; end; if Update = fLastUpdate then Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; end; end; finally Unlock; end; except end; end; procedure TCapitolTownsSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then RenderProperties(Prop); fCurrBlock := StrToInt(Prop.Values[tidCurrBlock]); finally Prop.Free; end; except end; end; procedure TCapitolTownsSheetHandler.threadedSetTownTax( const parms : array of const ); var Index : integer; Value : integer; MSProxy : olevariant; begin try Index := parms[0].vInteger; Value := parms[1].vInteger; if fHasAccess then try MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); MSProxy.RDOSetTownTaxes( Index, Value ); except beep; end; except end; end; procedure TCapitolTownsSheetHandler.threadedSitMayor(const parms : array of const); var town : string; tycoon : string; MSProxy : olevariant; begin try town := parms[0].vPCHar; tycoon := parms[1].vPCHar; if fHasAccess then try MSProxy := fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) and MSProxy.BindTo(fCurrBlock) then MSProxy.RDOSitMayor(town, tycoon); except beep; end; except end; end; function CapitolTownsHandlerCreator : IPropertySheetHandler; begin result := TCapitolTownsSheetHandler.Create; end; procedure TCapitolTownsSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TCapitolTownsSheetViewer.pbTaxMoveBar(Sender: TObject); begin if lvTowns.Selected <> nil then begin lbTax.Caption := GetFormattedLiteral('Literal194', [pbTax.Value]); lvTowns.Selected.SubItems[4] := IntToStr( pbTax.Value ) + '%'; fProperties.Values[tidTownTax + IntToStr(lvTowns.Selected.Index)] := IntToStr( pbTax.Value ); end; end; procedure TCapitolTownsSheetViewer.pbTaxChange(Sender: TObject); begin if lvTowns.Selected <> nil then begin lvTowns.Selected.SubItems[4] := IntToStr( pbTax.Value ) + '%'; fProperties.Values[tidTownTax + IntToStr(lvTowns.Selected.Index)] := IntToStr( pbTax.Value ); Fork( fHandler.threadedSetTownTax, priNormal, [lvTowns.Selected.Index, pbTax.Value] ); end; end; procedure TCapitolTownsSheetViewer.lvTownsChange(Sender: TObject; Item: TListItem; Change: TItemChange); var noMayor : boolean; begin if lvTowns.Selected <> nil then begin lbTax.Caption := GetFormattedLiteral('Literal195', [lvTowns.Selected.SubItems[4]]); pbTax.Value := StrToInt( fProperties.Values[tidTownTax + IntToStr(lvTowns.Selected.Index)] ); noMayor := lvTowns.Selected.ImageIndex = 0; lbMayor.Visible := noMayor; edMayor.Visible := noMayor; btnElect.Visible := noMayor; end; end; procedure TCapitolTownsSheetViewer.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var sum : integer; i : integer; dwStyles : DWORD; begin inherited; if (lvTowns <> nil) //and (lvTowns.Items <> nil) then begin sum := 0; for i := 0 to pred(lvTowns.Columns.Count-1) do inc(sum, lvTowns.Columns[i].Width); dwStyles := GetWindowLong(lvTowns.Handle, GWL_STYLE); if (dwStyles and WS_VSCROLL) <> 0 then Inc(sum, GetSystemMetrics(SM_CXVSCROLL)); lvTowns.Columns[lvTowns.Columns.Count-1].Width := lvTowns.Width-sum-2; end; end; procedure TCapitolTownsSheetViewer.btnElectClick(Sender: TObject); begin if (lvTowns.Selected <> nil) and (edMayor.Text <> '') then Fork(fHandler.threadedSitMayor, priNormal, [lvTowns.Selected.Caption, edMayor.Text]); end; procedure TCapitolTownsSheetViewer.SetParent(which: TWinControl); begin inherited; if InitSkinImage and (which<>nil) then begin InitializeCoolSB(lvTowns.Handle); if hThemeLib <> 0 then SetWindowTheme(lvTowns.Handle, ' ', ' '); CoolSBEnableBar(lvTowns.Handle, FALSE, TRUE); CustomizeListViewHeader( lvTowns ); end; end; initialization SheetHandlerRegistry.RegisterSheetHandler( 'CapitolTowns', CapitolTownsHandlerCreator ); end.
// the main code formatter engine, combines the parser and formatter do do the work // Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html) // Contributors: Thomas Mueller (http://www.dummzeuch.de) // Jens Borrisholt (Jens@borrisholt.dk) - Cleaning up the code, and making it aware of several language features unit GX_CodeFormatterEngine; {$I GX_CondDefine.inc} interface uses {$IFDEF debug} // NOTE: including DbugIntf adds around 300 k to the dll GX_DbugIntf, {$ENDIF} SysUtils, Classes, GX_GenericUtils, GX_CodeFormatterTokenList, GX_CodeFormatterTypes, GX_CodeFormatterTokens, GX_CodeFormatterSettings; (* WISHLIST: - suppress read-only file message - read capitalization from var const type blocks - sorting methods - Is it possible to insert a "user customisable" line or group of lines before each function/procedure, to allow the developer to comment it. Ex : {------------Name of the proc------------------------} (Simple) {*************************** * ...Comment ... * ...Comment ... ***************************/ (A few lines)} *) type TCodeFormatterEngine = class(TObject) private FSettings: TCodeFormatterSettings; function GetLine(_Tokens: TPascalTokenList; var _TokenNo: Integer): TGXUnicodeString; public constructor Create; destructor Destroy; override; {: @returns true if the formatting succeeded and the source code has changed } function Execute(_SourceCode: TGXUnicodeStringList): Boolean; property Settings: TCodeFormatterSettings read FSettings write FSettings; end; implementation uses StrUtils, GX_CodeFormatterFormatter, GX_CodeFormatterParser; constructor TCodeFormatterEngine.Create; begin inherited; FSettings := TCodeFormatterSettings.Create; end; destructor TCodeFormatterEngine.Destroy; begin FreeAndNil(FSettings); inherited; end; function TCodeFormatterEngine.Execute(_SourceCode: TGXUnicodeStringList): Boolean; var Line: TGXUnicodeString; TokenNo: Integer; OrigSource: TGXUnicodeString; Tokens: TPascalTokenList; NewSource: TGXUnicodeString; begin try _SourceCode.BeginUpdate; OrigSource := _SourceCode.Text; Tokens := TCodeFormatterParser.Execute(_SourceCode, FSettings); try TCodeFormatterFormatter.Execute(Tokens, FSettings); _SourceCode.Clear; if Assigned(Tokens) then begin TokenNo := 0; while TokenNo < Tokens.Count do begin Line := GetLine(Tokens, TokenNo); _SourceCode.Add(Line); end; end; finally Tokens.Free; end; NewSource := _SourceCode.Text; Result := SourceDifferentApartFromTrailingLineBreak(OrigSource, NewSource); except on E: Exception do begin Result := False; { ShowMessage('Error occurred, cannot format'); } end; end; _SourceCode.EndUpdate; end; function TCodeFormatterEngine.GetLine(_Tokens: TPascalTokenList; var _TokenNo: Integer): TGXUnicodeString; var Token: TPascalToken; i: Integer; begin Result := ''; if not Assigned(_Tokens) then Exit; if (_TokenNo < 0) or (_TokenNo >= _Tokens.Count) then Exit; Token := _Tokens[_TokenNo]; repeat Result := Result + Token.GetContent; Inc(_TokenNo); if _TokenNo >= _Tokens.Count then break; Token := _Tokens[_TokenNo]; until Token.ReservedType = rtLineFeed; // remove spaces and tabs at the end i := Length(Result); while (i > 0) and ((Result[i] = Space) or (Result[i] = Tab)) do Dec(i); SetLength(Result, i); end; end.
unit BackupInterfaces; interface uses SysUtils, Classes, SyncObjs; const NULLPROC : TMethod = ( Code : nil; Data : nil ); const IgnoredBufferSize = -1; type IBackupObject = interface procedure Lock; procedure Unlock; function GetPosition : integer; procedure Seek(offset : integer); function GetPath : string; property Path : string read GetPath; end; IBackupWriter = interface(IBackupObject) ['{56DFE440-9E79-11D1-A1A8-0080C817C099}'] procedure WriteString(Name : string; Value : string); stdcall; procedure WriteClass(Name : string; Value : string); stdcall; procedure WriteChar(Name : string; Value : char); stdcall; procedure WriteBoolean(Name : string; Value : boolean); stdcall; procedure WriteByte(Name : string; Value : byte); stdcall; procedure WriteWord(Name : string; Value : word); stdcall; procedure WriteInteger(Name : string; Value : integer); stdcall; procedure WriteInt64(Name : string; Value : int64); stdcall; procedure WriteSingle(Name : string; Value : single); stdcall; procedure WriteDouble(Name : string; Value : double); stdcall; procedure WriteCurrency(Name : string; Value : currency); stdcall; procedure WriteObject(Name : string; Value : TObject); stdcall; procedure WriteObjectRef(Name : string; Value : TObject); stdcall; procedure WriteLooseObject(Name : string; Value : TObject); stdcall; procedure WriteMethod(Name : string; Method : TMethod); stdcall; procedure WriteBuffer(Name : string; var buffer; size : integer); stdcall; procedure WriteUnsafeObject(Name : string; Value : TObject); stdcall; procedure WriteUnsafeLooseObject(Name : string; Value : TObject); stdcall; procedure WriteUnsafeObjectRef(Name : string; Value : TObject); stdcall; end; IBackupReader = interface ['{56DFE441-9E79-11D1-A1A8-0080C817C099}'] function ReadString(Name : string; DefVal : string) : string; stdcall; function ReadClass(Name : string; DefVal : string) : string; stdcall; function ReadChar(Name : string; DefVal : char) : char; stdcall; function ReadBoolean(Name : string; DefVal : boolean) : boolean; stdcall; function ReadByte(Name : string; DefVal : byte) : byte; stdcall; function ReadWord(Name : string; DefVal : word) : word; stdcall; function ReadInteger(Name : string; DefVal : integer) : integer; stdcall; function ReadInt64(Name : string; DefVal : int64) : int64; stdcall; function ReadSingle(Name : string; DefVal : single) : single; stdcall; function ReadDouble(Name : string; DefVal : double) : double; stdcall; function ReadCurrency(Name : string; DefVal : currency) : currency; stdcall; function ReadObject(Name : string; var O; DefVal : TObject) : string; stdcall; function ReadLooseObject(Name : string; var O; DefVal : TObject) : string; stdcall; procedure ReadMethod(Name : string; var Method : TMethod; DefVal : TMethod); stdcall; procedure ReadBuffer(Name : string; var buffer; DefVal : pointer; size : integer); stdcall; function GetFixups : TObject; stdcall; procedure SetFixups(Obj : TObject); stdcall; end; // Backup Agent root class type CBackupAgent = class of TBackupAgent; TBackupAgent = class public class procedure Register(const Classes : array of TClass); public class function CreateObject(aClass : TClass) : TObject; virtual; class procedure Write(Stream : IBackupWriter; Obj : TObject); virtual; abstract; class procedure Read (Stream : IBackupReader; Obj : TObject); virtual; abstract; end; EInternalBackupError = class(Exception); // Registration util functions procedure RegisterClass(aClass : TClass); function GetBackupAgent(ClassName : string; var Agent : CBackupAgent; var ClassType : TClass) : boolean; implementation // External routines procedure RegisterBackupAgent(aClass, anAgent : TClass); external 'BackupRegistry.dll'; procedure GetClassAgent(const ClassName : string; var TheAgent, TheClass : TClass); external 'BackupRegistry.dll'; // TBackupAgent class procedure TBackupAgent.Register(const Classes : array of TClass); var i : integer; begin try for i := low(Classes) to high(Classes) do RegisterBackupAgent(Classes[i], Self); except raise EInternalBackupError.Create('Class already registered'); end; end; class function TBackupAgent.CreateObject(aClass : TClass) : TObject; begin result := aClass.Create; end; // Utility functions procedure RegisterClass(aClass : TClass); var Agent : CBackupAgent; aux : TClass; Cls : TClass; begin Agent := nil; aux := aClass; while (aux <> nil) and (Agent = nil) do begin GetBackupAgent(aux.ClassName, Agent, Cls); aux := aux.ClassParent; end; if Agent <> nil then RegisterBackupAgent(aClass, Agent) else raise EInternalBackupError.Create('No class parent has been registered yet for "' + aClass.ClassName + '"'); end; function GetBackupAgent(ClassName : string; var Agent : CBackupAgent; var ClassType : TClass) : boolean; begin GetClassAgent(ClassName, TClass(Agent), ClassType); result := (Agent <> nil) and (ClassType <> nil); end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: Delphi encapsulation for SSLEAY32.DLL (OpenSSL) This is only the subset needed by ICS. Creation: Jan 12, 2003 Version: 1.09 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list ics-ssl@elists.org Follow "SSL" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2003-2011 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> SSL implementation includes code written by Arno Garrels, Berlin, Germany, contact: <arno.garrels@gmx.de> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: Dec 11, 2004 Fixed Load to correctly check for LoadLibrary failure and to return correct error number. Nov 08, 2005 F. Piette Worked around Delphi 6 bug related to type redefinition. Search for NoTypeEnforce in the type declarations. Nov 08, 2005 Arno Garrels - Checked non-dummy structures against different OpenSSL versions see comments. Changed declaration of TX509_EXTENSION according OpenSSL v.0.9.7g. Nov 19, 2005 F. Piette fixed internal error for Delphi 5. Same fix as Delphi 6. Introduced symbol NoTypeEnforce for that purpose. Dec 07, 2005 A. Garrels support of OSSL v0.9.8a added. Jan 27, 2006 A. Garrels made BDS2006 (BCB & Pascal) compilers happy. Mar 03, 2007 A. Garrels: Small changes to support OpenSSL 0.9.8e. Read comments in OverbyteIcsSslDefs.inc. Jun 30, 2008 A.Garrels made some changes to prepare code for Unicode. Added a few constants and dummy records. Aug 02, 2008 Still one PChar caught in one of the records. Dec 20, 2009 A.Garrels added plenty of stuff. Some is not yet used some is, like Server Name Indication (SNI). May 08, 2010 A. Garrels added two declarations required to support Open SSL 0.9.8n. Apr 23, 2011 A. Garrels added C-macro f_SSL_clear_options. Apr 24, 2011 Arno - Record TEVP_PKEY_st changed in 1.0.0 and had to be declared as dummy. See helper functions Ics_Ssl_EVP_PKEY_xxx in OverbyteIcsLibeay.pas. May 03, 2011 Arno added some function declarations. May 31, 2011 Arno removed the packed modifier from non-dummy records. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$I OverbyteIcsDefs.inc} {$I OverbyteIcsSslDefs.inc} {$A8} unit OverbyteIcsSSLEAY; {$IFDEF VER140} // Delphi 6 is bugged // [Erreur fatale] IcsSSLEAY.pas: Erreur interne : URW533 {$DEFINE NoTypeEnforce} {$ENDIF} {$IFDEF VER130} // Delphi 5 is bugged // [Erreur fatale] IcsSSLEAY.pas: Erreur interne : URW533 {$DEFINE NoTypeEnforce} {$ENDIF} interface {$IFDEF USE_SSL} uses Windows, SysUtils, OverbyteIcsUtils; const IcsSSLEAYVersion = 109; CopyRight : String = ' IcsSSLEAY (c) 2003-2011 F. Piette V1.09 '; EVP_MAX_IV_LENGTH = 16; { 03/02/07 AG } EVP_MAX_BLOCK_LENGTH = 32; { 11/08/07 AG } EVP_MAX_KEY_LENGTH = 32; { 11/08/07 AG } type EIcsSsleayException = class(Exception); PPChar = ^PChar; PPAnsiChar = ^PAnsiChar; //PInteger = ^Integer; // All datatypes defined below using the Dummy array can't be used // directly. They all must be used thru pointers only. If you really need // to use those structure, you must replace Dummy member with the actual // members defined in the OpenSSL header ! TCRYPTO_THREADID_st = packed record Dummy : array [0..0] of Byte; //ptr : Pointer; //val : LongWord; end; PCRYPTO_THREADID = ^TCRYPTO_THREADID_st; {$IFNDEF OPENSSL_NO_ENGINE} TEngine_st = record Dummy : array [0..0] of Byte; end; PENGINE = ^TEngine_st; {$ENDIF} TSSL_st = packed record Dummy : array [0..0] of Byte; end; PSSL = ^TSSL_st; TSSL_SESSION_st = packed record Dummy : array [0..0] of Byte; end; PSSL_SESSION = ^TSSL_SESSION_st; PPSSL_SESSION = ^PSSL_SESSION; TBIO_st = packed record Dummy : array [0..0] of Byte; end; PBIO = ^TBIO_st; PPBIO = ^PBIO; TBIO_METHOD_st = packed record Dummy : array [0..0] of Byte; end; PBIO_METHOD = ^TBIO_METHOD_st; TSSL_CTX_st = packed record Dummy : array [0..0] of Byte; end; PSSL_CTX = ^TSSL_CTX_st; TSSL_METHOD_st = packed record Dummy : array [0..0] of Byte; end; PSSL_METHOD = ^TSSL_METHOD_st; TX509_STORE_st = packed record Dummy : array [0..0] of Byte; end; PX509_STORE = ^TX509_STORE_st; TX509_STORE_CTX_st = packed record Dummy : array [0..0] of Byte; end; PX509_STORE_CTX = ^TX509_STORE_CTX_st; TX509_NAME_st = packed record Dummy : array [0..0] of Byte; end; PX509_NAME = ^TX509_NAME_st; TSTACK_st = packed record //AG Dummy : array [0..0] of Byte; end; PSTACK = ^TSTACK_st; TASN1_TYPE_st = packed record //AG Dummy : array [0..0] of Byte; end; PASN1_TYPE = ^TASN1_TYPE_st; { Stack - dummies i.e. STACK_OF(X509) } PSTACK_OF_X509_EXTENSION = PStack; //AG PSTACK_OF_X509_ALGOR = PStack; //AG PSTACK_OF_X509 = PSTACK; //AG PSTACK_OF_X509_CRL = PSTACK; //AG PPSTACK_OF_X509 = ^PSTACK_OF_X509; //AG PSTACK_OF_PKCS7_RECIP_INFO = PStack; //AG PSTACK_OF_X509_ATTRIBUTE = PStack; //AG PSTACK_OF_PKCS7_SIGNER_INFO = PStack; //AG PSTACK_OF_509_LOOKUP = PStack; //AG PSTACK_OF_X509_OBJECT = PStack; //AG PSTACK_OF_X509_NAME = {$IFNDEF NoTypeEnforce}type{$ENDIF} PStack; PSTACK_OF_X509_INFO = {$IFNDEF NoTypeEnforce}type{$ENDIF} PStack; TX509_lookup_method_st = packed record Dummy : array [0..0] of Byte; end; PX509_LOOKUP_METHOD = ^TX509_lookup_method_st; TX509_lookup_st = packed record Dummy : array [0..0] of Byte; end; PX509_LOOKUP = ^TX509_lookup_st; TX509_OBJECT_st = packed record //AG Dummy : array [0..0] of Byte; end; PX509_OBJECT = ^TX509_OBJECT_st; TX509_NAME_ENTRY_st = packed record //AG Dummy : array [0..0] of Byte; end; PX509_NAME_ENTRY = ^TX509_NAME_ENTRY_st; TEVP_MD_st = packed record //AG Dummy : array [0..0] of Byte; end; PEVP_MD = ^TEVP_MD_st; TRSA_st = packed record Dummy : array [0..0] of Byte; //AG end; PRSA = ^TRSA_st; TDSA_st = packed record //AG Dummy : array [0..0] of Byte; end; PDSA = ^TDSA_st; TDH_st = packed record //AG Dummy : array [0..0] of Byte; end; PDH = ^TDH_st; TEC_KEY_st = packed record //AG Dummy : array [0..0] of Byte; end; PEC_KEY = ^TEC_KEY_st; { We may no longer define it since changed in 1.0.0+ } { See helper functions Ics_Ssl_EVP_PKEYxxx in OverbyteIcsLibeay32 } TEVP_PKEY_st = packed record Dummy : array [0..0] of Byte; (* type_ : Longint; save_type : Longint; references : Longint; {OSSL_100 two fields added} ameth : Pointer; //PEVP_PKEY_ASN1_METHOD; engine : Pointer; //PENGINE; {/OSSL_100} case Integer of 0 : (ptr : PAnsiChar); 1 : (rsa : PRSA); // RSA 2 : (dsa : PDSA); // DSA 3 : (dh : PDH); // DH 4 : (ec : PEC_KEY); //* ECC */ { more not needed ... int save_parameters; STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */ } *) end; PEVP_PKEY = ^TEVP_PKEY_st; PPEVP_PKEY = ^PEVP_PKEY; TEVP_CIPHER_st = packed record Dummy : array [0..0] of Byte; end; PEVP_CIPHER = ^TEVP_CIPHER_st; TASN1_OBJECT_st = packed record Dummy : array [0..0] of Byte; end; PASN1_OBJECT = ^TASN1_OBJECT_st; TX509_ALGOR_st = record algorithm : PASN1_OBJECT; parameter : PASN1_TYPE; end; PX509_ALGOR = ^TX509_ALGOR_st; TX509_PURPOSE_st = packed record Dummy : array [0..0] of Byte; end; PX509_PURPOSE = ^TX509_PURPOSE_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TASN1_STRING_st = record length : Integer; type_ : Integer; data : PAnsiChar; //* The value of the following field depends on the type being //* held. It is mostly being used for BIT_STRING so if the //* input data has a non-zero 'unused bits' value, it will be //* handled correctly */ flags : Longword; end; PASN1_STRING = ^TASN1_STRING_st; TASN1_OCTET_STRING = TASN1_STRING_st; PASN1_OCTET_STRING = ^TASN1_OCTET_STRING; TASN1_BIT_STRING = TASN1_STRING_st; PASN1_BIT_STRING = ^TASN1_BIT_STRING; TASN1_TIME = {$IFNDEF NoTypeEnforce}type{$ENDIF} TASN1_STRING_st; PASN1_TIME = ^TASN1_TIME; TASN1_INTEGER = {$IFNDEF NoTypeEnforce}type{$ENDIF} TASN1_STRING_st; PASN1_INTEGER = ^TASN1_INTEGER; TASN1_VALUE_st = packed record Dummy : array [0..0] of Byte; end; PASN1_VALUE = ^TASN1_VALUE_st; PPASN1_VALUE = ^PASN1_VALUE; // 0.9.7g, 0.9.8a 0.9.8e, 1.0.0d TEVP_CIPHER_INFO_st = record { 03/02/07 AG } cipher : PEVP_CIPHER; iv : array [0..EVP_MAX_IV_LENGTH - 1] of AnsiChar; end; EVP_CIPHER_INFO = TEVP_CIPHER_INFO_st; PEVP_CIPHER_INFO = ^EVP_CIPHER_INFO; // 0.9.7g, 0.9.8a 0.9.8e, 1.0.0d TPrivate_key_st = record //AG //Dummy : array [0..0] of Byte; version : Integer; // The PKCS#8 data types enc_algor : PX509_ALGOR; enc_pkey : PASN1_OCTET_STRING; // encrypted pub key // When decrypted, the following will not be NULL dec_pkey : PEVP_PKEY; // used to encrypt and decrypt key_length : Integer ; key_data : PAnsiChar; key_free : Integer; // true if we should auto free key_data // expanded version of 'enc_algor' cipher : PEVP_CIPHER_INFO; references : Integer ; end; PX509_PKEY = ^TPrivate_key_st; TX509_REQ_st = packed record Dummy : array [0..0] of Byte; end; PX509_REQ = ^TX509_REQ_st; // 0.9.7g, 0.9.8a 0.9.8e, 1.0.0d TX509_CRL_INFO_st = record version : PASN1_INTEGER; sig_alg : PX509_ALGOR; issuer : PX509_NAME; lastUpdate : PASN1_TIME; nextUpdate : PASN1_TIME; { STACK_OF(X509_REVOKED) *revoked; STACK_OF(X509_EXTENSION) /* [0] */ *extensions; ASN1_ENCODING enc; } end; PX509_CRL_INFO = ^TX509_CRL_INFO_st; TX509_CRL_st = record //* actual signature *// crl : PX509_CRL_INFO; sig_alg : PX509_ALGOR; signature : PASN1_BIT_STRING; references: Integer; {more..} end; PX509_CRL = ^TX509_CRL_st; PPX509_CRL = ^PX509_CRL; PX509 = ^TX509_st; PPX509 = ^PX509; // 0.9.7g, 0.9.8a 0.9.8e, 1.0.0d TX509_INFO_st = record x509 : PX509; crl : PX509_CRL; x_pkey : PX509_PKEY; enc_cipher : EVP_CIPHER_INFO; enc_len : Integer; enc_data : PAnsiChar; references : Integer; end; PX509_INFO = ^TX509_INFO_st; (* // 0.9.6g {11/07/05 AG} TX509_EXTENSION = packed record object_ : PASN1_OBJECT; critical : SmallInt; netscape_hack : SmallInt; value : PASN1_OCTET_STRING; method : PX509V3_EXT_METHOD; ext_val : Pointer; // extension value end; PX509_EXTENSION = ^TX509_EXTENSION; *) // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TX509_VAL_st = record {AG 02/06/06} notBefore : PASN1_TIME; notAfter : PASN1_TIME; end; PX509_VAL = ^TX509_VAL_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TX509_PUBKEY_st = record //AG algor : PX509_ALGOR; public_key : PASN1_BIT_STRING; pkey : PEVP_PKEY; end; PX509_PUBKEY = ^TX509_PUBKEY_st; { Certinfo } // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d {AG 02/06/06} TX509_CINF_st = record version : PASN1_INTEGER; // [ 0 ] default of v1 serialNumber : PASN1_INTEGER; signature : PX509_ALGOR; issuer : PX509_NAME; validity : PX509_VAL; subject : PX509_NAME; key : PX509_PUBKEY; {issuerUID : PASN1_BIT_STRING; // [ 1 ] optional in v2 subjectUID : PASN1_BIT_STRING; // [ 2 ] optional in v2 extensions : PSTACK_OF_X509_EXTENSION; // [ 3 ] optional in v3} end; PX509_CINF = ^TX509_CINF_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d {11/07/05 AG} ASN1_BOOLEAN = {$IFNDEF NoTypeEnforce}type{$ENDIF} Longint; TX509_EXTENSION_st = record object_ : PASN1_OBJECT; critical : ASN1_BOOLEAN; value : PASN1_OCTET_STRING; end; PX509_EXTENSION = ^TX509_EXTENSION_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TX509_st = record cert_info : PX509_CINF; sig_alg : PX509_ALGOR; signature : PASN1_BIT_STRING; valid : Integer ; references : Integer; name : PAnsiChar; {more ...} end; TPKCS7_ISSUER_AND_SERIAL_st = packed record //AG Dummy : array [0..0] of Byte; end; PPKCS7_ISSUER_AND_SERIAL = ^TPKCS7_ISSUER_AND_SERIAL_st; TPKCS7_ENC_CONTENT_st = packed record //AG Dummy : array [0..0] of Byte; end; PPKCS7_ENC_CONTENT = ^TPKCS7_ENC_CONTENT_st; TPKCS7_DIGEST_st = packed record //AG Dummy : array [0..0] of Byte; end; PPKCS7_DIGEST = ^TPKCS7_DIGEST_st; TPKCS7_ENCRYPT_st = packed record //AG Dummy : array [0..0] of Byte; end; PPKCS7_ENCRYPT = ^TPKCS7_ENCRYPT_st; { Caution! Structures may change in future versions 0.96g-0.98 beta OK} {AG} { However needed for S/MIME PKCS#7 parsing } // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TPKCS7_SIGNER_INFO_st = record version : PASN1_INTEGER; // version 1 issuer_and_serial : PPKCS7_ISSUER_AND_SERIAL; digest_alg : PX509_ALGOR; auth_attr : PSTACK_OF_X509_ATTRIBUTE; // [ 0 ] digest_enc_alg : PX509_ALGOR; enc_digest : PASN1_OCTET_STRING; unauth_attr : PSTACK_OF_X509_ATTRIBUTE; // [ 1 ] // The private key to sign with // pkey : PEVP_PKEY; end; //PKCS7_SIGNER_INFO = ^TPKCS7_SIGNER_INFO_st; // **Name conflict with wincrypt.h** PKCS7_SIGNER_INFO_OSSL = ^TPKCS7_SIGNER_INFO_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TPKCS7_ENVELOPED_st = record version : PASN1_INTEGER; recipientinfo : PSTACK_OF_PKCS7_SIGNER_INFO; enc_data : PPKCS7_ENC_CONTENT; end; PPKCS7_ENVELOPE = ^TPKCS7_ENVELOPED_st; PPKCS7 = ^TPKCS7_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TPKCS7_SIGNED_st = record version : PASN1_INTEGER; md_algs : PSTACK_OF_X509_ALGOR; cert : PSTACK_OF_X509; crl : PSTACK_OF_X509_CRL; signer_info : PSTACK_OF_PKCS7_SIGNER_INFO; contents : PPKCS7; end; PPKCS7_SIGNED = ^TPKCS7_SIGNED_st; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d PKCS7_signedandenveloped = record version : PASN1_INTEGER; md_algs : PSTACK_OF_X509_ALGOR; cert : PSTACK_OF_X509; crl : PSTACK_OF_X509_CRL; signer_info : PSTACK_OF_PKCS7_SIGNER_INFO; enc_data : PPKCS7_ENC_CONTENT; recipientinfo : PSTACK_OF_PKCS7_RECIP_INFO; end; PPKCS7_SIGN_ENVELOPE = ^PKCS7_signedandenveloped; // 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TPKCS7_st = record //AG { The following is non NULL if it contains ASN1 encoding of this structure } asn1 : PAnsiChar; length : Integer; state : Integer; detached : Integer; type_ : PASN1_OBJECT; case Integer of 0: (ptr : PAnsiChar); // NID_pkcs7_data 1: (data : PASN1_OCTET_STRING); // NID_pkcs7_signed 2: (sign : PPKCS7_SIGNED); // NID_pkcs7_enveloped 3: (enveloped : PPKCS7_ENVELOPE); // NID_pkcs7_signedAndEnveloped 4: (signed_and_enveloped : PPKCS7_SIGN_ENVELOPE); // NID_pkcs7_digest 5: (digest : PPKCS7_DIGEST); // NID_pkcs7_encrypted 6: (encrypted : PPKCS7_ENCRYPT); // Anything else 7: (other : PASN1_TYPE); end; PPPKCS7 = ^PPKCS7; { Danger ends } {AG} TPKCS12_st = packed record //AG Dummy : array [0..0] of Byte; end; PPKCS12 = ^TPKCS12_st; PPPKCS12 = ^PPKCS12; TV3_EXT_CTX_st = packed record Dummy : array [0..0] of Byte; end; PV3_EXT_CTX = ^TV3_EXT_CTX_st; // 0.9.7g, 0.9.8a, 0.9.8e TCONF_VALUE = record Section : PAnsiChar; Name : PAnsiChar; Value : PAnsiChar; end; PCONF_VALUE = ^TCONF_VALUE; //used in old PostConnectionCheck() {11/07/05 AG} { TCONF_VALUE_STACK_st = packed record Dummy : array [0..0] of Byte; end; PCONF_VALUE_STACK = ^TCONF_VALUE_STACK_st; } TASN1_ITEM_st = packed record Dummy : array [0..0] of Byte; end; PASN1_ITEM = ^TASN1_ITEM_st; PASN1_ITEM_EXP = function: PASN1_ITEM; cdecl; PX509V3_EXT_NEW = function: Pointer; cdecl; PX509V3_EXT_FREE = procedure(Arg: Pointer); cdecl; PX509V3_EXT_D2I = function(Arg1: Pointer; Arg2: PPAnsiChar; Arg3: LongInt): Pointer; cdecl; PX509V3_EXT_I2D = function(Arg1: Pointer; Arg2: PPAnsiChar): Integer; cdecl; PX509V3_EXT_I2S = function(X509V3_EXT_METHOD: Pointer; Ext: Pointer): PAnsiChar; cdecl; PX509V3_EXT_S2I = function(X509V3_EXT_METHOD: Pointer; Ctx: PV3_EXT_CTX; S: PAnsiChar): Pointer; cdecl; PX509V3_EXT_I2V = function(X509V3_EXT_METHOD: Pointer; Ext: Pointer; ExtList: PSTACK): PSTACK; cdecl; PX509V3_EXT_V2I = function(X509V3_EXT_METHOD: Pointer; Ctx: PV3_EXT_CTX; Values: PSTACK): Pointer; cdecl; PX509V3_EXT_I2R = function(X509V3_EXT_METHOD: Pointer; Ext: Pointer; Output: PBIO; Indent: Integer): Integer; cdecl; PX509V3_EXT_R2I = function(X509V3_EXT_METHOD: Pointer; Ctx: PV3_EXT_CTX; S: PAnsiChar): Pointer; cdecl; // V3 extension structure 0.9.7g, 0.9.8a, 0.9.8e, 1.0.0d TX509V3_EXT_METHOD = record // struct v3_ext_method ext_nid : Integer; ext_flags : Integer; // If this is set the following four fields are ignored - since v0.9.0.7 it : PASN1_ITEM_EXP; //AG // Old style ASN1 calls ext_new : PX509V3_EXT_NEW; ext_free : PX509V3_EXT_FREE; d2i : PX509V3_EXT_D2I; i2d : PX509V3_EXT_I2D; // The following pair is used for string extensions i2s : PX509V3_EXT_I2S; s2i : PX509V3_EXT_S2I; // The following pair is used for multi-valued extensions i2v : PX509V3_EXT_I2V; v2i : PX509V3_EXT_V2I; // The following are used for raw extensions i2r : PX509V3_EXT_I2R; r2i : PX509V3_EXT_R2I; // Any extension specific data usr_data : Pointer; end; PX509V3_EXT_METHOD = ^TX509V3_EXT_METHOD; type TPem_password_cb = function(Buf : PAnsiChar; Num : Integer; RWFlag : Integer; UserData : Pointer) : Integer; cdecl; TRSA_genkey_cb = procedure(N1, N2 : Integer; //AG cb_arg : Pointer); cdecl; TSetVerify_cb = function(Ok : Integer; StoreCtx : PX509_STORE_CTX) : Integer; cdecl; TSetInfo_cb = procedure(const ssl: PSSL; CbType: Integer; Val: Integer); cdecl; TNew_session_cb = function(const Ssl : PSSL; Sess : PSSL_SESSION): Integer; cdecl; PNew_session_cb = ^TNew_session_cb; TRemove_session_cb = procedure(const Ctx : PSSL_CTX; Sess : PSSL_SESSION); cdecl; PRemove_session_cb = ^TRemove_session_cb; TGet_session_cb = function(const Ssl : PSSL; SessID : Pointer; IdLen : Integer; Ref : PInteger) : PSSL_SESSION; cdecl; PGet_session_cb = ^TGet_session_cb; TClient_cert_cb = function (Ssl : PSSL; X509 : PPX509; PKEY : PPEVP_PKEY): Integer; cdecl; PClient_cert_cb = ^TClient_cert_cb; {$IFNDEF OPENSSL_NO_TLSEXT} TCallback_ctrl_fp = procedure (p : Pointer); cdecl; TSsl_servername_cb = function (s: PSSL; var ad: Integer; arg: Pointer): Integer; cdecl; {$ENDIF} const SSL2_VERSION = $0002; SSL2_VERSION_MAJOR = $00; SSL2_VERSION_MINOR = $02; SSL3_VERSION = $0300; SSL3_VERSION_MAJOR = $03; SSL3_VERSION_MINOR = $00; TLS1_VERSION = $0301; TLS1_VERSION_MAJOR = $03; TLS1_VERSION_MINOR = $01; BIO_NOCLOSE = 0; BIO_CLOSE = 1; SSL_ERROR_NONE = 0; SSL_ERROR_SSL = 1; SSL_ERROR_WANT_READ = 2; SSL_ERROR_WANT_WRITE = 3; SSL_ERROR_WANT_X509_LOOKUP = 4; SSL_ERROR_SYSCALL = 5; SSL_ERROR_ZERO_RETURN = 6; SSL_ERROR_WANT_CONNECT = 7; SSL_ERROR_WANT_ACCEPT = 8; X509_FILETYPE_PEM = 1; X509_FILETYPE_ASN1 = 2; X509_FILETYPE_DEFAULT = 3; X509_EXT_PACK_UNKNOWN = 1; X509_EXT_PACK_STRING = 2; SSL_FILETYPE_ASN1 = X509_FILETYPE_ASN1; SSL_FILETYPE_PEM = X509_FILETYPE_PEM; SSL_VERIFY_NONE = 0; SSL_VERIFY_PEER = 1; SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 2; SSL_VERIFY_CLIENT_ONCE = 4; { Removed 12/07/05 - due to changes in v0.9.8a SSL_CTRL_NEED_TMP_RSA = 1; SSL_CTRL_SET_TMP_RSA = 2; SSL_CTRL_SET_TMP_DH = 3; SSL_CTRL_SET_TMP_RSA_CB = 4; SSL_CTRL_SET_TMP_DH_CB = 5; SSL_CTRL_GET_SESSION_REUSED = 6; SSL_CTRL_GET_CLIENT_CERT_REQUEST = 7; SSL_CTRL_GET_NUM_RENEGOTIATIONS = 8; SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS = 9; SSL_CTRL_GET_TOTAL_RENEGOTIATIONS = 10; SSL_CTRL_GET_FLAGS = 11; SSL_CTRL_EXTRA_CHAIN_CERT = 12;} { These constants will be set dynamically in IcsLibeay.Load() } //12/07/05 added SSL_CTRL_EXTRA_CHAIN_CERT : Integer = 12; // v.0.9.7 - Ssl.h SSL_CTRL_EXTRA_CHAIN_CERT; SSL_CTRL_GET_SESSION_REUSED : Integer = 6; // v.0.9.7 - Ssl.h SSL_CTRL_GET_SESSION_REUSED // stats SSL_CTRL_SESS_NUMBER = 20; SSL_CTRL_SESS_CONNECT = 21; SSL_CTRL_SESS_CONNECT_GOOD = 22; SSL_CTRL_SESS_CONNECT_RENEGOTIATE = 23; SSL_CTRL_SESS_ACCEPT = 24; SSL_CTRL_SESS_ACCEPT_GOOD = 25; SSL_CTRL_SESS_ACCEPT_RENEGOTIATE = 26; SSL_CTRL_SESS_HIT = 27; SSL_CTRL_SESS_CB_HIT = 28; SSL_CTRL_SESS_MISSES = 29; SSL_CTRL_SESS_TIMEOUTS = 30; SSL_CTRL_SESS_CACHE_FULL = 31; SSL_CTRL_OPTIONS = 32; SSL_CTRL_MODE = 33; SSL_CTRL_GET_READ_AHEAD = 40; SSL_CTRL_SET_READ_AHEAD = 41; SSL_CTRL_SET_SESS_CACHE_SIZE = 42; SSL_CTRL_GET_SESS_CACHE_SIZE = 43; SSL_CTRL_SET_SESS_CACHE_MODE = 44; SSL_CTRL_GET_SESS_CACHE_MODE = 45; SSL_CTRL_GET_RI_SUPPORT = 76; { 0.9.8n } SSL_CTRL_CLEAR_OPTIONS = 77; { 0.9.8n } SSL_OP_MICROSOFT_SESS_ID_BUG = $00000001; SSL_OP_NETSCAPE_CHALLENGE_BUG = $00000002; SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = $00000008; SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG = $00000010; SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER = $00000020; SSL_OP_MSIE_SSLV2_RSA_PADDING = $00000040; SSL_OP_SSLEAY_080_CLIENT_DH_BUG = $00000080; SSL_OP_TLS_D5_BUG = $00000100; SSL_OP_TLS_BLOCK_PADDING_BUG = $00000200; // Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added // in OpenSSL 0.9.6d. Usually (depending on the application protocol) // the workaround is not needed. Unfortunately some broken SSL/TLS //implementations cannot handle it at all, which is why we include //it in SSL_OP_ALL. SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = $00000800; //SSL_OP_ALL: various bug workarounds that should be rather harmless. //This used to be 0x000FFFFFL before 0.9.7. // 0.9.8h, 0.9.8n, 0.9.8e, 0.9.7g $00000FFF SSL_OP_ALL = $00000FFF; //SSL_OP_ALL = $80000FFF; 1.0.0d //* DTLS options */ since 0.9.8 SSL_OP_NO_QUERY_MTU = $00001000; //Turn on Cookie Exchange (on relevant for servers) SSL_OP_COOKIE_EXCHANGE = $00002000; // Don't use RFC4507 ticket extension SSL_OP_NO_TICKET = $00004000; // As server, disallow session resumption on renegotiation SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = $00010000; // Don't use compression even if supported SSL_OP_NO_COMPRESSION = $00020000; // 1.0.0x // Permit unsafe legacy renegotiation { 0.9.8n } // which can be set with SSL_CTX_set_options(). This is really // not recommended unless you know what you are doing. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = $00040000; SSL_OP_SINGLE_DH_USE = $00100000; SSL_OP_EPHEMERAL_RSA = $00200000; // Set on servers to choose the cipher according to the server's // preferences */ SSL_OP_CIPHER_SERVER_PREFERENCE = $00400000; // If set, a server will allow a client to issue a SSLv3.0 version number // as latest version supported in the premaster secret, even when TLSv1.0 // (version 3.1) was announced in the client hello. Normally this is // forbidden to prevent version rollback attacks. ////SSL_OP_TLS_ROLLBACK_BUG = $00000400; SSL_OP_TLS_ROLLBACK_BUG = $00800000; SSL_OP_NO_SSLv2 = $01000000; SSL_OP_NO_SSLv3 = $02000000; SSL_OP_NO_TLSv1 = $04000000; SSL_OP_PKCS1_CHECK_1 = $08000000; SSL_OP_PKCS1_CHECK_2 = $10000000; SSL_OP_NETSCAPE_CA_DN_BUG = $20000000; //SSL_OP_NON_EXPORT_FIRST = $40000000; SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = $40000000; // Make server add server-hello extension from early version of // cryptopro draft, when GOST ciphersuite is negotiated. // Required for interoperability with CryptoPro CSP 3.x SSL_OP_CRYPTOPRO_TLSEXT_BUG = $80000000; // 1.0.0x SSL_MODE_ENABLE_PARTIAL_WRITE = $00000001; SSL_SESS_CACHE_OFF = $0000; SSL_SESS_CACHE_CLIENT = $0001; SSL_SESS_CACHE_SERVER = $0002; SSL_SESS_CACHE_BOTH = (SSL_SESS_CACHE_CLIENT or SSL_SESS_CACHE_SERVER); SSL_SESS_CACHE_NO_AUTO_CLEAR = $0080; //* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */ SSL_SESS_CACHE_NO_INTERNAL_LOOKUP = $0100; SSL_SESS_CACHE_NO_INTERNAL_STORE = $0200; SSL_SESS_CACHE_NO_INTERNAL = (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP or SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_SESSION_CACHE_MAX_SIZE_DEFAULT = (1024 * 20); SSL_ST_CONNECT = $1000; SSL_ST_ACCEPT = $2000; SSL_ST_MASK = $0FFF; SSL_ST_INIT = (SSL_ST_CONNECT or SSL_ST_ACCEPT); SSL_ST_BEFORE = $4000; SSL_ST_OK = $03; SSL_ST_RENEGOTIATE = ($04 or SSL_ST_INIT); SSL_CB_LOOP = 1; SSL_CB_EXIT = 2; SSL_CB_READ = 4; SSL_CB_WRITE = 8; SSL_CB_ALERT = $4000; // used in callback SSL_CB_READ_ALERT = (SSL_CB_ALERT or SSL_CB_READ); SSL_CB_WRITE_ALERT = (SSL_CB_ALERT or SSL_CB_WRITE); SSL_CB_ACCEPT_LOOP = (SSL_ST_ACCEPT or SSL_CB_LOOP); SSL_CB_ACCEPT_EXIT = (SSL_ST_ACCEPT or SSL_CB_EXIT); SSL_CB_CONNECT_LOOP = (SSL_ST_CONNECT or SSL_CB_LOOP); SSL_CB_CONNECT_EXIT = (SSL_ST_CONNECT or SSL_CB_EXIT); SSL_CB_HANDSHAKE_START = $10; SSL_CB_HANDSHAKE_DONE = $20; SSL_NOTHING = 1; SSL_WRITING = 2; SSL_READING = 3; SSL_X509_LOOKUP = 4; // Used in SSL_set_shutdown()/SSL_get_shutdown() SSL_SENT_SHUTDOWN = 1; SSL_RECEIVED_SHUTDOWN = 2; X509_TRUST_COMPAT = 1; //AG X509_TRUST_SSL_CLIENT = 2; //AG X509_TRUST_SSL_SERVER = 3; //AG X509_TRUST_EMAIL = 4; //AG X509_TRUST_OBJECT_SIGN = 5; //AG X509_TRUST_OCSP_SIGN = 6; //AG X509_TRUST_OCSP_REQUEST = 7; //AG SSL_MAX_SSL_SESSION_ID_LENGTH = 32; //AG SSL_MAX_SID_CTX_LENGTH = 32; //AG {$IFNDEF OPENSSL_NO_TLSEXT} {* ExtensionType values from RFC 3546 *} TLSEXT_TYPE_server_name = 0; TLSEXT_TYPE_max_fragment_length = 1; TLSEXT_TYPE_client_certificate_url = 2; TLSEXT_TYPE_trusted_ca_keys = 3; TLSEXT_TYPE_truncated_hmac = 4; TLSEXT_TYPE_status_request = 5; TLSEXT_TYPE_elliptic_curves = 10; TLSEXT_TYPE_ec_point_formats = 11; TLSEXT_TYPE_session_ticket = 35; TLSEXT_MAXLEN_host_name = 255; TLSEXT_NAMETYPE_host_name = 0; SSL_CTRL_SET_TLSEXT_SERVERNAME_CB = 53; SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG = 54; SSL_CTRL_SET_TLSEXT_HOSTNAME = 55; SSL_CTRL_SET_TLSEXT_DEBUG_CB = 56; SSL_CTRL_SET_TLSEXT_DEBUG_ARG = 57; SSL_TLSEXT_ERR_OK = 0; SSL_TLSEXT_ERR_ALERT_WARNING = 1; SSL_TLSEXT_ERR_ALERT_FATAL = 2; SSL_TLSEXT_ERR_NOACK = 3; {$ENDIF} const f_SSL_do_handshake : function(S: PSSL): Integer; cdecl = nil; //AG f_SSL_renegotiate : function(S: PSSL): Integer; cdecl = nil; //AG f_SSL_renegotiate_pending : function(S: PSSL): Integer; cdecl = nil; //AG f_SSL_library_init : function: Integer; cdecl = nil; f_SSL_load_error_strings : procedure; cdecl = nil; f_SSLv2_method : function: PSSL_METHOD; cdecl = nil; f_SSLv2_client_method : function: PSSL_METHOD; cdecl = nil; f_SSLv2_server_method : function: PSSL_METHOD; cdecl = nil; f_SSLv3_method : function: PSSL_METHOD; cdecl = nil; f_SSLv3_client_method : function: PSSL_METHOD; cdecl = nil; f_SSLv3_server_method : function: PSSL_METHOD; cdecl = nil; f_SSLv23_method : function: PSSL_METHOD; cdecl = nil; f_SSLv23_client_method : function: PSSL_METHOD; cdecl = nil; f_SSLv23_server_method : function: PSSL_METHOD; cdecl = nil; f_TLSv1_method : function: PSSL_METHOD; cdecl = nil; f_TLSv1_client_method : function: PSSL_METHOD; cdecl = nil; f_TLSv1_server_method : function: PSSL_METHOD; cdecl = nil; f_SSL_CTX_new : function(Meth: PSSL_METHOD): PSSL_CTX; cdecl = nil; f_SSL_new : function(Ctx: PSSL_CTX): PSSL; cdecl = nil; f_SSL_set_bio : procedure(S: PSSL; RBio: PBIO; WBio: PBIO); cdecl = nil; f_SSL_set_session : function(S: PSSL; Session: PSSL_SESSION): Integer; cdecl = nil; f_SSL_get_session : function(S: PSSL): PSSL_SESSION; cdecl = nil; f_SSL_get_rbio : function(S: PSSL): PBIO; cdecl = nil; f_SSL_get_wbio : function(S: PSSL): PBIO; cdecl = nil; f_SSL_get1_session : function(S: PSSL): PSSL_SESSION; cdecl = nil; f_SSL_session_free : procedure(Session: PSSL_SESSION); cdecl = nil; f_d2i_SSL_SESSION : function(Session: PPSSL_SESSION; const pp: PPAnsiChar; Length: Longword): PSSL_SESSION; cdecl = nil; f_i2d_SSL_SESSION : function(InSession: PSSL_SESSION; pp: PPAnsiChar): Integer; cdecl = nil; f_SSL_SESSION_get_time : function(const Sess: PSSL_SESSION): Longword; cdecl = nil; f_SSL_SESSION_set_time : function(Sess: PSSL_SESSION; T: Longword): Longword; cdecl = nil; f_SSL_SESSION_get_timeout : function(const Sess: PSSL_SESSION): Longword; cdecl = nil; f_SSL_SESSION_set_timeout : function(Sess: PSSL_SESSION; T: Longword): Longword; cdecl = nil; f_SSL_CTX_set_session_id_context : function(Ctx: PSSL_CTX; const Sid_ctx: PAnsiChar; sid_ctx_len: Integer): Integer; cdecl = nil; f_SSL_CTX_set_timeout : function(Ctx: PSSL_CTX; Timeout: Longword): Longword; cdecl = nil; f_SSL_CTX_get_cert_store : function(const Ctx: PSSL_CTX): PX509_STORE; cdecl = nil; //AG f_SSL_set_session_id_context : function(S: PSSL; const Sid_ctx: PAnsiChar; sid_ctx_len: Integer): Integer; cdecl = nil; f_SSL_accept : function(S: PSSL): Integer; cdecl = nil; f_SSL_connect : function(S: PSSL): Integer; cdecl = nil; f_SSL_ctrl : function(S: PSSL; Cmd: Integer; LArg: LongInt; PArg: Pointer): LongInt; cdecl = nil; f_SSL_read : function(S: PSSL; Buf: Pointer; Num: Integer): Integer; cdecl = nil; f_SSL_want : function(S: PSSL): Integer; cdecl = nil; f_SSL_write : function(S: PSSL; const Buf: Pointer; Num: Integer): Integer; cdecl = nil; f_SSL_get_error : function(S: PSSL; ErrCode: Integer): Integer; cdecl = nil; f_SSL_get_shutdown : function(S: PSSL): Integer; cdecl = nil; f_SSL_shutdown : function(S: PSSL): Integer; cdecl = nil; f_SSL_clear : procedure(S: PSSL); cdecl = nil; f_SSL_free : procedure(S: PSSL); cdecl = nil; f_SSL_set_ex_data : function(S: PSSL; Idx: Integer; Arg: Pointer): Integer; cdecl = nil; f_SSL_get_ex_data : function(S: PSSL; Idx: Integer): Pointer; cdecl = nil; f_SSL_get_peer_certificate : function(S: PSSL): PX509; cdecl = nil; f_SSL_get_peer_cert_chain : function(const S: PSSL): PSTACK_OF_X509; cdecl = nil; f_SSL_get_verify_depth : function(const S: PSSL): Integer; cdecl = nil; f_SSL_get_verify_result : function(S: PSSL): LongInt; cdecl = nil; f_SSL_set_verify_result : procedure(S: PSSL; VResult: LongInt); cdecl = nil; f_SSL_set_info_callback : procedure(S: PSSL; cb : TSetInfo_cb); cdecl = nil; f_SSL_set_connect_state : procedure(S: PSSL); cdecl = nil; f_SSL_set_accept_state : procedure(S: PSSL); cdecl = nil; //AG f_SSL_set_shutdown : procedure(S: PSSL; Mode: Integer); cdecl = nil; f_SSL_get_version : function(S: PSSL): PAnsiChar; cdecl = nil; f_SSL_version : function(const S: PSSL): Integer; cdecl = nil; //AG f_SSL_get_current_cipher : function(S: PSSL): Pointer; cdecl = nil; f_SSL_state : function(S: PSSL): Integer; cdecl = nil; f_SSL_state_string_long : function(S: PSSL): PAnsiChar; cdecl = nil; f_SSL_alert_type_string_long : function(value: Integer): PAnsiChar; cdecl = nil; f_SSL_alert_desc_string_long : function(value: Integer): PAnsiChar; cdecl = nil; f_SSL_CIPHER_get_bits : function(Cipher, Alg_Bits: Pointer): Integer; cdecl = nil; f_SSL_CIPHER_get_name : function(Cipher: Pointer): PAnsiChar; cdecl = nil; f_SSL_CIPHER_description : function(Cipher: Pointer; buf: PAnsiChar; size: Integer): PAnsiChar; cdecl = nil; f_SSL_CTX_free : procedure(C: PSSL_CTX); cdecl = nil; f_SSL_CTX_set_info_callback: procedure(ctx: PSSL_CTX; cb : TSetInfo_cb); cdecl = nil; f_SSL_CTX_use_certificate_chain_file : function(C: PSSL_CTX; const FileName: PAnsiChar): Integer; cdecl = nil; f_SSL_CTX_use_certificate_file : function(C: PSSL_CTX; const FileName: PAnsiChar; type_: Integer): Integer; cdecl = nil; //AG f_SSL_CTX_set_default_passwd_cb : procedure(C: PSSL_CTX; CallBack: TPem_password_cb); cdecl = nil; f_SSL_CTX_set_default_passwd_cb_userdata : procedure(C: PSSL_CTX; UData: Pointer); cdecl = nil; f_SSL_CTX_use_PrivateKey_file : function(C: PSSL_CTX; const FileName: PAnsiChar; CertType: Integer): Integer; cdecl = nil; f_SSL_CTX_use_PrivateKey : function(C: PSSL_CTX; pkey: PEVP_PKEY): Integer; cdecl = nil; f_SSL_CTX_load_verify_locations : function(C: PSSL_CTX; const FileName: PAnsiChar; const SearchPath: PAnsiChar): Integer; cdecl = nil; f_SSL_CTX_set_default_verify_paths : function(C: PSSL_CTX): Integer; cdecl = nil; f_SSL_CTX_set_verify : procedure(C: PSSL_CTX; Mode: Integer; CallBack : TSetVerify_cb); cdecl = nil; f_SSL_set_verify : procedure(S: PSSL; Mode: Integer; CallBack : TSetVerify_cb); cdecl = nil; f_SSL_CTX_get_verify_mode : function(const C: PSSL_CTX): Integer; cdecl = nil; //AG f_SSL_CTX_get_verify_depth : function(const ctx: PSSL_CTX): Integer; cdecl = nil; //AG f_SSL_CTX_set_verify_depth : procedure(C: PSSL_CTX; Depth: Integer); cdecl = nil; f_SSL_CTX_ctrl : function(C: PSSL_CTX; Cmd: Integer; LArg: LongInt; PArg: PAnsiChar): LongInt; cdecl = nil; f_SSL_CTX_set_ex_data : function(C: PSSL_CTX; Idx: Integer; Arg: PAnsiChar): Integer; cdecl = nil; f_SSL_CTX_get_ex_data : function(const C: PSSL_CTX; Idx: Integer): PAnsiChar; cdecl = nil; f_SSL_CTX_set_cipher_list : function(C: PSSL_CTX; CipherString: PAnsiChar): Integer; cdecl = nil; f_SSL_CTX_set_trust : function(C: PSSL_CTX; Trust: Integer): Integer; cdecl = nil; //AG {$IFNDEF BEFORE_OSSL_098E} f_SSL_CTX_set_client_cert_cb: procedure(CTX: PSSL_CTX; CB: TClient_cert_cb); cdecl = nil; //AG f_SSL_CTX_get_client_cert_cb: function(CTX: PSSL_CTX): TClient_cert_cb; cdecl = nil; //AG f_SSL_CTX_sess_set_remove_cb: procedure(Ctx: PSSL_CTX; CB: TRemove_session_cb); cdecl = nil; //AG f_SSL_CTX_sess_get_remove_cb: function(CTX: PSSL_CTX): TRemove_session_cb; cdecl = nil; //AG f_SSL_CTX_sess_set_get_cb: procedure(Ctx: PSSL_CTX; CB: TGet_session_cb); cdecl = nil; //AG f_SSL_CTX_sess_get_get_cb: function(CTX: PSSL_CTX): TGet_session_cb; cdecl = nil; //AG f_SSL_CTX_sess_set_new_cb: procedure(Ctx: PSSL_CTX; CB: TNew_session_cb); cdecl = nil; //AG f_SSL_CTX_sess_get_new_cb: function (CTX: PSSL_CTX): TNew_session_cb; cdecl = nil; //AG f_SSL_SESSION_get_id: function (const Ses: PSSL_SESSION; var Len: LongInt): PAnsiChar; cdecl = nil; //AG {$ENDIF} { The next four functions are only useful for TLS/SSL servers. } f_SSL_CTX_add_client_CA : function(C: PSSL_CTX; CaCert: PX509): Integer; cdecl = nil; //AG f_SSL_add_client_CA : function(ssl: PSSL; CaCert: PX509): Integer; cdecl = nil; //AG f_SSL_CTX_set_client_CA_list : procedure(C: PSSL_CTX; List: PSTACK_OF_X509_NAME); cdecl = nil; //AG f_SSL_set_client_CA_list : procedure(s: PSSL; List: PSTACK_OF_X509_NAME); cdecl = nil; //AG {$IFNDEF OPENSSL_NO_ENGINE} f_SSL_CTX_set_client_cert_engine : function(Ctx: PSSL_CTX; e: PENGINE): Integer; cdecl = nil; //AG {$ENDIF} f_SSL_load_client_CA_file : function(const FileName: PAnsiChar): PSTACK_OF_X509_NAME; cdecl = nil; //AG f_SSL_get_ex_data_X509_STORE_CTX_idx: function: Integer; cdecl = nil; f_BIO_f_ssl : function : PBIO_METHOD; cdecl = nil; f_SSL_set_fd: function(S: PSSL; fd: Integer): Integer; cdecl = nil; // B.S. f_SSL_set_rfd: function(S: PSSL; fd: Integer): Integer; cdecl = nil; // B.S. f_SSL_set_wfd: function(S: PSSL; fd: Integer): Integer; cdecl = nil; // B.S. f_SSL_get_fd: function(S: PSSL): Integer; cdecl = nil; // B.S. f_SSL_get_rfd: function(S: PSSL): Integer; cdecl = nil; // B.S. f_SSL_get_wfd: function(S: PSSL): Integer; cdecl = nil; // B.S. f_SSL_get_SSL_CTX: function(const S: PSSL): PSSL_CTX; cdecl = nil; f_SSL_get_client_CA_list : function(const S: PSSL): PSTACK_OF_X509_NAME; cdecl = nil; {$IFNDEF OPENSSL_NO_TLSEXT} f_SSL_set_SSL_CTX: function(S: PSSL; ctx: PSSL_CTX): PSSL_CTX; cdecl = nil; f_SSL_get_servername: function(const S: PSSL; const type_: Integer): PAnsiChar; cdecl = nil; f_SSL_get_servername_type: function(const S: PSSL): Integer; cdecl = nil; f_SSL_CTX_callback_ctrl: function(ctx: PSSL_CTX; cb_id: Integer; fp: TCallback_ctrl_fp): Longint; cdecl = nil; f_SSL_callback_ctrl: function(s: PSSL; cb_id: Integer; fp: TCallback_ctrl_fp): Longint; cdecl = nil; {$ENDIF} function Load : Boolean; function WhichFailedToLoad : String; function GetFileVerInfo( const AppName : String; out FileVersion : String; out FileDescription : String): Boolean; function f_SSL_CTX_set_options(C: PSSL_CTX; Op: LongInt): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_CTX_get_options(C: PSSL_CTX): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_get_options(S: PSSL): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_set_options(S: PSSL; Op: LongInt): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_clear_options(S: PSSL; Op: LongInt): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_want_read(S: PSSL) : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_want_write(S: PSSL) : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_want_nothing(S: PSSL) : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_want_x509_lookup(S: PSSL) : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_session_reused(SSL: PSSL): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_CTX_set_session_cache_mode(Ctx: PSSL_CTX; Mode: Integer): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_CTX_sess_set_cache_size(Ctx: PSSL_CTX; CacheSize: Integer): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_CTX_add_extra_chain_cert(Ctx: PSSL_CTX; Cert: PX509): Longword; {$IFDEF USE_INLINE} inline; {$ENDIF} {$IFDEF BEFORE_OSSL_098E} //procedure f_SSL_session_get_id(Ses: PSSL_SESSION; var SessID: Pointer; var IdLen: Integer); function f_SSL_SESSION_get_id(const Ses: PSSL_SESSION; var IdLen: LongInt): PAnsiChar; procedure f_SSL_CTX_sess_set_new_cb(Ctx: PSSL_CTX; CB: TNew_session_cb); procedure f_SSL_CTX_sess_set_get_cb(Ctx: PSSL_CTX; CB: TGet_session_cb); procedure f_SSL_CTX_sess_set_remove_cb(Ctx: PSSL_CTX; CB: TRemove_session_cb); procedure f_SSL_CTX_set_client_cert_cb(Ctx: PSSL_CTX; CB: TClient_cert_cb); function f_SSL_CTX_get_client_cert_cb(CTX: PSSL_CTX): Pointer; {$ENDIF} {$IFNDEF OPENSSL_NO_TLSEXT} function f_SSL_set_tlsext_host_name(const S: PSSL; const name: String): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_CTX_set_tlsext_servername_callback(ctx: PSSL_CTX; cb: TCallback_ctrl_fp): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_CTX_set_tlsext_servername_arg(ctx: PSSL_CTX; arg: Pointer): LongInt; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_set_tlsext_debug_callback(S: PSSL; cb: TCallback_ctrl_fp): Longint; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_SSL_set_tlsext_debug_arg(S: PSSL; arg: Pointer): Longint; {$IFDEF USE_INLINE} inline; {$ENDIF} {$ENDIF} const GSSLEAY_DLL_Handle : THandle = 0; GSSLEAY_DLL_Name : String = 'SSLEAY32.DLL'; GSSLEAY_DLL_FileName : String = '*NOT_LOADED*'; GSSLEAY_DLL_FileVersion : String = ''; GSSLEAY_DLL_FileDescription : String = ''; {$ENDIF} // USE_SSL implementation {$IFDEF USE_SSL} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetFileVerInfo( const AppName : String; out FileVersion : String; out FileDescription : String): Boolean; const DEFAULT_LANG_ID = $0409; DEFAULT_CHAR_SET_ID = $04E4; type TTranslationPair = packed record Lang, CharSet: WORD; end; PTranslationIDList = ^TTranslationIDList; TTranslationIDList = array[0..MAXINT div SizeOf(TTranslationPair) - 1] of TTranslationPair; var Buffer, PStr : PChar; BufSize : DWORD; StrSize, IDsLen : DWORD; Status : Boolean; LangCharSet : String; IDs : PTranslationIDList; begin Result := FALSE; FileVersion := ''; FileDescription := ''; BufSize := GetFileVersionInfoSize(PChar(AppName), StrSize); if BufSize = 0 then Exit; GetMem(Buffer, BufSize); try // get all version info into Buffer Status := GetFileVersionInfo(PChar(AppName), 0, BufSize, Buffer); if not Status then Exit; // set language Id LangCharSet := '040904E4'; if VerQueryValue(Buffer, PChar('\VarFileInfo\Translation'), Pointer(IDs), IDsLen) then begin if IDs^[0].Lang = 0 then IDs^[0].Lang := DEFAULT_LANG_ID; if IDs^[0].CharSet = 0 then IDs^[0].CharSet := DEFAULT_CHAR_SET_ID; LangCharSet := Format('%.4x%.4x', [IDs^[0].Lang, IDs^[0].CharSet]); end; // now read real information Status := VerQueryValue(Buffer, PChar('\StringFileInfo\' + LangCharSet + '\FileVersion'), Pointer(PStr), StrSize); if Status then begin FileVersion := StrPas(PStr); Result := TRUE; end; Status := VerQueryValue(Buffer, PChar('\StringFileInfo\' + LangCharSet + '\FileDescription'), Pointer(PStr), StrSize); if Status then FileDescription := StrPas(PStr); finally FreeMem(Buffer); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Load : Boolean; var ErrCode : Integer; begin if GSSLEAY_DLL_Handle <> 0 then begin Result := TRUE; Exit; // Already loaded end; GetFileVerInfo(GSSLEAY_DLL_Name, GSSLEAY_DLL_FileVersion, GSSLEAY_DLL_FileDescription); GSSLEAY_DLL_Handle := LoadLibrary(PChar(GSSLEAY_DLL_Name)); if GSSLEAY_DLL_Handle = 0 then begin ErrCode := GetLastError; GSSLEAY_DLL_Handle := 0; if ErrCode = ERROR_MOD_NOT_FOUND then raise EIcsSsleayException.Create('File not found: ' + GSSLEAY_DLL_Name) else raise EIcsSsleayException.Create('Unable to load ' + GSSLEAY_DLL_Name + '. Win32 error #' + IntToStr(ErrCode)); end; SetLength(GSSLEAY_DLL_FileName, 256); SetLength(GSSLEAY_DLL_FileName, GetModuleFileName(GSSLEAY_DLL_Handle, PChar(GSSLEAY_DLL_FileName), Length(GSSLEAY_DLL_FileName))); f_SSL_do_handshake := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_do_handshake'); f_SSL_renegotiate := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_renegotiate'); f_SSL_renegotiate_pending := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_renegotiate_pending'); f_SSL_library_init := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_library_init'); f_SSL_load_error_strings := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_load_error_strings'); f_SSLv2_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv2_method'); f_SSLv2_client_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv2_client_method'); f_SSLv2_server_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv2_server_method'); f_SSLv3_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv3_method'); f_SSLv3_client_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv3_client_method'); f_SSLv3_server_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv3_server_method'); f_SSLv23_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv23_method'); f_SSLv23_client_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv23_client_method'); f_SSLv23_server_method := GetProcAddress(GSSLEAY_DLL_Handle, 'SSLv23_server_method'); f_TLSv1_method := GetProcAddress(GSSLEAY_DLL_Handle, 'TLSv1_method'); f_TLSv1_client_method := GetProcAddress(GSSLEAY_DLL_Handle, 'TLSv1_client_method'); f_TLSv1_server_method := GetProcAddress(GSSLEAY_DLL_Handle, 'TLSv1_server_method'); f_SSL_CTX_new := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_new'); f_SSL_new := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_new'); f_SSL_set_bio := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_bio'); f_SSL_set_session := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_session'); f_SSL_get_session := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_session'); f_SSL_get_rbio := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_rbio'); f_SSL_get_wbio := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_wbio'); f_SSL_get1_session := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get1_session'); f_SSL_SESSION_free := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_SESSION_free'); f_SSL_SESSION_set_timeout := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_SESSION_set_timeout'); f_SSL_SESSION_get_timeout := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_SESSION_get_timeout'); f_SSL_SESSION_set_time := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_SESSION_set_time'); f_SSL_SESSION_get_time := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_SESSION_get_time'); f_d2i_SSL_SESSION := GetProcAddress(GSSLEAY_DLL_Handle, 'd2i_SSL_SESSION'); f_i2d_SSL_SESSION := GetProcAddress(GSSLEAY_DLL_Handle, 'i2d_SSL_SESSION'); f_SSL_CTX_set_session_id_context := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_session_id_context'); f_SSL_set_session_id_context := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_session_id_context'); f_SSL_accept := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_accept'); f_SSL_connect := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_connect'); f_SSL_ctrl := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_ctrl'); f_SSL_read := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_read'); f_SSL_want := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_want'); f_SSL_write := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_write'); f_SSL_get_error := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_error'); f_SSL_get_shutdown := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_shutdown'); f_SSL_shutdown := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_shutdown'); f_SSL_clear := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_clear'); f_SSL_free := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_free'); f_SSL_set_ex_data := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_ex_data'); f_SSL_get_ex_data := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_ex_data'); f_SSL_get_peer_certificate := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_peer_certificate'); f_SSL_get_peer_cert_chain := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_peer_cert_chain'); f_SSL_get_verify_depth := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_verify_depth'); f_SSL_get_verify_result := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_verify_result'); f_SSL_set_verify_result := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_verify_result'); f_SSL_set_info_callback := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_info_callback'); f_SSL_set_connect_state := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_connect_state'); f_SSL_set_shutdown := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_shutdown'); f_SSL_set_accept_state := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_accept_state'); //AG f_SSL_get_version := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_version'); f_SSL_version := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_version'); //AG f_SSL_get_current_cipher := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_current_cipher'); f_SSL_state := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_state'); f_SSL_state_string_long := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_state_string_long'); f_SSL_alert_type_string_long := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_alert_type_string_long'); f_SSL_alert_desc_string_long := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_alert_desc_string_long'); f_SSL_CIPHER_get_bits := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CIPHER_get_bits'); f_SSL_CIPHER_get_name := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CIPHER_get_name'); f_SSL_CIPHER_description := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CIPHER_description'); f_SSL_CTX_free := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_free'); f_SSL_CTX_set_info_callback := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_info_callback'); f_SSL_CTX_set_timeout := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_timeout'); f_SSL_CTX_use_certificate_chain_file := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_use_certificate_chain_file'); f_SSL_CTX_use_certificate_file := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_use_certificate_file'); f_SSL_CTX_set_default_passwd_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_default_passwd_cb'); f_SSL_CTX_set_default_passwd_cb_userdata := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_default_passwd_cb_userdata'); f_SSL_CTX_use_PrivateKey_file := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_use_PrivateKey_file'); f_SSL_CTX_use_PrivateKey := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_use_PrivateKey'); f_SSL_CTX_load_verify_locations := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_load_verify_locations'); f_SSL_CTX_set_default_verify_paths := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_default_verify_paths'); f_SSL_CTX_set_verify := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_verify'); f_SSL_set_verify := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_verify'); f_SSL_CTX_get_verify_mode := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_get_verify_mode'); f_SSL_CTX_get_verify_depth := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_get_verify_depth'); f_SSL_CTX_set_verify_depth := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_verify_depth'); f_SSL_CTX_ctrl := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_ctrl'); f_SSL_CTX_set_cipher_list := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_cipher_list'); f_SSL_CTX_set_ex_data := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_ex_data'); f_SSL_CTX_get_ex_data := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_get_ex_data'); f_SSL_CTX_get_cert_store := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_get_cert_store'); f_SSL_CTX_set_trust := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_trust'); {$IFNDEF BEFORE_OSSL_098E} f_SSL_CTX_set_client_cert_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_client_cert_cb'); //AG f_SSL_CTX_get_client_cert_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_get_client_cert_cb'); //AG f_SSL_CTX_sess_set_remove_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_sess_set_remove_cb'); //AG f_SSL_CTX_sess_get_remove_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_sess_get_remove_cb'); //AG f_SSL_CTX_sess_set_get_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_sess_set_get_cb'); //AG f_SSL_CTX_sess_get_get_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_sess_get_get_cb'); //AG f_SSL_CTX_sess_set_new_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_sess_set_new_cb'); //AG f_SSL_CTX_sess_get_new_cb := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_sess_get_new_cb'); //AG f_SSL_SESSION_get_id := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_SESSION_get_id'); //AG {$ENDIF} f_SSL_CTX_add_client_CA := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_add_client_CA'); //AG f_SSL_add_client_CA := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_add_client_CA'); //AG f_SSL_CTX_set_client_CA_list := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_client_CA_list'); //AG f_SSL_set_client_CA_list := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_client_CA_list'); //AG {$IFNDEF OPENSSL_NO_ENGINE} f_SSL_CTX_set_client_cert_engine := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_set_client_cert_engine'); //AG {$ENDIF} f_SSL_load_client_CA_file := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_load_client_CA_file'); //AG f_SSL_get_ex_data_X509_STORE_CTX_idx := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_ex_data_X509_STORE_CTX_idx'); f_BIO_f_ssl := GetProcAddress(GSSLEAY_DLL_Handle, 'BIO_f_ssl'); f_SSL_set_fd := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_fd'); // B.S. f_SSL_set_rfd := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_rfd'); // B.S. f_SSL_set_wfd := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_wfd'); // B.S. f_SSL_get_fd := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_fd'); // B.S. f_SSL_get_rfd := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_rfd'); // B.S. f_SSL_get_wfd := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_wfd'); // B.S. f_SSL_get_SSL_CTX := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_SSL_CTX'); //AG f_SSL_get_client_CA_list := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_client_CA_list'); //AG {$IFNDEF OPENSSL_NO_TLSEXT} f_SSL_set_SSL_CTX := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_set_SSL_CTX'); //AG f_SSL_get_servername := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_servername'); //AG f_SSL_get_servername_type := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_get_servername_type'); //AG f_SSL_CTX_callback_ctrl := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_CTX_callback_ctrl'); //AG f_SSL_callback_ctrl := GetProcAddress(GSSLEAY_DLL_Handle, 'SSL_callback_ctrl'); //AG {$ENDIF} // Check if any failed Result := not ((@f_SSL_do_handshake = nil) or (@f_SSL_renegotiate = nil) or (@f_SSL_renegotiate_pending = nil) or (@f_SSL_library_init = nil) or (@f_SSL_load_error_strings = nil) or (@f_SSLv2_method = nil) or (@f_SSLv2_client_method = nil) or (@f_SSLv2_server_method = nil) or (@f_SSLv3_method = nil) or (@f_SSLv3_client_method = nil) or (@f_SSLv3_server_method = nil) or (@f_SSLv23_method = nil) or (@f_SSLv23_client_method = nil) or (@f_SSLv23_server_method = nil) or (@f_TLSv1_method = nil) or (@f_TLSv1_client_method = nil) or (@f_TLSv1_server_method = nil) or (@f_SSL_CTX_new = nil) or (@f_SSL_new = nil) or (@f_SSL_set_bio = nil) or (@f_SSL_set_session = nil) or (@f_SSL_get_session = nil) or (@f_SSL_get_rbio = nil) or (@f_SSL_get_wbio = nil) or (@f_SSL_get1_session = nil) or (@f_SSL_SESSION_free = nil) or (@f_SSL_SESSION_set_timeout = nil) or (@f_SSL_SESSION_get_timeout = nil) or (@f_SSL_SESSION_set_time = nil) or (@f_SSL_SESSION_get_time = nil) or (@f_d2i_SSL_SESSION = nil) or (@f_i2d_SSL_SESSION = nil) or (@f_SSL_CTX_set_session_id_context = nil) or (@f_SSL_set_session_id_context = nil) or (@f_SSL_accept = nil) or (@f_SSL_connect = nil) or (@f_SSL_ctrl = nil) or (@f_SSL_read = nil) or (@f_SSL_want = nil) or (@f_SSL_write = nil) or (@f_SSL_get_error = nil) or (@f_SSL_get_shutdown = nil) or (@f_SSL_shutdown = nil) or (@f_SSL_clear = nil) or (@f_SSL_free = nil) or (@f_SSL_set_ex_data = nil) or (@f_SSL_get_ex_data = nil) or (@f_SSL_get_peer_certificate = nil) or (@f_SSL_get_peer_cert_chain = nil) or (@f_SSL_get_verify_depth = nil) or (@f_SSL_get_verify_result = nil) or (@f_SSL_set_verify_result = nil) or (@f_SSL_set_info_callback = nil) or (@f_SSL_set_connect_state = nil) or (@f_SSL_set_shutdown = nil) or (@f_SSL_set_accept_state = nil) or //AG (@f_SSL_get_version = nil) or (@f_SSL_version = nil) or (@f_SSL_get_current_cipher = nil) or (@f_SSL_state = nil) or (@f_SSL_state_string_long = nil) or (@f_SSL_alert_type_string_long = nil) or (@f_SSL_alert_desc_string_long = nil) or (@f_SSL_CIPHER_get_bits = nil) or (@f_SSL_CIPHER_get_name = nil) or (@f_SSL_CIPHER_description = nil) or (@f_SSL_CTX_free = nil) or (@f_SSL_CTX_set_info_callback = nil) or (@f_SSL_CTX_set_timeout = nil) or (@f_SSL_CTX_use_certificate_chain_file = nil) or (@f_SSL_CTX_use_certificate_file = nil) or (@f_SSL_CTX_set_default_passwd_cb = nil) or (@f_SSL_CTX_set_default_passwd_cb_userdata = nil) or (@f_SSL_CTX_use_PrivateKey_file = nil) or (@f_SSL_CTX_load_verify_locations = nil) or (@f_SSL_CTX_set_default_verify_paths = nil) or (@f_SSL_CTX_set_verify = nil) or (@f_SSL_set_verify = nil) or (@f_SSL_CTX_get_verify_mode = nil) or (@f_SSL_CTX_ctrl = nil) or (@f_SSL_CTX_set_cipher_list = nil) or (@f_SSL_CTX_get_verify_depth = nil) or (@f_SSL_CTX_set_verify_depth = nil) or (@f_SSL_CTX_get_ex_data = nil) or (@f_SSL_CTX_set_ex_data = nil) or (@f_SSL_CTX_get_cert_store = nil) or (@f_SSL_CTX_set_trust = nil) or {$IFNDEF BEFORE_OSSL_098E} (@f_SSL_CTX_set_client_cert_cb = nil) or (@f_SSL_CTX_get_client_cert_cb = nil) or (@f_SSL_CTX_sess_set_remove_cb = nil) or (@f_SSL_CTX_sess_get_remove_cb = nil) or (@f_SSL_CTX_sess_set_get_cb = nil) or (@f_SSL_CTX_sess_get_get_cb = nil) or (@f_SSL_CTX_sess_set_new_cb = nil) or (@f_SSL_CTX_sess_get_new_cb = nil) or (@f_SSL_SESSION_get_id = nil) or {$ENDIF} (@f_SSL_CTX_add_client_CA = nil) or (@f_SSL_add_client_CA = nil) or (@f_SSL_CTX_set_client_CA_list = nil) or (@f_SSL_set_client_CA_list = nil) or {$IFNDEF OPENSSL_NO_ENGINE} (@f_SSL_CTX_set_client_cert_engine = nil) or {$ENDIF} (@f_SSL_load_client_CA_file = nil) or (@f_SSL_get_ex_data_X509_STORE_CTX_idx = nil) or (@f_BIO_f_ssl = nil) or (@f_SSL_set_fd = nil) or (@f_SSL_set_rfd = nil) or (@f_SSL_set_wfd = nil) or (@f_SSL_get_fd = nil) or (@f_SSL_get_rfd = nil) or (@f_SSL_get_wfd = nil) or (@f_SSL_CTX_use_PrivateKey = nil) or (@f_SSL_get_SSL_CTX = nil) or (@f_SSL_get_client_CA_list = nil) {$IFNDEF OPENSSL_NO_TLSEXT} or (@f_SSL_set_SSL_CTX = nil) or (@f_SSL_get_servername = nil) or (@f_SSL_get_servername_type = nil) or (@f_SSL_CTX_callback_ctrl = nil) or (@f_SSL_callback_ctrl = nil) {$ENDIF} ); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WhichFailedToLoad : String; begin Result := ''; if @f_SSL_do_handshake = nil then Result := Result + ' SSL_do_handshake'; if @f_SSL_renegotiate = nil then Result := Result + ' SSL_renegotiate'; if @f_SSL_renegotiate_pending = nil then Result := Result + ' SSL_renegotiate_pending'; if @f_SSL_library_init = nil then Result := Result + ' SSL_library_init'; if @f_SSL_load_error_strings = nil then Result := Result + ' SSL_load_error_strings'; if @f_SSLv2_method = nil then Result := Result + ' SSLv2_method'; if @f_SSLv2_client_method = nil then Result := Result + ' SSLv2_client_method'; if @f_SSLv2_server_method = nil then Result := Result + ' SSLv2_server_method'; if @f_SSLv3_method = nil then Result := Result + ' SSLv3_method'; if @f_SSLv3_client_method = nil then Result := Result + ' SSLv3_client_method'; if @f_SSLv3_server_method = nil then Result := Result + ' SSLv3_server_method'; if @f_SSLv23_method = nil then Result := Result + ' SSLv23_method'; if @f_SSLv23_client_method = nil then Result := Result + ' SSLv23_client_method'; if @f_SSLv23_server_method = nil then Result := Result + ' SSLv23_server_method'; if @f_TLSv1_method = nil then Result := Result + ' TLSv1_method'; if @f_TLSv1_client_method = nil then Result := Result + ' TLSv1_client_method'; if @f_TLSv1_server_method = nil then Result := Result + ' TLSv1_server_method'; if @f_SSL_CTX_new = nil then Result := Result + ' SSL_CTX_new'; if @f_SSL_new = nil then Result := Result + ' SSL_new'; if @f_SSL_set_bio = nil then Result := Result + ' SSL_set_bio'; if @f_SSL_set_session = nil then Result := Result + ' SSL_set_session'; if @f_SSL_get_session = nil then Result := Result + ' SSL_get_session'; if @f_SSL_get_rbio = nil then Result := Result + ' SSL_get_rbio'; if @f_SSL_get_wbio = nil then Result := Result + ' SSL_get_wbio'; if @f_SSL_get1_session = nil then Result := Result + ' SSL_get1_session'; if @f_SSL_SESSION_free = nil then Result := Result + ' SSL_SESSION_free'; if @f_SSL_SESSION_set_timeout = nil then Result := Result + ' SSL_SESSION_set_timeout'; if @f_SSL_SESSION_get_timeout = nil then Result := Result + ' SSL_SESSION_get_timeout'; if @f_SSL_SESSION_set_time = nil then Result := Result + ' SSL_SESSION_set_time'; if @f_SSL_SESSION_get_time = nil then Result := Result + ' SSL_SESSION_get_time'; if @f_d2i_SSL_SESSION = nil then Result := Result + ' d2i_SSL_SESSION'; if @f_i2d_SSL_SESSION = nil then Result := Result + ' i2d_SSL_SESSION'; if @f_SSL_CTX_set_session_id_context = nil then Result := Result + ' SSL_CTX_set_session_id_context'; if @f_SSL_set_session_id_context = nil then Result := Result + ' SSL_set_session_id_context'; if @f_SSL_accept = nil then Result := Result + ' SSL_accept'; if @f_SSL_connect = nil then Result := Result + ' SSL_connect'; if @f_SSL_ctrl = nil then Result := Result + ' SSL_ctrl'; if @f_SSL_read = nil then Result := Result + ' SSL_read'; if @f_SSL_want = nil then Result := Result + ' SSL_want'; if @f_SSL_write = nil then Result := Result + ' SSL_write'; if @f_SSL_get_error = nil then Result := Result + ' SSL_get_error'; if @f_SSL_get_shutdown = nil then Result := Result + ' SSL_get_shutdown'; if @f_SSL_shutdown = nil then Result := Result + ' SSL_shutdown'; if @f_SSL_clear = nil then Result := Result + ' SSL_clear'; if @f_SSL_free = nil then Result := Result + ' SSL_free'; if @f_SSL_set_ex_data = nil then Result := Result + ' SSL_set_ex_data'; if @f_SSL_get_ex_data = nil then Result := Result + ' SSL_get_ex_data'; if @f_SSL_get_peer_certificate = nil then Result := Result + ' SSL_get_peer_certificate'; if @f_SSL_get_peer_cert_chain = nil then Result := Result + ' SSL_get_peer_cert_chain'; if @f_SSL_get_verify_depth = nil then Result := Result + ' SSL_get_verify_depth'; if @f_SSL_get_verify_result = nil then Result := Result + ' SSL_get_verify_result'; if @f_SSL_set_verify_result = nil then Result := Result + ' SSL_set_verify_result'; if @f_SSL_set_info_callback = nil then Result := Result + ' SSL_set_info_callback'; if @f_SSL_set_connect_state = nil then Result := Result + ' SSL_set_connect_state'; if @f_SSL_set_shutdown = nil then Result := Result + ' SSL_set_shutdown'; if @f_SSL_set_accept_state = nil then Result := Result + ' SSL_set_accept_state';//AG if @f_SSL_set_bio = nil then Result := Result + ' SSL_set_bio'; if @f_SSL_get_version = nil then Result := Result + ' SSL_get_version'; if @f_SSL_version = nil then Result := Result + ' SSL_version'; if @f_SSL_get_current_cipher = nil then Result := Result + ' SSL_get_current_cipher'; if @f_SSL_state = nil then Result := Result + ' SSL_state'; if @f_SSL_state_string_long = nil then Result := Result + ' SSL_state_string_long'; if @f_SSL_alert_type_string_long = nil then Result := Result + ' SSL_alert_type_string_long'; if @f_SSL_alert_desc_string_long = nil then Result := Result + ' SSL_alert_desc_string_long'; if @f_SSL_CIPHER_get_bits = nil then Result := Result + ' SSL_CIPHER_get_bits'; if @f_SSL_CIPHER_get_name = nil then Result := Result + ' SSL_CIPHER_get_name'; if @f_SSL_CIPHER_description = nil then Result := Result + ' SSL_CIPHER_description'; if @f_SSL_CTX_free = nil then Result := Result + ' SSL_CTX_free'; if @f_SSL_CTX_set_info_callback = nil then Result := Result + ' SSL_CTX_set_info_callback'; if @f_SSL_CTX_set_timeout = nil then Result := Result + ' SSL_CTX_set_timeout'; if @f_SSL_CTX_use_certificate_chain_file = nil then Result := Result + ' SSL_CTX_use_certificate_chain_file'; if @f_SSL_CTX_use_certificate_file = nil then Result := Result + ' SSL_CTX_use_certificate_file'; if @f_SSL_CTX_use_PrivateKey = nil then Result := Result + ' SSL_CTX_use_certificate'; if @f_SSL_CTX_set_default_passwd_cb = nil then Result := Result + ' SSL_CTX_set_default_passwd_cb'; if @f_SSL_CTX_set_default_passwd_cb_userdata = nil then Result := Result + ' SSL_CTX_set_default_passwd_cb_userdata'; if @f_SSL_CTX_use_PrivateKey_file = nil then Result := Result + ' SSL_CTX_use_PrivateKey_file'; if @f_SSL_CTX_load_verify_locations = nil then Result := Result + ' SSL_CTX_load_verify_locations'; if @f_SSL_CTX_set_default_verify_paths = nil then Result := Result + ' SSL_CTX_set_default_verify_paths'; if @f_SSL_CTX_set_verify = nil then Result := Result + ' SSL_CTX_set_verify'; if @f_SSL_set_verify = nil then Result := Result + ' SSL_set_verify'; if @f_SSL_CTX_get_verify_mode = nil then Result := Result + ' SSL_CTX_get_verify_mode'; if @f_SSL_CTX_ctrl = nil then Result := Result + ' SSL_CTX_ctrl'; if @f_SSL_CTX_set_cipher_list = nil then Result := Result + ' SSL_CTX_set_cipher_list'; if @f_SSL_CTX_get_verify_depth = nil then Result := Result + ' SSL_CTX_get_verify_depth'; if @f_SSL_CTX_set_verify_depth = nil then Result := Result + ' SSL_CTX_set_verify_depth'; if @f_SSL_CTX_get_ex_data = nil then Result := Result + ' SSL_CTX_get_ex_data'; if @f_SSL_CTX_set_ex_data = nil then Result := Result + ' SSL_CTX_set_ex_data'; if @f_SSL_CTX_get_cert_store = nil then Result := Result + ' SSL_CTX_get_cert_store'; if @f_SSL_CTX_set_trust = nil then Result := Result + ' SSL_CTX_set_trust'; {$IFNDEF BEFORE_OSSL_098E} if @f_SSL_CTX_set_client_cert_cb = nil then Result := Result + ' SSL_CTX_set_client_cert_cb'; if @f_SSL_CTX_get_client_cert_cb = nil then Result := Result + ' SSL_CTX_get_client_cert_cb'; if @f_SSL_CTX_sess_set_remove_cb = nil then Result := Result + ' SSL_CTX_sess_set_remove_cb'; if @f_SSL_CTX_sess_get_remove_cb = nil then Result := Result + ' SSL_CTX_sess_get_remove_cb'; if @f_SSL_CTX_sess_set_get_cb = nil then Result := Result + ' SSL_CTX_sess_set_get_cb'; if @f_SSL_CTX_sess_get_get_cb = nil then Result := Result + ' SSL_CTX_sess_get_get_cb'; if @f_SSL_CTX_sess_set_new_cb = nil then Result := Result + ' SSL_CTX_sess_set_new_cb'; if @f_SSL_CTX_sess_get_new_cb = nil then Result := Result + ' SSL_CTX_sess_get_new_cb'; if @f_SSL_SESSION_get_id = nil then Result := Result + ' SSL_SESSION_get_id'; {$ENDIF} if @f_SSL_CTX_add_client_CA = nil then Result := Result + ' SSL_CTX_add_client_CA'; if @f_SSL_add_client_CA = nil then Result := Result + ' SSL_add_client_CA'; if @f_SSL_CTX_set_client_CA_list = nil then Result := Result + ' SSL_CTX_set_client_CA_list'; if @f_SSL_set_client_CA_list = nil then Result := Result + ' SSL_set_client_CA_list'; {$IFNDEF OPENSSL_NO_ENGINE} if @f_SSL_CTX_set_client_cert_engine = nil then Result := Result + ' SSL_CTX_set_client_cert_engine'; {$ENDIF} if @f_SSL_load_client_CA_file = nil then Result := Result + ' SSL_load_client_CA_file'; if @f_SSL_get_ex_data_X509_STORE_CTX_idx = nil then Result := Result + ' SSL_get_ex_data_X509_STORE_CTX_idx'; if @f_BIO_f_ssl = nil then Result := Result + ' BIO_f_ssl'; if @f_SSL_set_fd = nil then Result := Result + ' SSL_set_fd'; if @f_SSL_set_rfd = nil then Result := Result + ' SSL_set_rfd'; if @f_SSL_set_wfd = nil then Result := Result + ' SSL_set_wfd'; if @f_SSL_get_fd = nil then Result := Result + ' SSL_get_fd'; if @f_SSL_get_rfd = nil then Result := Result + ' SSL_get_rfd'; if @f_SSL_get_wfd = nil then Result := Result + ' SSL_get_wfd'; if @f_SSL_get_SSL_CTX = nil then Result := Result + ' SSL_get_SSL_CTX'; if @f_SSL_get_client_CA_list = nil then Result := Result + ' SSL_get_client_CA_list'; {$IFNDEF OPENSSL_NO_TLSEXT} if @f_SSL_set_SSL_CTX = nil then Result := Result + ' SSL_set_SSL_CTX'; if @f_SSL_get_servername = nil then Result := Result + ' SSL_get_servername'; if @f_SSL_get_servername_type = nil then Result := Result + ' SSL_get_servername_type'; if @f_SSL_CTX_callback_ctrl = nil then Result := Result + ' SSL_CTX_callback_ctrl'; if @f_SSL_callback_ctrl = nil then Result := Result + ' SSL_callback_ctrl'; {$ENDIF} if Length(Result) > 0 then Delete(Result, 1, 1); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_set_options(C: PSSL_CTX; Op: LongInt): LongInt; begin Result := f_SSL_CTX_ctrl(C, SSL_CTRL_OPTIONS, Op, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_get_options(C: PSSL_CTX): LongInt; begin Result := f_SSL_CTX_ctrl(C, SSL_CTRL_OPTIONS, 0, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_set_options(S: PSSL; Op: LongInt): LongInt; begin Result := f_SSL_ctrl(S, SSL_CTRL_OPTIONS, Op, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_clear_options(S: PSSL; Op: LongInt): LongInt; begin Result := f_SSL_ctrl(S, SSL_CTRL_CLEAR_OPTIONS, Op, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_get_options(S: PSSL): LongInt; begin Result := f_SSL_ctrl(S, SSL_CTRL_OPTIONS, 0, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_want_read(S: PSSL) : Boolean; begin Result := (f_SSL_want(S) = SSL_READING); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_want_write(S: PSSL) : Boolean; begin Result := (f_SSL_want(S) = SSL_WRITING); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_want_nothing(S: PSSL) : Boolean; begin Result := (f_SSL_want(S) = SSL_NOTHING); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_want_x509_lookup(S: PSSL) : Boolean; begin Result := (f_SSL_want(S) = SSL_X509_LOOKUP); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_set_session_cache_mode(Ctx: PSSL_CTX; Mode: Integer): Integer; begin Result := f_SSL_CTX_ctrl(Ctx, SSL_CTRL_SET_SESS_CACHE_MODE, Mode, nil) end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_session_reused(SSL: PSSL): Integer; begin Result := f_SSL_ctrl(SSL, SSL_CTRL_GET_SESSION_REUSED, 0, nil) end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_sess_set_cache_size(Ctx: PSSL_CTX; CacheSize: Integer): Integer; begin Result := f_SSL_CTX_ctrl(Ctx, SSL_CTRL_SET_SESS_CACHE_SIZE, CacheSize, nil) end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_add_extra_chain_cert(Ctx: PSSL_CTX; Cert: PX509): Longword; begin Result := f_SSL_CTX_ctrl(Ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, PAnsiChar(Cert)) end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF BEFORE_OSSL_098E} function f_SSL_SESSION_get_id(const Ses: PSSL_SESSION; var IdLen: LongInt): PAnsiChar; { 03/02/07 AG } begin // This is a hack : SSL_SESSION structure has not been defined. // There's also no function in openssl to get the session_id // from the SSL_SESSION_st. IdLen := PInteger(PAnsiChar(Ses) + 68)^; Result := PAnsiChar(Ses) + 72; end; { procedure f_SSL_session_get_id(Ses: PSSL_SESSION; var SessID: Pointer; var IdLen: Integer); begin // This is a hack : SSL_SESSION structure has not been defined. // There's also no function in openssl to get the session_id // from the SSL_SESSION_st. IdLen := PInteger(PAnsiChar(Ses) + 68)^; SessID := Pointer(PAnsiChar(Ses) + 72); end; } {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure f_SSL_CTX_sess_set_new_cb(Ctx: PSSL_CTX; CB: TNew_session_cb); begin // This is a hack : Ctx structure has not been defined. But we know // CB member is the 11th 32 bit field in the structure (index is 10) // This could change when OpenSSL is updated. Check "struct ssl_ctx_st". PNew_session_cb(PAnsiChar(Ctx) + 10 * 4)^ := @CB; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure f_SSL_CTX_sess_set_remove_cb(Ctx: PSSL_CTX; CB: TRemove_session_cb); begin // This is a hack : Ctx structure has not been defined. But we know // CB member is the 12th 32 bit field in the structure (index is 11) // This could change when OpenSSL is updated. Check "struct ssl_ctx_st". PRemove_session_cb(PAnsiChar(Ctx) + 11 * 4)^ := @CB; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure f_SSL_CTX_sess_set_get_cb(Ctx: PSSL_CTX; CB: TGet_session_cb); begin // This is a hack : Ctx structure has not been defined. But we know // CB member is the 13th 32 bit field in the structure (index is 12) // This could change when OpenSSL is updated. Check "struct ssl_ctx_st". PGet_session_cb(PAnsiChar(Ctx) + 12 * 4)^ := @CB; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure f_SSL_CTX_set_client_cert_cb(CTX: PSSL_CTX; CB: TClient_cert_cb); begin // This is a hack : Ctx structure has not been defined. But we know // CB member is the 30th 32 bit field in the structure (index is 29) // This could change when OpenSSL is updated. Check "struct ssl_ctx_st". PClient_cert_cb(PAnsiChar(CTX) + 29 * 4)^ := @CB; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_get_client_cert_cb(CTX: PSSL_CTX): Pointer; begin // This is a hack : Ctx structure has not been defined. But we know // CB member is the 30th 32 bit field in the structure (index is 29) // This could change when OpenSSL is updated. Check "struct ssl_ctx_st". Result := PAnsiChar(CTX) + 29 * 4; if PAnsiChar(Result)^ = #0 then Result := nil end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF OPENSSL_NO_TLSEXT} function f_SSL_set_tlsext_host_name(const S: PSSL; const name: String): Longint; begin Result := f_SSL_ctrl(S, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, Pointer(StringToUtf8(name))); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_set_tlsext_servername_callback(ctx: PSSL_CTX; cb: TCallback_ctrl_fp): Longint; begin Result := f_SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cb); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_CTX_set_tlsext_servername_arg(ctx: PSSL_CTX; arg: Pointer): Longint; begin Result := f_SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, arg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_set_tlsext_debug_callback(S: PSSL; cb: TCallback_ctrl_fp): Longint; begin Result := f_SSL_callback_ctrl(S, SSL_CTRL_SET_TLSEXT_DEBUG_CB, cb); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_set_tlsext_debug_arg(S: PSSL; arg: Pointer): Longint; begin Result := f_SSL_ctrl(S, SSL_CTRL_SET_TLSEXT_DEBUG_ARG, 0, arg); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$ENDIF}//USE_SSL end.
unit MainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSBaseControl, FMX.TMSMemo, FMX.Controls.Presentation, FMX.Menus, FMX.Edit, FMX.Layouts, FMX.Objects, FMX.TMSMemoStyles, FMX.TMSMemoDialogs, FMX.ListBox; type TOpenSCADStyler = class(TTMSFMXMemoCustomStyler) constructor Create(AOwner: TComponent); override; end; TFView = class(TForm) Header: TToolBar; Footer: TToolBar; HeaderLabel: TLabel; MainMenu: TMainMenu; MenuItemFile: TMenuItem; MenuItemSearch: TMenuItem; MenuItemNew: TMenuItem; Separator01: TMenuItem; MenuItemOpen: TMenuItem; MenuItemSave: TMenuItem; MenuItemSaveAs: TMenuItem; Separator02: TMenuItem; MenuItemExit: TMenuItem; MenuItemFind: TMenuItem; MenuItemReplace: TMenuItem; MenuItemRun: TMenuItem; MenuItemRunRun: TMenuItem; ToolBar: TToolBar; BtnLoadFromFile: TSpeedButton; Image4: TImage; BtnSaveToFile: TSpeedButton; Image5: TImage; BtnCut: TSpeedButton; Image6: TImage; BtnCopy: TSpeedButton; Image7: TImage; BtnPaste: TSpeedButton; Image8: TImage; BtnUndo: TSpeedButton; Image9: TImage; BtnRedo: TSpeedButton; Image10: TImage; LayoutSeparator1: TLayout; BtnBookmark: TSpeedButton; Image11: TImage; LayoutSeparator2: TLayout; BtnSearch: TSpeedButton; Image12: TImage; Layout2: TLayout; EditHighlight: TEdit; BtnHighlight: TSpeedButton; Image13: TImage; DialogSave: TSaveDialog; DialogOpen: TOpenDialog; DialogSearch: TTMSFMXMemoFindDialog; BtnRun: TSpeedButton; Image1: TImage; BtnLaunchOpenSCAD: TSpeedButton; DialogFindAndReplace: TTMSFMXMemoFindAndReplaceDialog; CheckBoxAutoSave: TCheckBox; CheckBoxAutoExecute: TCheckBox; TimerExecute: TTimer; BtnChangeTimerInterval: TSpeedButton; Image2: TImage; Layout1: TLayout; Layout3: TLayout; Layout4: TLayout; MenuItemAbout: TMenuItem; ExpanderExecuteOptions: TExpander; TextEditor: TTMSFMXMemo; DialogGetOpenSCADPath: TOpenDialog; CheckBoxApplyViewAll: TCheckBox; PathDialog: TOpenDialog; BtnPathToExe: TSpeedButton; Image3: TImage; LabelExePath: TLabel; ComboBoxFileType: TComboBox; CheckBoxAndOpen: TCheckBox; BtnExport: TSpeedButton; Image14: TImage; EditFileName: TEdit; LabelExport: TLabel; StyleBookCustomized: TStyleBook; procedure BtnLoadFromFileClick(Sender: TObject); procedure BtnSaveToFileClick(Sender: TObject); procedure BtnUndoClick(Sender: TObject); procedure BtnRedoClick(Sender: TObject); procedure BtnPasteClick(Sender: TObject); procedure BtnCutClick(Sender: TObject); procedure BtnCopyClick(Sender: TObject); procedure BtnSearchClick(Sender: TObject); procedure BtnBookmarkClick(Sender: TObject); procedure BtnHighlightClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure BtnRunClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure MenuItemReplaceClick(Sender: TObject); procedure MenuItemSaveAsClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure MenuItemNewClick(Sender: TObject); procedure MenuItemExitClick(Sender: TObject); procedure TextEditorKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure CheckBoxAutoExecuteChange(Sender: TObject); procedure BtnChangeTimerIntervalClick(Sender: TObject); procedure MenuItemAboutClick(Sender: TObject); procedure BtnPathToExeClick(Sender: TObject); procedure EditFileNameDblClick(Sender: TObject); procedure BtnExportClick(Sender: TObject); private const MainCaption = 'senCilleSCAD IDE'; TextNotPath = 'Path to exe not informed'; var FFileName :string; FTempFileName :string; FOpenSCADPath :string; FINIFileName :string; FTimerInterval :Integer; FOpenSCADStyler :TOpenSCADStyler; FPathToExe :string; procedure SetFileName(Value :string); function GetOpenSCADPath:string; procedure CallWebHelp; procedure CreateDefaultConfigFile; procedure SaveConfiguration; function CheckExtension(AFileName :string):string; function OpenURL(sCommand: string):Integer; procedure SetPathToExe(Value :string); public property FileName :string read FFileName write SetFileName; property OpenSCADPath :string read GetOpenSCADPath write FOpenSCADPath; property PathToExe :string read FPathToExe write SetPathToExe; end; var FView: TFView; implementation {$R *.fmx} uses {$IFDEF ANDROID} FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes, {$ELSE} {$IFDEF IOS} iOSapi.Foundation, FMX.Helpers.iOS, {$ENDIF IOS} {$ENDIF ANDROID} {$IFDEF MSWINDOWS} Winapi.ShellAPI, Winapi.Windows, {$ELSEIF DEFINED(MACOS)} Posix.Stdlib, {$ENDIF} {IdURI,} System.IOUtils, System.INIFiles, FMX.DialogService, FMX.DialogService.Async, AboutsenCille; {} constructor TOpenSCADStyler.Create(AOwner: TComponent); var itm :TElementStyle; begin inherited; BlockStart := '{'; BlockEnd := '}'; LineComment := '//'; MultiCommentLeft := '/*'; MultiCommentRight := '*/'; CommentStyle.TextColor := TAlphaColorRec.Navy; CommentStyle.BkColor := TAlphaColorRec.Null; CommentStyle.Style := [TFontStyle.fsItalic]; NumberStyle.TextColor := TAlphaColorRec.Fuchsia; NumberStyle.BkColor := TAlphaColorRec.Null ; NumberStyle.Style := [TFontStyle.fsBold] ; itm := AllStyles.Add; itm.Info := 'OpenSCAD'; itm.FontColor := TAlphaColorRec.Green; itm.Font.Style := [TFontStyle.fsBold]; {--- Syntax ---} itm.KeyWords.Add('var' ); itm.KeyWords.Add('value' ); itm.KeyWords.Add('module' ); itm.KeyWords.Add('function'); itm.KeyWords.Add('include' ); itm.KeyWords.Add('use' ); {--- 2D ---} itm.KeyWords.Add('circle' ); itm.KeyWords.Add('square' ); itm.KeyWords.Add('polygon' ); itm.KeyWords.Add('text' ); {--- 3D ---} itm.KeyWords.Add('sphere' ); itm.KeyWords.Add('cube' ); itm.KeyWords.Add('cylinder' ); itm.KeyWords.Add('polyhedron'); {--- Transformations ---} itm.KeyWords.Add('translate'); itm.KeyWords.Add('rotate' ); itm.KeyWords.Add('scale' ); itm.KeyWords.Add('resize' ); itm.KeyWords.Add('mirror' ); itm.KeyWords.Add('mulmatrix'); itm.KeyWords.Add('color' ); itm.KeyWords.Add('offset' ); itm.KeyWords.Add('hull' ); itm.KeyWords.Add('minkowsky'); {--- Boolean operations ---} itm.KeyWords.Add('union' ); itm.KeyWords.Add('difference' ); itm.KeyWords.Add('intersection'); {--- Mathematical ---} itm.KeyWords.Add('abs' ); itm.KeyWords.Add('sign' ); itm.KeyWords.Add('sin' ); itm.KeyWords.Add('cos' ); itm.KeyWords.Add('tan' ); itm.KeyWords.Add('acos' ); itm.KeyWords.Add('asin' ); itm.KeyWords.Add('atan' ); itm.KeyWords.Add('atan2'); itm.KeyWords.Add('floor'); itm.KeyWords.Add('round'); itm.KeyWords.Add('cell' ); itm.KeyWords.Add('ln' ); itm.KeyWords.Add('len' ); itm.KeyWords.Add('let' ); itm.KeyWords.Add('log' ); itm.KeyWords.Add('pow' ); itm.KeyWords.Add('sqrt' ); itm.KeyWords.Add('exp' ); itm.KeyWords.Add('rands'); itm.KeyWords.Add('min' ); itm.KeyWords.Add('max' ); //itm.KeyWords.Add(' //itm.KeyWords.Add(' //itm.KeyWords.Add(' //itm.KeyWords.Add(' (*item Font.Family = 'Courier New' Font.Size = 8.000000000000000000 FontColor = claBlue BGColor = claNull StyleType = stBracket BracketStart = #39 BracketEnd = #39 Info = 'Simple Quote' end item Font.Family = 'Courier New' Font.Size = 8.000000000000000000 FontColor = claBlue BGColor = claNull StyleType = stBracket BracketStart = '"' BracketEnd = '"' Info = 'Double Quote' end item Font.Family = 'Courier New' Font.Size = 8.000000000000000000 FontColor = claRed BGColor = claNull StyleType = stSymbol BracketStart = #0 BracketEnd = #0 Symbols = ' ,;:.()[]=-*/^%&^<>|!~'#13#10 Info = 'Symbols Delimiters' end item CommentLeft = '/*' CommentRight = '*/' Font.Family = 'Courier New' Font.Size = 9.000000000000000000 FontColor = claBlack BGColor = claNull StyleType = stKeyword BracketStart = #0 BracketEnd = #0 Info = 'Open SCAD' end>*) HintParameter.TextColor := TAlphaColorRec.Black; HintParameter.BkColor := TAlphaColorRec.Yellow; HintParameter.HintCharStart := '('; HintParameter.HintCharEnd := ')'; HintParameter.HintCharDelimiter := ';'; HintParameter.HintClassDelimiter := '.'; HintParameter.HintCharWriteDelimiter := ','; HexIdentifier := '0x' ; Description := 'Open SCAD Styler'; Filter := 'Open SCAD|*.scad'; DefaultExtension := '.scad' ; StylerName := 'Open SCAD Styler'; Extensions := 'scad' ; (*RegionDefinitions = < item Identifier = 'namespace' RegionStart = '{' RegionEnd = '}' RegionType = rtClosed ShowComments = False end item Identifier = '#region' RegionStart = '#region' RegionEnd = '#endregion' RegionType = rtClosed ShowComments = False end item Identifier = 'public' RegionStart = '{' RegionEnd = '}' RegionType = rtClosed ShowComments = False end item Identifier = 'private' RegionStart = '{' RegionEnd = '}' RegionType = rtClosed ShowComments = False end>*) end; procedure TFView.FormCreate(Sender: TObject); var INIFile :TIniFile; ExeName :string; Extension :string; AppName :string; AppFolder :string; FileType :string; begin FTimerInterval := 1500; FView.TimerExecute.Enabled := False; FView.ExpanderExecuteOptions.IsExpanded := False; FView.LabelExePath.Text := TextNotPath; FPathToExe := ''; FView.TextEditor.Font.Family := 'Courier New'; FView.TextEditor.Font.Size := 12; AppFolder := TPath.GetDirectoryName(ParamStr(0)); ExeName := ExtractFileName(ParamStr(0)); Extension := ExtractFileExt (ParamStr(0)); AppName := Copy(ExeName, 1, Length(ExeName) - Length(Extension)); FINIFileName := GetEnvironmentVariable('APPDATA')+PathDelim+AppName+'.ini'; {--- Things in development ---} FView.CheckBoxApplyViewAll.Visible := False; FView.CheckBoxAndOpen.Visible := False; {-----------------------------} if not TFile.Exists(FINIFileName) then begin CreateDefaultConfigFile; end; INIFile := TIniFile.Create(FINIFileName); try {OPTIONS} OpenSCADPath := INIFile.ReadString('OPTIONS', 'OpenSCADPath', ''); FView.CheckBoxAutoSave.IsChecked := INIFile.ReadString('OPTIONS', 'AutoSave', 'N') = 'Y'; FView.CheckBoxAutoExecute.IsChecked := INIFile.ReadString('OPTIONS', 'AutoExecute', 'N') = 'Y'; FileName := INIFile.ReadString('OPTIONS', 'LastFile', ''); if FileName <> '' then begin if TFile.Exists(FileName) then begin FView.TextEditor.Lines.LoadFromFile(FileName); FView.TextEditor.SyntaxStyles := FOpenSCADStyler; FView.TextEditor.UseStyler := True; end; end; FTimerInterval := INIFile.ReadInteger('OPTIONS', 'TimerInterval', 1500); PathToExe := INIFile.ReadString('EXECUTE', 'PathToExe', ''); FView.CheckBoxApplyViewAll.IsChecked := INIFile.ReadString('EXECUTE', 'ApplyViewAll', 'Y') = 'Y'; FView.CheckBoxAndOpen.IsChecked := INIFile.ReadString('EXPORT', 'AndOpen', 'Y') = 'Y'; FView.EditFileName.Text := INIFile.ReadString('EXPORT', 'FileName', ''); FileType := INIFile.ReadString('EXPORT', 'FileType', ''); if FileType = 'PNG' then FView.ComboBoxFileType.ItemIndex := 0 else if FileType = 'STL' then FView.ComboBoxFileType.ItemIndex := 1 else if FileType = 'OFF' then FView.ComboBoxFileType.ItemIndex := 2 else if FileType = 'DXF' then FView.ComboBoxFileType.ItemIndex := 3 else if FileType = 'CSG' then FView.ComboBoxFileType.ItemIndex := 4 else FView.ComboBoxFileType.ItemIndex := -1; finally INIFile.Free; end; {--- Editor Configuration ---} FView.TextEditor.ActiveLineSettings.ActiveLineAtCursor := True; FView.TextEditor.ActiveLineSettings.ShowActiveLine := True; FView.TextEditor.ActiveLineSettings.ShowActiveLineIndicator := True; FView.TextEditor.AutoIndent := True; FView.TextEditor.DelErase := True; FView.TextEditor.SmartTabs := True; FView.TextEditor.WantTab := True; FView.TextEditor.ShowRightMargin := False; {---} FOpenSCADStyler := TOpenSCADStyler.Create(FView); FView.TextEditor.SyntaxStyles := FOpenSCADStyler; FView.TextEditor.UseStyler := True; end; procedure TFView.SaveConfiguration; var INIFile :TIniFile; lBool :string; begin INIFile := TIniFile.Create(FINIFileName); try if FView.CheckBoxAutoSave.IsChecked then lBool := 'Y' else lBool := 'N'; INIFile.WriteString('OPTIONS', 'AutoSave', lBool); if FView.CheckBoxAutoExecute.IsChecked then lBool := 'Y' else lBool := 'N'; INIFile.WriteString('OPTIONS', 'AutoExecute', lBool); INIFile.WriteString('OPTIONS', 'LastFile', FileName); INIFile.WriteString('OPTIONS', 'LastFile', FileName); INIFile.WriteInteger('OPTIONS', 'TimerInterval', FTimerInterval); {-----} INIFile.WriteString('EXECUTE', 'PathToExe', PathToExe); if FView.CheckBoxApplyViewAll.IsChecked then lBool := 'Y' else lBool := 'N'; INIFile.WriteString('EXECUTE', 'ApplyViewAll', lBool); if FView.CheckBoxAndOpen.IsChecked then lBool := 'Y' else lBool := 'N'; INIFile.WriteString('EXPORT', 'AndOpen', lBool); INIFile.WriteString('EXPORT', 'FileName', EditFileName.Text); case FView.ComboBoxFileType.ItemIndex of 0 :INIFile.WriteString('EXPORT', 'FileType', 'PNG'); 1 :INIFile.WriteString('EXPORT', 'FileType', 'STL'); 2 :INIFile.WriteString('EXPORT', 'FileType', 'OFF'); 3 :INIFile.WriteString('EXPORT', 'FileType', 'DXF'); 4 :INIFile.WriteString('EXPORT', 'FileType', 'CSG'); else INIFile.WriteString('EXPORT', 'FileType', '' ); end; INIFile.UpdateFile; finally INIFile.Free; end; end; procedure TFView.SetFileName(Value :string); begin if FFileName <> Value then begin FFileName := Value; FView.Caption := ExtractFileName(Value) + ' ('+MainCaption+')'; end; end; procedure TFView.SetPathToExe(Value: string); begin if FPathToExe <> Value then begin FPathToExe := Value; LabelExePath.Text := Value; end; end; procedure TFView.BtnPathToExeClick(Sender: TObject); begin if FView.PathDialog.Execute then begin PathToExe := FView.PathDialog.FileName; end; end; procedure TFView.TextEditorKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin FView.TimerExecute.Enabled := False; FView.TimerExecute.Interval := FTimerInterval; FView.TimerExecute.Enabled := True; end; procedure TFView.BtnBookmarkClick(Sender: TObject); begin FView.TextEditor.Bookmark[FView.TextEditor.CurY] := not FView.TextEditor.Bookmark[FView.TextEditor.CurY]; end; procedure TFView.BtnChangeTimerIntervalClick(Sender: TObject); var Value :Integer; begin TDialogServiceAsync.InputQuery('Interval Between Executions', ['Miliseconds'], [IntToStr(FTimerInterval)], procedure(const AResult: TModalResult; const AValues: array of string) begin if AResult = mrOk then begin if TryStrToInt(AValues[0], Value) then FTimerInterval := Value; end; end ); end; procedure TFView.BtnCopyClick(Sender: TObject); begin FView.TextEditor.CopyToClipboard; end; procedure TFView.BtnCutClick(Sender: TObject); begin FView.TextEditor.CutToClipboard; end; {$IFDEF MSWINDOWS} // Runs application and returns PID. 0 if failed. function RunApplication(const AExecutableFile, AParameters: string; const AShowOption: Integer = SW_SHOWNORMAL): Integer; var _SEInfo: TShellExecuteInfo; begin Result := 0; if not FileExists(AExecutableFile) then Exit; FillChar(_SEInfo, SizeOf(_SEInfo), 0); _SEInfo.cbSize := SizeOf(TShellExecuteInfo); _SEInfo.fMask := SEE_MASK_NOCLOSEPROCESS; // _SEInfo.Wnd := Application.Handle; _SEInfo.lpFile := PChar(AExecutableFile); _SEInfo.lpParameters := PChar(AParameters); _SEInfo.nShow := AShowOption; if ShellExecuteEx(@_SEInfo) then begin WaitForInputIdle(_SEInfo.hProcess, 3000); Result := GetProcessID(_SEInfo.hProcess); end; end; {$ENDIF} procedure TFView.BtnExportClick(Sender: TObject); var Parameters :string; NewFileName :string; begin if FView.PathToExe.Trim = '' then begin ShowMessage('Indicate first, the path to de OpenSCAD executable.'); Exit; end; if FView.FileName.Trim = '' then begin ShowMessage('Specify a name for the output file.'); Exit; end; NewFileName := TPath.GetDirectoryName(FileName)+'\'+EditFileName.Text.Trim+'.'+ComboBoxFileType.Items[ComboBoxFileType.ItemIndex]; Parameters := ' -o '; {$IFDEF MSWINDOWS} RunApplication(PathToExe, Parameters+' "'+NewFileName+'" "'+FTempFileName+'"'); {$ENDIF} if FView.CheckBoxAndOpen.IsChecked then begin OpenURL('"'+NewFileName+'"'); //ShellExecute(0, 'OPEN', PChar(NewFileName), '', '', SW_SHOWNORMAL); end; (* [ --camera=translatex,y,z,rotx,y,z,dist | \ --camera=eyex,y,z,centerx,y,z ] \ [ --autocenter ] \ [ --viewall ] \ [ --imgsize=width,height ] [ --projection=(o)rtho|(p)ersp] \ [ --render | --preview[=throwntogether] ] \ [ --colorscheme=[Cornfield|Sunset|Metallic|Starnight|BeforeDawn|Nature|DeepOcean] ] \ [ --csglimit=num ]\ *) end; procedure TFView.BtnHighlightClick(Sender: TObject); begin FView.TextEditor.HighlightText := FView.EditHighlight.Text; end; procedure TFView.BtnLoadFromFileClick(Sender: TObject); begin if FView.DialogOpen.Execute then begin FileName := FView.DialogOpen.FileName; FView.TextEditor.Lines.LoadFromFile(FFileName); FView.TextEditor.SyntaxStyles := FOpenSCADStyler; FView.TextEditor.UseStyler := True; end; end; procedure TFView.BtnPasteClick(Sender: TObject); begin FView.TextEditor.PasteFromClipboard; end; procedure TFView.BtnRedoClick(Sender: TObject); begin FView.TextEditor.Redo; end; procedure TFView.BtnRunClick(Sender: TObject); var Parameters :string; begin Parameters := ''; if FView.CheckBoxApplyViewAll.IsChecked then Parameters := ' --viewall '; //Parameters := ' --colorscheme=Metallic '; if FTempFileName.Trim = '' then begin FTempFileName := TPath.GetTempPath+ExtractFileName(TPath.GetRandomFileName)+'.scad'; FView.TextEditor.Lines.SaveToFile(FTempFileName); if PathToExe.Trim <> '' then begin //RunApplication(PathToExe, Parameters+' "'+FTempFileName+'"'); OpenURL(FTempFileName{+' '+Parameters}); //ShellExecute(0, 'OPEN', PChar('"'+PathToExe+'" '+Parameters+'"'+FTempFileName+'"'), '', '', SW_SHOWNORMAL); (* --colorscheme=Metallic [ --camera=translatex,y,z,rotx,y,z,dist | \ --camera=eyex,y,z,centerx,y,z ] \ [ --autocenter ] \ [ --viewall ] \ [ --imgsize=width,height ] [ --projection=(o)rtho|(p)ersp] \ [ --render | --preview[=throwntogether] ] \ [ --colorscheme=[Cornfield|Sunset|Metallic|Starnight|BeforeDawn|Nature|DeepOcean] ] \ [ --csglimit=num ]\ *) end else OpenURL(FTempFileName); end else begin FView.TextEditor.Lines.SaveToFile(FTempFileName); end; end; function TFView.OpenURL(sCommand: string):Integer; begin {$IF DEFINED(MACOS)} _system(PAnsiChar('open ' + '"' + AnsiString(sCommand) + '"')); {$ELSEIF DEFINED(MSWINDOWS)} Result := ShellExecute(0, 'OPEN', PChar(sCommand), '', '', SW_SHOWNORMAL); {$ELSEIF DEFINED(IOS)} Result := prvOpenURL(sCommand); {$ELSEIF DEFINED(ANDROID)} Result := prvOpenURL(sCommand); {$ENDIF} end; procedure TFView.BtnSaveToFileClick(Sender: TObject); begin if FFileName.Trim <> '' then begin FView.TextEditor.Lines.SaveToFile(FFileName); end else if FView.DialogSave.Execute then begin FView.TextEditor.Lines.SaveToFile(FView.DialogSave.FileName); end; end; procedure TFView.BtnSearchClick(Sender: TObject); begin FView.DialogSearch.Memo := FView.TextEditor; FView.DialogSearch.Execute; end; procedure TFView.BtnUndoClick(Sender: TObject); begin FView.TextEditor.Undo; end; procedure TFView.CallWebHelp; begin OpenURL('https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language#'+FView.TextEditor.FullWordAtCursor); end; function TFView.GetOpenSCADPath:string; var Path :string; begin if FOpenSCADPath.Trim = '' then begin if FView.DialogGetOpenSCADPath.Execute then begin Path := FView.DialogGetOpenSCADPath.FileName; FOpenSCADPath := Path; Result := FOpenSCADPath; end; end else Result := FOpenSCADPath; end; procedure TFView.MenuItemSaveAsClick(Sender: TObject); begin if FFileName.Trim <> '' then begin FView.DialogSave.FileName := ExtractFileName(FileName); end; if FView.DialogSave.Execute then begin FView.TextEditor.Lines.SaveToFile(FView.DialogSave.FileName); FileName := FView.DialogSave.FileName; end; end; procedure TFView.MenuItemAboutClick(Sender: TObject); var View :TAboutInvoicingView; begin View := TAboutInvoicingView.Create(Application); try View.ShowModal; finally View.Close; end; end; procedure TFView.MenuItemExitClick(Sender: TObject); begin FView.Close; end; procedure TFView.MenuItemNewClick(Sender: TObject); var AllowClear :Boolean; begin if FView.TextEditor.Modified then begin TDialogService.PreferredMode := TDialogService.TPreferredMode.Platform; TDialogService.MessageDialog('do you want to discard current changes?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbOk, TMsgDlgBtn.mbCancel], TMsgDlgBtn.mbCancel, 0, procedure(const AResult: TModalResult) begin case AResult of mrOk : AllowClear := True; mrCancel: AllowClear := False; end; end); end else AllowClear := True; if AllowClear then begin FileName := ''; TextEditor.Clear; end; end; procedure TFView.MenuItemReplaceClick(Sender: TObject); begin FView.DialogFindAndReplace.Memo := FView.TextEditor; FView.DialogFindAndReplace.Execute; end; procedure TFView.CreateDefaultConfigFile; var INIFile :TIniFile; begin INIFile := TIniFile.Create(FINIFileName); try INIFile.WriteString('OPTIONS', 'OpenSCADPath', ''); INIFile.UpdateFile; finally INIFile.Free; end; end; procedure TFView.EditFileNameDblClick(Sender: TObject); var Name :string; Ext :string; begin Name := ExtractFileName(FileName); Ext := ExtractFileExt (Name ); EditFileName.Text := Copy(Name, 1, Length(Name) - Length(Ext)); end; procedure TFView.CheckBoxAutoExecuteChange(Sender: TObject); begin FView.TimerExecute.Enabled := FView.CheckBoxAutoExecute.IsChecked; end; function TFView.CheckExtension(AFileName :string):string; var Extension :string; begin Extension := TPath.GetExtension(AFileName); if Extension.Trim = '' then Result := AFileName+'.scad' else Result := AFileName; end; procedure TFView.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var AllowClose :Boolean; begin if FView.CheckBoxAutoSave.IsChecked then begin if FView.TextEditor.Modified then begin if FileName <> '' then begin FView.TextEditor.Lines.SaveToFile(FFileName); CanClose := True; end else begin FView.DialogSave.FileName := ExtractFileName(FileName); if FView.DialogSave.Execute then begin FileName := CheckExtension(FView.DialogSave.FileName); FView.TextEditor.Lines.SaveToFile(FileName); CanClose := True; end else CanClose := False; end; end else begin {Not modified} CanClose := True; end; end else begin {not Autosave checked} if FView.TextEditor.Modified then begin TDialogService.PreferredMode := TDialogService.TPreferredMode.Platform; TDialogService.MessageDialog('do you want to discard current changes?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbOk, TMsgDlgBtn.mbCancel], TMsgDlgBtn.mbCancel, 0, procedure(const AResult: TModalResult) begin case AResult of mrOk : AllowClose := True; mrCancel: AllowClose := False; end; end); CanClose := AllowClose; end; end; if CanClose then SaveConfiguration; end; procedure TFView.FormDestroy(Sender: TObject); begin FOpenSCADStyler.Free; end; procedure TFView.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin case Key of vkF1 :begin FView.CallWebHelp; Key := 0; end; else begin case Key of //vkF3 :begin if FView.BtnModify.Enabled then begin FView.BtnModify.SetFocus; FView.BtnModify.OnClick(Self); Key := 0; end; end; //vkF8 :begin if FView.BtnReport.Enabled then begin FView.BtnReport.SetFocus; FView.BtnReport.OnClick(Self); Key := 0; end; end; vkF9 :begin if FView.BtnRun.Enabled then begin FView.BtnRun.SetFocus; FView.BtnRun.OnClick(Self); Key := 0; end; end; //vkESCAPE:begin if FView.BtnCancel.Enabled then begin FView.BtnCancel.SetFocus; FView.BtnCancel.OnClick(Self); Key := 0; end; end; end; end; end; end; end. openscad [ -o output_file [ -d deps_file ] ]\ [ -m make_command ] [ -D var=val [..] ] \ [ --help ] print this help message and exit \ [ --version ] [ --info ] \ [ --camera=translatex,y,z,rotx,y,z,dist | \ --camera=eyex,y,z,centerx,y,z ] \ [ --autocenter ] \ [ --viewall ] \ [ --imgsize=width,height ] [ --projection=(o)rtho|(p)ersp] \ [ --render | --preview[=throwntogether] ] \ [ --colorscheme=[Cornfield|Sunset|Metallic|Starnight|BeforeDawn|Nature|DeepOcean] ] \ [ --csglimit=num ]\ filename
unit VariantMatrixLib; interface uses streaming_class_lib,variants,TypInfo,SysUtils,classes; function VarMatrix: TVarType; type TMatrix=class(TStreamingClass) private fRows,fCols: Integer; fData: array of Real; //одномерный как-то надежнее, можно ускорить выполнение fTolerance: Real; procedure SetData(i,j: Integer; Value: Real); function GetData(i,j: Integer): Real; function GetAsString: string; procedure SetAsString(text: string); procedure SwitchRows(row1,row2: Integer); procedure SwitchCols(col1,col2: Integer); protected public constructor Create(owner: TComponent); overload; override; constructor Create(text: string); reintroduce; overload; constructor CopyFrom(const AData: TMatrix); constructor CreateUnity(size: Integer); constructor CreateZero(rows,cols: Integer); procedure Assign(source: TPersistent); override; function isNumber: Boolean; function isVector: Boolean; procedure SetSize(rows,cols: Integer); //тупо меняет размеры, не заботясь о сохранности данных procedure Resize(rows,cols: Integer); //данные сохраняются, справа и снизу появл. нули procedure DoAdd(term: TMatrix); procedure DoSubtract(term: TMatrix); procedure DoMultiply(term: TMatrix); // procedure DoLeftMultiply(term: TMatrix); procedure Invert; function CreateInvertedMatrix: TMatrix; property Data[i,j: Integer]: Real read GetData write SetData; default; published property AsString: string read GetAsString write SetAsString; property Rows: Integer read fRows; property Cols: Integer read fCols; property Tolerance: Real read fTolerance write fTolerance; end; TMatrixVarData = packed record VType: TVarType; Reserved1, Reserved2, Reserved3: Word; VMatrix: TMatrix; Reserved4: LongInt; end; TMatrixVariantType=class(TPublishableVariantType) protected function GetInstance(const V: TVarData): TObject; override; function LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override; procedure Simplify(var V: TVarData); public function DoFunction(var Dest: TVarData; const V: TVarData; const Name: string; const Arguments: TVarDataArray): Boolean; override; procedure Clear(var V: TVarData); override; procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override; procedure Cast(var Dest: TVarData; const Source: TVarData); override; procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override; procedure BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); override; end; function VarMatrixCreate(rows,cols: Integer): Variant; overload; function VarMatrixCreate(text: string): Variant; overload; function VarMatrixCreate(matrix: TMatrix): Variant; overload; function VarUnityMatrix(size: Integer): Variant; function VarXRotationMatrix(angle: Real): Variant; function VarYRotationMatrix(angle: Real): Variant; function VarZRotationMatrix(angle: Real): Variant; implementation uses simple_parser_lib,vector_lib,littlefuncs; var MatrixVariantType: TMatrixVariantType; function TMatrixVariantType.GetInstance(const V: TVarData): TObject; begin Result:=TMatrixVarData(V).VMatrix; end; procedure TMatrixVariantType.Clear(var V: TVarData); begin V.VType := varEmpty; FreeAndNil(TMatrixVarData(V).VMatrix); end; procedure TMatrixVariantType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); begin if Indirect and VarDataIsByRef(Source) then VarDataCopyNoInd(Dest, Source) else with TMatrixVarData(Dest) do begin VType := VarType; VMatrix := TMatrix.CopyFrom(TMatrixVarData(Source).VMatrix); end; end; procedure TMatrixVariantType.CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); var LTemp: TVarData; matrix: TMatrix; begin matrix:=TMatrixVarData(Source).VMatrix; if Source.VType = VarType then case AVarType of varOleStr: VarDataFromOleStr(Dest, matrix.AsString); varString: VarDataFromStr(Dest, matrix.AsString); varSingle,varDouble,varCurrency,varInteger: if matrix.isNumber then begin VarDataInit(LTemp); LTemp.VType:=varDouble; LTemp.VDouble:=Matrix[1,1]; VarDataCastTo(Dest,LTemp,AVarType); end else RaiseCastError; else if (AVarType=VarVector) and Matrix.isVector then Variant(Dest):=VarVectorCreate(matrix[1,1],matrix[1,2],matrix[1,3]) else begin VarDataInit(LTemp); try VarDataFromStr(Ltemp,TMatrixVarData(Source).VMatrix.AsString); VarDataCastTo(Dest, LTemp, AVarType); finally VarDataClear(LTemp); end; end; end else inherited; end; procedure TMatrixVariantType.Cast(var Dest: TVarData; const Source: TVarData); var matrix: TMatrix; vector: TVector; begin matrix:=TMatrix.CreateZero(1,1); TMatrixVarData(Dest).VMatrix:=matrix; case Source.VType of varDouble: matrix[1,1]:=Source.VDouble; varSingle: matrix[1,1]:=Source.VSingle; varCurrency: matrix[1,1]:=Source.VCurrency; varInteger: matrix[1,1]:=Source.VInteger; else if Source.VType=VarVector then begin matrix.SetSize(3,1); vector:=TVectorVarData(source).VVector; matrix[1,1]:=vector.X; matrix[1,2]:=vector.Y; matrix[1,3]:=vector.Z; end else TMatrixVarData(Dest).VMatrix.AsString:=VarDataToStr(Source); end; Dest.VType:=varType; end; procedure TMatrixVariantType.BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); begin if Right.VType = VarType then case Left.VType of varString: case Operator of opAdd: Variant(Left) := Variant(Left) + TMatrixVarData(Right).VMatrix.AsString; else RaiseInvalidOp; end; else if Left.VType = VarType then case Operator of opAdd: begin TMatrixVarData(Left).VMatrix.DoAdd(TMatrixVarData(Right).VMatrix); Simplify(Left); end; opSubtract: begin TMatrixVarData(Left).VMatrix.DoSubtract(TMatrixVarData(Right).VMatrix); Simplify(Left); end; opMultiply: begin TMatrixVarData(Left).VMatrix.DoMultiply(TMatrixVarData(Right).VMatrix); Simplify(Left); end; else RaiseInvalidOp; end else RaiseInvalidOp; end else RaiseInvalidOp; end; function TMatrixVariantType.DoFunction(var Dest: TVarData; const V: TVarData; const Name: string; const Arguments: TVarDataArray): Boolean; begin if (Name='CELLS') and (Length(Arguments)=2) then begin Dest.VType:=varDouble; Dest.VDouble:=TMatrixVarData(V).VMatrix[Variant(Arguments[0]),Variant(Arguments[1])]; Result:=true; end else Result:=false; end; function TMatrixVariantType.LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; begin { TypeX Op Complex } if (Operator = opAdd) and VarDataIsStr(V) then RequiredVarType := varString else RequiredVarType := VarType; Result := True; end; procedure TMatrixVariantType.Simplify(var V: TVarData); var matrix: TMatrix; begin //попытаемся привести к более простому виду matrix:=TMatrixVarData(V).VMatrix; if matrix.isNumber then CastTo(V,V,varDouble); if matrix.isVector then CastTo(V,V,varVector); end; (* TMatrix *) procedure TMatrix.Assign(source: TPersistent); var s: TMatrix absolute source; begin if source is TMatrix then begin fCols:=s.fCols; fRows:=s.fRows; fData:=Copy(s.fData); end else inherited Assign(source); end; constructor TMatrix.Create(owner: TComponent); begin inherited Create(owner); SetSubComponent(true); end; constructor TMatrix.CopyFrom(const AData: TMatrix); begin Create(nil); Assign(AData); end; constructor TMatrix.Create(text: string); begin Create(nil); AsString:=text; end; constructor TMatrix.CreateZero(rows,cols: Integer); var i: Integer; begin Create(nil); SetSize(rows,cols); for i:=0 to Length(fData)-1 do fData[i]:=0; end; constructor TMatrix.CreateUnity(size: Integer); var i: Integer; begin CreateZero(size,size); for i:=1 to size do Data[i,i]:=1; end; procedure TMatrix.SetSize(rows,cols: Integer); begin frows:=rows; fcols:=cols; SetLength(fdata,frows*fcols); end; procedure TMatrix.Resize(rows,cols: Integer); var temp: TMatrix; i,j: Integer; begin temp:=TMatrix.Create(self); SetSize(rows,cols); for j:=1 to temp.fRows do for i:=1 to temp.fCols do Data[i,j]:=temp[i,j]; temp.Free; end; procedure TMatrix.SetData(i,j: Integer; value: Real); begin fData[i-1+(j-1)*fCols]:=value; end; function TMatrix.GetData(i,j: Integer): Real; begin Result:=fData[i-1+(j-1)*fCols]; end; function TMatrix.GetAsString: string; var s: string; i,j: Integer; begin s:='('; for j:=1 to fRows do begin s:=s+'('; for i:=1 to fCols do begin s:=s+FloatToStr(Data[i,j]); if i<fCols then s:=s+';'; end; s:=s+')'; if j<fRows then s:=s+';'; end; s:=s+')'; Result:=s; end; procedure TMatrix.SetAsString(text: string); var P: TSimpleParser; i,j,k: Integer; c: char; begin P:=TSimpleParser.Create(text); p.delimiter:=''; c:=P.NextChar; if c<>'(' then begin //одно-единственное число SetSize(1,1); Data[1,1]:=P.getFloat; Exit; end; //начинается с открывающей скобочки P.getChar; i:=1; j:=1; //начальные размеры SetSize(1,1); repeat c:=P.nextChar; if c=')' then break; if c=';' then begin P.getChar; inc(j); Resize(j,i); continue; end; if c='(' then begin //вложенная скобка P.getChar; //пропускаем скобку k:=1; repeat c:=P.NextChar; if c=')' then begin P.getChar; break; end; if c=';' then begin P.getChar; inc(k); if k>i then begin i:=k; Resize(j,i); end; continue; end else Data[k,j]:=P.getFloat; until false; end else Data[1,j]:=P.getFloat; until false; end; function TMatrix.isNumber: Boolean; begin Result:=(fCols=1) and (fRows=1); end; function TMatrix.isVector: Boolean; begin Result:=(fCols=1) and (fRows=3); end; procedure TMatrix.DoAdd(term: TMatrix); var i,j: Integer; begin if (fCols=term.fCols) and (fRows=term.fRows) then begin for j:=1 to fRows do for i:=1 to fCols do Data[i,j]:=Data[i,j]+term[i,j]; end else Raise Exception.Create('TMatrix.DoAdd: sizes of matrices are not equal'); end; procedure TMatrix.DoSubtract(term: TMatrix); var i,j: Integer; begin if (fCols=term.fCols) and (fRows=term.fRows) then begin for j:=1 to fRows do for i:=1 to fCols do Data[i,j]:=Data[i,j]-term[i,j]; end else Raise Exception.Create('TMatrix.DoSubtract: sizes of matrices are not equal'); end; procedure TMatrix.DoMultiply(term: TMatrix); //умножение на матрицу справа var i,j,k: Integer; temp: TMatrix; x: Real; begin if (fCols=term.fRows) then begin temp:=TMatrix.CopyFrom(self); SetSize(fRows,term.fCols); for j:=1 to fRows do begin for i:=1 to fCols do begin data[i,j]:=0; for k:=1 to term.fRows do data[i,j]:=data[i,j]+temp[k,j]*term[i,k]; end; end; temp.Free; end else if term.isNumber then begin x:=term[1,1]; for j:=1 to fRows do for i:=1 to fCols do data[i,j]:=data[i,j]*x; end else if isNumber then begin x:=data[1,1]; Assign(term); for j:=1 to fRows do for i:=1 to fCols do data[i,j]:=data[i,j]*x; end else Raise Exception.Create('TMatrix.DoMultiply: wrong sizes'); end; procedure TMatrix.Invert; var temp: TMatrix; begin temp:=CreateInvertedMatrix; fdata:=Copy(temp.fData); temp.Free; end; function TMatrix.CreateInvertedMatrix: TMatrix; var temp: TMatrix; i,j,k: Integer; max_elem: Real; row_num,col_num: Integer; ratio: Real; begin if frows<>fcols then Raise Exception.Create('TMatrix.CreateInvertedMatrix: source matrix is non-square'); Result:=TMatrix.CreateUnity(frows); temp:=TMatrix.Clone(self); try for j:=1 to frows do begin //ищем макс. элемент не выше и не левее (j,j) (* max_elem:=-1; row_num:=-1; //при попытке заменить такие элем. выругается на index out of bounds col_num:=-1; for i:=j to frows do for k:=j to frows do if abs(temp[i,k])>max_elem then begin max_elem:=abs(temp[j,i]); row_num:=k; col_num:=i; end; if max_elem<=ftolerance then //сплошь одни нули, не можем новый диаг. элем найти raise Exception.Create('TMatrix.CreateInvertedMatrix: source matrix has zero determinant'); temp.SwitchRows(j,row_num); Result.SwitchRows(j,row_num); temp.SwitchCols(j,col_num); Result.SwitchCols(j,col_num); //элем (j,j) - лучший из лучших! *) max_elem:=temp[j,j]; //чтобы знак не потерять, вверху же абс. знач if abs(max_elem-1)>ftolerance then begin ratio:=1/max_elem; (* data[j,j]:=1; for i:=j+1 to fRows do data[i,j]:=data[i,j]*ratio; *) for i:=1 to fRows do begin temp[i,j]:=temp[i,j]*ratio; Result.data[i,j]:=Result.data[i,j]*ratio; end; end; //теперь вычитаем нашу строку из всех остальных, чтобы остались нули в данном столбце for i:=1 to frows do begin if (i=j) or (abs(temp[j,i])<=ftolerance) then continue; //довольно частый случай ratio:=temp[j,i]; (* data[j,i]:=0; for k:=j+1 to fRows do data[k,i]:=data[k,i]-ratio*data[k,j]; *) for k:=1 to fRows do begin temp[k,i]:=temp[k,i]-ratio*temp[k,j]; Result.data[k,i]:=Result.data[k,i]-ratio*Result.data[k,j]; end; end; end; finally temp.Free; end; end; procedure TMatrix.SwitchRows(row1,row2: Integer); var i: Integer; bias1,bias2: Integer; begin //data[i,j] <=> fData[i-1+(j-1)*fCols] //и нумерация от 1 до rows/cols if row1<>row2 then begin bias1:=(row1-1)*fCols-1; bias2:=(row2-1)*fCols-1; for i:=1 to fcols do SwapFloats(fdata[i+bias1],fdata[i+bias2]); // SwapFloats(data[i,row1],data[i,row2]); end; end; procedure TMatrix.SwitchCols(col1,col2: Integer); var i: Integer; bias1,bias2: Integer; begin if col1<>col2 then begin bias1:=col1-1-fcols; bias2:=col2-1-fcols; for i:=1 to frows do SwapFloats(fdata[i*fcols+bias1],fdata[i*fcols+bias2]); end; end; (* 'Fabric' *) procedure VarMatrixCreateInto(var ADest: Variant; const AMatrix: TMatrix); begin VarClear(ADest); TMatrixVarData(ADest).VType := VarMatrix; TMatrixVarData(ADest).VMatrix := AMatrix; end; function VarMatrixCreate(rows,cols: Integer): Variant; begin VarMatrixCreateInto(Result,TMatrix.CreateZero(rows,cols)); end; function VarMatrixCreate(text: string): Variant; begin VarMatrixCreateInto(Result,Tmatrix.Create(text)); end; function VarMatrixCreate(matrix: TMatrix): Variant; begin VarMatrixCreateInto(Result,Tmatrix.CopyFrom(matrix)); end; function VarUnityMatrix(size: Integer): Variant; begin VarMatrixCreateInto(Result,TMatrix.CreateUnity(size)); end; function VarMatrix: TVarType; begin Result:=MatrixVariantType.VarType; end; function VarXRotationMatrix(angle: Real): Variant; var m: TMatrix; si,co: Real; begin si:=sin(angle); co:=cos(angle); m:=TMatrix.CreateUnity(3); m[2,2]:=co; m[3,3]:=co; m[3,2]:=-si; m[2,3]:=si; VarMatrixCreateInto(Result,m); end; function VarYRotationMatrix(angle: Real): Variant; var m: TMatrix; si,co: Real; begin si:=sin(angle); co:=cos(angle); m:=TMatrix.CreateUnity(3); m[1,1]:=co; m[3,3]:=co; m[3,1]:=si; m[1,3]:=-si; VarMatrixCreateInto(Result,m); end; function VarZRotationMatrix(angle: Real): Variant; var m: TMatrix; si,co: Real; begin si:=sin(angle); co:=cos(angle); m:=TMatrix.CreateUnity(3); m[1,1]:=co; m[2,2]:=co; m[2,1]:=-si; m[1,2]:=si; VarMatrixCreateInto(Result,m); end; initialization RegisterClass(TMatrix); MatrixVariantType:=TMatrixVariantType.Create; finalization FreeAndNil(MatrixVariantType); end.
unit NewTabSet; { Inno Setup Copyright (C) 1997-2004 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. TNewTabSet - modern VS.NET-style tabs $jrsoftware: issrc/Components/NewTabSet.pas,v 1.3 2010/08/18 03:36:36 jr Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms; type TNewTabSet = class(TCustomControl) private FTabs: TStrings; FTabIndex: Integer; function GetTabRect(Index: Integer): TRect; procedure InvalidateTab(Index: Integer); procedure ListChanged(Sender: TObject); procedure SetTabs(Value: TStrings); procedure SetTabIndex(Value: Integer); protected procedure CreateParams(var Params: TCreateParams); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Align; property Font; property ParentFont; property TabIndex: Integer read FTabIndex write SetTabIndex; property Tabs: TStrings read FTabs write SetTabs; property OnClick; end; procedure Register; implementation procedure Register; begin RegisterComponents('JR', [TNewTabSet]); end; procedure RGBToHSV(const R, G, B: Integer; var H, S: Double; var V: Integer); var Max, Min, C: Integer; begin Max := R; if G > Max then Max := G; if B > Max then Max := B; Min := R; if G < Min then Min := G; if B < Min then Min := B; C := Max - Min; if C = 0 then begin H := 0; S := 0; end else begin if Max = R then H := (60 * (G - B)) / C else if Max = G then H := (60 * (B - R)) / C + 120 else if Max = B then H := (60 * (R - G)) / C + 240; if H < 0 then H := H + 360; S := C / Max; end; V := Max; end; procedure HSVtoRGB(const H, S: Double; const V: Integer; var R, G, B: Integer); var I, P, Q, T: Integer; F: Double; begin I := Trunc(H / 60); F := Frac(H / 60); P := Round(V * (1.0 - S)); Q := Round(V * (1.0 - S * F)); T := Round(V * (1.0 - S * (1.0 - F))); case I of 0: begin R := V; G := t; B := p; end; 1: begin R := q; G := V; B := p; end; 2: begin R := p; G := V; B := t; end; 3: begin R := p; G := q; B := V; end; 4: begin R := t; G := p; B := V; end; 5: begin R := V; G := p; B := q; end; else { Should only get here with bogus input } R := 0; G := 0; B := 0; end; end; function LightenColor(const Color: TColorRef; const Amount: Integer): TColorRef; var H, S: Double; V, R, G, B: Integer; begin RGBtoHSV(Byte(Color), Byte(Color shr 8), Byte(Color shr 16), H, S, V); Inc(V, Amount); if V > 255 then V := 255; if V < 0 then V := 0; HSVtoRGB(H, S, V, R, G, B); Result := R or (G shl 8) or (B shl 16); end; { TNewTabSet } const TabPaddingX = 5; TabPaddingY = 3; TabSpacing = 1; constructor TNewTabSet.Create(AOwner: TComponent); begin inherited; FTabs := TStringList.Create; TStringList(FTabs).OnChange := ListChanged; ControlStyle := ControlStyle + [csOpaque]; Width := 129; Height := 20; end; procedure TNewTabSet.CreateParams(var Params: TCreateParams); begin inherited; with Params.WindowClass do style := style and not (CS_HREDRAW or CS_VREDRAW); end; destructor TNewTabSet.Destroy; begin FTabs.Free; inherited; end; function TNewTabSet.GetTabRect(Index: Integer): TRect; var I: Integer; Size: TSize; begin Canvas.Font.Assign(Font); Result.Right := 4; for I := 0 to FTabs.Count-1 do begin Size := Canvas.TextExtent(FTabs[I]); Result := Bounds(Result.Right, 0, Size.cx + (TabPaddingX * 2) + TabSpacing, Size.cy + (TabPaddingY * 2)); if Index = I then Exit; end; SetRectEmpty(Result); end; procedure TNewTabSet.InvalidateTab(Index: Integer); var R: TRect; begin if HandleAllocated and (Index >= 0) and (Index < FTabs.Count) then begin R := GetTabRect(Index); { Inc R.Right since the trailing separator of a tab overwrites the first pixel of the next tab } Inc(R.Right); InvalidateRect(Handle, @R, False); end; end; procedure TNewTabSet.ListChanged(Sender: TObject); begin Invalidate; end; procedure TNewTabSet.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; R: TRect; begin if Button = mbLeft then begin for I := 0 to FTabs.Count-1 do begin R := GetTabRect(I); if (X >= R.Left) and (X < R.Right) then begin TabIndex := I; Break; end; end; end; end; procedure TNewTabSet.Paint; var HighColorMode: Boolean; procedure DrawTabs(const SelectedTab: Boolean); var I: Integer; R: TRect; begin for I := 0 to FTabs.Count-1 do begin R := GetTabRect(I); if SelectedTab and (FTabIndex = I) then begin Dec(R.Right, TabSpacing); Canvas.Brush.Color := clBtnFace; Canvas.FillRect(R); Canvas.Pen.Color := clBtnHighlight; Canvas.MoveTo(R.Left, R.Top); Canvas.LineTo(R.Left, R.Bottom-1); Canvas.Pen.Color := clBtnText; Canvas.LineTo(R.Right-1, R.Bottom-1); Canvas.LineTo(R.Right-1, R.Top-1); Canvas.Font.Color := clBtnText; Canvas.TextOut(R.Left + TabPaddingX, R.Top + TabPaddingY, FTabs[I]); ExcludeClipRect(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom); Break; end; if not SelectedTab and (FTabIndex <> I) then begin if HighColorMode and (ColorToRGB(clBtnFace) <> clBlack) then Canvas.Font.Color := LightenColor(ColorToRGB(clBtnShadow), -43) else begin { Like VS.NET, if the button face color is black, or if running in low color mode, use plain clBtnHighlight as the text color } Canvas.Font.Color := clBtnHighlight; end; Canvas.TextOut(R.Left + TabPaddingX, R.Top + TabPaddingY, FTabs[I]); if HighColorMode then Canvas.Pen.Color := clBtnShadow else Canvas.Pen.Color := clBtnFace; Canvas.MoveTo(R.Right, R.Top+3); Canvas.LineTo(R.Right, R.Bottom-2); end; end; end; var CR: TRect; begin Canvas.Font.Assign(Font); HighColorMode := (GetDeviceCaps(Canvas.Handle, BITSPIXEL) * GetDeviceCaps(Canvas.Handle, PLANES)) >= 15; CR := ClientRect; { Work around an apparent NT 4.0/2000/??? bug. If the width of the DC is greater than the width of the screen, then any call to ExcludeClipRect inexplicably shrinks the DC's clipping rectangle to the screen width. Calling IntersectClipRect first with the entire client area as the rectangle solves this (don't ask me why). } IntersectClipRect(Canvas.Handle, CR.Left, CR.Top, CR.Right, CR.Bottom); { Selected tab } DrawTabs(True); { Top line } Canvas.Pen.Color := clBtnText; Canvas.MoveTo(0, 0); Canvas.LineTo(CR.Right, 0); { Background fill } if HighColorMode then Canvas.Brush.Color := LightenColor(ColorToRGB(clBtnFace), 35) else Canvas.Brush.Color := clBtnShadow; Inc(CR.Top); Canvas.FillRect(CR); { Non-selected tabs } DrawTabs(False); end; procedure TNewTabSet.SetTabIndex(Value: Integer); begin if FTabIndex <> Value then begin InvalidateTab(FTabIndex); FTabIndex := Value; InvalidateTab(Value); Click; end; end; procedure TNewTabSet.SetTabs(Value: TStrings); begin FTabs.Assign(Value); end; end.
unit Model.Clientes; interface uses Common.ENum, FireDAC.Comp.Client; type TClientes = class private FCodigo: Integer; FNome: String; FOS: Integer; FAcao: TAcao; FVerba: Double; FCliente: Integer; public property Cliente: Integer read FCliente write FCliente; property Codigo: Integer read FCodigo write FCodigo; property Nome: String read FNome write FNome; property Verba: Double read FVerba write FVerba; property OS: Integer read FOS write FOS; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TClientes } uses DAO.Clientes; function TClientes.Gravar: Boolean; var clienteDAO : TClientesDAO; begin try Result := False; clienteDAO := TClientesDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := clienteDAO.Inserir(Self); Common.ENum.tacAlterar: Result := clienteDAO.Alterar(Self); Common.ENum.tacExcluir: Result := clienteDAO.Excluir(Self); end; finally clienteDAO.Free; end; end; function TClientes.Localizar(aParam: array of variant): TFDQuery; var clientesDAO: TClientesDAO; begin try clientesDAO := TClientesDAO.Create; Result := clientesDAO.Pesquisar(aParam); finally clientesDAO.Free; end; end; end.
unit HGM.Controls.Labels; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.UITypes, Vcl.Direct2D, Winapi.D2D1, HGM.Common, HGM.Common.Utils; type ThLink = class(TLabel) private FOnMouseLeave: TNotifyEvent; FOnMouseEnter: TNotifyEvent; procedure MouseEnter(Sender:TObject); procedure MouseLeave(Sender:TObject); public constructor Create(AOwner: TComponent); override; published property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; end; TLabelEx = class(TShape) private FLabel:string; FTextFormat:TTextFormat; FEllipseRectVertical:Boolean; FIgnorBounds:Boolean; FFont:TFont; FOnPaint:TNotifyEvent; FRoundRectParam:TPoint; procedure SetLabel(const Value: string); procedure SetFont(const Value: TFont); procedure SetTextFormat(const Value: TTextFormat); procedure SetEllipseRectVertical(const Value: Boolean); procedure SetRoundRectParam(const Value: TPoint); procedure SetIgnorBounds(const Value: Boolean); protected procedure Paint; override; public procedure StyledColor(Value:TColor); constructor Create(AOwner: TComponent); override; published property Caption:string read FLabel write SetLabel; property Font:TFont read FFont write SetFont; property OnPaint:TNotifyEvent read FOnPaint write FOnPaint; property TextFormat:TTextFormat read FTextFormat write SetTextFormat; property RoundRectParam:TPoint read FRoundRectParam write SetRoundRectParam; property IgnorBounds:Boolean read FIgnorBounds write SetIgnorBounds; property EllipseRectVertical:Boolean read FEllipseRectVertical write SetEllipseRectVertical; end; procedure Register; implementation procedure Register; begin RegisterComponents(PackageName, [ThLink]); RegisterComponents(PackageName, [TLabelEx]); end; { TLableButton } constructor ThLink.Create(AOwner: TComponent); begin inherited; inherited OnMouseEnter:=MouseEnter; inherited OnMouseLeave:=MouseLeave; Font.Color:=$00D8963B; Cursor:=crHandPoint; end; procedure ThLink.MouseEnter(Sender: TObject); begin Font.Style:=Font.Style + [fsUnderLine]; if Assigned(OnMouseEnter) then OnMouseEnter(Sender); end; procedure ThLink.MouseLeave(Sender: TObject); begin Font.Style:=Font.Style - [fsUnderLine]; if Assigned(OnMouseLeave) then OnMouseLeave(Sender); end; { TLabelEx } constructor TLabelEx.Create(AOwner: TComponent); begin inherited; StyledColor($00996666); FLabel:=Name; FFont:=TFont.Create; FFont.Color:=clWhite; FFont.Size:=10; Width:=90; Height:=30; FRoundRectParam:=Point(0, 0); FIgnorBounds:=True; FTextFormat:=[tfCenter, tfVerticalCenter, tfWordBreak, tfWordEllipsis, tfSingleLine]; end; procedure TLabelEx.Paint; var LD2DCanvas: TDirect2DCanvas; var X, Y, W, H, S, Rx, Ry:Integer; //DF:TDrawTextFlags; FRect:TRect; d:Double; Str:string; begin LD2DCanvas:=TDirect2DCanvas.Create(Canvas, ClientRect); with LD2DCanvas do begin RenderTarget.BeginDraw; RenderTarget.SetTransform(TD2DMatrix3x2F.Identity); Pen.Assign(Self.Pen); Brush.Assign(Self.Brush); X:=Pen.Width div 2; Y:=X; W:=Width - Pen.Width + 1; H:=Height - Pen.Width + 1; if Pen.Width = 0 then begin Dec(W); Dec(H); end; if W < H then S:=W else S:=H; if Self.Shape in [stSquare, stRoundSquare, stCircle] then begin Inc(X, (W - S) div 2); W:=S; Inc(Y, (H - S) div 2); H:=S; end; case Self.Shape of stRectangle, stSquare: Rectangle(X, Y, X + W, Y + H); stRoundRect, stRoundSquare: begin if FRoundRectParam.X = 0 then Rx:=S div 4 else Rx:=FRoundRectParam.X; if FRoundRectParam.Y = 0 then Ry:=S div 4 else Ry:=FRoundRectParam.Y; RoundRect(X, Y, X + W, Y + H, Rx, Ry); end; stCircle, stEllipse: Ellipse(X, Y, X + W, Y + H); end; RenderTarget.EndDraw; end; LD2DCanvas.Free; Canvas.Font.Assign(FFont); Canvas.Brush.Style:=bsClear; if FIgnorBounds then FRect:=ClientRect else begin d:=1.6; //6.8 if FEllipseRectVertical then FRect:=Rect(Round(X + W / (6.8 / d)), Round(Y + H / (6.8 * d)), Round(X + W - W / (6.8 / d)), Round(Y + H - H / (6.8 * d))) else FRect:=Rect(Round(X + W / (6.8 * d)), Round(Y + H / (6.8 / d)), Round(X + W - W / (6.8 * d)), Round(Y + H - H / (6.8 / d))); end; //DF:=TTextFormatFlags(FTextFormat); Str:=FLabel; Canvas.TextRect(FRect, Str, FTextFormat); //DrawTextCentered(Canvas, FRect, Str, DF); end; procedure TLabelEx.SetEllipseRectVertical(const Value: Boolean); begin FEllipseRectVertical:= Value; Repaint; end; procedure TLabelEx.SetFont(const Value: TFont); begin FFont:=Value; Repaint; end; procedure TLabelEx.SetIgnorBounds(const Value: Boolean); begin FIgnorBounds:=Value; Repaint; end; procedure TLabelEx.SetLabel(const Value: string); begin FLabel:=Value; Repaint; end; procedure TLabelEx.SetRoundRectParam(const Value: TPoint); begin FRoundRectParam:= Value; Repaint; end; procedure TLabelEx.SetTextFormat(const Value: TTextFormat); begin FTextFormat:= Value; Repaint; end; procedure TLabelEx.StyledColor(Value: TColor); begin Brush.Color:=Value; Pen.Color:=ColorDarker(Brush.Color); end; end.
unit MultiplexList; interface uses Classes, SplitSocket, SysUtils, {$ifdef Lazarus}TCPSocket_Lazarus{$else}TCPSocket{$endif}, StatusThread; type TSocketMultiplexListOnOpeningTunnel = procedure(Sender: TObject; SMulti: TSocketMultiplex; Tunnel: TSplitSocket; var Accept: Boolean) of object; TSocketMultiplexListOnOpenedTunnel = procedure(Sender: TObject; SMulti: TSocketMultiplex; Tunnel: TSplitSocket) of object; TSocketMultiplexListOnRemoveSocket = procedure(Sender: TObject; SMulti: TSocketMultiplex) of object; TSocketMultiplexList = class private FList: TList; function GetSocket(i: Integer): TSocketMultiplex; procedure SocketMultiplexOnThreadExit(Sender: TObject); procedure SocketMultiplexOnOpeningTunnel_ReadThread(Sender: TObject; Tunnel: TSplitSocket; var Accept: Boolean); procedure SocketMultiplexOnOpenedTunnel(Sender: TObject; Tunnel: TSplitSocket); function SocketMultiplexOnHandleException(Sender: TThread; E: Exception; msg: String): Boolean; procedure RemoveSocketMultiplex(SMulti: TSocketMultiplex); public OnSocketOpeningTunnel_ReadThread: TSocketMultiplexListOnOpeningTunnel; OnSocketOpenedTunnel: TSocketMultiplexListOnOpenedTunnel; OnRemoveSocket: TSocketMultiplexListOnRemoveSocket; OnNewSocket: TSocketMultiplexListOnRemoveSocket; OnHandleException: THandleExceptionEvent; constructor Create; destructor Destroy; override; procedure AddSocketMultiplex(SMulti: TSocketMultiplex); overload; property Sockets[i: integer]: TSocketMultiplex read GetSocket; default; function Count: Integer; function AddSocketMultiplex(Socket: TSocket; Master: Boolean): TSocketMultiplex; overload; end; TSocketMultiplexListComponent = class(TComponent) private procedure SetOnSocketOpeningTunnel( P: TSocketMultiplexListOnOpeningTunnel); function GetOnSocketOpeningTunnel: TSocketMultiplexListOnOpeningTunnel; procedure SetOnSocketOpenedTunnel( P: TSocketMultiplexListOnOpenedTunnel); function GetOnSocketOpenedTunnel: TSocketMultiplexListOnOpenedTunnel; procedure SetOnRemoveSocket(P: TSocketMultiplexListOnRemoveSocket); function GetOnRemoveSocket: TSocketMultiplexListOnRemoveSocket; procedure SetOnNewSocket(P: TSocketMultiplexListOnRemoveSocket); function GetOnNewSocket: TSocketMultiplexListOnRemoveSocket; procedure SetOnException(P: THandleExceptionEvent); function GetOnException: THandleExceptionEvent; public SocketList: TSocketMultiplexList; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnNewSocket: TSocketMultiplexListOnRemoveSocket read GetOnNewSocket write SetOnNewSocket; property OnSocketOpeningTunnel: TSocketMultiplexListOnOpeningTunnel read GetOnSocketOpeningTunnel write SetOnSocketOpeningTunnel; property OnSocketOpenedTunnel: TSocketMultiplexListOnOpenedTunnel read GetOnSocketOpenedTunnel write SetOnSocketOpenedTunnel; property OnException: THandleExceptionEvent read GetOnException write SetOnException; property OnRemoveSocket: TSocketMultiplexListOnRemoveSocket read GetOnRemoveSocket write SetOnRemoveSocket; end; procedure Register; implementation uses Math; procedure Register; begin RegisterComponents('nice things', [TSocketMultiplexListComponent]); end; procedure TSocketMultiplexList.AddSocketMultiplex( SMulti: TSocketMultiplex); begin if Assigned(OnNewSocket) then OnNewSocket(Self,SMulti); FList.Add(SMulti); {$ifdef Lazarus} SMulti.OnNoConnection := @SocketMultiplexOnNoConnection; SMulti.OnOpeningTunnel := @SocketMultiplexOnOpeningTunnel; SMulti.OnOpenedTunnel := @SocketMultiplexOnOpenedTunnel; SMulti.OnException := @SocketMultiplexOnException; {$else} SMulti.OnThreadExit := SocketMultiplexOnThreadExit; SMulti.OnOpeningTunnel_ReadThread := SocketMultiplexOnOpeningTunnel_ReadThread; SMulti.OnOpenedTunnel := SocketMultiplexOnOpenedTunnel; SMulti.OnHandleException := SocketMultiplexOnHandleException; {$endif} SMulti.StartWorking; //Empfang starten, erst nachdem der socket in der liste! end; function TSocketMultiplexList.AddSocketMultiplex( Socket: TSocket; Master: Boolean): TSocketMultiplex; begin Result := TSocketMultiplex.Create(TTCPSocket.Create(Socket), Master); AddSocketMultiplex(Result); end; function TSocketMultiplexList.Count: Integer; begin Result := FList.Count; end; constructor TSocketMultiplexList.Create; begin OnSocketOpeningTunnel_ReadThread := nil; OnSocketOpenedTunnel := nil; OnRemoveSocket := nil; OnNewSocket := nil; OnHandleException := nil; inherited; FList := TList.Create; end; destructor TSocketMultiplexList.Destroy; begin while Count > 0 do Sockets[0].Free; FList.Free; inherited; end; function TSocketMultiplexList.GetSocket(i: Integer): TSocketMultiplex; begin if (i >= 0)and(i < FList.Count) then begin Result := TSocketMultiplex(FList[i]); end else raise Exception.Create('TSocketMultiplexList.GetSocket: Fehler bei Bereichsüberprüfung!'); end; procedure TSocketMultiplexList.RemoveSocketMultiplex( SMulti: TSocketMultiplex); begin SMulti.OnThreadExit := nil; SMulti.OnOpeningTunnel_ReadThread := nil; SMulti.OnOpenedTunnel := nil; SMulti.OnHandleException := nil; FList.Remove(SMulti); if Assigned(OnRemoveSocket) then OnRemoveSocket(Self,SMulti); end; procedure TSocketMultiplexList.SocketMultiplexOnThreadExit( Sender: TObject); begin RemoveSocketMultiplex(TSocketMultiplex(Sender)); end; procedure TSocketMultiplexList.SocketMultiplexOnOpeningTunnel_ReadThread( Sender: TObject; Tunnel: TSplitSocket; var Accept: Boolean); begin if Assigned(OnSocketOpeningTunnel_ReadThread) then OnSocketOpeningTunnel_ReadThread(Self,TSocketMultiplex(Sender),Tunnel,Accept); end; procedure TSocketMultiplexList.SocketMultiplexOnOpenedTunnel( Sender: TObject; Tunnel: TSplitSocket); begin if Assigned(OnSocketOpenedTunnel) then OnSocketOpenedTunnel(Self,TSocketMultiplex(Sender),Tunnel); end; function TSocketMultiplexList.SocketMultiplexOnHandleException(Sender: TThread; E: Exception; msg: String): Boolean; begin if Assigned(OnHandleException) then Result := OnHandleException(Sender,E,msg) else Result := False; end; constructor TSocketMultiplexListComponent.Create(AOwner: TComponent); begin inherited; SocketList := TSocketMultiplexList.Create; end; destructor TSocketMultiplexListComponent.Destroy; begin SocketList.Free; inherited; end; function TSocketMultiplexListComponent.GetOnSocketOpenedTunnel: TSocketMultiplexListOnOpenedTunnel; begin Result := SocketList.OnSocketOpenedTunnel; end; function TSocketMultiplexListComponent.GetOnRemoveSocket: TSocketMultiplexListOnRemoveSocket; begin Result := SocketList.OnRemoveSocket; end; function TSocketMultiplexListComponent.GetOnSocketOpeningTunnel: TSocketMultiplexListOnOpeningTunnel; begin Result := SocketList.OnSocketOpeningTunnel_ReadThread; end; procedure TSocketMultiplexListComponent.SetOnRemoveSocket( P: TSocketMultiplexListOnRemoveSocket); begin SocketList.OnRemoveSocket := P; end; procedure TSocketMultiplexListComponent.SetOnSocketOpenedTunnel( P: TSocketMultiplexListOnOpenedTunnel); begin SocketList.OnSocketOpenedTunnel := P; end; procedure TSocketMultiplexListComponent.SetOnSocketOpeningTunnel( P: TSocketMultiplexListOnOpeningTunnel); begin SocketList.OnSocketOpeningTunnel_ReadThread := P; end; procedure TSocketMultiplexListComponent.SetOnNewSocket( P: TSocketMultiplexListOnRemoveSocket); begin SocketList.OnNewSocket := P; end; function TSocketMultiplexListComponent.GetOnNewSocket: TSocketMultiplexListOnRemoveSocket; begin Result := SocketList.OnNewSocket; end; procedure TSocketMultiplexListComponent.SetOnException( P: THandleExceptionEvent); begin SocketList.OnHandleException := P; end; function TSocketMultiplexListComponent.GetOnException: THandleExceptionEvent; begin Result := SocketList.OnHandleException; end; end.
unit AddNewUserResponseUnit; interface uses REST.Json.Types, GenericParametersUnit; type TAddNewUserResponse = class(TGenericParameters) private [JSONName('member_id')] FMemberId: integer; public property MemberId: integer read FMemberId write FMemberId; end; implementation end.
unit Unit2; interface uses System.Classes, StdCtrls, SysUtils, SyncObjs, IdGlobal, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTPCommon, IdFTP; type TUploadProgress = procedure(Current, Max: Int64) of object; TUploadStatus = procedure(const AStatusText: String) of object; TFtpWork = (stFtpUpload, stFtpDownload); TFtpThread = class(TThread) private FFTP: TIdFTP; FFileName: String; FDestFileName: string; FErrorMsg: String; FWorkMax: Int64; FFtpWork: TFtpWork; FPauseEvent: TEvent; FOnProgress: TUploadProgress; FOnStatus: TUploadStatus; procedure CheckAborted(SendAbort: Boolean = False); procedure FTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); procedure FTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure FTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure FTPWorkEnd(ASender: TObject; AWorkMode: TWorkMode); function GetFtpWork: TFtpWork; procedure SetFtpWork(const Value: TFtpWork); protected procedure Execute; override; procedure DoTerminate; override; public constructor Create(const Host: string; Port: TIdPort; const FileName: String; const DestFilenName: String; const DoWork: TFtpWork); reintroduce; destructor Destroy; override; procedure Pause; procedure Unpause; property ErrorMessage: String read FErrorMsg; property ReturnValue; property OnProgress: TUploadProgress read FOnProgress write FOnProgress; property OnStatus: TUploadStatus read FOnStatus write FOnStatus; property DoFtpWork: TFtpWork read GetFtpWork write SetFtpWork; end; implementation { TUpload } // -------------------------------------------------------------------------- constructor TFtpThread.Create(const Host: string; Port: TIdPort; const FileName: String; const DestFilenName: String; const DoWork: TFtpWork); begin inherited Create(False); FreeOnTerminate := True; FPauseEvent := TEvent.Create(nil, True, True, ''); Fftpwork:= dowork; FFTP := TIdFTP.Create(nil); FFTP.Host := Host; FFTP.Port := Port; FFTP.Username := 'avtoefi'; FFTP.Password := 'RuR7nSTh7IZo'; FFTP.OnStatus := FTPStatus; FFTP.OnWork := FTPWork; FFTP.OnWorkBegin := FTPWorkBegin; FFTP.OnWorkEnd := FTPWorkEnd; FFileName := FileName; FDestFileName:=DestFilenName; end; // ----------------------------------------------------------------------------- destructor TFtpThread.Destroy; begin FFTP.Free; FPauseEvent.Free; inherited Destroy; end; // ----------------------------------------------------------------------------- procedure TFtpThread.CheckAborted(SendAbort: Boolean = False); begin FPauseEvent.WaitFor(INFINITE); if Terminated then begin if SendAbort then FFTP.Abort; SysUtils.Abort; end; end; // ----------------------------------------------------------------------------- procedure TFtpThread.Pause; begin FPauseEvent.ResetEvent; end; procedure TFtpThread.SetFtpWork(const Value: TFtpWork); begin FFtpWork := Value; end; // ----------------------------------------------------------------------------- procedure TFtpThread.Unpause; begin FPauseEvent.SetEvent; end; // ----------------------------------------------------------------------------- procedure TFtpThread.Execute; begin CheckAborted; try FFTP.Connect; except on E: Exception do raise Exception.Create('Connection error: ' + E.Message); end; try CheckAborted; try FFTP.ChangeDir('/'); except on E: Exception do raise Exception.Create('Change dir error > ' + E.Message); end; CheckAborted; try FFTP.TransferType := ftBinary; case FFtpWork of stFtpUpload: FFTP.Put(FFileName, ExtractFileName(FFileName)); stFtpDownload: FFTP.Get( ExtractFileName(FFileName),FDestFileName); end; except on E: EAbort do raise; on E: Exception do raise Exception.Create('Error in process: ' + E.Message); end; ReturnValue := 1; finally FFTP.Disconnect; end; end; // ------------------------------------------------------------------------------ procedure TFtpThread.DoTerminate; begin if FatalException <> nil then begin if Exception(FatalException) is EAbort then case FFtpWork of stFtpUpload: FErrorMsg := 'Upload cancel!'; stFtpDownload: FErrorMsg := 'Download cancel!'; end else FErrorMsg := Exception(FatalException).Message; end; inherited DoTerminate; end; // ------------------------------------------------------------------------------ procedure TFtpThread.FTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin if Assigned(FOnStatus) then begin Synchronize( procedure begin if Assigned(FOnStatus) then FOnStatus(AStatusText); end); end; end; // ------------------------------------------------------------------------------ procedure TFtpThread.FTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin case FFtpWork of stFtpUpload: if AWorkMode <> wmWrite then Exit; stFtpDownload: if AWorkMode <> wmRead then Exit; end ; if Assigned(FOnProgress) then begin Synchronize( procedure begin if Assigned(FOnProgress) then FOnProgress(AWorkCount, FWorkMax); end); end; CheckAborted(True); end; // ------------------------------------------------------------------------------ procedure TFtpThread.FTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin case FFtpWork of stFtpUpload: if AWorkMode <> wmWrite then Exit; stFtpDownload: if AWorkMode <> wmRead then Exit; end ; FWorkMax := AWorkCountMax; if Assigned(FOnProgress) then begin Synchronize( procedure begin if Assigned(FOnProgress) then FOnProgress(0, FWorkMax); end); end; CheckAborted(True); end; // ------------------------------------------------------------------------------ procedure TFtpThread.FTPWorkEnd(ASender: TObject; AWorkMode: TWorkMode); begin case FFtpWork of stFtpUpload: if AWorkMode <> wmWrite then Exit; stFtpDownload: if AWorkMode <> wmRead then Exit; end; if Assigned(FOnProgress) then begin Synchronize( procedure begin if Assigned(FOnProgress) then FOnProgress(FWorkMax, FWorkMax); end); end; end; function TFtpThread.GetFtpWork: TFtpWork; begin Result := FFtpWork; end; // ------------------------------------------------------------------------------ end.
unit wProjExemplo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm44 = class(TForm) Memo1: TMemo; Button1: TButton; CheckBox1: TCheckBox; procedure Button1Click(Sender: TObject); private procedure add(s: String); { Private declarations } public { Public declarations } end; var Form44: TForm44; implementation {$R *.dfm} uses System.Diagnostics, System.SyncObjs, System.Threading; procedure TForm44.add(s: String); begin TThread.Queue(TThread.CurrentThread, procedure begin Memo1.lines.add(s); end); end; // criando WaitForAllEx Type TTaskHelper = class helper for TTask private type TUnsafeTaskEx = record private [Unsafe] // preciso de um record UNSAFE para nao incrementar o RefCount da Interface FTask: TTask; public property Value: TTask read FTask write FTask; end; public class function WaitForAllEx(AArray: Array of ITask; ATimeOut: int64 = INFINITE): boolean; end; class function TTaskHelper.WaitForAllEx(AArray: array of ITask; ATimeOut: int64 = INFINITE): boolean; var FEvent: TEvent; task: TUnsafeTaskEx; i: integer; taskInter: TArray<TUnsafeTaskEx>; completou: boolean; Canceled, Exceptions: boolean; ProcCompleted: TProc<ITask>; LHandle: THandle; LStop: TStopwatch; begin LStop := TStopwatch.StartNew; ProcCompleted := procedure(ATask: ITask) begin FEvent.SetEvent; end; Canceled := false; Exceptions := false; result := true; try for i := low(AArray) to High(AArray) do begin task.Value := TTask(AArray[i]); if task.Value = nil then raise EArgumentNilException.Create('Wait Nil Task'); completou := task.Value.IsComplete; if not completou then begin taskInter := taskInter + [task]; end else begin if task.Value.HasExceptions then Exceptions := true else if task.Value.IsCanceled then Canceled := true; end; end; try FEvent := TEvent.Create(); for task in taskInter do begin try FEvent.ResetEvent; if LStop.ElapsedMilliseconds > ATimeOut then break; LHandle := FEvent.Handle; task.Value.AddCompleteEvent(ProcCompleted); while not task.Value.IsComplete do begin if LStop.ElapsedMilliseconds > ATimeOut then break; if MsgWaitForMultipleObjectsEx(1, LHandle, ATimeOut - LStop.ElapsedMilliseconds, QS_ALLINPUT, 0) = WAIT_OBJECT_0 + 1 then application.ProcessMessages; end; if task.Value.IsComplete then begin if task.Value.HasExceptions then Exceptions := true else if task.Value.IsCanceled then Canceled := true; end; finally task.Value.removeCompleteEvent(ProcCompleted); end; end; finally FEvent.Free; end; except result := false; end; if (not Exceptions and not Canceled) then Exit; if Exceptions or Canceled then raise EOperationCancelled.Create ('One Or More Tasks HasExceptions/Canceled'); end; procedure TForm44.Button1Click(Sender: TObject); var tsk: array [0 .. 2] of ITask; i, n: integer; begin tsk[0] := TTask.Create( procedure begin TThread.Queue(nil, procedure begin caption := 'xxx'; // sincronizar a atualização da janela. end); end); tsk[0].Start; tsk[2] := TTask.Create( procedure var k: integer; begin i := 1; Sleep(10000); for k := 0 to 10000 do inc(i); end); tsk[1] := TTask.Create( procedure var k: integer; begin n := n; for k := 0 to 1000 do inc(n); add('N'); end); tsk[2].Start; tsk[1].Start; if CheckBox1.Checked then TTask.WaitForAllEx(tsk) else TTask.WaitForAll(tsk); Memo1.lines.add('xxxxxxxx N: ' + IntToStr(n) + ' I: ' + IntToStr(i)); TParallel.For(100, 105, procedure(i: integer) begin add(IntToStr(i)); end); Memo1.lines.add(' N: ' + IntToStr(n) + ' I: ' + IntToStr(i)); end; { TTaskHelper } end.
unit dcDateEditBtn; interface {$I RX.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, DateUtil, datacontroller, db, FFSUtils, ffstypes; type TFFSPopupWindow = class(TPopupWindow); TDateStorageFormat = (dsfMMDDYYYY, dsfYYYYMMDD); TFFSCustomPopupDate = class(TCustomComboEdit) private FClearing: boolean; procedure SetClearing(const Value: boolean); function GetDataBufIndex: integer; procedure SetDataBufIndex(const Value: integer); private FOnAcceptDate: TExecDateDialog; FDefaultToday: Boolean; FHooked: Boolean; FPopupColor: TColor; FCheckOnExit: Boolean; FBlanksChar: Char; FCalendarHints: TStrings; FStartOfWeek: TDayOfWeekName; FWeekends: TDaysOfWeek; FWeekendColor: TColor; FFormatting: Boolean; FNonDates: TFFSNonDates; BeforePopup : string; fdcLink : TdcLink; fRequired : boolean; OldReadonly : boolean; FStorageFormat: TDateStorageFormat; procedure SetStorageFormat(const Value: TDateStorageFormat); function GetDate: TDateTime; procedure SetDate(Value: TDateTime); function GetPopupColor: TColor; procedure SetPopupColor(Value: TColor); procedure SetCalendarHints(Value: TStrings); procedure CalendarHintsChanged(Sender: TObject); procedure SetWeekendColor(Value: TColor); procedure SetWeekends(Value: TDaysOfWeek); procedure SetStartOfWeek(Value: TDayOfWeekName); procedure SetBlanksChar(Value: Char); function TextStored: Boolean; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure SetNonDates(const Value: TFFSNonDates); function DateIsBlank(s:string):boolean; property Clearing:boolean read FClearing write SetClearing; protected // std data awareness function GetDataSource:TDataSource; procedure SetDataSource(value:Tdatasource); function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); procedure DoEnter;override; procedure DoExit;override; procedure Change; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DestroyWindowHandle; override; function AcceptPopup(var Value: Variant): Boolean; override; procedure AcceptValue(const Value: Variant); override; procedure SetPopupValue(const Value: Variant); override; procedure ApplyDate(Value: TDateTime); virtual; function GetDefaultBitmap(var DestroyNeeded: Boolean): TBitmap; override; procedure UpdatePopup; property BlanksChar: Char read FBlanksChar write SetBlanksChar default ' '; property CalendarHints: TStrings read FCalendarHints write SetCalendarHints; property CheckOnExit: Boolean read FCheckOnExit write FCheckOnExit default False; property DefaultToday: Boolean read FDefaultToday write FDefaultToday default False; property EditMask stored False; property Formatting: Boolean read FFormatting; property GlyphKind default gkDefault; property PopupColor: TColor read GetPopupColor write SetPopupColor default clBtnFace; property StartOfWeek: TDayOfWeekName read FStartOfWeek write SetStartOfWeek default Mon; property Weekends: TDaysOfWeek read FWeekends write SetWeekends default [Sun]; property WeekendColor: TColor read FWeekendColor write SetWeekendColor default clRed; property OnAcceptDate: TExecDateDialog read FOnAcceptDate write FOnAcceptDate; property MaxLength stored False; property Text stored TextStored; procedure CheckValidDate; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Date: TDateTime read GetDate write SetDate; property PopupVisible; property NonDates:TFFSNonDates read FNonDates write SetNonDates; property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDatasource; property Required : boolean read fRequired write fRequired; property StorageFormat : TDateStorageFormat read FStorageFormat write SetStorageFormat; published property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex; end; { TDateEdit } TdcDateEditBtn = class(TFFSCustomPopupDate) public published property NonDates; property AutoSelect; property BorderStyle; property ButtonHint; property ClickKey; property Color; property Ctl3D; property DirectInput; property DragCursor; property DragMode; property Enabled; property Font; property GlyphKind; { Ensure GlyphKind is declared before Glyph and ButtonWidth } property Glyph; property ButtonWidth; property HideSelection; {$IFDEF RX_D4} property Anchors; property BiDiMode; property Constraints; property CheckOnExit; property DragKind; property ParentBiDiMode; {$ENDIF} {$IFDEF WIN32} {$IFNDEF VER90} property ImeMode; property ImeName; {$ENDIF} {$ENDIF} property MaxLength; property NumGlyphs; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupAlign; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property OnButtonClick; 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; {$IFDEF WIN32} property OnStartDrag; {$ENDIF} {$IFDEF RX_D5} property OnContextPopup; {$ENDIF} {$IFDEF RX_D4} property OnEndDock; property OnStartDock; {$ENDIF} property DataController; property DataField; property DataSource; property Required; property StorageFormat; end; procedure Register; implementation uses StrUtils, PickDate; const DateBitmap: TBitmap = nil; sDateBmp = 'DEDITBMP'; { Date editor button glyph } sDateFormat = 'mm/dd/yyyy'; DateEditMask = '99/99/9999;1'; dsfString : array[TDateStorageFormat] of string = ('mm/dd/yyyy', 'yyyymmdd'); procedure Register; begin RegisterComponents('FFS Data Entry', [TdcDateEditBtn]); end; { TFFSCustomPopupDate } { TFFSCustomPopupDate } function NvlDate(DateValue, DefaultValue: TDateTime): TDateTime; begin if (DateValue = NullDate) or (DateValue = BadDate) then Result := DefaultValue else Result := DateValue; end; constructor TFFSCustomPopupDate.Create(AOwner: TComponent); begin inherited Create(AOwner); FBlanksChar := ' '; FPopupColor := clBtnFace; FDefNumGlyphs := 2; FStartOfWeek := Sun; FWeekends := [Sat,Sun]; FWeekendColor := clRed; FCalendarHints := TStringList.Create; TStringList(FCalendarHints).OnChange := CalendarHintsChanged; ClickKey := scNone + VK_F3; ControlState := ControlState + [csCreating]; width := 89; try {$IFDEF DEFAULT_POPUP_CALENDAR} FPopup := TPopupWindow(CreatePopupCalendar(Self {$IFDEF RX_D4}, BiDiMode {$ENDIF})); TPopupWindow(FPopup).OnCloseUp := PopupCloseUp; TFFSPopupWindow(FPopup).Color := FPopupColor; {$ENDIF DEFAULT_POPUP_CALENDAR} GlyphKind := gkDefault; { force update } finally ControlState := ControlState - [csCreating]; end; FCheckOnExit := true; UpdatePopup; fdclink := tdclink.create(self); fdclink.OnReadData := ReadData; fdclink.OnWriteData := WriteData; fdclink.OnClearData := ClearData; fStorageFormat := dsfMMDDYYYY; end; destructor TFFSCustomPopupDate.Destroy; begin if FHooked then FHooked := False; if FPopup <> nil then TPopupWindow(FPopup).OnCloseUp := nil; fdclink.free; FPopup.Free; FPopup := nil; TStringList(FCalendarHints).OnChange := nil; FCalendarHints.Free; FCalendarHints := nil; inherited Destroy; end; procedure TFFSCustomPopupDate.CreateWindowHandle(const Params: TCreateParams); begin inherited CreateWindowHandle(Params); if Handle <> 0 then begin if not (csDesigning in ComponentState) and not (IsLibrary or FHooked) then begin FHooked := True; end; end; end; procedure TFFSCustomPopupDate.DestroyWindowHandle; begin if FHooked then begin FHooked := False; end; inherited DestroyWindowHandle; end; function TFFSCustomPopupDate.TextStored: Boolean; begin Result := not IsEmptyStr(Text, [#0, ' ', DateSeparator, FBlanksChar]); end; procedure TFFSCustomPopupDate.CheckValidDate; var okdate : boolean; dt : TFFSDate; begin try FFormatting := True; try dt := ffsutils.ConvertToDate(Text); if dt = baddate then raise exception.create('Invalid Date Entered'); SetDate(dt); finally FFormatting := False; end; except okdate := false; if (ndCont in nondates) and (copy(text,1,1) = copy(dvStrings[ndCont],1,1)) then okdate := true; if (ndWaived in nondates) and (copy(text,1,1) = copy(dvStrings[ndWaived],1,1)) then okdate := true; if (ndHist in nondates) and (copy(text,1,1) = copy(dvStrings[ndHist],1,1)) then okdate := true; if (ndNA in nondates) and (copy(text,1,1) = copy(dvStrings[ndNA],1,1)) then okdate := true; if (ndSatisfied in nondates) and (copy(text,1,1) = copy(dvStrings[ndSatisfied],1,1)) then okdate := true; if DateisBlank(Text) then // = ' / / ' then begin EditMask := ''; Text := ''; Okdate := true; end; if not okdate then begin if CanFocus then SetFocus; raise; end; end; end; procedure TFFSCustomPopupDate.CMExit(var Message: TCMExit); begin if not (csDesigning in ComponentState) and CheckOnExit then CheckValidDate; inherited; end; function TFFSCustomPopupDate.GetDefaultBitmap(var DestroyNeeded: Boolean): TBitmap; begin DestroyNeeded := False; if DateBitmap = nil then begin DateBitmap := TBitmap.Create; DateBitmap.Handle := LoadBitmap(hInstance, sDateBmp); end; Result := DateBitmap; end; procedure TFFSCustomPopupDate.SetBlanksChar(Value: Char); begin if Value <> FBlanksChar then begin if (Value < ' ') then Value := ' '; FBlanksChar := Value; end; end; function TFFSCustomPopupDate.GetDate: TDateTime; begin if DefaultToday then Result := SysUtils.Date else Result := NullDate; Result := ffsUtils.ConvertToDate(text);// StrToDateFmtDef(sDateFormat, Text, Result); end; procedure TFFSCustomPopupDate.SetDate(Value: TDateTime); var D: TDateTime; begin if not DateUtil.ValidDate(Value) or (Value = NullDate) then begin if DefaultToday then Value := SysUtils.Date else Value := NullDate; end; D := self.Date; if Value = NullDate then begin Text := ''; EditMask := ''; end else begin EditMask := DateEditMask; Text := ffsutils.DateToShortString(value);// FormatDateTime(sDateFormat, Value); end; Modified := D <> Date; end; procedure TFFSCustomPopupDate.ApplyDate(Value: TDateTime); begin SetDate(Value); SelectAll; end; procedure TFFSCustomPopupDate.UpdatePopup; begin if FPopup <> nil then SetupPopupCalendar(FPopup, FStartOfWeek, FWeekends, FWeekendColor, FCalendarHints, true); end; function TFFSCustomPopupDate.GetPopupColor: TColor; begin if FPopup <> nil then Result := TFFSPopupWindow(FPopup).Color else Result := FPopupColor; end; procedure TFFSCustomPopupDate.SetPopupColor(Value: TColor); begin if Value <> PopupColor then begin if FPopup <> nil then TFFSPopupWindow(FPopup).Color := Value; FPopupColor := Value; end; end; procedure TFFSCustomPopupDate.SetCalendarHints(Value: TStrings); begin FCalendarHints.Assign(Value); end; procedure TFFSCustomPopupDate.CalendarHintsChanged(Sender: TObject); begin TStringList(FCalendarHints).OnChange := nil; try while (FCalendarHints.Count > 4) do FCalendarHints.Delete(FCalendarHints.Count - 1); finally TStringList(FCalendarHints).OnChange := CalendarHintsChanged; end; if not (csDesigning in ComponentState) then UpdatePopup; end; procedure TFFSCustomPopupDate.SetWeekendColor(Value: TColor); begin if Value <> FWeekendColor then begin FWeekendColor := Value; UpdatePopup; end; end; procedure TFFSCustomPopupDate.SetWeekends(Value: TDaysOfWeek); begin if Value <> FWeekends then begin FWeekends := Value; UpdatePopup; end; end; procedure TFFSCustomPopupDate.SetStartOfWeek(Value: TDayOfWeekName); begin if Value <> FStartOfWeek then begin FStartOfWeek := Value; UpdatePopup; end; end; procedure TFFSCustomPopupDate.KeyDown(var Key: Word; Shift: TShiftState); var s : string; n, ok : integer; begin if (Key in [VK_PRIOR, VK_NEXT, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_ADD, VK_SUBTRACT]) and PopupVisible then begin if readonly then begin key := 0; exit; end; TFFSPopupWindow(FPopup).KeyDown(Key, Shift); Key := 0; end else if DirectInput then begin if readonly then begin key := 0; exit; end; case Key of Ord('A') : if (shift = []) then begin s := ''; if inputquery('Advance Date by Months','Number of months to advance',s) then begin val(s,n,ok); if ok = 0 then ApplyDate(IncMonth(NvlDate(Date, Now), n)); SelectAll; end; Key := 0; end; Ord('Q') : if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(IncMonth(NvlDate(Date, Now),-3)) else ApplyDate(IncMonth(NvlDate(Date, Now),3)); SelectAll; key := 0; end; Ord('Y') : if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(IncMonth(NvlDate(Date, Now),-12)) else ApplyDate(IncMonth(NvlDate(Date, Now),12)); SelectAll; key := 0; end; Ord('M') : if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(IncMonth(NvlDate(Date, Now),-1)) else ApplyDate(IncMonth(NvlDate(Date, Now),1)); SelectAll; key := 0; end; Ord('D') : if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(NvlDate(Date, Now)-1) else ApplyDate(NvlDate(Date, Now)+1); SelectAll; key := 0; end; VK_PRIOR : if (shift = [ssCtrl]) or (shift = []) then begin if shift = [ssCtrl] then ApplyDate(IncMonth(NvlDate(Date, Now),-12)) else ApplyDate(IncMonth(NvlDate(Date, Now),-1)); SelectAll; Key := 0; end; VK_NEXT : if (shift = [ssCtrl]) or (shift = []) then begin if shift = [ssCtrl] then ApplyDate(IncMonth(NvlDate(Date, Now),12)) else ApplyDate(IncMonth(NvlDate(Date, Now),1)); SelectAll; Key := 0; end; VK_UP, VK_SUBTRACT : if (shift = []) then begin ApplyDate(NvlDate(Date, Now)-1); SelectAll; Key := 0; end; VK_DOWN, VK_ADD : if (shift = []) then begin ApplyDate(NvlDate(Date, Now)+1); SelectAll; Key := 0; end; VK_DELETE, VK_BACK : if (shift = []) then begin if editmask = '' then begin text := ''; key := 0; end else begin if (sellength = 10) and (editmask = DateEditMask) then begin EditMask := ''; Text := ''; key := 0; end; end; end; end; end; inherited KeyDown(Key, Shift); end; procedure TFFSCustomPopupDate.KeyPress(var Key: Char); procedure UpdateValue(var akey:char); begin if PopupVisible then PopupCloseUp(self, false); EditMask := ''; case upcase(akey) of 'C' : text := dvStrings[ndCont]; 'W' : text := dvStrings[ndWaived]; 'H' : text := dvStrings[ndHist]; 'N' : text := dvStrings[ndNA]; 'S' : text := dvStrings[ndSatisfied]; end; SelectAll; akey := #0; end; begin if not readonly then begin if key = ' ' then key := 'T'; // default space to TODAY case upcase(key) of 'C' : if ndCont in nondates then UpdateValue(Key) else key := #0; 'W' : if ndWaived in nondates then UpdateValue(Key) else key := #0; 'H' : if ndHist in nondates then UpdateValue(Key) else key := #0; 'N' : if ndNA in nondates then UpdateValue(Key) else key := #0; 'S' : if ndSatisfied in nondates then UpdateValue(Key) else key := #0; 'T', '0'..'9' : begin if EditMask <> DateEditMask then begin text := EmptyStr; EditMask := DateEditMask; end; end; #13 : CheckValidDate; else if not popupvisible then key := #0; end; // if (Key in ['T', 't', '+', '-']) and PopupVisible then begin TFFSPopupWindow(FPopup).KeyPress(Key); Key := #0; end else if DirectInput then begin case upcase(key) of 'T' : begin ApplyDate(Trunc(Now)); Key := #0; end; end; end; end; inherited KeyPress(key); end; function TFFSCustomPopupDate.AcceptPopup(var Value: Variant): Boolean; var D: TDateTime; begin Result := True; if Assigned(FOnAcceptDate) then begin {$IFDEF WIN32} if VarIsNull(Value) or VarIsEmpty(Value) then D := NullDate else try D := VarToDateTime(Value); except if DefaultToday then D := SysUtils.Date else D := NullDate; end; {$ELSE} if DefaultToday then D := SysUtils.Date else D := NullDate; D := ffsUtils.ConvertToDate(Value);//StrToDateDef(Value, D); {$ENDIF} FOnAcceptDate(Self, D, Result); if Result then Value := VarFromDateTime(D); end; end; {$IFDEF WIN32} procedure TFFSCustomPopupDate.SetPopupValue(const Value: Variant); var s : string; begin s := VarToStr(Value); if DateIsBlank(s) then s := ffsutils.SystemDateString; // FormatDateTime(sDateFormat, sysutils.date); inherited SetPopupValue(ConvertToDate(s));// StrToDateFmtDef(sDateFormat, s, SysUtils.Date)); end; procedure TFFSCustomPopupDate.AcceptValue(const Value: Variant); begin SetDate(VarToDateTime(Value)); UpdatePopupVisible; if Modified then inherited Change; end; {$ENDIF} procedure TFFSCustomPopupDate.Change; begin if not FFormatting then begin if assigned(fdclink) then if not clearing then fdclink.BeginEdit; inherited Change; end; end; procedure TFFSCustomPopupDate.SetNonDates(const Value: TFFSNonDates); begin FNonDates := Value; end; function TFFSCustomPopupDate.DateIsBlank(s:string):boolean; var x : integer; nb : boolean; begin nb := false; for x := 1 to length(s) do begin if not (s[x] in [' ', '/']) then nb := true; end; result := not nb; end; procedure TFFSCustomPopupDate.ClearData(sender: TObject); begin clearing := true; editmask := ''; text := ''; clearing := false; end; procedure TFFSCustomPopupDate.DoEnter; begin OldReadOnly := ReadOnly; if DataController <> nil then ReadOnly := DataController.ReadOnly; inherited; end; procedure TFFSCustomPopupDate.DoExit; begin ReadOnly := OldReadonly; inherited; end; function TFFSCustomPopupDate.GetDataController: TDataController; begin result := fdcLink.DataController; end; function TFFSCustomPopupDate.GetDataField: string; begin result := fdclink.FieldName; end; function TFFSCustomPopupDate.GetDataSource: TDataSource; begin result := fdclink.DataSource; end; procedure TFFSCustomPopupDate.ReadData(sender: TObject); var originalData : string; begin if not assigned(fdclink.DataController) then exit; OriginalData := ''; if (DataBufIndex = 0) and (DataField <> '') then OriginalData := fdcLink.DataController.dcStrings.StrVal[DataField] else if assigned(fdclink.datacontroller.databuf) then OriginalData := fdclink.datacontroller.databuf.AsString[DataBufIndex]; if (OriginalData > '') then begin if not (Originaldata[1] in ['0'..'9']) then editmask := '' else editmask := dateEditMask; if (StorageFormat = dsfYYYYMMDD) then begin if OriginalData[1] in ['0'..'9'] then OriginalData := copy(OriginalData,5,2) + '/' + copy(originaldata,7,2) + '/' + copy(originaldata,1,4); end; end else editmask := ''; text := OriginalData; try CheckValidDate; except end; end; procedure TFFSCustomPopupDate.SetDataController(value: TDataController); begin fdcLink.datacontroller := value; end; procedure TFFSCustomPopupDate.SetDataField(value: string); begin fdclink.FieldName := value; end; procedure TFFSCustomPopupDate.SetDataSource(value: Tdatasource); begin end; procedure TFFSCustomPopupDate.SetStorageFormat(const Value: TDateStorageFormat); begin FStorageFormat := Value; end; procedure TFFSCustomPopupDate.WriteData(sender: TObject); var s : string; begin if not assigned(fdclink.DataController) then exit; if ValidDate(self.Date) and (self.date <> NULLDATE) then begin case StorageFormat of dsfMMDDYYYY : s := FormatDateTime('mm/dd/yyyy', self.date); dsfYYYYMMDD : s := FormatDateTime('yyyymmdd', self.date); end; end else s := text; if (DataBufIndex = 0) and (DataField <> '') then fdcLink.DataController.dcStrings.StrVal[DataField] := s else if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asString[DataBufIndex] := s; end; procedure TFFSCustomPopupDate.SetClearing(const Value: boolean); begin FClearing := Value; end; function TFFSCustomPopupDate.GetDataBufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TFFSCustomPopupDate.SetDataBufIndex(const Value: integer); begin end; end.
{$I ok_sklad.inc} unit EditAtt; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ssBaseDlg, cxLookAndFeelPainters, ssFormStorage, ActnList, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, cxTimeEdit,ssBaseConst, Buttons, cxDropDownEdit, cxCalendar, ImgList, ssSpeedButton, ssPanel, ssGradientPanel, xButton, ssBevel; type TfrmEditAtt = class(TBaseDlg) ssBevel1: TssBevel; lNum: TLabel; edAttNum: TcxTextEdit; lAttOndate: TLabel; edAttDate: TcxDateEdit; lReceived: TLabel; cbReceived: TcxComboBox; procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure sbNowTimeClick(Sender: TObject); procedure edNumPropertiesChange(Sender: TObject); procedure edDatePropertiesChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure cbReceivedEnter(Sender: TObject); procedure cbReceivedExit(Sender: TObject); public procedure SetCaptions; override; end; var frmEditAtt: TfrmEditAtt; implementation uses prFun, prConst, xLngManager, udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} //============================================================================================== procedure TfrmEditAtt.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.ActionListUpdate') else _udebug := nil;{$ENDIF} edAttDate.Enabled := trim(edAttNum.Text)<>''; aOk.Enabled := True;//(trim(edAttNum.Text)<>'')and(trim(edAttDate.Text)<>''); aApply.Enabled := aOk.Enabled and FModified; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.FormShow(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.FormShow') else _udebug := nil;{$ENDIF} FModified:=false; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.FormCloseQuery(Sender: TObject; var CanClose: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.FormCloseQuery') else _udebug := nil;{$ENDIF} if ModalResult in [mrOK, mrYes] then begin CanClose:=False; case ModalResult of mrOK: CanClose:=true; mrYes: FModified:=false; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.sbNowTimeClick(Sender: TObject); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.sbNowTimeClick') else _udebug := nil;{$ENDIF} edTime1.Time:=Now; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmEditAtt.edNumPropertiesChange(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.edNumPropertiesChange') else _udebug := nil;{$ENDIF} FModified := true; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.edDatePropertiesChange(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.edDatePropertiesChange') else _udebug := nil;{$ENDIF} FModified:=true; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.FormKeyPress(Sender: TObject; var Key: Char); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.FormKeyPress') else _udebug := nil;{$ENDIF} if Key = #13 then begin Key := #0; Perform(WM_NEXTDLGCTL,0,0); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.SetCaptions; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.SetCaptions') else _udebug := nil;{$ENDIF} inherited; with LangMan do begin lNum.Caption := GetRS('fmWaybill', 'AttNumEx') + ':'; lAttOnDate.Caption := GetRS('fmWaybill', 'AttDateEx') + ':'; lReceived.Caption := GetRS('fmWaybill', 'MPerson') + ':'; aOK.Caption := GetRS('Common', 'OK'); aCancel.Caption := GetRS('Common', 'Cancel'); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.FormCreate(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.FormCreate') else _udebug := nil;{$ENDIF} SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditAtt.cbReceivedEnter(Sender: TObject); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.cbReceivedEnter') else _udebug := nil;{$ENDIF} if Trim(cbReceived.Text) = '' then cbReceived.DroppedDown := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmEditAtt.cbReceivedExit(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditAtt.cbReceivedExit') else _udebug := nil;{$ENDIF} cbReceived.SelStart := 0; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('EditAtt', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit UnitSipka; interface uses Classes, Vcl.Controls, Vcl.Graphics; type TDruhTvaru = (tvSipkaDole, tvSipkaHore, tvSipkaDolava, tvSipkaDoprava); TSipka = class(TGraphicControl) private FPen: TPen; FBrush: TBrush; FDruhTvaru: TDruhTvaru; procedure SetBrush(Value: TBrush); procedure SetPen(Value: TPen); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Canvas; published property Brush: TBrush read FBrush write SetBrush; property Pen: TPen read FPen write SetPen; property DruhTvaru: TDruhTvaru read FDruhTvaru write FDruhTvaru; end; procedure Register; implementation uses Types; constructor TSipka.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FPen := TPen.Create; FBrush := TBrush.Create; Pen.Width := 1; Pen.Color := clBlack; FDruhTvaru := tvSipkaDoprava; Invalidate; end; destructor TSipka.Destroy; begin FPen.Free; FBrush.Free; inherited Destroy; end; procedure TSipka.SetBrush(Value: TBrush); begin FBrush.Assign(Value); Invalidate; end; procedure TSipka.SetPen(Value: TPen); begin FPen.Assign(Value); Invalidate; end; procedure TSipka.Paint; var P1, P2, P3, P4, P5, P6, P7: TPoint; begin case FDruhTvaru of tvSipkaDoprava: with Canvas do begin Pen := FPen; Brush := FBrush; P1 :=Point(Pen.Width div 2, height div 4); P2 :=Point(width*3 div 4, P1.Y); P3 :=Point(P2.X, P1.X); P4 :=Point(width - Pen.Width, height div 2); P5 :=Point(P2.X, height - P1.X); P6 :=Point(P2.X, height*3 div 4); P7 :=Point(P1.X, P6.Y); Polygon([P1, P2, P3, P4, P5, P6, P7]); end; tvSipkaDolava: with Canvas do begin Pen := FPen; Brush := FBrush; P1 :=Point(Pen.Width div 2, Height div 2); P2 :=Point(Width div 4, P1.X); P3 :=Point(P2.X, Height div 4); P4 :=Point(width - Pen.Width, P3.Y); P5 :=Point(P4.X, height*3 div 4); P6 :=Point(P2.X, P5.Y); P7 :=Point(P2.X, Height - P1.X); Polygon([P1, P2, P3, P4, P5, P6, P7]); end; tvSipkaHore: with Canvas do begin Pen := FPen; Brush := FBrush; P1 :=Point(width div 4, height - pen.width); P2 :=Point(width div 4, height div 4); P3 :=Point(pen.width div 2, height div 4); P4 :=Point(width div 2, pen.width); P5 :=Point(width - pen.width div 2, height div 4); P6 :=Point(width*3 div 4, height div 4); P7 :=Point(width*3 div 4, height - pen.width); Polygon([P1, P2, P3, P4, P5, P6, P7]); end; tvSipkaDole: with Canvas do begin Pen := FPen; Brush := FBrush; P1 :=Point(width*3 div 4, pen.width); P2 :=Point(width*3 div 4, height*3 div 4); P3 :=Point(width - pen.width div 2, height*3 div 4); P4 :=Point(width div 2,height - pen.width); P5 :=Point(pen.width div 2, height*3 div 4); P6 :=Point(width div 4, height*3 div 4); P7 :=Point(width div 4, pen.width); Polygon([P1, P2, P3, P4, P5, P6, P7]); end; end; end; procedure Register; begin RegisterComponents('Pokus', [TSipka]); end; end.
{ Subroutine SST_W_C_DECLARE (DECL) * * Write the implicit declaration indicated by DECL. DECL must be one of the * constants of name DECL_xxx_K. } module sst_w_c_DECLARE; define sst_w_c_declare; %include 'sst_w_c.ins.pas'; procedure sst_w_c_declare ( {write out one of the implicit declarations} in decl: decl_k_t); {selects which implicit declaration to write} const max_msg_parms = 1; {max parameters we can pass to a message} var msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if decl in decl_done then return; {this declaration already written before ?} case decl of {which declaration is being requested ?} decl_nil_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define nil 0'(0)); end; decl_true_k: begin sst_w_c_pos_push (sment_type_declg_k); if sst_config.os = sys_os_domain_k then begin {OS is Aegis, we need to talk to Pascal} sst_w.appends^ ('#define true 255'(0)); end else begin {OS is not Aegis, use native C TRUE value} sst_w.appends^ ('#define true 1'(0)); end ; end; decl_false_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define false 0'(0)); end; decl_nullset_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define nullset 0'(0)); end; decl_unspec_int_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_int 0'(0)); end; decl_unspec_enum_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_enum 0'(0)); end; decl_unspec_float_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_float 0.0'(0)); end; decl_unspec_bool_k: begin sst_w_c_declare (decl_false_k); sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_bool false'(0)); end; decl_unspec_char_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_char 0'(0)); end; decl_unspec_set_k: begin sst_w_c_declare (decl_nullset_k); sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_set nullset'(0)); end; decl_unspec_pnt_k: begin sst_w_c_declare (decl_nil_k); sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#define unspec_pnt nil'(0)); end; decl_stdlib_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#include <stdlib.h>'(0)); end; decl_stddef_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#include <stddef.h>'(0)); end; decl_stdio_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#include <stdio.h>'(0)); end; decl_string_k: begin sst_w_c_declare (decl_stddef_k); {STTDEF must come before STRING} sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#include <string.h>'(0)); end; decl_math_k: begin sst_w_c_pos_push (sment_type_declg_k); sst_w.appends^ ('#include <math.h>'(0)); end; otherwise sys_msg_parm_int (msg_parm[1], ord(decl)); sys_message_bomb ('sst_c_write', 'const_implicit_bad', msg_parm, 1); end; sst_w.line_close^; sst_w_c_pos_pop; decl_done := decl_done + [decl]; {flag this particular constant as written} end;
unit cAcaoAcesso; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils, Vcl.Forms, Vcl.Buttons; type TAcaoAcesso = class private ConexaoDB: TFDConnection; F_cod_acao_acesso: Integer; F_descricao: string; F_chave: string; class procedure PreencherAcoes(aForm: TForm; aConexao: TFDConnection); static; class procedure VerificarUsuarioAcao(aUsuarioId, aAcaoAcessoId: Integer; aConexao: TFDConnection); static; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; function ChaveExiste(aChave: String; aID: Integer = 0): Boolean; class procedure CriarAcoes(aNomeForm: TFormClass; aConexao: TFDConnection); static; class procedure PreencherUsuariosVsAcoes(aConexao: TFDConnection); static; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property cod_acao_acesso: Integer read F_cod_acao_acesso write F_cod_acao_acesso; property descricao: string read F_descricao write F_descricao; property chave: string read F_chave write F_chave; end; implementation { TAcaoAcesso } function TAcaoAcesso.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_cod_acao_acesso) + #13 + 'Descrição: ' + F_descricao, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add ('DELETE FROM tb_acao_acesso WHERE cod_acao_acesso=:cod_acao_acesso'); Qry.ParamByName('cod_acao_acesso').AsInteger := F_cod_acao_acesso; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result := false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TAcaoAcesso.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE tb_acao_acesso ' + ' SET descricao=:descricao, chave=:chave ' + ' WHERE cod_acao_acesso=:cod_acao_acesso'); Qry.ParamByName('cod_acao_acesso').AsInteger := self.F_cod_acao_acesso; Qry.ParamByName('descricao').AsString := self.F_descricao; Qry.ParamByName('chave').AsString := self.F_chave; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TAcaoAcesso.ChaveExiste(aChave: String; aID: Integer): Boolean; var Qry: TFDQuery; begin try Result := false; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add ('select count(cod_acao_acesso) as QTD from tb_acao_acesso where chave =:chave '); if aID > 0 then begin Qry.SQL.Add(' AND cod_acao_acesso<>:cod_acao_acesso'); Qry.ParamByName('cod_acao_acesso').AsInteger := aID; end; Qry.ParamByName('chave').AsString := aChave; try Qry.Open; if Qry.FieldByName('QTD').AsInteger > 0 then Result := True else Result := false; except Result := false; end; finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry) end; end; constructor TAcaoAcesso.Create(aConexao: TFDConnection); begin ConexaoDB := aConexao; end; destructor TAcaoAcesso.Destroy; begin inherited; end; function TAcaoAcesso.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tb_acao_acesso ' + ' (descricao, chave) ' + ' VALUES(:descricao, :chave)'); Qry.ParamByName('descricao').AsString := self.F_descricao; Qry.ParamByName('chave').AsString := self.F_chave; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; class procedure TAcaoAcesso.PreencherAcoes(aForm: TForm; aConexao: TFDConnection); var i: Integer; oAcaoAcesso: TAcaoAcesso; begin try oAcaoAcesso := TAcaoAcesso.Create(aConexao); oAcaoAcesso.descricao := aForm.Caption; oAcaoAcesso.chave := aForm.Name; if not oAcaoAcesso.ChaveExiste(oAcaoAcesso.chave) then oAcaoAcesso.Inserir; for i := 0 to aForm.ComponentCount - 1 do begin if (aForm.Components[i].Tag = 99) then begin oAcaoAcesso.descricao := ' - BOTÃO ' + StringReplace(TBitBtn(aForm.Components[i]).Caption, '&', '', [rfReplaceAll]); oAcaoAcesso.chave := aForm.Name + '_' + TBitBtn(aForm.Components[i]).Name; if not oAcaoAcesso.ChaveExiste(oAcaoAcesso.chave) then oAcaoAcesso.Inserir; end; end; finally if Assigned(oAcaoAcesso) then FreeAndNil(oAcaoAcesso); end; end; class procedure TAcaoAcesso.CriarAcoes(aNomeForm: TFormClass; aConexao: TFDConnection); var form: TForm; begin try form := aNomeForm.Create(Application); PreencherAcoes(form, aConexao); finally if Assigned(form) then form.Release; end; end; function TAcaoAcesso.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT cod_acao_acesso, descricao, chave ' + ' FROM tb_acao_acesso where cod_acao_acesso=:cod_acao_acesso '); Qry.ParamByName('cod_acao_acesso').AsInteger := id; try Qry.Open; self.F_cod_acao_acesso := Qry.FieldByName('cod_acao_acesso').AsInteger; self.F_descricao := Qry.FieldByName('descricao').AsString; self.F_chave := Qry.FieldByName('chave').AsString; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; class procedure TAcaoAcesso.VerificarUsuarioAcao(aUsuarioId, aAcaoAcessoId: Integer; aConexao: TFDConnection); var Qry: TFDQuery; begin try Qry := TFDQuery.Create(nil); Qry.Connection := aConexao; Qry.SQL.Clear; Qry.SQL.Add('SELECT cod_usuario ' + ' FROM tb_usuarios_acao_acesso ' + ' WHERE cod_usuario=:cod_usuario ' + ' AND cod_acao_acesso=:cod_acao_acesso '); Qry.ParamByName('cod_usuario').AsInteger := aUsuarioId; Qry.ParamByName('cod_acao_acesso').AsInteger := aAcaoAcessoId; Qry.Open; if Qry.IsEmpty then begin Qry.Close; Qry.SQL.Clear; Qry.SQL.Add ('INSERT INTO tb_usuarios_acao_acesso (cod_usuario, cod_acao_acesso, ativo) ' + ' VALUES (:cod_usuario, :cod_acao_acesso, :ativo) '); Qry.ParamByName('cod_usuario').AsInteger := aUsuarioId; Qry.ParamByName('cod_acao_acesso').AsInteger := aAcaoAcessoId; Qry.ParamByName('ativo').AsBoolean := True; Try aConexao.StartTransaction; Qry.ExecSQL; aConexao.Commit; Except aConexao.Rollback; End; end; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; class procedure TAcaoAcesso.PreencherUsuariosVsAcoes(aConexao: TFDConnection); var Qry: TFDQuery; QryAcaoAcesso: TFDQuery; begin try Qry := TFDQuery.Create(nil); Qry.Connection := aConexao; Qry.SQL.Clear; QryAcaoAcesso := TFDQuery.Create(nil); QryAcaoAcesso.Connection := aConexao; QryAcaoAcesso.SQL.Clear; Qry.SQL.Add('select codigo from tb_usuario '); Qry.Open; QryAcaoAcesso.SQL.Add('select cod_acao_acesso from tb_acao_acesso '); QryAcaoAcesso.Open; Qry.First; while not Qry.Eof do begin QryAcaoAcesso.First; while not QryAcaoAcesso.Eof do begin VerificarUsuarioAcao(Qry.FieldByName('codigo').AsInteger, QryAcaoAcesso.FieldByName('cod_acao_acesso').AsInteger, aConexao); QryAcaoAcesso.Next; end; Qry.Next; end; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; end.
unit Acme.Robot.Core.CleanBot; interface uses System.Rtti, System.SysUtils, Acme.Robot.Core.Bot, Acme.Robot.Core.Communications; function NewCleanBot(const AName: string; ACommunicator: ICommunicator): ITalkingBot; implementation resourcestring StrDone = 'Done.'; StrTurningOff = 'I am turning off.'; StrTurnedOn = 'Ready for new jobs!'; StrMoving = 'Moving %d steps going %s.'; type TCleanBot = class(TBot, ITalkingBot) private FCommunicator: ICommunicator; function HasCommunicator: Boolean; protected procedure AfterMoving(ASteps: Integer); override; procedure AfterTurningOn; override; procedure BeforeMoving(ASteps: Integer); override; procedure BeforeTurningOff; override; public procedure Express(AMood: TBotMood); procedure Say(const AText: string); property Communicator: ICommunicator read FCommunicator write FCommunicator; end; procedure TCleanBot.AfterMoving(ASteps: Integer); begin inherited; Say(StrDone); end; procedure TCleanBot.AfterTurningOn; begin inherited; Express(TBotMood.Happy); Say(StrTurnedOn); end; procedure TCleanBot.BeforeMoving(ASteps: Integer); begin inherited; Say(Format(StrMoving, [ASteps, TRttiEnumerationType.GetName(GetOrientation)])); end; procedure TCleanBot.BeforeTurningOff; begin inherited; Express(TBotMood.Grumpy); Say(StrTurningOff); end; procedure TCleanBot.Express(AMood: TBotMood); var LEnhancedCommunicator: IEnhancedCommunicator; begin if not HasCommunicator then Exit; if Supports(FCommunicator, IEnhancedCommunicator, LEnhancedCommunicator) then LEnhancedCommunicator.ShowMood(AMood); end; function TCleanBot.HasCommunicator: Boolean; begin Result := FCommunicator <> nil; end; procedure TCleanBot.Say(const AText: string); begin if not HasCommunicator then Exit; FCommunicator.SayMessage(AText); end; function NewCleanBot(const AName: string; ACommunicator: ICommunicator): ITalkingBot; var LBot: TCleanBot; begin LBot := TCleanBot.Create(AName); LBot.Communicator := ACommunicator; Result := LBot; end; end.
unit System.Console; interface type TConsole = class public function ReadKey: Word; end; implementation {$IFDEF MSWINDOWS} uses Winapi.Windows; function IsSystemKey(VirtualKeyCode: Word): Boolean; begin Result:=VirtualKeyCode in [VK_LWIN,VK_RWIN,VK_APPS,VK_SHIFT,VK_CONTROL,VK_MENU]; end; function IsValidInputKeyEvent(const InputRecord: TInputRecord): Boolean; begin Result:=(InputRecord.EventType=KEY_EVENT) and InputRecord.Event.KeyEvent.bKeyDown and not IsSystemKey(InputRecord.Event.KeyEvent.wVirtualKeyCode); end; function TConsole.ReadKey: Word; var InputHandle: THandle; InputRecord: TInputRecord; Event: Cardinal; begin Result:=0; InputHandle:=GetStdHandle(STD_INPUT_HANDLE); while ReadConsoleInput(InputHandle,InputRecord,1,Event) do if IsValidInputKeyEvent(InputRecord) then Exit(InputRecord.Event.KeyEvent.wVirtualKeyCode); end; {$ENDIF} {$IFDEF LINUX} function TConsole.ReadKey: Word; begin Result:=0; end; {$ENDIF} end.
unit AppHandler; interface uses VoyagerInterfaces, Forms, Controls; type TAppHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler ) public constructor Create( anAppWindow : TForm ); private fAppWindow : TForm; // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; end; const tidMetaHandlerName_App = 'AppHandler'; const htmlAction_Close = 'CLOSE'; const evnCanClose = 20; implementation uses URLParser; constructor TAppHandler.Create( anAppWindow : TForm ); begin inherited Create; fAppWindow := anAppWindow; end; function TAppHandler.getName : string; begin result := tidMetaHandlerName_App; end; function TAppHandler.getOptions : TURLHandlerOptions; begin result := [hopNonVisual]; end; function TAppHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TAppHandler.Instantiate : IURLHandler; begin result := self; end; function TAppHandler.HandleURL( URL : TURL ) : TURLHandlingResult; var Action : string; cancel : boolean; begin Action := URLParser.GetURLAction( URL ); if Action = htmlAction_Close then begin cancel := false; fMasterURLHandler.HandleEvent( evnCanClose, cancel ); if not cancel then fAppWindow.Close; result := urlHandled; end else result := urlNotHandled; end; function TAppHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; begin result := evnNotHandled; end; function TAppHandler.getControl : TControl; begin result := nil; end; procedure TAppHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; end; end.
unit UNetProtocolVersion; interface { Net Protocol: 3 different types: Request,Response or Auto-send Request: <Magic Net Identification (4b)><request (2b)><operation (2b)><0x0000 (2b)><request_id(4b)><protocol info(4b)><data_length(4b)><request_data (data_length bytes)> Response: <Magic Net Identification (4b)><response (2b)><operation (2b)><error_code (2b)><request_id(4b)><protocol info(4b)><data_length(4b)><response_data (data_length bytes)> Auto-send: <Magic Net Identification (4b)><autosend (2b)><operation (2b)><0x0000 (2b)><0x00000000 (4b)><protocol info(4b)><data_length(4b)><data (data_length bytes)> Min size: 4b+2b+2b+2b+4b+4b+4b = 22 bytes Max size: (depends on last 4 bytes) = 22..(2^32)-1 } type TNetProtocolVersion = Record protocol_version, protocol_available : Word; end; implementation end.
unit uGeral; interface uses uDM, System.SysUtils, 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; type TGeral = class private public function ProximoId(Tabela: string): Integer; function ProximoCodigo(Tabela, Campo: string): Integer; end; implementation { TGeral } function TGeral.ProximoCodigo(Tabela, Campo: string): Integer; var lQry: TFDQuery; begin lQry := TFDQuery.Create(Nil); try lQry.Connection := DM.Conexao; lQry.SQL.CommaText := 'SELECT MAX(' + Campo + ') FROM ' + Tabela; lQry.Open(); Result := lQry.Fields[0].AsInteger + 1; finally FreeAndNil(lQry); end; end; function TGeral.ProximoId(Tabela: string): Integer; var lQry: TFDQuery; begin lQry := TFDQuery.Create(Nil); try lQry.Connection := DM.Conexao; lQry.SQL.Text := 'SELECT IDENT_CURRENT(' + QuotedStr(Tabela) + ')'; lQry.Open(); Result := lQry.Fields[0].AsInteger + 1; finally FreeAndNil(lQry); end; end; end.
unit View.LancamentosExtratos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, cxTextEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxMaskEdit, cxDropDownEdit, cxCalendar, cxButtonEdit, cxCalc, cxCheckBox, cxSpinEdit, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons, System.Actions, Vcl.ActnList, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Common.ENum, Control.EntregadoresExpressas, Control.Lancamentos; type Tview_LancamentosExtratosExpressas = class(TForm) layoutControlPadraoGroup_Root: TdxLayoutGroup; layoutControlPadrao: TdxLayoutControl; labelTitle: TcxLabel; layoutItemLabelTitle: TdxLayoutItem; layoutGroupLancamento: TdxLayoutGroup; textEditDescricao: TcxTextEdit; layoutItemDescricao: TdxLayoutItem; dateEditData: TcxDateEdit; layoutItemData: TdxLayoutItem; buttonEditCodigoEntregador: TcxButtonEdit; layoutItemCodigoEntregador: TdxLayoutItem; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; textEditNomeEntregador: TcxTextEdit; layoutItemNomeEntregador: TdxLayoutItem; comboBoxTipo: TcxComboBox; layoutItemTipoLancamento: TdxLayoutItem; dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup; calcEditValor: TcxCalcEdit; layoutItemValor: TdxLayoutItem; layoutGroupHistorico: TdxLayoutGroup; checkBoxProcessado: TcxCheckBox; layoutItemProcessado: TdxLayoutItem; maskEditDataProcessamento: TcxMaskEdit; layoutItemDataProcessamento: TdxLayoutItem; textEditExtrato: TcxTextEdit; layoutItemExtrato: TdxLayoutItem; maskEditDataCadastro: TcxMaskEdit; layoutItemDataCadastro: TdxLayoutItem; buttonEditReferencia: TcxButtonEdit; layoutItemReferencia: TdxLayoutItem; TextEditUsuario: TcxTextEdit; layoutItemUsuario: TdxLayoutItem; layoutGroupParcelamento: TdxLayoutGroup; spinEditIntervaloDias: TcxSpinEdit; layoutItemIntervalo: TdxLayoutItem; dxLayoutAutoCreatedGroup3: TdxLayoutAutoCreatedGroup; dateEditDataInicial: TcxDateEdit; layoutItemDataInicial: TdxLayoutItem; buttonProcessar: TcxButton; layoutItemProcessar: TdxLayoutItem; actionListLancamentos: TActionList; actionNovo: TAction; actionEditar: TAction; actionCancelar: TAction; actionExcluir: TAction; actionGravar: TAction; actionLocalizar: TAction; actionFechar: TAction; actionProcessar: TAction; gridParcelamentoDBTableView1: TcxGridDBTableView; gridParcelamentoLevel1: TcxGridLevel; gridParcelamento: TcxGrid; layoutItemGridParcelamento: TdxLayoutItem; memTableParcelamento: TFDMemTable; memTableParcelamentonum_parcela: TIntegerField; memTableParcelamentodat_parcela: TDateField; memTableParcelamentoval_parcela: TCurrencyField; fdParcelamentos: TDataSource; gridParcelamentoDBTableView1num_parcela: TcxGridDBColumn; gridParcelamentoDBTableView1dat_parcela: TcxGridDBColumn; gridParcelamentoDBTableView1val_parcela: TcxGridDBColumn; comboBoxProcessamento: TcxComboBox; layoutItemProcessamento: TdxLayoutItem; actionReferencia: TAction; layoutGroupOpcoes: TdxLayoutGroup; buttonNovo: TcxButton; layoutItemNovo: TdxLayoutItem; buttonEditar: TcxButton; layoutItemEditar: TdxLayoutItem; buttonCancelar: TcxButton; layoutItemCancelar: TdxLayoutItem; buttonExcluir: TcxButton; layoutItemExcluir: TdxLayoutItem; buttonLocalizar: TcxButton; layoutItemLocalizar: TdxLayoutItem; buttonGravar: TcxButton; layoutItemGravar: TdxLayoutItem; buttonFechar: TcxButton; layoutItemFechar: TdxLayoutItem; actionPesquisaEntregadores: TAction; spinEditParcelas: TcxSpinEdit; layoutItemParcelas: TdxLayoutItem; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actionEditarExecute(Sender: TObject); procedure actionExcluirExecute(Sender: TObject); procedure actionNovoExecute(Sender: TObject); procedure actionCancelarExecute(Sender: TObject); procedure actionFecharExecute(Sender: TObject); procedure actionLocalizarExecute(Sender: TObject); procedure buttonEditCodigoEntregadorPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure comboBoxTipoPropertiesChange(Sender: TObject); procedure calcEditValorPropertiesChange(Sender: TObject); procedure comboBoxProcessamentoPropertiesChange(Sender: TObject); procedure actionProcessarExecute(Sender: TObject); procedure actionPesquisaEntregadoresExecute(Sender: TObject); private { Private declarations } procedure Modo; procedure LimpaCampos; procedure PesquisaEntregadores; procedure PesquisaLancamentos; procedure ProcessaParcelamento; procedure SetupForm(iID: integer); procedure SetupClass; function VerificaProcesso(): Boolean; function RetornaNomeEntregador(iCodigo: integer): String; public { Public declarations } end; var view_LancamentosExtratosExpressas: Tview_LancamentosExtratosExpressas; lancamentos : TLancamentosControl; FAcao : TAcao; iCadastro: Integer; iID: Integer; implementation {$R *.dfm} uses Data.SisGeF, View.PesquisarPessoas; procedure Tview_LancamentosExtratosExpressas.actionCancelarExecute(Sender: TObject); begin Facao := tacIndefinido; LimpaCampos; Modo; end; procedure Tview_LancamentosExtratosExpressas.actionEditarExecute(Sender: TObject); begin if not VerificaProcesso() then begin Application.MessageBox('Lançamento já processado (Descontato ou creditado). A edição não é permitida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; FAcao := tacAlterar; Modo; end; procedure Tview_LancamentosExtratosExpressas.actionExcluirExecute(Sender: TObject); begin if not VerificaProcesso() then begin Application.MessageBox('Lançamento já processado (Descontato ou creditado). A exclusão não é permitida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; end; procedure Tview_LancamentosExtratosExpressas.actionFecharExecute(Sender: TObject); begin Close; end; procedure Tview_LancamentosExtratosExpressas.actionLocalizarExecute(Sender: TObject); begin PesquisaLancamentos; end; procedure Tview_LancamentosExtratosExpressas.actionNovoExecute(Sender: TObject); begin FAcao := tacIncluir; LimpaCampos; Modo; textEditDescricao.SetFocus; end; procedure Tview_LancamentosExtratosExpressas.actionPesquisaEntregadoresExecute(Sender: TObject); begin PesquisaEntregadores; end; procedure Tview_LancamentosExtratosExpressas.actionProcessarExecute(Sender: TObject); begin ProcessaParcelamento; end; procedure Tview_LancamentosExtratosExpressas.buttonEditCodigoEntregadorPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin if (FAcao <> tacIncluir) and (FAcao <> tacAlterar) then begin Exit end; textEditNomeEntregador.Text := RetornaNomeEntregador(buttonEditCodigoEntregador.EditValue); end; procedure Tview_LancamentosExtratosExpressas.calcEditValorPropertiesChange(Sender: TObject); begin if comboBoxTipo.ItemIndex = 2 then begin calcEditValor.Value := 0 - calcEditValor.Value; calcEditValor.Style.Font.Color := clRed; end else begin calcEditValor.Style.Font.Color := clNone; end; end; procedure Tview_LancamentosExtratosExpressas.comboBoxProcessamentoPropertiesChange(Sender: TObject); begin if FAcao = tacIncluir then begin if comboBoxProcessamento.ItemIndex >= 2 then begin dateEditDataInicial.Date := dateEditData.Date; layoutGroupParcelamento.Visible := True; end else begin layoutGroupParcelamento.Visible := False; end; end; end; procedure Tview_LancamentosExtratosExpressas.comboBoxTipoPropertiesChange(Sender: TObject); begin if comboBoxTipo.ItemIndex = 2 then begin comboBoxTipo.Style.Font.Color := clRed; end else begin comboBoxTipo.Style.Font.Color := clNone; end; end; procedure Tview_LancamentosExtratosExpressas.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; view_LancamentosExtratos := nil; end; procedure Tview_LancamentosExtratosExpressas.FormShow(Sender: TObject); begin labelTitle.Caption := Self.Caption; FAcao := tacIndefinido; LimpaCampos; Modo; end; procedure Tview_LancamentosExtratosExpressas.LimpaCampos; begin iID := 0; textEditDescricao.EditValue := ''; dateEditData.Clear; iCadastro := 0; buttonEditCodigoEntregador.EditValue := 0; comboBoxTipo.ItemIndex := 0; calcEditValor.Value := 0; spinEditIntervaloDias.Value := 15; dateEditDataInicial.Clear; if memTableParcelamento.Active then memTableParcelamento.Close; checkBoxProcessado.EditValue := 'N'; maskEditDataProcessamento.Clear; textEditExtrato.Clear; maskEditDataCadastro.Clear; buttonEditReferencia.EditValue := 0; TextEditUsuario.Clear; end; procedure Tview_LancamentosExtratosExpressas.Modo; begin if FAcao = tacIndefinido then begin actionNovo.Enabled := True; actionEditar.Enabled := False; actionLocalizar.Enabled := True; actionCancelar.Enabled := False; actionGravar.Enabled := False; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := False; textEditDescricao.Properties.ReadOnly := True; dateEditData.Properties.ReadOnly := True; buttonEditCodigoEntregador.Properties.ReadOnly := True; comboBoxTipo.Properties.ReadOnly := True; calcEditValor.Properties.ReadOnly := True; layoutItemProcessamento.Visible := False; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := False; layoutGroupHistorico.Visible := False; end else if FAcao = tacIncluir then begin actionNovo.Enabled := False; actionEditar.Enabled := False; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := True; textEditDescricao.Properties.ReadOnly := False; dateEditData.Properties.ReadOnly := False; buttonEditCodigoEntregador.Properties.ReadOnly := False; comboBoxTipo.Properties.ReadOnly := False; calcEditValor.Properties.ReadOnly := False; layoutItemProcessamento.Visible := True; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := False; end else if FAcao = tacAlterar then begin actionNovo.Enabled := False; actionEditar.Enabled := False; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := True; textEditDescricao.Properties.ReadOnly := False; dateEditData.Properties.ReadOnly := False; buttonEditCodigoEntregador.Properties.ReadOnly := False; comboBoxTipo.Properties.ReadOnly := False; calcEditValor.Properties.ReadOnly := False; layoutItemProcessamento.Visible := False; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := True; end else if FAcao = tacPesquisa then begin actionNovo.Enabled := False; actionEditar.Enabled := True; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionReferencia.Enabled := True; actionPesquisaEntregadores.Enabled := False; textEditDescricao.Properties.ReadOnly := False; dateEditData.Properties.ReadOnly := False; buttonEditCodigoEntregador.Properties.ReadOnly := False; comboBoxTipo.Properties.ReadOnly := False; calcEditValor.Properties.ReadOnly := False; layoutItemProcessamento.Visible := False; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := True; end; end; procedure Tview_LancamentosExtratosExpressas.PesquisaEntregadores; var sSQL: String; sWhere: String; aParam: array of variant; sQuery: String; entregadores : TEntregadoresExpressasControl; begin try sSQL := ''; sWhere := ''; entregadores := TEntregadoresExpressasControl.Create; if not Assigned(View_PesquisarPessoas) then begin View_PesquisarPessoas := TView_PesquisarPessoas.Create(Application); end; View_PesquisarPessoas.dxLayoutItem1.Visible := True; View_PesquisarPessoas.dxLayoutItem2.Visible := True; sSQL := 'select tbcodigosentregadores.cod_entregador as "Cód. Entregador", ' + 'tbcodigosentregadores.nom_fantasia as "Nome Entregador", tbcodigosentregadores.des_chave as "Cód. ERP", ' + 'tbcodigosentregadores.cod_cadastro as "Cód. Cadastro", tbentregadores.des_razao_social as "Nome Cadastro", ' + 'tbcodigosentregadores.cod_agente as "Cód. Agente" ' + 'from tbcodigosentregadores ' + 'inner join tbentregadores ' + 'on tbentregadores.cod_cadastro = tbcodigosentregadores.cod_cadastro '; sWhere := 'where tbcodigosentregadores.cod_entregador like paraN or tbcodigosentregadores.nom_fantasia like "%param%" or ' + 'tbcodigosentregadores.des_chave like "%param%" or tbcodigosentregadores.cod_cadastro like paraN or ' + 'tbentregadores.des_razao_social like "%param%" or ' + 'tbcodigosentregadores.cod_agente like paraN;'; View_PesquisarPessoas.sSQL := sSQL; View_PesquisarPessoas.sWhere := sWhere; View_PesquisarPessoas.bOpen := False; View_PesquisarPessoas.Caption := 'Localizar Entregadores'; if View_PesquisarPessoas.ShowModal = mrOK then begin buttonEditCodigoEntregador.EditValue := View_PesquisarPessoas.qryPesquisa.Fields[1].AsInteger; textEditNomeEntregador.Text := View_PesquisarPessoas.qryPesquisa.Fields[2].AsString; end; finally entregadores.Free; View_PesquisarPessoas.qryPesquisa.Close; View_PesquisarPessoas.tvPesquisa.ClearItems; FreeAndNil(View_PesquisarPessoas); end; end; procedure Tview_LancamentosExtratosExpressas.PesquisaLancamentos; var sSQL: String; sWhere: String; aParam: array of variant; sQuery: String; begin try sSQL := ''; sWhere := ''; lancamentos := TLancamentosControl.Create; if not Assigned(View_PesquisarPessoas) then begin View_PesquisarPessoas := TView_PesquisarPessoas.Create(Application); end; View_PesquisarPessoas.dxLayoutItem1.Visible := True; View_PesquisarPessoas.dxLayoutItem2.Visible := True; sSQL := 'select tblancamentos.cod_lancamento as ID,' + 'tblancamentos.cod_entregador as "Código", tbcodigosentregadores.nom_fantasia as Nome, ' + 'tblancamentos.des_lancamento as "Descrição", ' + 'format(if(tblancamentos.des_tipo = "CREDITO", tblancamentos.val_lancamento, 0), 2, "de_DE") as "Crédito", ' + 'format(if(tblancamentos.des_tipo = "DEBITO", 0 - tblancamentos.val_lancamento, 0), 2, "de_DE") as "Débito", ' + 'dom_desconto as Descontado ' + 'from tblancamentos ' + 'inner join tbcodigosentregadores ' + 'on tbcodigosentregadores.cod_entregador = tblancamentos.cod_entregador '; sWhere := 'where tblancamentos.cod_lancamento like paraN or ' + 'tblancamentos.cod_lancamento like paraN or ' + 'tbcodigosentregadores.nom_fantasia like "%param%" '; View_PesquisarPessoas.sSQL := sSQL; View_PesquisarPessoas.sWhere := sWhere; View_PesquisarPessoas.bOpen := False; View_PesquisarPessoas.Caption := 'Localizar Lançamentos'; if View_PesquisarPessoas.ShowModal = mrOK then begin lancamentos := TLancamentosControl.Create; SetLength(aParam,2); aParam := ['CODIGO', View_PesquisarPessoas.qryPesquisa.Fields[1].AsInteger]; if not lancamentos.Localizar(aParam).IsEmpty then begin LimpaCampos; iCadastro := lancamentos.Lancamentos.Codigo; textEditDescricao.Text := lancamentos.Lancamentos.Descricao; dateEditData.Date := lancamentos.Lancamentos.Data; iCadastro := lancamentos.Lancamentos.Cadastro; buttonEditCodigoEntregador.EditValue := lancamentos.Lancamentos.Entregador; if lancamentos.Lancamentos.Tipo = 'CREDITO' then begin comboBoxTipo.ItemIndex := 1; end else begin comboBoxTipo.ItemIndex := 2; end; textEditNomeEntregador.Text := RetornaNomeEntregador(lancamentos.Lancamentos.Entregador); calcEditValor.Value := lancamentos.Lancamentos.Valor; checkBoxProcessado.EditValue := lancamentos.Lancamentos.Desconto; maskEditDataProcessamento.EditText := FormatDateTime('dd/mm/yyyy hh:mm:ss', lancamentos.Lancamentos.DataDesconto); textEditExtrato.text := lancamentos.Lancamentos.Extrato; maskEditDataCadastro.EditText := FormatDateTime('dd/mm/yyyy hh:mm:ss', lancamentos.Lancamentos.DataCadastro); buttonEditReferencia.EditValue := lancamentos.Lancamentos.Referencia; TextEditUsuario.Text := lancamentos.Lancamentos.Usuario; Facao := tacPesquisa; Modo; end; end; finally View_PesquisarPessoas.qryPesquisa.Close; View_PesquisarPessoas.tvPesquisa.ClearItems; FreeAndNil(View_PesquisarPessoas); end; end; procedure Tview_LancamentosExtratosExpressas.ProcessaParcelamento; var dtData : TDate; i, iDias, iParcelas : integer; dValor : Double; begin if memTableParcelamento.Active then begin memTableParcelamento.Close; end; memTableParcelamento.Open; iParcelas := spinEditParcelas.Value; dValor := calcEditValor.Value / iParcelas; dtData := dateEditDataInicial.Date; iDias := spinEditIntervaloDias.Value; for i := 1 to iParcelas do begin memTableParcelamento.Insert; memTableParcelamentonum_parcela.AsInteger := i; memTableParcelamentodat_parcela.AsDateTime := dtData; memTableParcelamentoval_parcela.AsFloat := dValor; memTableParcelamento.Post; end; if not memTableParcelamento.IsEmpty then begin memTableParcelamento.First; end; end; function Tview_LancamentosExtratosExpressas.RetornaNomeEntregador(iCodigo: integer): String; var entregador : TEntregadoresExpressasControl; sRetorno: String; begin try Result := ''; sRetorno := ''; entregador := TEntregadoresExpressasControl.Create; if icodigo <> 0 then begin sRetorno := entregador.GetField('NOM_FANTASIA', 'COD_ENTREGADOR', iCodigo.ToString) end; if sRetorno.IsEmpty then begin sRetorno := 'NONE'; end; Result := sRetorno; finally entregador.free; end; end; procedure Tview_LancamentosExtratosExpressas.SetupClass; begin lancamentos := TLancamentosControl.Create; lancamentos.Lancamentos.Descricao := textEditDescricao.Text; lancamentos.Lancamentos.Data := dateEditData.Date; lancamentos.Lancamentos.Cadastro := 0; lancamentos.Lancamentos.Entregador := buttonEditCodigoEntregador.EditValue; if comboBoxTipo.ItemIndex = 1 then begin lancamentos.Lancamentos.Tipo := 'CREDITO'; end else begin lancamentos.Lancamentos.Tipo := 'DEBITO'; end; lancamentos.Lancamentos.Valor := calcEditValor.Value; if checkBoxProcessado.Checked then begin lancamentos.Lancamentos.Desconto := 'S'; lancamentos.Lancamentos.DataDesconto := StrToDate(maskEditDataProcessamento.EditText); lancamentos.Lancamentos.Extrato := textEditExtrato.Text; lancamentos.Lancamentos.Referencia := buttonEditReferencia.EditValue; end else begin lancamentos.Lancamentos.Desconto := 'N'; lancamentos.Lancamentos.DataDesconto := StrToDate('31/12/1899'); lancamentos.Lancamentos.Extrato := ''; end; lancamentos.Lancamentos.Persistir := 'N'; lancamentos.Lancamentos.Referencia := 0; if FAcao = tacIncluir then begin lancamentos.Lancamentos.DataCadastro := Now; end else begin lancamentos.Lancamentos.DataCadastro := StrToDate(maskEditDataCadastro.EditText); end; //lancamentos.Lancamentos.Usuario end; procedure Tview_LancamentosExtratosExpressas.SetupForm(iID: integer); var aParam: array of variant; begin lancamentos := TLancamentosControl.Create; SetLength(aParam,2); aParam := ['CODIGO', iID]; if not lancamentos.Localizar(aParam).IsEmpty then begin textEditDescricao.Text := lancamentos.Lancamentos.Descricao; dateEditData.Date := lancamentos.Lancamentos.Data; buttonEditCodigoEntregador.EditValue := lancamentos.Lancamentos.Entregador; textEditNomeEntregador.Text := RetornaNomeEntregador(lancamentos.Lancamentos.Entregador); if lancamentos.Lancamentos.Tipo = 'CREDITO' then begin comboBoxTipo.ItemIndex := 1; end else if lancamentos.Lancamentos.Tipo = 'DEBITO' then begin comboBoxTipo.ItemIndex := 2; end else begin comboBoxTipo.ItemIndex := 0; end; calcEditValor.EditValue := lancamentos.Lancamentos.Valor; if lancamentos.Lancamentos.Desconto = 'S' then begin checkBoxProcessado.Checked := True; end else begin checkBoxProcessado.Checked := False; end; maskEditDataProcessamento.Text := FormatDateTime('dd/mm/yyyy', lancamentos.Lancamentos.DataDesconto); textEditExtrato.Text := lancamentos.Lancamentos.Extrato; maskEditDataCadastro.Text := FormatDateTime('dd/mm/yyyy', lancamentos.Lancamentos.DataCadastro); buttonEditReferencia.Text := lancamentos.Lancamentos.Codigo.ToString; end; end; function Tview_LancamentosExtratosExpressas.VerificaProcesso: Boolean; begin Result := False; if checkBoxProcessado.EditValue = 'S' then begin Exit; end; Result := True; end; end.
unit nscSimpleEditor; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Nemesis$Tails" // Модуль: "w:/common/components/gui/Garant/Nemesis/nscSimpleEditor.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<GuiControl::Class>> Shared Delphi::Nemesis$Tails::Editors::TnscSimpleEditor // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Nemesis\nscDefine.inc} interface uses evCustomMemo, Classes, nevBase, evEditorWithOperations ; type TBreakingParaEvent = procedure (aSender: TObject; out aHandled: Boolean) of object; //#UC START# *4CFF6CF60266ci* //#UC END# *4CFF6CF60266ci* TnscSimpleEditor = class(TevCustomMemo) private // private fields f_OnBreakingPara : TBreakingParaEvent; protected // overridden protected methods function AllowDrawDocumentEdge: Boolean; override; function DoBreakPara(aDrawLines: Boolean; const anOp: InevOp): Boolean; override; function DefineProvideOperations: TevEditorProvideOperationTypes; override; {* Какие операции публикуются компонентом. } function SelectWhenUnfocused: Boolean; override; public // overridden public methods constructor Create(AOwner: TComponent); override; //#UC START# *4CFF6CF60266publ* published property Align; property TabOrder; property TextSource; property IsStaticText; property ScrollStyle;// default ssNone; property OnGetHotSpotInfo; property OnJumpTo; property OnMouseAction; property Visible; property AutoHeightByText default True; property OnBreakingPara: TBreakingParaEvent read f_OnBreakingPara write f_OnBreakingPara; property AutoHideSelection default True; property AfterAdjustHeight; //#UC END# *4CFF6CF60266publ* end;//TnscSimpleEditor implementation uses StdCtrls ; // start class TnscSimpleEditor constructor TnscSimpleEditor.Create(AOwner: TComponent); //#UC START# *47D1602000C6_4CFF6CF60266_var* //#UC END# *47D1602000C6_4CFF6CF60266_var* begin //#UC START# *47D1602000C6_4CFF6CF60266_impl* inherited; ParentFont := False; AutoHeightByText := True; AutoHideSelection := True; PlainText := False; KeepAllFormatting := True; ScrollStyle := ssNone; //#UC END# *47D1602000C6_4CFF6CF60266_impl* end;//TnscSimpleEditor.Create function TnscSimpleEditor.AllowDrawDocumentEdge: Boolean; //#UC START# *482BFBEE00D5_4CFF6CF60266_var* //#UC END# *482BFBEE00D5_4CFF6CF60266_var* begin //#UC START# *482BFBEE00D5_4CFF6CF60266_impl* Result := False; //#UC END# *482BFBEE00D5_4CFF6CF60266_impl* end;//TnscSimpleEditor.AllowDrawDocumentEdge function TnscSimpleEditor.DoBreakPara(aDrawLines: Boolean; const anOp: InevOp): Boolean; //#UC START# *482BFCBF01F0_4CFF6CF60266_var* //#UC END# *482BFCBF01F0_4CFF6CF60266_var* begin //#UC START# *482BFCBF01F0_4CFF6CF60266_impl* if Assigned(f_OnBreakingPara) then begin f_OnBreakingPara(Self, Result); if Result then Exit; end; Result := inherited DoBreakPara(aDrawLines,anOp); //#UC END# *482BFCBF01F0_4CFF6CF60266_impl* end;//TnscSimpleEditor.DoBreakPara function TnscSimpleEditor.DefineProvideOperations: TevEditorProvideOperationTypes; //#UC START# *48735C4A03C3_4CFF6CF60266_var* //#UC END# *48735C4A03C3_4CFF6CF60266_var* begin //#UC START# *48735C4A03C3_4CFF6CF60266_impl* Result := []; //#UC END# *48735C4A03C3_4CFF6CF60266_impl* end;//TnscSimpleEditor.DefineProvideOperations function TnscSimpleEditor.SelectWhenUnfocused: Boolean; //#UC START# *48E22AD302CE_4CFF6CF60266_var* //#UC END# *48E22AD302CE_4CFF6CF60266_var* begin //#UC START# *48E22AD302CE_4CFF6CF60266_impl* Result := True; //#UC END# *48E22AD302CE_4CFF6CF60266_impl* end;//TnscSimpleEditor.SelectWhenUnfocused //#UC START# *4CFF6CF60266impl* //#UC END# *4CFF6CF60266impl* end.
{ 2020/05/11 5.01 Move tests from unit flcTests into seperate units. } {$INCLUDE flcTCPTest.inc} unit flcTCPTest_Buffer; interface { } { Test } { } {$IFDEF TCP_TEST} procedure Test; {$ENDIF} implementation {$IFDEF TCP_TEST} uses flcStdTypes, flcTCPBuffer; {$ENDIF} { } { Test } { } {$IFDEF TCP_TEST} {$ASSERTIONS ON} procedure Test_Buffer; var A : TTCPBuffer; B : Byte; S : RawByteString; I, L : Integer; begin TCPBufferInitialise(A, 1500, 1000); Assert(TCPBufferUsed(A) = 0); Assert(TCPBufferAvailable(A) = 1500); TCPBufferSetMaxSize(A, 2000); Assert(TCPBufferAvailable(A) = 2000); S := 'Fundamentals'; L := Length(S); TCPBufferAddBuf(A, S[1], L); Assert(TCPBufferUsed(A) = L); Assert(not TCPBufferEmpty(A)); S := ''; for I := 1 to L do S := S + 'X'; Assert(S = 'XXXXXXXXXXXX'); TCPBufferPeek(A, S[1], 3); Assert(S = 'FunXXXXXXXXX'); Assert(TCPBufferPeekByte(A, B)); Assert(B = Ord('F')); S := ''; for I := 1 to L do S := S + #0; TCPBufferRemove(A, S[1], L); Assert(S = 'Fundamentals'); Assert(TCPBufferUsed(A) = 0); S := 'X'; for I := 1 to 2001 do begin S[1] := ByteChar(I mod 256); TCPBufferAddBuf(A, S[1], 1); Assert(TCPBufferUsed(A) = I); Assert(TCPBufferAvailable(A) = 2000 - I); end; for I := 1 to 2001 do begin S[1] := 'X'; TCPBufferRemove(A, S[1], 1); Assert(S[1] = ByteChar(I mod 256)); Assert(TCPBufferUsed(A) = 2001 - I); end; Assert(TCPBufferEmpty(A)); TCPBufferShrink(A); Assert(TCPBufferEmpty(A)); TCPBufferFinalise(A); end; procedure Test; begin Test_Buffer; end; {$ENDIF} end.
unit fTransparentForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, AppEvnts; type TfrmTransparent = class(TForm) Panel1: TPanel; ApplicationEvents1: TApplicationEvents; procedure FormCreate(Sender: TObject); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure FormDestroy(Sender: TObject); protected procedure CreateParams(var Params: TCreateParams); override; procedure RestoreCursor; public procedure UpdateCursor; end; var frmTransparent: TfrmTransparent; implementation uses fMainWithBmp; {$R *.dfm} var iconInfo: TIconInfo; horgcursor: HCURSOR; hmycursor: HCURSOR; const crMyCursor = 1; procedure TfrmTransparent.FormCreate(Sender: TObject); begin { Next five properties can also be set at design-time } Borderstyle := bsNone; // AlphaBlend := true; // AlphaBlendvalue := 1; // Color := clBlack; Formstyle := fsStayOnTop; Boundsrect := Screen.DesktopRect; horgcursor := Screen.Cursors[crDefault]; UpdateCursor; end; procedure TfrmTransparent.FormDestroy(Sender: TObject); begin RestoreCursor; end; procedure TfrmTransparent.RestoreCursor; begin Screen.Cursors[crDefault] := horgcursor; DestroyIcon(hmycursor); Screen.Cursor := crDefault; end; procedure TfrmTransparent.UpdateCursor; var bmpMask : TBitmap; bmpColor: TBitmap; icentre: Integer; iminus, iplus: integer; begin if hmycursor <> 0 then begin Screen.Cursors[crDefault] := horgcursor; DestroyIcon(hmycursor); end; bmpMask := TBitmap.Create; bmpColor := TBitmap.Create; try icentre := 30 div 2; iminus := frmMainBmp.btnPenSize.Tag div 2; iplus := frmMainBmp.btnPenSize.Tag - iminus + 1; bmpMask.Monochrome := True; bmpMask.Height := 30; bmpMask.Width := 30; bmpMask.Canvas.Brush.Color := clWhite; //white = 1 bmpMask.Canvas.FillRect( Rect(0, 0, bmpMask.Width, bmpMask.Height) ); bmpMask.Canvas.Brush.Color := clBlack; //black = 0 bmpMask.Canvas.Ellipse(icentre - iminus, icentre - iminus, icentre + iplus, icentre + iplus); //bmpMask.SaveToFile('cursormask.bmp'); bmpColor.Height := 30; bmpColor.Width := 30; bmpColor.Canvas.Brush.Color := clBlack; //black = 0 bmpColor.Canvas.FillRect( Rect(0, 0, bmpColor.Width, bmpColor.Height) ); bmpColor.Canvas.Pen.Color := frmMainBmp.cbColorBox.Selected; bmpColor.Canvas.Brush.Color := frmMainBmp.cbColorBox.Selected; bmpColor.Canvas.Ellipse(icentre - iminus, icentre - iminus, icentre + iplus, icentre + iplus); //bmpColor.SaveToFile('cursorcolor.bmp'); { AND bitmask XOR bitmask Display 0 0 Black 0 1 White 1 0 Screen 1 1 Reverse screen } with iconInfo do begin fIcon := false; xHotspot := 15; yHotspot := 15; hbmMask := bmpMask.Handle; //AND hbmColor := bmpColor.Handle; //XOR end; hmycursor := CreateIconIndirect(iconInfo); Screen.Cursors[crMyCursor] := hmycursor; Screen.Cursor := crMyCursor; finally bmpMask.Free; bmpColor.Free; end; end; var down: Boolean; FPreviousPoint: TPoint; procedure TfrmTransparent.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin Handled := False; if Msg.message = WM_LBUTTONDOWN then begin down := True; FPreviousPoint := Msg.pt; end else if Msg.message = WM_LBUTTONUP then down := False; if (Msg.message = WM_MOUSEMOVE) and down then //(Abs(FPreviousPoint.X - Msg.pt.X) > 5) and //(Abs(FPreviousPoint.Y - Msg.pt.Y) > 5) then begin Handled := True; { TODO : kleur + grootte doorgeven via properties } Self.Canvas.Brush.Color := frmMainBmp.cbColorBox.Selected; Self.Canvas.Brush.Style := bsClear; Self.Canvas.Pen.Color := frmMainBmp.cbColorBox.Selected; Self.Canvas.Pen.Style := psSolid; Self.Canvas.Pen.Mode := pmCopy; Self.Canvas.Pen.Width := frmMainBmp.btnPenSize.Tag; { Self.Canvas.Brush.Color := clRed; Self.Canvas.Brush.Style := bsClear; Self.Canvas.Pen.Color := clRed; Self.Canvas.Pen.Style := psSolid; Self.Canvas.Pen.Mode := pmCopy; Self.Canvas.Pen.Width := 4; } Self.Canvas.MoveTo( FPreviousPoint.X, FPreviousPoint.Y); if (Abs(FPreviousPoint.X - Msg.pt.X) > 1) or (Abs(FPreviousPoint.Y - Msg.pt.Y) > 1) then Self.Canvas.LineTo( Msg.pt.X, Msg.pt.Y ); FPreviousPoint := Msg.pt; end; end; procedure TfrmTransparent.CreateParams(var Params: TCreateParams); // override; begin inherited; //params.exstyle := params.ExStyle or WS_EX_TRANSPARENT; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.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. * ********************************************************************************************************************** * TERRA_Matrix4x4 * Implements a 4x4 matrix *********************************************************************************************************************** } Unit TERRA_Matrix4x4; {$I terra.inc} Interface Uses TERRA_Math, TERRA_Vector3D, TERRA_Plane; Type MatrixColumns = Array[0..2] Of Vector3D; PMatrix4x4 = ^Matrix4x4; Matrix4x4 = Packed {$IFDEF USE_OLD_OBJECTS}Object{$ELSE}Record{$ENDIF} V:Array [0..15] Of Single; Function GetEulerAngles:Vector3D; Function Transform(Const P:Vector3D):Vector3D; Function TransformNormal(Const P:Vector3D):Vector3D; Procedure OrthoNormalize; Procedure SetValue(I,J:Integer; Value:Single); Function Get(I,J:Integer):Single; Function GetTranslation:Vector3D; Function GetColumns:MatrixColumns; End; PMatrix4x4Array=^Matrix4x4Array; Matrix4x4Array=Array[0..255] Of Matrix4x4; Const Matrix4x4Identity:Matrix4x4= (V:(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)); // Returns a rotation Matrix4x4 Function Matrix4x4Rotation(Const Rotation:Vector3D):Matrix4x4; Overload; {$IFDEF FPC}Inline;{$ENDIF} Function Matrix4x4Rotation(Const X,Y,Z:Single):Matrix4x4; Overload; {$IFDEF FPC}Inline;{$ENDIF} Function Matrix4x4Rotation(Const Axis:Vector3D; Const Angle:Single):Matrix4x4; Overload; // Returns a translation Matrix4x4 Function Matrix4x4Translation(Const Translation:Vector3D):Matrix4x4;Overload; {$IFDEF FPC}Inline;{$ENDIF} Function Matrix4x4Translation(Const X,Y,Z:Single):Matrix4x4;Overload; {$IFDEF FPC}Inline;{$ENDIF} Function Matrix4x4Transform(Const Position,Rotation,Scale:Vector3D):Matrix4x4; Function Matrix4x4Orientation(Const Position,Direction,Up,Scale:Vector3D):Matrix4x4; Function Matrix4x4Lerp(Const A,B:Matrix4x4; Const S:Single):Matrix4x4; // Inverts a Matrix4x4 Function Matrix4x4Inverse(Const A:Matrix4x4):Matrix4x4; Function Matrix4x4Scale(Const Scale:Vector3D):Matrix4x4;Overload; {$IFDEF FPC}Inline;{$ENDIF} Function Matrix4x4Scale(Const X,Y,Z:Single):Matrix4x4;Overload; {$IFDEF FPC}Inline;{$ENDIF} // Returns a reflection Matrix4x4 Function Matrix4x4Reflection(Const P:Plane):Matrix4x4; Function Matrix4x4Mirror(Const Source,Normal:Vector3D):Matrix4x4; Function Matrix4x4Transpose(Const Source:Matrix4x4):Matrix4x4; // Multiplys two matrices Function Matrix4x4Multiply4x3(Const A,B:Matrix4x4):Matrix4x4; Function Matrix4x4Multiply4x4(Const A,B:Matrix4x4):Matrix4x4; {$IFDEF BENCHMARK} Function Matrix4x4Multiply4x3SSE(Const A,B:Matrix4x4):Matrix4x4; Function Matrix4x4Multiply4x4SSE(Const A,B:Matrix4x4):Matrix4x4; {$ENDIF} Function Matrix4x4Perspective(FOV, AspectRatio, zNear, zFar:Single):Matrix4x4; Function Matrix4x4LookAt(Eye, LookAt, Roll:Vector3D):Matrix4x4; Function Matrix4x4Ortho(left, right, bottom, top, nearVal, farVal:Single):Matrix4x4; //Function Matrix4x4Isometric(X,Y, Height:Single):Matrix4x4; // modifies projection Matrix4x4 in place // clipPlane is in camera space Procedure CalculateObliqueMatrix4x4ClipPlane(Var projection:Matrix4x4; {Const Transform:Matrix4x4;} clipPlane:Plane); Implementation Uses TERRA_Vector4D, Math{$IFDEF NEON_FPU},TERRA_NEON{$ENDIF}; // modifies projection Matrix4x4 in place // clipPlane is in camera space Procedure CalculateObliqueMatrix4x4ClipPlane(Var projection:Matrix4x4; clipPlane:Plane); Var Q,C:Vector4D; D:Single; Begin C := VectorCreate4D(clipPlane.A, clipPlane.B, clipPlane.C, clipPlane.D); // Calculate the clip-space corner point opposite the clipping plane // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and // transform it into camera space by multiplying it // by the inverse of the projection Matrix4x4 q.x := (sgn(C.x)-Projection.V[8]) / Projection.V[0]; q.y := (sgn(C.y)-Projection.V[9]) / Projection.V[5]; q.z := -1.0; q.w := (1.0 + Projection.V[10]) / Projection.V[14]; // Calculate the scaled plane vector D := 2.0 / Vector4DDot(C, Q); C := Vector4DScale(C, D); // Replace the third row of the projection Matrix4x4 Projection.V[2] := c.x; Projection.V[6] := c.y; Projection.V[10] := c.z + 1.0; Projection.V[14] := c.w; (*q.x := (sgn(C.x)) / Projection.V[0]; q.y := (sgn(C.y)) / Projection.V[5]; q.z := 1.0; q.w := 1.0; // Calculate the scaled plane vector D := 2.0 / Vector4DDot(C, Q); C := Vector4DScale(C, D); // Replace the third row of the projection Matrix4x4 Projection.V[2] := c.x - Projection.V[3]; Projection.V[6] := c.y - Projection.V[7]; Projection.V[10] := c.z - Projection.V[11]; Projection.V[14] := c.w - Projection.V[15];*) End; { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15 } (*Var Q,C:Vector4D; M,Inverse:Matrix4x4; D:Single; I:Integer; Normal, P:Vector3D; Begin Normal := VectorCreate(clipPlane.A, clipPlane.B, clipPlane.C); Normal.Normalize(); P := VectorScale(Normal, clipPlane.D); M := Matrix4x4Multiply4x4(Projection, Transform); //M := Projection; //M := Transform; M := Matrix4x4Inverse(M); M := Matrix4x4Transpose(M); P := M.Transform(P); D := -VectorDot(P, Normal); C := Vector4DCreate(Normal.X, Normal.Y, Normal.Z, D); C := Vector4DCreate(clipPlane.A, clipPlane.B, clipPlane.C, clipPlane.D); C.Transform(M); {Inverse := Matrix4x4Inverse(Projection); C.Transform(Inverse);} C.Normalize(); C.W := C.W - 1.0; If (C.Z < 0) Then C := Vector4DScale(C, -1); // third row = clip plane - fourth row { projection.V[8] := c.x; projection.V[9] := c.y; projection.V[10] := c.z; projection.V[11] := c.w; } Projection.V[2] := c.x; Projection.V[6] := c.y; Projection.V[10] := c.z; Projection.V[14] := c.w; End;*) Function Matrix4x4Reflection(Const P:Plane):Matrix4x4; Begin P.Normalize(); Result.V[0] := -2 * P.a * P.a + 1; Result.V[1] := -2 * P.b * P.a; Result.V[2] := -2 * P.c * P.a; Result.V[3] := 0; Result.V[4] := -2 * P.a * P.b; Result.V[5] := -2 * P.b * P.b + 1; Result.V[6] := -2 * P.c * P.b; Result.V[7] := 0; Result.V[8] := -2 * P.a * P.c; Result.V[9] := -2 * P.b * P.c; Result.V[10] := -2 * P.c * P.c + 1; Result.V[11] := 0; Result.V[12] := -2 * P.a * P.d; Result.V[13] := -2 * P.b * P.d; Result.V[14] := -2 * P.c * P.d; Result.V[15] := 1; End; (*Function Matrix4x4Isometric(X,Y, Height:Single):Matrix4x4; Begin //http://toxicdump.org/blog/view/7/Haunted-Mansion-DevBlog-_02---Oblique-vs-Isometric-perspective-and-perfect-depth-sorting //http://www.xnaresources.com/default.asp?page=Tutorial:TileEngineSeries:4 //http://www.gamedev.net/topic/226797-isometric-camera-problems/ //glRotatef(30.0, 1,0,0); //glRotatef(-45.0, 0,1,0); //glTranslatef(-x, -m_cameraheight, -z); End;*) Function Matrix4x4Transpose(Const Source:Matrix4x4):Matrix4x4; Begin Result.V[0] := Source.V[0]; Result.V[1] := Source.V[4]; Result.V[2] := Source.V[8]; Result.V[3] := Source.V[12]; Result.V[4] := Source.V[1]; Result.V[5] := Source.V[5]; Result.V[6] := Source.V[9]; Result.V[7] := Source.V[13]; Result.V[8] := Source.V[2]; Result.V[9] := Source.V[6]; Result.V[10] := Source.V[10]; Result.V[11] := Source.V[14]; Result.V[12] := Source.V[3]; Result.V[13] := Source.V[7]; Result.V[14] := Source.V[11]; Result.V[15] := Source.V[15]; End; Function Matrix4x4Ortho(left, right, bottom, top, nearVal, farVal:Single):Matrix4x4; Var N:Single; Tx, Ty, Tz:Single; Begin TX := -(Right + Left)/(Right - Left); TY := -(Top + Bottom)/(Top - Bottom); TZ := -(farVal + nearVal)/(farVal - nearVal); N := (Right - Left); If (N<>0) Then Result.V[0] := 2 / N Else Result.V[0] := 0.0; Result.V[1] := 0; Result.V[2] := 0; Result.V[3] := 0; Result.V[4] := 0; N := (Top - Bottom); If (N<>0) Then Result.V[5] := 2 / N Else Result.V[5] := 0.0; Result.V[6] := 0; Result.V[7] := 0; Result.V[8] := 0; Result.V[9] := 0; N := (farVal - nearVal); If (N<>0) Then Result.V[10] := -2 / N Else Result.V[10] := 0.0; Result.V[11] := 0; Result.V[12] := tx; Result.V[13] := ty; Result.V[14] := tz; Result.V[15] := 1.0; // + 0.375 End; //TESTME Procedure Matrix4x4.SetValue(I,J:Integer; Value:Single); Begin V[J*4+I] := Value; End; Function Matrix4x4.Get(I, J: Integer): Single; Begin Result := V[J*4+I]; End; Function Matrix4x4.GetColumns: MatrixColumns; Begin Result[0] := VectorCreate(V[0], V[4], V[8]); Result[1] := VectorCreate(V[1], V[5], V[9]); Result[2] := VectorCreate(V[2], V[6], V[10]); End; Function Matrix4x4.GetEulerAngles:Vector3D; Var sinPitch, cosPitch, sinRoll, cosRoll, sinYaw, cosYaw:Double; Inv:Double; Begin sinPitch := -V[2]; // [2][0]; cosPitch := Sqrt(1 - Sqr(sinPitch)); If (Abs(cosPitch) > EPSILON ) Then Begin Inv := 1.0 / cosPitch; sinRoll := V[9] * Inv; cosRoll := V[10] * Inv; sinYaw := V[1] * Inv; cosYaw := V[0] * Inv; End Else Begin sinRoll := -V[6]; cosRoll := V[5]; sinYaw := 0.0; cosYaw := 1.0; End; Result.X := atan2(sinYaw, cosYaw); Result.Y := atan2(sinPitch, cosPitch); Result.Z := atan2(sinRoll, cosRoll); End; Function Matrix4x4.GetTranslation:Vector3D; Begin Result.X := V[12]; Result.Y := V[13]; Result.Z := V[14]; End; Procedure Matrix4x4.Orthonormalize; Var fInvLength:Single; fDot0, fDot1:Single; Function Index(I,J:Integer):Integer; Begin Result := J*4+I; End; Begin exit; // Algorithm uses Gram-Schmidt orthogonalization. If 'this' Matrix4x4 is // M = [m0|m1|m2], then orthonormal output Matrix4x4 is Q = [q0|q1|q2], // // q0 = m0/|m0| // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| // // where |V| indicates length of vector V and A*B indicates dot // product of vectors A and B. // compute q0 fInvLength := InvSqrt( Sqr(V[Index(0,0)]) + Sqr(V[Index(1,0)]) + Sqr(V[Index(2,0)])); V[Index(0,0)] := V[Index(0,0)] * fInvLength; V[Index(1,0)] := V[Index(1,0)] * fInvLength; V[Index(2,0)] := V[Index(2,0)] * fInvLength; // compute q1 fDot0 := V[Index(0,0)]*V[Index(0,1)] + V[Index(1,0)]*V[Index(1,1)] + V[Index(2,0)]*V[Index(2,1)]; V[Index(0,1)] := V[Index(0,1)] - fDot0 * V[Index(0,0)]; V[Index(1,1)] := V[Index(1,1)] - fDot0 * V[Index(1,0)]; V[Index(2,1)] := V[Index(2,1)] - fDot0 * V[Index(2,0)]; fInvLength := InvSqrt(Sqr(V[Index(0,1)])+Sqr(V[Index(1,1)]) +Sqr(V[Index(2,1)])); V[Index(0,1)] := V[Index(0,1)] * fInvLength; V[Index(1,1)] := V[Index(1,1)] * fInvLength; V[Index(2,1)] := V[Index(2,1)] * fInvLength; // compute q2 fDot1 := V[Index(0,1)]*V[Index(0,2)] + V[Index(1,1)]*V[Index(1,2)] + V[Index(2,1)]*V[Index(2,2)]; fDot0 := V[Index(0,0)]*V[Index(0,2)] + V[Index(1,0)]*V[Index(1,2)] + V[Index(2,0)]*V[Index(2,2)]; V[Index(0,2)] := V[Index(0,2)] - fDot0*V[Index(0,0)] + fDot1*V[Index(0,1)]; V[Index(1,2)] := V[Index(1,2)] - fDot0*V[Index(1,0)] + fDot1*V[Index(1,1)]; V[Index(2,2)] := V[Index(2,2)] - fDot0*V[Index(2,0)] + fDot1*V[Index(2,1)]; fInvLength := InvSqrt(Sqr(V[Index(0,2)]) + Sqr(V[Index(1,2)]) + Sqr(V[Index(2,2)])); V[Index(0,2)] := V[Index(0,2)] * fInvLength; V[Index(1,2)] := V[Index(1,2)] * fInvLength; V[Index(2,2)] := V[Index(2,2)] * fInvLength; End; Function Matrix4x4.Transform(Const P:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF} Begin {$IFDEF NEON_FPU} matvec3_neon(@Self,@P,@Result); {$ELSE} Result.X := P.X*V[0] + P.Y*V[4] + P.Z*V[8] + V[12]; Result.Y := P.X*V[1] + P.Y*V[5] + P.Z*V[9] + V[13]; Result.Z := P.X*V[2] + P.Y*V[6] + P.Z*V[10] + V[14]; {$ENDIF} End; Function Matrix4x4.TransformNormal(Const P:Vector3D):Vector3D; {$IFDEF FPC}Inline;{$ENDIF} Begin Result.X := P.X*V[0] + P.Y*V[4] + P.Z*V[8]; Result.Y := P.X*V[1] + P.Y*V[5] + P.Z*V[9]; Result.Z := P.X*V[2] + P.Y*V[6] + P.Z*V[10]; End; Function Matrix4x4Transform(Const Position,Rotation,Scale:Vector3D):Matrix4x4; Var CosRx,CosRy,CosRz:Single; SinRx,SinRy,SinRz:Single; Begin CosRx := Cos(Rotation.x); //Used 6x CosRy := Cos(Rotation.y); //Used 4x CosRz := Cos(Rotation.z); //Used 4x SinRx := Sin(Rotation.x); //Used 5x SinRy := Sin(Rotation.y); //Used 5x SinRz := Sin(Rotation.z); //Used 5x Result.V[0] := CosRy*CosRz*Scale.x; Result.V[1] := CosRy*SinRz*Scale.x; Result.V[2] := -SinRy*Scale.x; Result.V[3] := 0.0; Result.V[4] := (CosRz*SinRx*SinRy*Scale.y) - (CosRx*SinRz*Scale.y); Result.V[5] := (CosRx*CosRz*Scale.y) + (SinRx*SinRy*SinRz*Scale.y); Result.V[6] := CosRy*SinRx*Scale.y; Result.V[7] := 0.0; Result.V[8] := (CosRx*CosRz*SinRy*Scale.z) + (SinRx*SinRz*Scale.z); Result.V[9] := (-CosRz*SinRx*Scale.z) + (CosRx*SinRy*SinRz*Scale.z); Result.V[10] := CosRx*CosRy*Scale.z; Result.V[11] := 0.0; Result.V[12] := Position.x; Result.V[13] := Position.y; Result.V[14] := Position.z; Result.V[15] := 1.0; End; Function Matrix4x4Orientation(Const Position,Direction,Up,Scale:Vector3D):Matrix4x4; Var TX,TZ:Vector3D; Begin TZ := VectorCross(Direction, Up); TZ.Normalize; TX := VectorCross(Up, TZ); TX.Normalize; Result.V[0] := TX.X * Scale.X; Result.V[1] := TX.Y * Scale.X; Result.V[2] := TX.Z * Scale.X; Result.V[3] := 0.0; Result.V[4] := Up.X * Scale.y; Result.V[5] := Up.Y * Scale.y; Result.V[6] := Up.Z * Scale.Y; Result.V[7] := 0.0; Result.V[8] := TZ.X * Scale.Z; Result.V[9] := TZ.Y * Scale.Z; Result.V[10] := TZ.Z * Scale.Z; Result.V[11] := 0.0; Result.V[12] := Position.x; Result.V[13] := Position.y; Result.V[14] := Position.z; Result.V[15] := 1.0; End; Function Matrix4x4Rotation(Const Axis:Vector3D; Const Angle:Single):Matrix4x4; Var C,S,T:Single; X,Y,Z:Single; Begin C := Cos(Angle); S := Sin(Angle); T := 1-C; X := Axis.X; Y := Axis.Y; Z := Axis.Z; Result.V[0] := T * Sqr(X) + C; Result.V[1] := (T * X * Y) - (s *Z); Result.V[2] := (T * X * Z) + (s * Y); Result.V[3] := 0.0; Result.V[4] := (t * X * Y) + (s * Z); Result.V[5] := (t * Y * Y)+ C; Result.V[6] := (T * Y * Z) - (S * X); Result.V[7] := 0.0; Result.V[8] := (T * X * Z) - (S * Y); Result.V[9] := (T * Y * Z) + (S * X); Result.V[10] := (T * Z * Z) + C; Result.V[11] := 0.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function Matrix4x4Rotation(Const Rotation:Vector3D):Matrix4x4; {$IFDEF FPC}Inline;{$ENDIF} Begin Result := Matrix4x4Rotation(Rotation.X, Rotation.Y, Rotation.Z); End; Function Matrix4x4Rotation(Const X,Y,Z:Single):Matrix4x4; {$IFDEF FPC}Inline;{$ENDIF} Var Cr,Sr,Cp,Sp,Cy,Sy,Srsp,Crsp:Single; Begin cr := Cos(X); sr := Sin(X); cp := Cos(Y); sp := Sin(Y); cy := Cos(Z); sy := Sin(Z); Result.V[0] := cp * cy; Result.V[1] := cp * sy; Result.V[2] := -sp; If Result.V[2] = -0 Then Result.V[2] := 0; Result.V[3] := 0.0; srsp := sr * sp; crsp := cr * sp; Result.V[4] := (srsp * cy) - (cr * sy); Result.V[5] := (srsp * sy) + (cr * cy); Result.V[6] := (sr * cp); Result.V[7] := 0.0; Result.V[8] := (crsp * cy) + (sr * sy); Result.V[9] := (crsp * sy) - (sr * cy); Result.V[10] := (cr * cp); Result.V[11] := 0.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function Matrix4x4Translation(Const Translation:Vector3D):Matrix4x4; {$IFDEF FPC}Inline;{$ENDIF} Begin Result := Matrix4x4Translation(Translation.X,Translation.Y,Translation.Z); End; Function Matrix4x4Translation(Const X,Y,Z:Single):Matrix4x4; {$IFDEF FPC}Inline;{$ENDIF} Begin Result.V[0] := 1.0; Result.V[1] := 0.0; Result.V[2] := 0.0; Result.V[3] := 0.0; Result.V[4] := 0.0; Result.V[5] := 1.0; Result.V[6] := 0.0; Result.V[7] := 0.0; Result.V[8] := 0.0; Result.V[9] := 0.0; Result.V[10] := 1.0; Result.V[11] := 0.0; Result.V[12] := X; Result.V[13] := Y; Result.V[14] := Z; Result.V[15] := 1.0; End; Function Matrix4x4Scale(Const Scale:Vector3D):Matrix4x4; {$IFDEF FPC}Inline;{$ENDIF} Begin Result := Matrix4x4Scale(Scale.X,Scale.Y,Scale.Z); End; Function Matrix4x4Scale(Const X,Y,Z:Single):Matrix4x4; {$IFDEF FPC}Inline;{$ENDIF} Begin Result.V[0] := X; Result.V[1] := 0.0; Result.V[2] := 0.0; Result.V[3] := 0.0; Result.V[4] := 0.0; Result.V[5] := Y; Result.V[6] := 0.0; Result.V[7] := 0.0; Result.V[8] := 0.0; Result.V[9] := 0.0; Result.V[10] := Z; Result.V[11] := 0.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := 0.0; Result.V[15] := 1.0; End; Function Matrix4x4Perspective(FOV, aspectRatio, znear, zfar:Single):Matrix4x4; Var left, right, bottom, top:Single; ymax, xmax:Single; temp, temp2, temp3, temp4:Single; Begin ymax := znear * Tan(FOV * 0.5 * Rad); xmax := ymax * aspectRatio; left := -xmax; right := xmax; bottom := -ymax; top := ymax; temp := znear * 2.0; temp2 := (xmax * 2.0); temp3 := (top - bottom); temp4 := 1.0 / (zfar - znear); Result.V[0] := temp / temp2; Result.V[1] := 0.0; Result.V[2] := 0.0; Result.V[3] := 0.0; Result.V[4] := 0.0; Result.V[5] := temp / temp3; Result.V[6] := 0.0; Result.V[7] := 0.0; Result.V[8] := (right + left) / temp2; Result.V[9] := (top + bottom) / temp3; Result.V[10] := (-zfar - znear) * temp4; Result.V[11] := -1.0; Result.V[12] := 0.0; Result.V[13] := 0.0; Result.V[14] := (-temp * zfar) * temp4; Result.V[15] := 0.0; End; Function Matrix4x4LookAt(Eye, LookAt, Roll:Vector3D):Matrix4x4; Var xaxis, yaxis, zaxis:Vector3D; Begin zaxis := VectorSubtract(Eye, lookAt); zaxis.Normalize(); xaxis := VectorCross(Roll, zaxis); xaxis.Normalize(); If (xaxis.LengthSquared()<=0) Then Begin Roll := VectorCreate(-Roll.Z, -Roll.X, -Roll.Y); xaxis := VectorCross(Roll, zaxis); xaxis.Normalize(); End; yaxis := VectorCross(zaxis, xaxis); Result.V[0] := xaxis.x; Result.V[1] := yaxis.x; Result.V[2] := zaxis.x; Result.V[3] := 0.0; Result.V[4] := xaxis.y; Result.V[5] := yaxis.y; Result.V[6] := zaxis.y; Result.V[7] := 0.0; Result.V[8] := xaxis.z; Result.V[9] := yaxis.z; Result.V[10] := zaxis.z; Result.V[11] := 0.0; Result.V[12] := -xaxis.dot(eye); Result.V[13] := -yaxis.dot(eye); Result.V[14] := -zaxis.dot(eye); Result.V[15] := 1.0; End; Function Matrix4x4Mirror(Const Source,Normal:Vector3D):Matrix4x4; Var Dot:Single; Begin Dot := VectorDot(Source,Normal); Result.V[0] := 1.0 - (2.0 *Normal.X * Normal.X); Result.V[1] := - (2.0 * Normal.Y * Normal.X); Result.V[2] := - (2.0 * Normal.Z * Normal.X); Result.V[3] := 0.0; Result.V[4] := - (2.0 * Normal.X * Normal.Y); Result.V[5] := 1.0 - (2.0 * Normal.Y * Normal.Y); Result.V[6] := - (2.0 * Normal.Z * Normal.Y); Result.V[7] := 0.0; Result.V[8] := - (2.0 * Normal.X * Normal.Z); Result.V[9] := - (2.0 * Normal.Y * Normal.Z); Result.V[10] := 1.0 - (2.0 * Normal.Z * Normal.Z); Result.V[11] := 0.0; Result.V[12]:= 2.0 * Dot * Normal.X; Result.V[13]:= 2.0 * Dot * Normal.Y; Result.V[14]:= 2.0 * Dot * Normal.Z; Result.V[15]:= 1.0; End; Function Matrix4x4GetTranslation(Const A:Matrix4x4):Vector3D; Begin Result.X := A.V[12]; Result.Y := A.V[13]; Result.Z := A.V[14]; End; Function Matrix4x4GetScale(Const A:Matrix4x4):Vector3D; Begin Result.X := A.V[0]; Result.Y := A.V[5]; Result.Z := A.V[10]; End; // 4x4 Matrix4x4 inverse using Gauss-Jordan algorithm with row pivoting // originally written by Nathan Reed, now released into the public domain. Function Matrix4x4Inverse(Const A:Matrix4x4):Matrix4x4; Var I:Integer; a0, a1, a2, a3, a4, a5: Single; b0, b1, b2, b3, b4, b5: Single; Det, invDet:Single; Begin a0 := A.V[ 0] * A.V[ 5] - A.V[ 1] *A.V[ 4]; a1 := A.V[ 0] * A.V[ 6] - A.V[ 2] *A.V[ 4]; a2 := A.V[ 0] * A.V[ 7] - A.V[ 3] *A.V[ 4]; a3 := A.V[ 1] * A.V[ 6] - A.V[ 2] *A.V[ 5]; a4 := A.V[ 1] * A.V[ 7] - A.V[ 3] *A.V[ 5]; a5 := A.V[ 2] * A.V[ 7] - A.V[ 3] *A.V[ 6]; b0 := A.V[ 8] * A.V[13] - A.V[ 9] *A.V[12]; b1 := A.V[ 8] * A.V[14] - A.V[10] *A.V[12]; b2 := A.V[ 8] * A.V[15] - A.V[11] *A.V[12]; b3 := A.V[ 9] * A.V[14] - A.V[10] *A.V[13]; b4 := A.V[ 9] * A.V[15] - A.V[11] *A.V[13]; b5 := A.V[10] * A.V[15] - A.V[11] *A.V[14]; Det := a0*b5 - a1*b4 + a2*b3 + a3*b2 - a4*b1 + a5*b0; If (Abs(Det) > Epsilon) Then Begin Result.V[ 0] := + A.V[ 5]*b5 - A.V[ 6]*b4 + A.V[ 7]*b3; Result.V[ 4] := - A.V[ 4]*b5 + A.V[ 6]*b2 - A.V[ 7]*b1; Result.V[ 8] := + A.V[ 4]*b4 - A.V[ 5]*b2 + A.V[ 7]*b0; Result.V[12] := - A.V[ 4]*b3 + A.V[ 5]*b1 - A.V[ 6]*b0; Result.V[ 1] := - A.V[ 1]*b5 + A.V[ 2]*b4 - A.V[ 3]*b3; Result.V[ 5] := + A.V[ 0]*b5 - A.V[ 2]*b2 + A.V[ 3]*b1; Result.V[ 9] := - A.V[ 0]*b4 + A.V[ 1]*b2 - A.V[ 3]*b0; Result.V[13] := + A.V[ 0]*b3 - A.V[ 1]*b1 + A.V[ 2]*b0; Result.V[ 2] := + A.V[13]*a5 - A.V[14]*a4 + A.V[15]*a3; Result.V[ 6] := - A.V[12]*a5 + A.V[14]*a2 - A.V[15]*a1; Result.V[10] := + A.V[12]*a4 - A.V[13]*a2 + A.V[15]*a0; Result.V[14] := - A.V[12]*a3 + A.V[13]*a1 - A.V[14]*a0; Result.V[ 3] := - A.V[ 9]*a5 + A.V[10]*a4 - A.V[11]*a3; Result.V[ 7] := + A.V[ 8]*a5 - A.V[10]*a2 + A.V[11]*a1; Result.V[11] := - A.V[ 8]*a4 + A.V[ 9]*a2 - A.V[11]*a0; Result.V[15] := + A.V[ 8]*a3 - A.V[ 9]*a1 + A.V[10]*a0; invDet := 1.0 / Det; For I:=0 To 15 Do Result.V[ I] := Result.V[ I] * invDet; End Else FillChar(Result, SizeOf(Result), 0); End; Function Matrix4x4Lerp(Const A,B:Matrix4x4; Const S:Single):Matrix4x4; Var I:Integer; Begin For I:=0 To 15 Do Result.V[I] := A.V[I] * (1.0 - S) + B.V[I] * S; End; { // According to fastcall convention in Delphi // eax = ths, edx = m1, ecx = m2 // We do not need to reserve eax, ecx and edx, only reserve esi, edi, ebx push esi push edi movss xmm0, dword ptr [eax] movaps xmm1, [edx] shufps xmm0, xmm0, 0 movss xmm2, dword ptr [eax+4] mulps xmm0, xmm1 shufps xmm2, xmm2, 0 movaps xmm3, [edx+$10] movss xmm7, dword ptr [eax+8] mulps xmm2, xmm3 shufps xmm7, xmm7, 0 addps xmm0, xmm2 movaps xmm4, [edx+$20] movss xmm2, dword ptr [eax+$0C] mulps xmm7, xmm4 shufps xmm2, xmm2, 0 addps xmm0, xmm7 movaps xmm5, [edx+$30] movss xmm6, dword ptr [eax+$10] mulps xmm2, xmm5 movss xmm7, dword ptr [eax+$14] shufps xmm6, xmm6, 0 addps xmm0, xmm2 shufps xmm7, xmm7, 0 movlps qword ptr [ecx], xmm0 movhps qword ptr [ecx+8], xmm0 mulps xmm7, xmm3 movss xmm0, dword ptr [eax+18h] mulps xmm6, xmm1 shufps xmm0, xmm0, 0 addps xmm6, xmm7 mulps xmm0, xmm4 movss xmm2, dword ptr [eax+24h] addps xmm6, xmm0 movss xmm0, dword ptr [eax+1Ch] movss xmm7, dword ptr [eax+20h] shufps xmm0, xmm0, 0 shufps xmm7, xmm7, 0 mulps xmm0, xmm5 mulps xmm7, xmm1 addps xmm6, xmm0 shufps xmm2, xmm2, 0 movlps qword ptr [ecx+10h], xmm6 movhps qword ptr [ecx+18h], xmm6 mulps xmm2, xmm3 movss xmm6, dword ptr [eax+28h] addps xmm7, xmm2 shufps xmm6, xmm6, 0 movss xmm2, dword ptr [eax+2Ch] mulps xmm6, xmm4 shufps xmm2, xmm2, 0 addps xmm7, xmm6 mulps xmm2, xmm5 movss xmm0, dword ptr [eax+34h] addps xmm7, xmm2 shufps xmm0, xmm0, 0 movlps qword ptr [ecx+20h], xmm7 movss xmm2, dword ptr [eax+30h] movhps qword ptr [ecx+28h], xmm7 mulps xmm0, xmm3 shufps xmm2, xmm2, 0 movss xmm6, dword ptr [eax+38h] mulps xmm2, xmm1 shufps xmm6, xmm6, 0 addps xmm2, xmm0 mulps xmm6, xmm4 movss xmm7, dword ptr [eax+3Ch] shufps xmm7, xmm7, 0 addps xmm2, xmm6 mulps xmm7, xmm5 addps xmm2, xmm7 movaps [ecx+$30], xmm2 pop edi pop esi } {$IFDEF BENCHMARK}{$UNDEF SSE}{$ENDIF} {$IFNDEF SSE} Function Matrix4x4Multiply4x4(Const A,B:Matrix4x4):Matrix4x4; Begin {$IFDEF NEON_FPU} matmul4_neon(@A,@B,@Result); {$ELSE} Result.V[0] := A.V[0]*B.V[0] + A.V[4]*B.V[1] + A.V[8]*B.V[2] + A.V[12]*B.V[3]; Result.V[1] := A.V[1]*B.V[0] + A.V[5]*B.V[1] + A.V[9]*B.V[2] + A.V[13]*B.V[3]; Result.V[2] := A.V[2]*B.V[0] + A.V[6]*B.V[1] + A.V[10]*B.V[2] + A.V[14]*B.V[3]; Result.V[3] := A.V[3]*B.V[0] + A.V[7]*B.V[1] + A.V[11]*B.V[2] + A.V[15]*B.V[3]; Result.V[4] := A.V[0]*B.V[4] + A.V[4]*B.V[5] + A.V[8]*B.V[6] + A.V[12]*B.V[7]; Result.V[5] := A.V[1]*B.V[4] + A.V[5]*B.V[5] + A.V[9]*B.V[6] + A.V[13]*B.V[7]; Result.V[6] := A.V[2]*B.V[4] + A.V[6]*B.V[5] + A.V[10]*B.V[6] + A.V[14]*B.V[7]; Result.V[7] := A.V[3]*B.V[4] + A.V[7]*B.V[5] + A.V[11]*B.V[6] + A.V[15]*B.V[7]; Result.V[8] := A.V[0]*B.V[8] + A.V[4]*B.V[9] + A.V[8]*B.V[10] + A.V[12]*B.V[11]; Result.V[9] := A.V[1]*B.V[8] + A.V[5]*B.V[9] + A.V[9]*B.V[10] + A.V[13]*B.V[11]; Result.V[10] := A.V[2]*B.V[8] + A.V[6]*B.V[9] + A.V[10]*B.V[10] + A.V[14]*B.V[11]; Result.V[11] := A.V[3]*B.V[8] + A.V[7]*B.V[9] + A.V[11]*B.V[10] + A.V[15]*B.V[11]; Result.V[12] := A.V[0]*B.V[12] + A.V[4]*B.V[13] + A.V[8]*B.V[14] + A.V[12]*B.V[15]; Result.V[13] := A.V[1]*B.V[12] + A.V[5]*B.V[13] + A.V[9]*B.V[14] + A.V[13]*B.V[15]; Result.V[14] := A.V[2]*B.V[12] + A.V[6]*B.V[13] + A.V[10]*B.V[14] + A.V[14]*B.V[15]; Result.V[15] := A.V[3]*B.V[12] + A.V[7]*B.V[13] + A.V[11]*B.V[14] + A.V[15]*B.V[15]; {$ENDIF} End; Function Matrix4x4Multiply4x3(Const A,B:Matrix4x4):Matrix4x4; Begin {$IFDEF NEON_FPU} matmul4_neon(@A,@B,@Result); {$ELSE} Result.V[0] := A.V[0]*B.V[0] + A.V[4]*B.V[1] + A.V[8]*B.V[2]; Result.V[1] := A.V[1]*B.V[0] + A.V[5]*B.V[1] + A.V[9]*B.V[2]; Result.V[2] := A.V[2]*B.V[0] + A.V[6]*B.V[1] + A.V[10]*B.V[2]; Result.V[3] := 0.0; Result.V[4] := A.V[0]*B.V[4] + A.V[4]*B.V[5] + A.V[8]*B.V[6]; Result.V[5] := A.V[1]*B.V[4] + A.V[5]*B.V[5] + A.V[9]*B.V[6]; Result.V[6] := A.V[2]*B.V[4] + A.V[6]*B.V[5] + A.V[10]*B.V[6]; Result.V[7] := 0.0; Result.V[8] := A.V[0]*B.V[8] + A.V[4]*B.V[9] + A.V[8]*B.V[10]; Result.V[9] := A.V[1]*B.V[8] + A.V[5]*B.V[9] + A.V[9]*B.V[10]; Result.V[10] := A.V[2]*B.V[8] + A.V[6]*B.V[9] + A.V[10]*B.V[10]; Result.V[11] := 0.0; Result.V[12] := A.V[0]*B.V[12] + A.V[4]*B.V[13] + A.V[8]*B.V[14] + A.V[12]; Result.V[13] := A.V[1]*B.V[12] + A.V[5]*B.V[13] + A.V[9]*B.V[14] + A.V[13]; Result.V[14] := A.V[2]*B.V[12] + A.V[6]*B.V[13] + A.V[10]*B.V[14] + A.V[14]; Result.V[15] := 1.0; {$ENDIF} End; {$ENDIF} {$IFDEF BENCHMARK}{$DEFINE SSE}{$ENDIF} {$IFDEF SSE} Procedure MultMatrix4x4_SSE(A, B, Dest: Pointer);Register; Asm push esi push edi mov edi, A movaps xmm4, [edi] movaps xmm5, [edi+16] movaps xmm6, [edi+32] movaps xmm7, [edi+48] mov esi, B mov eax, 0 @@L1: movaps xmm0, [esi+eax] movaps xmm1, xmm0 movaps xmm2, xmm0 movaps xmm3, xmm0 shufps xmm0, xmm2, 000h shufps xmm1, xmm2, 055h shufps xmm2, xmm2, 0AAh shufps xmm3, xmm3, 0FFh mulps xmm0, [edi] mulps xmm1, [edi+16] mulps xmm2, [edi+32] mulps xmm3, [edi+48] addps xmm0, xmm1 addps xmm0, xmm2 addps xmm0, xmm3 mov edx, Dest add edx, eax movaps [edx], xmm0 add eax, 16 cmp eax, 48 jle @@L1 pop edi pop esi End; Var _AlignedA, _AlignedB, _AlignedC:PMatrix4x4; _P1, _P2, _P3: Pointer; { 0 0 1 4 2 8 3 12 X 4 16 5 20 6 24 7 28 X 8 32 9 36 10 40 11 44 X 12 48 13 52 14 56 15 60 X } {$IFDEF BENCHMARK} Function Matrix4x4Multiply4x3SSE(Const A,B:Matrix4x4):Matrix4x4; {$ELSE} Function Matrix4x4Multiply4x3(Const A,B:Matrix4x4):Matrix4x4; {$ENDIF} Asm movss xmm0, dword ptr [edx] movups xmm1, [eax] shufps xmm0, xmm0, 0 movss xmm2, dword ptr [edx+4] mulps xmm0, xmm1 shufps xmm2, xmm2, 0 movups xmm3, [eax+10h] movss xmm7, dword ptr [edx+8] mulps xmm2, xmm3 shufps xmm7, xmm7, 0 addps xmm0, xmm2 movups xmm4, [eax+20h] // movss xmm2, dword ptr [edx+12] mulps xmm7, xmm4 // shufps xmm2, xmm2, 0 addps xmm0, xmm7 movups xmm5, [eax+48] movss xmm6, dword ptr [edx+16] // mulps xmm2, xmm5 movss xmm7, dword ptr [edx+20] shufps xmm6, xmm6, 0 // addps xmm0, xmm2 shufps xmm7, xmm7, 0 movlps qword ptr [ecx], xmm0 movhps qword ptr [ecx+8], xmm0 mulps xmm7, xmm3 movss xmm0, dword ptr [edx+24] mulps xmm6, xmm1 shufps xmm0, xmm0, 0 addps xmm6, xmm7 mulps xmm0, xmm4 movss xmm2, dword ptr [edx+36] addps xmm6, xmm0 // movss xmm0, dword ptr [edx+28] movss xmm7, dword ptr [edx+32] // shufps xmm0, xmm0, 0 shufps xmm7, xmm7, 0 // mulps xmm0, xmm5 mulps xmm7, xmm1 // addps xmm6, xmm0 shufps xmm2, xmm2, 0 movlps qword ptr [ecx+10h], xmm6 movhps qword ptr [ecx+18h], xmm6 mulps xmm2, xmm3 movss xmm6, dword ptr [edx+40] addps xmm7, xmm2 shufps xmm6, xmm6, 0 // movss xmm2, dword ptr [edx+44] mulps xmm6, xmm4 // shufps xmm2, xmm2, 0 addps xmm7, xmm6 // mulps xmm2, xmm5 movss xmm0, dword ptr [edx+52] // addps xmm7, xmm2 shufps xmm0, xmm0, 0 movlps qword ptr [ecx+20h], xmm7 movss xmm2, dword ptr [edx+30h] movhps qword ptr [ecx+40], xmm7 mulps xmm0, xmm3 shufps xmm2, xmm2, 0 movss xmm6, dword ptr [edx+56] mulps xmm2, xmm1 shufps xmm6, xmm6, 0 addps xmm2, xmm0 mulps xmm6, xmm4 // movss xmm7, dword ptr [edx+60] // shufps xmm7, xmm7, 0 addps xmm2, xmm6 //mulps xmm7, xmm5 addps xmm2, xmm5 //xmm7 movups [ecx+48], xmm2 {Begin Move(A, _AlignedA^, SizeOf(Matrix4x4)); Move(B, _AlignedB^, SizeOf(Matrix4x4)); MultMatrix4x4_SSE(_AlignedA, _AlignedB, _AlignedC); Move(_AlignedC^, Result, SizeOf(Matrix4x4));} End; {$IFDEF BENCHMARK} Function Matrix4x4Multiply4x4SSE(Const A,B:Matrix4x4):Matrix4x4; {$ELSE} Function Matrix4x4Multiply4x4(Const A,B:Matrix4x4):Matrix4x4; {$ENDIF} Asm movss xmm0, dword ptr [edx] movups xmm1, [eax] shufps xmm0, xmm0, 0 movss xmm2, dword ptr [edx+4] mulps xmm0, xmm1 shufps xmm2, xmm2, 0 movups xmm3, [eax+10h] movss xmm7, dword ptr [edx+8] mulps xmm2, xmm3 shufps xmm7, xmm7, 0 addps xmm0, xmm2 movups xmm4, [eax+20h] movss xmm2, dword ptr [edx+0Ch] mulps xmm7, xmm4 shufps xmm2, xmm2, 0 addps xmm0, xmm7 movups xmm5, [eax+30h] movss xmm6, dword ptr [edx+10h] mulps xmm2, xmm5 movss xmm7, dword ptr [edx+14h] shufps xmm6, xmm6, 0 addps xmm0, xmm2 shufps xmm7, xmm7, 0 movlps qword ptr [ecx], xmm0 movhps qword ptr [ecx+8], xmm0 mulps xmm7, xmm3 movss xmm0, dword ptr [edx+18h] mulps xmm6, xmm1 shufps xmm0, xmm0, 0 addps xmm6, xmm7 mulps xmm0, xmm4 movss xmm2, dword ptr [edx+24h] addps xmm6, xmm0 movss xmm0, dword ptr [edx+1Ch] movss xmm7, dword ptr [edx+20h] shufps xmm0, xmm0, 0 shufps xmm7, xmm7, 0 mulps xmm0, xmm5 mulps xmm7, xmm1 addps xmm6, xmm0 shufps xmm2, xmm2, 0 movlps qword ptr [ecx+10h], xmm6 movhps qword ptr [ecx+18h], xmm6 mulps xmm2, xmm3 movss xmm6, dword ptr [edx+28h] addps xmm7, xmm2 shufps xmm6, xmm6, 0 movss xmm2, dword ptr [edx+2Ch] mulps xmm6, xmm4 shufps xmm2, xmm2, 0 addps xmm7, xmm6 mulps xmm2, xmm5 movss xmm0, dword ptr [edx+34h] addps xmm7, xmm2 shufps xmm0, xmm0, 0 movlps qword ptr [ecx+20h], xmm7 movss xmm2, dword ptr [edx+30h] movhps qword ptr [ecx+28h], xmm7 mulps xmm0, xmm3 shufps xmm2, xmm2, 0 movss xmm6, dword ptr [edx+38h] mulps xmm2, xmm1 shufps xmm6, xmm6, 0 addps xmm2, xmm0 mulps xmm6, xmm4 movss xmm7, dword ptr [edx+3Ch] shufps xmm7, xmm7, 0 addps xmm2, xmm6 mulps xmm7, xmm5 addps xmm2, xmm7 movups [ecx+30h], xmm2 End; {$ENDIF} Initialization {$IFDEF SSE} GetMem(_P1, SizeOf(Matrix4x4) + 15); _AlignedA := PMatrix4x4((Cardinal(_P1) + $0F) and $FFFFFFF0); GetMem(_P2, SizeOf(Matrix4x4) + 15); _AlignedB := PMatrix4x4((Cardinal(_P2) + $0F) and $FFFFFFF0); GetMem(_P3, SizeOf(Matrix4x4) + 15); _AlignedC := PMatrix4x4((Cardinal(_P3) + $0F) and $FFFFFFF0); Finalization FreeMem(_P1); FreeMem(_P2); FreeMem(_P3); {$ENDIF} End.
unit utc_localtz; interface uses windows, sysutils; function UtcToLocalDateTime(aUTC : TDateTime) : TDateTime; function LocalDateTimeToUtc(aLocalTime : TDateTime) : TDateTime; // This Function is missing in the "windows"-api-header from Delphi // can be removed when this bug is fixed function TzSpecificLocalTimeToSystemTime(lpTimeZoneInformation: PTimeZoneInformation; var lpLocalTime, lpUniversalTime: TSystemTime): BOOL; stdcall; {$EXTERNALSYM TzSpecificLocalTimeToSystemTime} implementation function TzSpecificLocalTimeToSystemTime; external kernel32 name 'TzSpecificLocalTimeToSystemTime'; function UtcToLocalDateTime(aUTC : TDateTime) : TDateTime; var tzi : TIME_ZONE_INFORMATION; utc : TSystemTime; localtime : TSystemTime; begin DateTimeToSystemTime(aUTC,utc); GetTimeZoneInformation(tzi); SystemTimeToTzSpecificLocalTime(@tzi,utc,localtime); Result := SystemTimeToDateTime(localtime); end; function LocalDateTimeToUtc(aLocalTime : TDateTime) : TDateTime; var tzi : TIME_ZONE_INFORMATION; utc : TSystemTime; localtime : TSystemTime; begin DateTimeToSystemTime(aLocalTime,localtime); GetTimeZoneInformation(tzi); TzSpecificLocalTimeToSystemTime(@tzi,localtime,utc); Result := SystemTimeToDateTime(utc); end; end.
{ Subroutine SST_R_PAS_SMENT_MODULE (STR_MOD_H) * * Process MODULE_STATEMENT syntax. We assume we stay in this module until * a new MODULE statement. STR_MOD_H is the string handle to the MODULE_STATEMENT * syntax. } module sst_r_pas_SMENT_MODULE; define sst_r_pas_sment_module; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_sment_module ( {proces MODULE_STATEMENT syntax} in str_mod_h: syo_string_t); {string handle to MODULE_STATEMENT syntax} var tag: sys_int_machine_t; {syntax tag from .syn file} str_h: syo_string_t; {handle to string for a tag} sym_p: sst_symbol_p_t; {pointer to module name symbol descriptor} stat: sys_err_t; begin case nest_level of {how deep are we nested in blocks} 0: ; {not in any block, no problem} 1: begin {already in top MODULE or PROGRAM block} sst_opcode_pos_pop; {this finishes block we are currently in} sst_scope_old; {pop back to previous scope} nest_level := nest_level - 1; {should now be above any top block} end; otherwise syo_error (str_mod_h, 'sst_pas_read', 'module_not_allowed_here', nil, 0); end; nest_level := nest_level + 1; {down into this MODULE block} top_block := top_block_module_k; {indicate top block is a MODULE} syo_level_down; {down into MODULE_STATEMENT syntax level} syo_get_tag_msg ( {get tag for module name} tag, str_h, 'sst_pas_read', 'statement_module_bad', nil, 0); if tag <> 1 then begin {unexpected TAG value} syo_error_tag_unexp (tag, str_h); end; sst_symbol_new ( {add module name to symbol table} str_h, syo_charcase_down_k, sym_p, stat); sst_scope_new; {make new scope level for this module} sym_p^.module_scope_p := sst_scope_p; {point symbol to module's scope} syo_error_abort (stat, str_h, '', '', nil, 0); sym_p^.symtype := sst_symtype_module_k; {this symbol is a module name} sym_p^.flags := sym_p^.flags + [sst_symflag_def_k, sst_symflag_used_k]; sst_scope_p^.symbol_p := sym_p; {point scope to its defining symbol} sst_opcode_new; {make opcode for this module} sst_opc_p^.opcode := sst_opc_module_k; {this opcode is a module} sst_opc_p^.str_h := str_h; {save source file string handle} sst_opc_p^.module_sym_p := sym_p; {point opcode to module symbol} sst_opcode_pos_push (sst_opc_p^.module_p); {new opcodes are for this module} syo_get_tag_msg ( {get next tag in MODULE_STATEMENT} tag, str_h, 'sst_pas_read', 'statement_module_bad', nil, 0); if tag <> syo_tag_end_k then begin {there should be no tag here} syo_error_tag_unexp (tag, str_h); end; syo_level_up; {back up from MODULE_STATEMENT syntax} end;
unit uCadastraAcoes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ExtCtrls, JvExControls, JvNavigationPane, ComCtrls, JvExComCtrls, JvDBTreeView, DB, DBClient, ZAbstractRODataset, ZDataset, ImgList, funcoes, StdCtrls, Buttons; type TfrmCadastraAcoes = class(TForm) tvMemus: TJvDBTreeView; JvNavPanelHeader1: TJvNavPanelHeader; Bevel1: TBevel; grdAcao: TJvDBUltimGrid; ImageList1: TImageList; qrMenus: TZReadOnlyQuery; dsMenus: TDataSource; cdsAcao: TClientDataSet; cdsAcaoid: TIntegerField; cdsAcaoid_menu: TIntegerField; cdsAcaodescricao: TStringField; dsAcao: TDataSource; qrAcao: TZReadOnlyQuery; btnGrava: TBitBtn; cdsAcaoname: TStringField; btnAlterar: TBitBtn; btnCancelar: TBitBtn; btnSair: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tvMemusGetImageIndex(Sender: TObject; Node: TTreeNode); procedure tvMemusGetSelectedIndex(Sender: TObject; Node: TTreeNode); procedure dsMenusDataChange(Sender: TObject; Field: TField); procedure grdAcaoEnter(Sender: TObject); procedure grdAcaoExit(Sender: TObject); procedure grdAcaoKeyPress(Sender: TObject; var Key: Char); procedure btnGravaClick(Sender: TObject); procedure cdsAcaoAfterInsert(DataSet: TDataSet); procedure cdsAcaoBeforePost(DataSet: TDataSet); procedure cdsAcaoBeforeInsert(DataSet: TDataSet); procedure cdsAcaoAfterCancel(DataSet: TDataSet); procedure cdsAcaoBeforeEdit(DataSet: TDataSet); procedure dsAcaoDataChange(Sender: TObject; Field: TField); procedure btnAlterarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnSairClick(Sender: TObject); private { Private declarations } procedure VeAcao; procedure VeAcaoMenu(const AID_Menu: Integer); procedure GravaAcao; procedure VeEdicao(AEditar: Boolean); public { Public declarations } end; var frmCadastraAcoes: TfrmCadastraAcoes; implementation uses udmPrincipal; {$R *.dfm} procedure TfrmCadastraAcoes.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmCadastraAcoes.FormCreate(Sender: TObject); begin grdAcao.Columns[0].ReadOnly := True; qrMenus.Open; cdsAcao.CreateDataSet; VeAcao; VeEdicao(False); end; procedure TfrmCadastraAcoes.FormDestroy(Sender: TObject); begin qrMenus.Close; cdsAcao.Close; end; procedure TfrmCadastraAcoes.tvMemusGetImageIndex(Sender: TObject; Node: TTreeNode); var idxImagem: integer; begin idxImagem := -1; if Node.Parent = nil then idxImagem := 0 else idxImagem := 1; if not Node.HasChildren then idxImagem := 6; Node.ImageIndex := idxImagem; Node.SelectedIndex := idxImagem; Node.StateIndex := idxImagem; end; procedure TfrmCadastraAcoes.tvMemusGetSelectedIndex(Sender: TObject; Node: TTreeNode); begin if not Node.HasChildren then Node.SelectedIndex := 7; end; procedure TfrmCadastraAcoes.VeAcao; begin cdsAcao.AfterInsert := nil; cdsAcao.BeforePost := nil; try cdsAcao.EmptyDataSet; qrAcao.Close; qrAcao.Open; qrAcao.First; while not qrAcao.Eof do begin cdsAcao.Append; cdsAcaoid.AsInteger := qrAcao.fieldbyname('id').AsInteger; cdsAcaoid_menu.AsInteger := qrAcao.fieldbyname('id_menu').AsInteger; cdsAcaoname.AsString := qrAcao.fieldbyname('name').AsString; cdsAcaodescricao.AsString := qrAcao.fieldbyname('descricao').AsString; cdsAcao.Post; qrAcao.Next; end; finally cdsAcao.AfterInsert := cdsAcaoAfterInsert; cdsAcao.BeforePost := cdsAcaoBeforePost; qrAcao.Close; end; end; procedure TfrmCadastraAcoes.VeAcaoMenu(const AID_Menu: Integer); begin if not cdsAcao.Active then Exit; if cdsAcao.State in [dsEdit, dsInsert] then Exit; cdsAcao.Filtered := False; cdsAcao.Filter := 'id_menu=' + IntToStr(AID_Menu); cdsAcao.Filtered := True; end; procedure TfrmCadastraAcoes.dsMenusDataChange(Sender: TObject; Field: TField); begin VeAcaoMenu(qrMenus.fieldbyname('id').AsInteger); cdsAcao.IndexFieldNames := 'descricao'; end; procedure TfrmCadastraAcoes.grdAcaoEnter(Sender: TObject); begin if btnGrava.Enabled then if (cdsAcao.IsEmpty) and (not (cdsAcao.State in [dsInsert, dsEdit])) then cdsAcao.Append; end; procedure TfrmCadastraAcoes.grdAcaoExit(Sender: TObject); begin if cdsAcao.State in [dsEdit, dsInsert] then if (cdsAcao.State = dsInsert) and (StringEmBranco(cdsAcaodescricao.AsString)) then cdsAcao.Cancel else cdsAcao.Post; end; procedure TfrmCadastraAcoes.grdAcaoKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) and (btnGrava.Enabled) then begin key := #0; if grdAcao.SelectedIndex = 0 then grdAcao.SelectedIndex := 1 else if grdAcao.SelectedIndex = 1 then begin if cdsAcao.State in [dsEdit, dsInsert] then cdsAcao.Post; if (cdsAcao.RecNo = cdsAcao.RecordCount) and (btnGrava.Enabled) then begin grdAcao.SelectedIndex := 0; cdsAcao.Append; end else cdsAcao.Next; end; end; end; procedure TfrmCadastraAcoes.GravaAcao; var qrAcoesGrava: TZReadOnlyQuery; Value, OldValue: string; begin qrAcoesGrava := TZReadOnlyQuery.Create(nil); cdsAcao.DisableControls; try with qrAcoesGrava do begin Connection := dmPrincipal.Database; SQL.Add('INSERT INTO acoes(id,name,descricao,id_menu) VALUES'); SQL.Add('(:id,:name,:descricao,:id_menu)'); //Novas Ações cdsAcao.Filtered := False; cdsAcao.Filter := 'id=0'; cdsAcao.Filtered := True; cdsAcao.IndexFieldNames := 'id'; cdsAcao.First; while not cdsAcao.Eof do begin if not StringEmBranco(cdsAcaoname.AsString) then begin ParamByName('id').AsInteger := RetornaProximoCodigoAcao; ParamByName('name').AsString := cdsAcaoname.AsString; ParamByName('descricao').AsString := cdsAcaodescricao.AsString; ParamByName('id_menu').AsInteger := cdsAcaoid_menu.AsInteger; ExecSQL; end; cdsAcao.Next; end; SQL.Clear; SQL.Add('UPDATE acoes SET descricao=:pDescricao WHERE id=:pID'); //Ações Modificadas cdsAcao.Filtered := False; cdsAcao.Filter := 'id>0'; cdsAcao.Filtered := True; cdsAcao.IndexFieldNames := 'id'; cdsAcao.First; while not cdsAcao.Eof do begin if VarIsNull(cdsAcaodescricao.OldValue) then OldValue := EmptyStr else OldValue := cdsAcaodescricao.OldValue; if VarIsNull(cdsAcaodescricao.Value) then Value := EmptyStr else Value := cdsAcaodescricao.Value; if Value <> OldValue then begin ParamByName('pID').AsInteger := cdsAcaoid.AsInteger; ParamByName('pDescricao').AsString := cdsAcaodescricao.AsString; ExecSQL; end; cdsAcao.Next; end; end; finally FreeAndNil(qrAcoesGrava); cdsAcao.EnableControls; end; end; procedure TfrmCadastraAcoes.btnGravaClick(Sender: TObject); begin GravaAcao; VeAcao; VeAcaoMenu(qrMenus.fieldbyname('id').AsInteger); VeEdicao(False); end; procedure TfrmCadastraAcoes.cdsAcaoAfterInsert(DataSet: TDataSet); begin if cdsAcao.State = dsInsert then begin cdsAcaoid.Value := 0; cdsAcaoid_menu.Value := qrMenus.fieldbyname('id').AsInteger; end; end; procedure TfrmCadastraAcoes.cdsAcaoBeforePost(DataSet: TDataSet); begin if cdsAcao.State in [dsEdit, dsInsert] then begin if StringEmBranco(cdsAcaoname.AsString) then begin MessageBox(handle, 'Você não pode deixar o nome do componente em branco!', 'Erro', mb_ok + mb_IconError); grdAcao.SelectedIndex := 0; Abort; end; if StringEmBranco(cdsAcaodescricao.AsString) then begin cdsAcao.Cancel; Abort; end; end; end; procedure TfrmCadastraAcoes.cdsAcaoBeforeInsert(DataSet: TDataSet); begin cdsAcao.IndexFieldNames := EmptyStr; end; procedure TfrmCadastraAcoes.cdsAcaoAfterCancel(DataSet: TDataSet); begin dsMenusDataChange(nil, nil); end; procedure TfrmCadastraAcoes.cdsAcaoBeforeEdit(DataSet: TDataSet); begin cdsAcao.IndexFieldNames := EmptyStr; end; procedure TfrmCadastraAcoes.dsAcaoDataChange(Sender: TObject; Field: TField); begin grdAcao.Columns[0].ReadOnly := not StringEmBranco(cdsAcaoname.AsString); end; procedure TfrmCadastraAcoes.VeEdicao(AEditar: Boolean); begin btnGrava.Enabled := AEditar; btnCancelar.Enabled := AEditar; btnSair.Enabled := not AEditar; dsAcao.AutoEdit := AEditar; grdAcao.ReadOnly := not AEditar; btnAlterar.Enabled := not AEditar; grdAcao.AutoAppend := AEditar; if AEditar then begin grdAcao.Options := grdAcao.Options - [dgRowSelect] + [dgEditing]; grdAcao.SetFocus; end else grdAcao.Options := grdAcao.Options + [dgRowSelect] - [dgEditing]; end; procedure TfrmCadastraAcoes.btnAlterarClick(Sender: TObject); begin VeEdicao(True); end; procedure TfrmCadastraAcoes.btnCancelarClick(Sender: TObject); begin VeAcao; VeAcaoMenu(qrMenus.fieldbyname('id').AsInteger); VeEdicao(False); end; procedure TfrmCadastraAcoes.btnSairClick(Sender: TObject); begin Close; end; end.
unit ntvPixelGrids; {** * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey * * * Thanks to * * Ref: * https://sites.google.com/a/gorilla3d.com/fpc-docs/built-in-units/fcl-image/filling-the-circle * https://forum.lazarus.freepascal.org/index.php?topic=35424.msg234045 * https://wiki.freepascal.org/Graphics_-_Working_with_TCanvas * https://wiki.freepascal.org/GraphicTest * https://wiki.freepascal.org/Accessing_the_Interfaces_directly * https://wiki.freepascal.org/Fast_direct_pixel_access * http://free-pascal-general.1045716.n5.nabble.com/FPImage-and-GetDataLineStart-td4329151.html * *} {$mode objfpc}{$H+} interface uses LMessages, SysUtils, Classes, Graphics, Controls, Variants, Types, fgl, LCLIntf, LCLType, IntfGraphics, FPImage, FPCanvas, FPImgCanv, GraphType, EasyLazFreeType, LazFreeTypeIntfDrawer, LazCanvas, mnUtils; const cDotSize = 11; cDotPadding = 1; cDefaultWidth = 32; cDefaultHeight = 32; cForeColor = clBlack; cBackColor = clSilver; colWhiteTransparent: TFPColor = (Red: $ffff; Green: $ffff; Blue: $ffff; Alpha: alphaTransparent); colFuchsiaTransparent: TFPColor = (Red: $ffff; Green: $0000; Blue: $ffff; Alpha: alphaTransparent); type TRGBAColor = TFPCompactImgRGBA8BitValue; { TRGBAImage } TRGBAImage = class(TFPCompactImgRGBA8Bit) private function GetRGBAColor(x, y: integer): TRGBAColor; procedure SetRGBAColor(x, y: integer; AValue: TRGBAColor); public function GetDataSize: Integer; procedure CopyPixels(ASource: TRGBAImage); virtual; function AlphaBlend(const color1, color2: TRGBAColor): TRGBAColor; constructor CreateCompatible(AImage: TRGBAImage; AWidth, AHeight: integer); procedure ScalePixels(Source: TRGBAImage; ScaleBy: Integer = 1; WithAlphaBlend: Boolean = True); //1 = no scale procedure FillPixels(const Color: TFPColor); virtual; procedure FillPixels(const Color: TRGBAColor); virtual; property RGBAColors [x, y: integer]: TRGBAColor read GetRGBAColor write SetRGBAColor; default; end; { TLazIntfImageHelper } TLazIntfImageHelper = class helper for TFPCustomImage public procedure ScalePixels(Source: TLazIntfImage; ScaleBy: Integer = 1; WithAlphaBlend: Boolean = True); //1 = no scale end; TImageClass = TPortableNetworkGraphic; TntvPaintTool = class; TPixelGridInfo = record BackColor: TColor; DotSize: Integer; DotPadding: Integer; end; //TDisplayImage = TLazIntfImage; TDisplayImage = TRGBAImage; { TntvHistoryObject } TntvHistoryObject = class(TObject) public Image: TDisplayImage; constructor Create(AImage: TDisplayImage); destructor Destroy; override; end; TntvHistory = class (specialize TFPGObjectList<TntvHistoryObject>) end; { TntvDisplayDots } TntvDisplayDots = class(TPersistent) private FScrachImage: TDisplayImage; FScrachCanvas: TFPImageCanvas; FImage: TDisplayImage; FCanvas: TFPImageCanvas; //FDrawer: TIntfFreeTypeDrawer; FFont: TFreeTypeFont; FOffsetX: Integer; FOffsetY: Integer; FUpdateCount: Integer; FHistory: TntvHistory; ScaledImage: TDisplayImage; //ScaledCanvas: TFPImageCanvas; BackgroundImage: TDisplayImage; BackgroundCanvas: TFPImageCanvas; procedure CanvasChanged(Sender: TObject); function GetFontName: string; function GetHeight: Integer; function GetPixel(x, y: integer): TColor; function GetWidth: Integer; procedure PaintBackground; procedure SetDotPadding(const AValue: Integer); procedure SetDotSize(const AValue: Integer); procedure SetFontName(AValue: string); procedure SetWidth(const AValue: Integer); procedure SetHeight(const AValue: Integer); procedure SetOffsetX(const AValue: Integer); procedure SetOffsetY(const AValue: Integer); function GetUpdating: Boolean; procedure SetPixel(x, y: integer; const AValue: TColor); procedure SetBackColor(const AValue: TColor); protected IsChanged: Boolean; Matrix: TPixelGridInfo; procedure Changed; procedure Invalidate; procedure DoInvalidate; virtual; procedure UpdateSize; procedure PushHistory; procedure PopHistory; property Canvas: TFPImageCanvas read FCanvas; function VisualToReal(VistualPoint: TPoint; out RealPoint: TPoint): Boolean; public constructor Create; virtual; destructor Destroy; override; procedure Paint(vCanvas: TCanvas; vRect: TRect; PaintTool: TntvPaintTool); //y here is the base line of text, bottom of text procedure DrawText(x, y: Integer; AText: string; AColor: TColor); procedure SetSize(const AWidth, AHeight: Integer); procedure SaveToFile(FileName: string); procedure LoadFromFile(FileName: string); procedure BeginUpdate; procedure EndUpdate; procedure Clear; virtual; procedure Reset; virtual; procedure Scroll(x, y: Integer); procedure Assign(Source: TPersistent); override; property Updating: Boolean read GetUpdating; property ScrachImage: TDisplayImage read FScrachImage; property ScrachCanvas: TFPImageCanvas read FScrachCanvas; property Image: TDisplayImage read FImage; property Pixels[x, y:integer] : TColor read GetPixel write SetPixel; property Width: Integer read GetWidth write SetWidth; property Height: Integer read GetHeight write SetHeight; //Scroll the dots property OffsetX: Integer read FOffsetX write SetOffsetX; property OffsetY: Integer read FOffsetY write SetOffsetY; published property BackColor: TColor read Matrix.BackColor write SetBackColor default cBackColor; property DotSize: Integer read Matrix.DotSize write SetDotSize default cDotSize; property DotPadding: Integer read Matrix.DotPadding write SetDotPadding default cDotPadding; property FontName: string read GetFontName write SetFontName; end; TntvPixelGrid = class; { TntvGridDisplayDots } TntvGridDisplayDots = class(TntvDisplayDots) private FControl: TntvPixelGrid; protected procedure DoInvalidate; override; end; TntvPixelGridInfo = record CurrentColor: TColor; CurrentAlpha: Byte; CurrentMerge: Boolean; end; TntvPaintToolStyle = set of ( ptsDirect, //Direct Paint on Canvas, like Pixel and FloodFill ptsEnd //Finish work after first paint (MouseDown) ); { TntvPaintTool } TntvPaintTool = class abstract(TObject) private FControl: TntvPixelGrid; protected FStyle: TntvPaintToolStyle; StartPoint: TPoint; CurrentPoint: TPoint; property Control: TntvPixelGrid read FControl; procedure Created; virtual; public constructor Create(AStartPoint: TPoint; AControl: TntvPixelGrid); virtual; procedure Paint(Canvas: TFPImageCanvas); virtual; abstract; property Style: TntvPaintToolStyle read FStyle; end; TntvPaintToolClass = class of TntvPaintTool; TntvPaintTools = class (specialize TFPGObjectList<TntvPaintTool>) end; { TntvPixel } TntvPixel = class(TntvPaintTool) public procedure Paint(Canvas: TFPImageCanvas); override; procedure Created; override; end; { TntvDraw } TntvDraw = class(TntvPaintTool) public LastPoint: TPoint; procedure Paint(Canvas: TFPImageCanvas); override; procedure Created; override; end; { TntvLine } TntvLine = class(TntvPaintTool) public procedure Paint(Canvas: TFPImageCanvas); override; end; { TntvRectangle } TntvRectangle = class(TntvPaintTool) public procedure Paint(Canvas: TFPImageCanvas); override; end; { TntvCircle } TntvCircle = class(TntvPaintTool) public procedure Paint(Canvas: TFPImageCanvas); override; end; { TntvFill } TntvFill = class(TntvPaintTool) public procedure Created; override; procedure Paint(Canvas: TFPImageCanvas); override; end; { TntvReplaceColor } TntvReplaceColor = class(TntvPaintTool) public procedure Paint(Canvas: TFPImageCanvas); override; end; { TntvPixelGrid } TntvPixelGrid = class(TCustomControl) private FCurrentTool: TntvPaintTool; FCurrentToolClass: TntvPaintToolClass; FDots: TntvDisplayDots; Info: TntvPixelGridInfo; protected procedure FontChanged(Sender: TObject); override; procedure Paint; override; procedure CMBidModeChanged(var Message: TLMessage); message CM_BIDIMODECHANGED; procedure SetCurrentTool(AValue: TntvPaintTool); procedure StartTool(RealPoint: TPoint); virtual; procedure EndTool(Cancel: Boolean); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure EraseBackground(DC: HDC); override; procedure Resize; override; procedure Loaded; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure BeginUpdate; procedure EndUpdate; procedure Clear; property Dots: TntvDisplayDots read FDots; property CurrentToolClass: TntvPaintToolClass read FCurrentToolClass write FCurrentToolClass; property CurrentTool: TntvPaintTool read FCurrentTool; property CurrentColor: TColor read Info.CurrentColor write Info.CurrentColor; property CurrentAlpha: Byte read Info.CurrentAlpha write Info.CurrentAlpha; property CurrentMerge: Boolean read Info.CurrentMerge write Info.CurrentMerge; //TODO published property Align; property Anchors; property Color default cBackColor; property BidiMode; property Font; property ParentBidiMode; property ParentFont; property BorderWidth; property BorderStyle; end; implementation function ToFPColor(AColor: TColor; AAlpha: Byte): TFPColor; begin Result := TColorToFPColor(AColor); Result.Alpha := MAXWORD * AAlpha div 255; end; { TRGBAImage } function TRGBAImage.GetRGBAColor(x, y: integer): TRGBAColor; begin Result := FData[ x + y * Width]; end; procedure TRGBAImage.SetRGBAColor(x, y: integer; AValue: TRGBAColor); begin FData[x + y * Width]:= AValue; end; function TRGBAImage.GetDataSize: Integer; begin Result := SizeOf(TRGBAColor) * Width* Height; end; procedure TRGBAImage.CopyPixels(ASource: TRGBAImage); begin SetSize(ASource.Width, ASource.Height); System.Move(ASource.FData^, FData^, GetDataSize); end; function TRGBAImage.AlphaBlend(const color1, color2: TRGBAColor): TRGBAColor; var factor1, factor2: single; //factor1, factor2: Integer; begin if color2.A = $ff then Result := color2 else if color2.A = 0 then Result := color1 else if color1.A = 0 then Result := color2 else begin factor1 := (color1.A / $ff) * (1 - color2.A / $ff); factor2 := color2.A / $ff; //factor1 := color1.A * ($ff - color2.A) div $ff; //factor2 := color2.A div $ff; Result.R := Round(color1.R * factor1 + color2.R * factor2); Result.G := Round(color1.G * factor1 + color2.G * factor2); Result.B := Round(color1.B * factor1 + color2.B * factor2); Result.A := Round(factor1 * $ff + color2.A); end; end; constructor TRGBAImage.CreateCompatible(AImage: TRGBAImage; AWidth, AHeight: integer); begin Inherited Create(AWidth, AHeight); end; procedure TRGBAImage.ScalePixels(Source: TRGBAImage; ScaleBy: Integer; WithAlphaBlend: Boolean); var x, y: Integer; sx, sy: Integer; dx, dy: integer; begin //BeginUpdate; try //TODO check if source greater than self x := 0; sx := 0; while sx < Source.Width do begin dx := 0; while dx < ScaleBy do begin y := 0; sy := 0; while sy < Source.Height do begin dy := 0; while dy < ScaleBy do begin if WithAlphaBlend then RGBAColors[x, y] := AlphaBlend(RGBAColors[x,y], Source.RGBAColors[sx, sy]) else RGBAColors[x, y] := Source.RGBAColors[sx, sy]; inc(y); inc(dy); end; inc(sy); end; inc(x); inc(dx); end; inc(sx); end; finally //EndUpdate; end; end; procedure TRGBAImage.FillPixels(const Color: TFPColor); var x, y: Integer; begin for y:=0 to Height-1 do for x:=0 to Width-1 do SetInternalColor(x,y,Color); end; procedure TRGBAImage.FillPixels(const Color: TRGBAColor); var x, y: Integer; begin for y:=0 to Height-1 do for x:=0 to Width-1 do RGBAColors[x, y] := Color; end; { TLazIntfImageHelper } procedure TLazIntfImageHelper.ScalePixels(Source: TLazIntfImage; ScaleBy: Integer; WithAlphaBlend: Boolean); var x, y: Integer; sx, sy: Integer; dx, dy: integer; begin //BeginUpdate; try //TODO check if source greater than self x := 0; sx := 0; while sx < Source.Width do begin dx := 0; while dx < ScaleBy do begin y := 0; sy := 0; while sy < Source.Height do begin dy := 0; while dy < ScaleBy do begin if WithAlphaBlend then Colors[x, y] := FPImage.AlphaBlend(Colors[x,y], Source.Colors[sx, sy]) else Colors[x, y] := Source.Colors[sx, sy]; inc(y); inc(dy); end; inc(sy); end; inc(x); inc(dx); end; inc(sx); end; finally //EndUpdate; end; end; { TntvDraw } procedure TntvDraw.Paint(Canvas: TFPImageCanvas); begin Canvas.Pen.FPColor := ToFPColor(Control.CurrentColor, Control.CurrentAlpha); Canvas.Brush.Style := bsClear; Canvas.Line(LastPoint, CurrentPoint); LastPoint := CurrentPoint; end; procedure TntvDraw.Created; begin inherited Created; FStyle := FStyle + [ptsDirect]; LastPoint := CurrentPoint; end; { TntvPaintTool } procedure TntvPaintTool.Created; begin end; constructor TntvPaintTool.Create(AStartPoint: TPoint; AControl: TntvPixelGrid); begin inherited Create; FControl := AControl; StartPoint := AStartPoint; CurrentPoint := AStartPoint; FStyle := []; Created; end; { TntvLine } procedure TntvLine.Paint(Canvas: TFPImageCanvas); begin Canvas.Pen.FPColor := ToFPColor(Control.CurrentColor, Control.CurrentAlpha); Canvas.Brush.Style := bsClear; Canvas.Line(StartPoint, CurrentPoint); end; { TntvReplaceColor } procedure TntvReplaceColor.Paint(Canvas: TFPImageCanvas); begin //Canvas. end; { TntvFill } procedure TntvFill.Created; begin inherited Created; FStyle := FStyle + [ptsDirect, ptsEnd]; end; procedure TntvFill.Paint(Canvas: TFPImageCanvas); var c: TFPColor; begin c := ToFPColor(Control.CurrentColor, Control.CurrentAlpha); if Canvas.Image.Colors[CurrentPoint.X, CurrentPoint.Y] <> c then begin //Canvas.Pen.FPColor := c; Canvas.Brush.Style := bsSolid; Canvas.Brush.FPColor := c; Canvas.FloodFill(CurrentPoint.X, CurrentPoint.Y); end; end; { TntvCircle } procedure TntvCircle.Paint(Canvas: TFPImageCanvas); begin Canvas.Pen.FPColor := ToFPColor(Control.CurrentColor, Control.CurrentAlpha); Canvas.Brush.Style := bsClear; Canvas.Ellipse(StartPoint.x, StartPoint.y, CurrentPoint.x, CurrentPoint.y); end; { TntvRectangle } procedure TntvRectangle.Paint(Canvas: TFPImageCanvas); begin Canvas.Pen.FPColor := ToFPColor(Control.CurrentColor, Control.CurrentAlpha); Canvas.Brush.Style := bsClear; Canvas.Rectangle(StartPoint.x, StartPoint.y, CurrentPoint.x, CurrentPoint.y); end; { TntvHistoryObject } constructor TntvHistoryObject.Create(AImage: TDisplayImage); begin inherited Create; Image := AImage; end; destructor TntvHistoryObject.Destroy; begin inherited Destroy; FreeAndNil(Image); end; { TntvPixel } procedure TntvPixel.Paint(Canvas: TFPImageCanvas); begin Canvas.Colors[CurrentPoint.x, CurrentPoint.y] := ToFPColor(Control.CurrentColor, Control.CurrentAlpha); end; procedure TntvPixel.Created; begin inherited Created; FStyle := FStyle + [ptsDirect]; end; { TntvPaintTool } { TntvGridDisplayDots } procedure TntvGridDisplayDots.DoInvalidate; begin inherited DoInvalidate; if FControl <> nil then FControl.Invalidate; end; function TntvDisplayDots.GetFontName: string; begin Result := FFont.Name; end; { TntvPixelGrid } constructor TntvPixelGrid.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csCaptureMouse, csDoubleClicks] - [csOpaque]; FDots := TntvGridDisplayDots.Create; (FDots as TntvGridDisplayDots).FControl:= Self; Color := cBackColor; Info.CurrentColor := clBlack; Info.CurrentAlpha := 255; CurrentToolClass := TntvPixel; end; destructor TntvPixelGrid.Destroy; begin EndTool(True); FreeAndNil(FDots); inherited; end; procedure TntvPixelGrid.SetCurrentTool(AValue: TntvPaintTool); begin if FCurrentTool = AValue then Exit; FCurrentTool := AValue; Dots.Changed; end; procedure TntvPixelGrid.StartTool(RealPoint: TPoint); begin EndTool(True); FCurrentTool := FCurrentToolClass.Create(RealPoint, Self); end; procedure TntvPixelGrid.EndTool(Cancel: Boolean); begin if FCurrentTool <> nil then begin if not Cancel then begin if not (ptsDirect in FCurrentTool.Style) then Dots.Image.CopyPixels(Dots.ScrachImage); end; FreeAndNil(FCurrentTool); end; end; procedure TntvPixelGrid.FontChanged(Sender: TObject); begin inherited FontChanged(Sender); end; procedure TntvPixelGrid.Paint; begin inherited; Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); Dots.Paint(Canvas, ClientRect, CurrentTool); end; procedure TntvPixelGrid.EraseBackground(DC: HDC); begin //To reduce the flicker do not inherite end; procedure TntvPixelGrid.CMBidModeChanged(var Message: TLMessage); begin BeginUpdate; try Inherited; finally EndUpdate; end; end; procedure TntvPixelGrid.Resize; begin inherited; if not (csLoading in ComponentState) then begin end; end; procedure TntvPixelGrid.Loaded; begin inherited Loaded; end; procedure TntvPixelGrid.MouseMove(Shift: TShiftState; X, Y: Integer); var RealPoint: TPoint; begin inherited; if FCurrentTool <> nil then if Dots.VisualToReal(Point(X, Y), RealPoint) then begin if (RealPoint.X <> FCurrentTool.CurrentPoint.X) or (RealPoint.Y <> FCurrentTool.CurrentPoint.Y) then begin FCurrentTool.CurrentPoint := RealPoint; Dots.ScrachImage.CopyPixels(Dots.Image); FCurrentTool.Paint(Dots.ScrachCanvas); if ptsDirect in FCurrentTool.Style then Dots.Image.CopyPixels(Dots.ScrachImage); Dots.Changed; end; end; end; procedure TntvPixelGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; EndTool(False); end; procedure TntvPixelGrid.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if Shift = [] then begin case Key of VK_ESCAPE: EndTool(True); end; end else if Shift = [ssCtrl] then begin case Key of VK_Z: Dots.PopHistory; end; end; end; procedure TntvPixelGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var RealPoint: TPoint; begin inherited; SetFocus; if Dots.VisualToReal(Point(X, Y), RealPoint) then begin if FCurrentToolClass <> nil then begin Dots.PushHistory; StartTool(RealPoint); Dots.ScrachImage.CopyPixels(Dots.Image); FCurrentTool.Paint(Dots.ScrachCanvas); if ptsDirect in FCurrentTool.Style then Dots.Image.CopyPixels(Dots.ScrachImage); if ptsEnd in FCurrentTool.Style then EndTool(True); Dots.Changed; end; end else ReleaseCapture; end; procedure TntvPixelGrid.BeginUpdate; begin Dots.BeginUpdate; end; procedure TntvPixelGrid.EndUpdate; begin Dots.EndUpdate; end; procedure TntvPixelGrid.Clear; begin Dots.Clear; end; { TntvDisplayDots } procedure TntvDisplayDots.BeginUpdate; begin Inc(FUpdateCount); end; procedure TntvDisplayDots.Paint(vCanvas: TCanvas; vRect: TRect; PaintTool: TntvPaintTool); var Img: TBitmap; tt, t, td: int64; procedure printdiff(s: string); begin tt := GetTickCount64; td := tt - t; t := tt; WriteLn(s + ': ' , td); end; begin t := GetTickCount64; if IsChanged then begin IsChanged := False; ScaledImage.CopyPixels(BackgroundImage); printdiff('copy'); //ScaledCanvas.DrawingMode := dmAlphaBlend; //ScaledCanvas.Interpolation := TFPBoxInterpolation.Create; moved to after create ScaledCanvas //ScaledCanvas.Draw(0, 0, ScrachImage); for testing //ScaledCanvas.StretchDraw(0, 0, ScaledImage.Width, ScaledImage.Height, ScrachImage); ScaledImage.ScalePixels(ScrachImage, DotSize, True); //still slow printdiff('scale'); end; //(vCanvas as TFPCustomCanvas).Draw(0, 0, ScaledImage); //very slow than loading it into bmp Img := CreateBitmapFromFPImage(ScaledImage); //maybe make it as cache printdiff('bitmap'); try vCanvas.Draw(0, 0, Img); printdiff('draw'); finally Img.Free; end; end; procedure TntvDisplayDots.PaintBackground; procedure DrawIt(Canvas: TFPImageCanvas; x: integer; y: integer); var R: TRect; d: Integer; begin Canvas.Brush.Style := bsSolid; R.Left := x; R.Top := y; R.Right := R.Left + DotSize - 1; R.Bottom := R.Top + DotSize - 1; Canvas.Brush.FPColor := colBlack; Canvas.FillRect(R); R.Left := x; R.Top := y; R.Right := R.Left + DotSize - DotPadding - 1; R.Bottom := R.Top + DotSize - DotPadding - 1; Canvas.Brush.FPColor := colLtGray; Canvas.FillRect(R); Canvas.Brush.FPColor := colWhite; d := (DotSize - DotPadding) div 2; R.Left := x; R.Top := y; R.Right := R.Left + d - 1; R.Bottom := R.Top + d - 1 ; Canvas.FillRect(R); R.Left := x + d; R.Top := y + d; R.Right := R.Left + d - 1; R.Bottom := R.Top + d - 1; Canvas.FillRect(R); end; var x, y: integer; ix, iy: integer; begin y := 0; iy := 0; while iy < Height do begin x := 0; ix := 0; while ix < Width do begin DrawIt(BackgroundCanvas, x, y); x := x + DotSize; Inc(ix); end; y := y + DotSize; Inc(iy); end; end; procedure TntvDisplayDots.DrawText(x, y: Integer; AText: string; AColor: TColor); begin //FDrawer.DrawText(AText, FFont, x, y, TColorToFPColor(AColor)); Changed; end; procedure TntvDisplayDots.SetSize(const AWidth, AHeight: Integer); begin FImage.SetSize(AWidth, AHeight); UpdateSize; end; procedure TntvDisplayDots.SaveToFile(FileName: string); var png: TPortableNetworkGraphic; begin png := TPortableNetworkGraphic.Create; try //png.LoadFromIntfImage(FImage); png.Transparent := True; png.SaveToFile(FileName); finally png.Free; end; end; procedure TntvDisplayDots.LoadFromFile(FileName: string); var png: TPortableNetworkGraphic; begin png := TPortableNetworkGraphic.Create; try png.LoadFromFile(FileName); //FImage.LoadFromBitmap(png.Handle, png.MaskHandle); UpdateSize; finally png.Free; end; end; procedure TntvDisplayDots.EndUpdate; begin if FUpdateCount > 0 then begin Dec(FUpdateCount); if (FUpdateCount = 0) then Changed; end; end; procedure TntvDisplayDots.Clear; begin FImage.FillPixels(colWhiteTransparent); FScrachImage.FillPixels(colWhiteTransparent); Changed; end; procedure TntvDisplayDots.Reset; begin BeginUpdate; try OffsetX := 0; OffsetY := 0; Clear; finally EndUpdate; end; end; procedure TntvDisplayDots.Scroll(x, y: Integer); begin BeginUpdate; try FOffsetX := FOffsetX + x; if Abs(FOffsetX) >= Width - 1 then FOffsetX := 0; FOffsety := FOffsety + y; if Abs(FOffsetY) >= Height - 1 then FOffsetY := 0; finally EndUpdate; end; end; procedure TntvDisplayDots.Assign(Source: TPersistent); begin if Source is TntvDisplayDots then begin end else inherited; end; function TntvDisplayDots.GetUpdating: Boolean; begin Result := FUpdateCount > 0; end; procedure TntvDisplayDots.Invalidate; begin if not Updating then DoInvalidate; end; procedure TntvDisplayDots.DoInvalidate; begin end; procedure TntvDisplayDots.UpdateSize; begin ScrachImage.SetSize(Width, Height); ScaledImage.SetSize(Width * DotSize, Height * DotSize); BackgroundImage.SetSize(Width * DotSize, Height * DotSize); PaintBackground; ScrachImage.CopyPixels(Image); Changed; end; procedure TntvDisplayDots.PushHistory; var AImage: TDisplayImage; begin //AImage := TLazIntfImage.CreateCompatible(FImage, FImage.Width, FImage.Height); AImage := TDisplayImage.CreateCompatible(FImage, FImage.Width, FImage.Height); AImage.CopyPixels(FImage); FHistory.Add(TntvHistoryObject.Create(AImage)); if FHistory.Count > 20 then FHistory.Delete(0); end; procedure TntvDisplayDots.PopHistory; var AImage: TDisplayImage; begin if FHistory.Count > 0 then begin AImage := FHistory.Last.Image; Image.CopyPixels(AImage); ScrachImage.CopyPixels(AImage); FHistory.Delete(FHistory.Count - 1); Changed; end; end; function TntvDisplayDots.VisualToReal(VistualPoint: TPoint; out RealPoint: TPoint): Boolean; var aSize: Integer; begin if (VistualPoint.x >= 0) and (VistualPoint.y >= 0) then begin aSize := Matrix.DotSize; RealPoint.x := (VistualPoint.x + aSize) div aSize - 1; RealPoint.y := (VistualPoint.y + aSize) div aSize - 1; Result := (RealPoint.x < Width) and (RealPoint.y < Height); end else Result := False; end; procedure TntvDisplayDots.SetDotPadding(const AValue: Integer); begin if Matrix.DotPadding <> AValue then begin Matrix.DotPadding := AValue; Changed; end; end; procedure TntvDisplayDots.CanvasChanged(Sender: TObject); begin Changed; end; function TntvDisplayDots.GetHeight: Integer; begin Result := FImage.Height; end; function TntvDisplayDots.GetPixel(x, y: integer): TColor; begin Result := FPColorToTColor(Image.Colors[x, y]); end; function TntvDisplayDots.GetWidth: Integer; begin Result := FImage.Width; end; procedure TntvDisplayDots.SetHeight(const AValue: Integer); begin if FImage.Height <> AValue then begin SetSize(Width, AValue); end; end; procedure TntvDisplayDots.SetOffsetX(const AValue: Integer); begin if FOffsetX <> AValue then begin FOffsetX := AValue; Changed; end; end; procedure TntvDisplayDots.SetOffsetY(const AValue: Integer); begin if FOffsetY <> AValue then begin FOffsetY := AValue; Changed; end; end; procedure TntvDisplayDots.SetPixel(x, y: integer; const AValue: TColor); begin Image.Colors[x, y] := TColorToFPColor(AValue); Changed; end; procedure TntvDisplayDots.SetWidth(const AValue: Integer); begin if FImage.Width <> AValue then begin SetSize(AValue, Height); end; end; constructor TntvDisplayDots.Create; begin inherited; Matrix.BackColor := cBackColor; Matrix.DotSize := cDotSize; Matrix.DotPadding := cDotPadding; FImage := TDisplayImage.Create(cDefaultWidth, cDefaultHeight{, [riqfRGB, riqfAlpha]}); FCanvas := TFPImageCanvas.Create(FImage); //FDrawer := TIntfFreeTypeDrawer.Create(FImage); FFont := TFreeTypeFont.Create; FFont.Name := 'c:\Windows\fonts\Arial.ttf'; FFont.SizeInPixels := 9; FFont.Hinted := False; FFont.ClearType := False; FFont.Quality := grqLowQuality; FScrachImage := TDisplayImage.CreateCompatible(FImage, cDefaultWidth, cDefaultHeight); FScrachCanvas := TFPImageCanvas.Create(FScrachImage); ScaledImage := TDisplayImage.CreateCompatible(ScrachImage, ScrachImage.Width * DotSize, ScrachImage.Height * DotSize); //ScaledCanvas := TFPImageCanvas.Create(ScaledImage); //ScaledCanvas.Interpolation := TFPBoxInterpolation.Create; BackgroundImage := TDisplayImage.CreateCompatible(ScrachImage, ScrachImage.Width * DotSize, ScrachImage.Height * DotSize); BackgroundCanvas := TFPImageCanvas.Create(BackgroundImage); FHistory := TntvHistory.Create; SetSize(cDefaultWidth, cDefaultHeight); Clear; end; procedure TntvDisplayDots.SetDotSize(const AValue: Integer); begin if Matrix.DotSize <> AValue then begin Matrix.DotSize := AValue; Changed; end; end; procedure TntvDisplayDots.SetFontName(AValue: string); begin FFont.Name := AValue; end; destructor TntvDisplayDots.Destroy; begin BackgroundImage.Free; BackgroundCanvas.Free; ScaledImage.Free; //ScaledCanvas.Interpolation.Free; //ScaledCanvas.Free; FreeAndNil(FHistory); FreeAndNil(FCanvas); FreeAndNil(FScrachCanvas); //FreeAndNil(FDrawer); FreeAndNil(FFont); FreeAndNil(FImage); FreeAndNil(FScrachImage); inherited; end; procedure TntvDisplayDots.SetBackColor(const AValue: TColor); begin if Matrix.BackColor <> AValue then begin Matrix.BackColor := AValue; Changed; end; end; procedure TntvDisplayDots.Changed; begin IsChanged := True; Invalidate; end; end.
unit nsProgressDialog; interface uses Windows, SysUtils, nsDownloaderInterfaces, nscSystemProgressDialog; type TnsDownloadProgressDialog = class(TInterfacedObject, InsDownloadProgressDialog, InsDownloaderStateObserver) private FDialog: IProgressDialog; FDownloader: Pointer; procedure InitDialog; constructor Create(const ADownloader: InsAsyncDownloader); protected function GetDownloader: InsAsyncDownloader; procedure NotifyDownloaderStateChanged(const ADownloaderState: InsDownloaderState); procedure StopProgressDialog; property Downloader: InsAsyncDownloader read GetDownloader; public class function Make(const ADownloader: InsAsyncDownloader): InsDownloadProgressDialog; destructor Destroy; override; end; implementation uses ActiveX, ShlObj, Classes, Forms; function AnsiToWide(aText: AnsiString): WideString; var l_wText: PWideChar; l_ansiSize: integer; l_wideSize: integer; begin l_wText := nil; Result := ''; if (aText = '') then Exit; try l_ansiSize := Length(aText) + 1; l_wideSize := l_ansiSize * SizeOf(WideChar); l_wText := AllocMem(l_wideSize); try MultiByteToWideChar(CP_ACP, 0, PChar(aText), l_ansiSize, l_wText, l_wideSize); Result := l_wText; finally FreeMem(l_wText); end; except end; end; { TnsDownloadProgressDialog } procedure TnsDownloadProgressDialog.InitDialog; var l_Title: WideString; l_nilPointer: Pointer; l_S1: WideString; l_S2: WideString; l_S3: WideString; begin FDialog := GetProgressDialog; Assert(FDialog <> nil); l_Title := Application.Title; l_nilPointer := nil; l_S1 := 'Загрузка файла'; l_S2 := Downloader.DownloadParams.URL; l_S3 := Downloader.DownloadParams.FileName; FDialog.SetTitle(PWideChar(l_Title)); FDialog.SetLine(1, PWideChar(l_S1), True, l_nilPointer); FDialog.SetLine(2, PWideChar(l_S2), True, l_nilPointer); FDialog.SetLine(3, PWideChar(l_S3), True, l_nilPointer); FDialog.StartProgressDialog(0, nil, PROGDLG_NORMAL, l_nilPointer); Sleep(2000); end; constructor TnsDownloadProgressDialog.Create(const ADownloader: InsAsyncDownloader); var l_Downloader: InsAsyncDownloader; l_State: InsDownloaderState; begin inherited Create; Assert(ADownloader <> nil); FDownloader := Pointer(ADownloader); l_Downloader := Downloader; Assert(l_Downloader <> nil); l_State := l_Downloader.State; Assert(l_State <> nil); l_State.Subscribe(Self); InitDialog; end; function TnsDownloadProgressDialog.GetDownloader: InsAsyncDownloader; begin Result := InsAsyncDownloader(FDownloader); end; procedure TnsDownloadProgressDialog.NotifyDownloaderStateChanged(const ADownloaderState: InsDownloaderState); begin FDialog.SetProgress(ADownloaderState.Current, ADownloaderState.Total); ADownloaderState.CancelledByUser := FDialog.HasUserCancelled; end; procedure TnsDownloadProgressDialog.StopProgressDialog; var l_DlgHWND: HWND; l_OleWindow: IOleWindow; l_hr: HRESULT; begin if (FDialog <> nil) then begin if Supports(FDialog, IOleWindow, l_OleWindow) then try if (not Succeeded(l_OleWindow.GetWindow(l_DlgHWND))) then l_DlgHWND := 0; finally l_OleWindow := nil; end; FDialog.StopProgressDialog; if (l_DlgHWND <> 0) then ShowWindow(l_DlgHWND, SW_HIDE); Application.ProcessMessages; FDialog := nil; end; end; class function TnsDownloadProgressDialog.Make(const ADownloader: InsAsyncDownloader): InsDownloadProgressDialog; var l_Inst: InsDownloadProgressDialog; begin l_Inst := Create(ADownloader); Result := l_Inst; end; destructor TnsDownloadProgressDialog.Destroy; begin if (FDialog <> nil) then FDialog.StopProgressDialog; FDialog := nil; if (Downloader <> nil) then Downloader.State.Unsubscribe(Self); FDownloader := nil; inherited; end; end.
unit GetTeamActivitiesUnit; interface uses SysUtils, BaseExampleUnit; type TGetTeamActivities = class(TBaseExample) public procedure Execute(RouteId: String; Limit, Offset: integer); end; implementation uses ActivityUnit; procedure TGetTeamActivities.Execute(RouteId: String; Limit, Offset: integer); var ErrorString: String; Activities: TActivityList; Activity: TActivity; Total: integer; begin Activities := Route4MeManager.ActivityFeed.GetTeamActivities( RouteId, Limit, Offset, Total, ErrorString); try WriteLn(''); if (Activities <> nil) and (Activities.Count > 0) then begin WriteLn(Format('GetActivities executed successfully, %d activities returned', [Activities.Count])); WriteLn(''); for Activity in Activities do WriteLn(Format('Activity id: %s', [Activity.Id.Value])); WriteLn(''); end else WriteLn(Format('GetActivities error: "%s"', [ErrorString])); finally FreeAndNil(Activities); end; end; end.
unit CsNotifier; { $Id: CsNotifier.pas,v 1.12 2013/04/24 09:35:37 lulin Exp $ } // $Log: CsNotifier.pas,v $ // Revision 1.12 2013/04/24 09:35:37 lulin // - портируем. // // Revision 1.11 2013/04/19 13:09:32 lulin // - портируем. // // Revision 1.10 2009/07/22 08:20:23 narry // - новая процедура KeepAlive // - cleanup // // Revision 1.9 2008/03/20 09:48:27 lulin // - cleanup. // // Revision 1.8 2008/02/07 14:44:35 lulin // - класс _Tl3LongintList переехал в собственный модуль. // // Revision 1.7 2007/01/17 08:44:28 lulin // - поменял местами создание списка и и захват критической секции для его наполнения. Пытаемся бороться с dead-lock'ами. // // Revision 1.6 2006/11/22 16:23:56 fireton // - подготовка к большому UserID // // Revision 1.5 2006/03/16 15:50:16 narry // - еще один шажок в сторону клиент-сервера // // Revision 1.4 2006/03/10 09:29:12 voba // - enh. убрал CsFree etc. // // Revision 1.3 2006/03/09 11:47:12 narry // - изменение: новая технология передачи заданий // // Revision 1.2 2006/02/08 17:24:29 step // выполнение запросов перенесено из классов-потомков в процедуры объектов // {$I CsDefine.inc} interface uses IdGlobal, IdIOHandler, IdUdpClient, CsCommon, CsObject, CsNotification, CsActiveClients, CsConst {$IfDef XE} , System.SyncObjs {$EndIf XE} ; const c_MaxNotificationLength = 512; c_AllClients = High(TCsClientId); type TCsNotifier = class(TCsObject) private f_CriticalSection: TCriticalSection; f_UdpClient: TIdUdpClient; f_ActiveClients: TCsActiveClients; protected procedure Cleanup; override; public constructor Create(aActiveClients: TCsActiveClients); procedure Send(aClientId: TCsClientId; aNotification: TCsNotification); procedure Broadcast(aNotification: TCsNotification; aExcepting: TCsClientId = c_WrongClientId); procedure SendNotify(aClientId: TCsClientId; aType: TCsNotificationType; aNumber: Integer; const aText: string); overload; procedure SendNotify(const aIP: String; aPort: Integer; aType: TCsNotificationType; aNumber: Integer; const aText: string); overload; end; implementation { TCsNotifier } uses Classes, l3Base, l3LongintList ; procedure TCsNotifier.Broadcast(aNotification: TCsNotification; aExcepting: TCsClientId); var l_Ids: Tl3LongintList; I: Integer; begin l_Ids := Tl3LongintList.Make; try f_CriticalSection.Enter; try f_ActiveClients.AllClientIds(l_Ids); for I := 0 to l_Ids.Hi do if (TCsClientId(l_Ids[I]) <> aExcepting) then Send(TCsClientId(l_Ids[I]), aNotification); finally f_CriticalSection.Leave; end;//try..finally finally l3Free(l_Ids); end;//try..finally end; procedure TCsNotifier.Cleanup; begin l3Free(f_UdpClient); l3Free(f_CriticalSection); f_ActiveClients := nil; inherited; end; constructor TCsNotifier.Create(aActiveClients: TCsActiveClients); begin inherited Create; Assert(aActiveClients <> nil); f_ActiveClients := aActiveClients; f_CriticalSection := TCriticalSection.Create; f_UdpClient := TIdUdpClient.Create; f_UdpClient.BufferSize := c_MaxNotificationLength; end; procedure TCsNotifier.Send(aClientId: TCsClientId; aNotification: TCsNotification); var l_ListenerIp: TCsIp; l_ListenerPort: TCsPort; begin f_CriticalSection.Enter; try if f_ActiveClients.FindAddress(aClientId, l_ListenerIp, l_ListenerPort) then f_UdpClient.SendBuffer(l_ListenerIp, l_ListenerPort, TidBytes(aNotification.AsBytes)); finally f_CriticalSection.Leave; end; end; procedure TCsNotifier.SendNotify(aClientId: TCsClientId; aType: TCsNotificationType; aNumber: Integer; const aText: string); var l_N: TCsNotification; begin l_N := TCSNotification.Create(aType, aNumber, aText); try if aClientID <> c_AllClients then Send(aClientID, l_N) else Broadcast(l_N); finally l3Free(l_N); end; end; procedure TCsNotifier.SendNotify(const aIP: String; aPort: Integer; aType: TCsNotificationType; aNumber: Integer; const aText: string); var l_N: TCsNotification; begin l_N := TCSNotification.Create(aType, aNumber, aText); try f_CriticalSection.Enter; try f_UdpClient.SendBuffer(aIp, aPort, TidBytes(l_N.AsBytes)); finally f_CriticalSection.Leave; end; finally l3Free(l_N); end; end; end.
{***********************************************************} { } { Ace Reporter - Export Filter Extensions } { } { Copyright © 2000-2004 Gnostice Information Technologies } { http://www.gnostice.com } { Developed for SCT Associates, Inc. } { } {***********************************************************} unit AceXport; interface uses windows, SysUtils, Classes, Graphics, Forms, AceUtil, AceTypes; type TAceExportFilter = class(TComponent) private FActive: Boolean; FDisplayName: string; FFileExtension: string; FIsGraphicExport: Boolean; procedure SetActive(Value: Boolean); protected FMainStream: TStream; FFileName: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure GenerateToFile(AceFileStream: TStream; FileName: string; CurrentPage: Integer); virtual; abstract; procedure GenerateToStream(AceFileStream: TStream; UserStream: TStream; CurrentPage: Integer); virtual; abstract; procedure BeginDoc; virtual; abstract; procedure EndDoc; virtual; abstract; procedure BeginPage; virtual; abstract; procedure EndPage; virtual; abstract; procedure SetFont(Font: TFont); virtual; abstract; procedure SetLogFont(Font: TFont; LogFont: TAceLogFont); virtual; abstract; procedure SetPen(Pen: TPen); virtual; abstract; procedure SetBrush(Brush: TBrush); virtual; abstract; procedure SetTextAlign(Flags: Word); virtual; abstract; procedure Textout(X, Y: Integer; const Text: string); virtual; abstract; procedure MoveTo(X, Y: Integer); virtual; abstract; procedure LineTo(X, Y: Integer); virtual; abstract; procedure PTextout(X, Y: Integer; Text: PChar; Count: LongInt); virtual; abstract; procedure ExtTextout(X, Y: Integer; Options: Word; Rect: TRect; Text: PChar; Count: Word); virtual; abstract; procedure TextRect(Rect: TRect; X, Y: Integer; const Text: string); virtual; abstract; procedure FillRect(Rect: TRect); virtual; abstract; procedure Rectangle(X1, Y1, X2, Y2: Integer); virtual; abstract; procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); virtual; abstract; procedure Ellipse(X1, Y1, X2, Y2: Integer); virtual; abstract; procedure Draw(X, Y: Integer; Graphic: TGraphic); virtual; abstract; procedure StretchDraw(Rect: TRect; Graphic: TGraphic); virtual; abstract; procedure DrawBitmap(X, Y: Integer; Stream: TStream); virtual; abstract; procedure StretchDrawBitmap(Rect: TRect; Stream: TStream); virtual; abstract; procedure ShadeRect(Rect: TRect; Shade: TAceShadePercent); virtual; abstract; procedure SetBkColor(bkColor: LongInt); virtual; abstract; procedure TextJustify(Rect: TRect; X, Y: Integer; const Text: string; EndParagraph: Boolean; FullRect: TRect); virtual; abstract; procedure RtfDraw(Rect: TRect; Stream: TStream; StartPos, EndPos: LongInt; SetDefFont: Boolean); virtual; abstract; procedure DrawCheckBox(Rect: TRect; CheckStyle: TAceCheckStyle; Color: TColor; Thickness: Integer); virtual; abstract; procedure DrawShapeType(dt: TAceDrawType; X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); virtual; abstract; procedure PolyDrawType(pt: TAcePolyType; const Points: array of TPoint; Count: Integer); virtual; abstract; procedure Print3of9Barcode( Left, Top, Width, Height, NarrowWidth, WideWidth: Integer; Inches, Vertical: Boolean; BarData: String); virtual; abstract; procedure Print2of5Barcode( Left, Top, Width, Height, NarrowWidth, WideWidth: Integer; Inches, Vertical: Boolean; BarData: String); virtual; abstract; property IsGraphicExport: Boolean read FIsGraphicExport write FIsGraphicExport; published property Active: Boolean read FActive write SetActive default True; property DisplayName: string read FDisplayName write FDisplayName; property FileExtension: string read FFileExtension write FFileExtension; end; procedure RegisterAceFilter(ExportFilter: TAceExportFilter); procedure UnRegisterAceFilter(ExportFilter: TAceExportFilter); var ExportFiltersList: TList; implementation uses dialogs; {------------------------------------------------------------------------------} procedure RegisterAceFilter(ExportFilter: TAceExportFilter); begin {$ifndef VER_EXCLUDE_PRO} if not Assigned(ExportFiltersList) then ExportFiltersList := TList.Create; if ExportFiltersList.IndexOf(ExportFilter) = -1 then ExportFiltersList.Add(ExportFilter); {$else} ShowMessage('Export Filters are only supported in ACE Professional'+AceVersion); {$endif} end; {------------------------------------------------------------------------------} procedure UnRegisterAceFilter(ExportFilter: TAceExportFilter); var I: Integer; begin {$ifndef VER_EXCLUDE_PRO} if Assigned(ExportFiltersList) then begin I := ExportFiltersList.IndexOf(ExportFilter); if I >= 0 then ExportFiltersList.Delete(I); if ExportFiltersList.Count < 1 then begin ExportFiltersList.Free; ExportFiltersList := nil; end; end; {$endif} end; {------------------------------------------------------------------------------} { TAceExportFilter } constructor TAceExportFilter.Create(AOwner: TComponent); begin inherited Create(AOwner); Active := True; end; {------------------------------------------------------------------------------} destructor TAceExportFilter.Destroy; begin UnRegisterAceFilter(Self); inherited Destroy; end; {------------------------------------------------------------------------------} procedure TAceExportFilter.SetActive(Value: Boolean); begin if Value then RegisterAceFilter(Self) else UnRegisterAceFilter(Self); FActive := Value; end; {------------------------------------------------------------------------------} end.
// // opus_multistream.h header binding for the Free Pascal Compiler aka FPC // // Binaries and demos available at http://www.djmaster.com/ // (* Copyright (c) 2011 Xiph.Org Foundation Written by Jean-Marc Valin *) (* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) (** * @file opus_multistream.h * @brief Opus reference implementation multistream API *) unit opus_multistream; {$mode objfpc}{$H+} interface uses ctypes, opus; const LIB_OPUS = 'libopus-0.dll'; // #ifndef OPUS_MULTISTREAM_H // #define OPUS_MULTISTREAM_H // #include "opus.h" // #ifdef __cplusplus // extern "C" { // #endif (** @cond OPUS_INTERNAL_DOC *) (** Macros to trigger compilation errors when the wrong types are provided to a * CTL. *) (**@{*) //TODO #define __opus_check_encstate_ptr(ptr) ((ptr) + ((ptr) - (OpusEncoder**)(ptr))) //TODO #define __opus_check_decstate_ptr(ptr) ((ptr) + ((ptr) - (OpusDecoder**)(ptr))) (**@}*) (** These are the actual encoder and decoder CTL ID numbers. * They should not be used directly by applications. * In general, SETs should be even and GETs should be odd.*) (**@{*) const OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST = 5120; OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST = 5122; (**@}*) (** @endcond *) (** @defgroup opus_multistream_ctls Multistream specific encoder and decoder CTLs * * These are convenience macros that are specific to the * opus_multistream_encoder_ctl() and opus_multistream_decoder_ctl() * interface. * The CTLs from @ref opus_genericctls, @ref opus_encoderctls, and * @ref opus_decoderctls may be applied to a multistream encoder or decoder as * well. * In addition, you may retrieve the encoder or decoder state for an specific * stream via #OPUS_MULTISTREAM_GET_ENCODER_STATE or * #OPUS_MULTISTREAM_GET_DECODER_STATE and apply CTLs to it individually. *) (**@{*) (** Gets the encoder state for an individual stream of a multistream encoder. * @param[in] x <tt>opus_int32</tt>: The index of the stream whose encoder you * wish to retrieve. * This must be non-negative and less than * the <code>streams</code> parameter used * to initialize the encoder. * @param[out] y <tt>OpusEncoder**</tt>: Returns a pointer to the given * encoder state. * @retval OPUS_BAD_ARG The index of the requested stream was out of range. * @hideinitializer *) //TODO #define OPUS_MULTISTREAM_GET_ENCODER_STATE(x,y) OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST, __opus_check_int(x), __opus_check_encstate_ptr(y) (** Gets the decoder state for an individual stream of a multistream decoder. * @param[in] x <tt>opus_int32</tt>: The index of the stream whose decoder you * wish to retrieve. * This must be non-negative and less than * the <code>streams</code> parameter used * to initialize the decoder. * @param[out] y <tt>OpusDecoder**</tt>: Returns a pointer to the given * decoder state. * @retval OPUS_BAD_ARG The index of the requested stream was out of range. * @hideinitializer *) //TODO #define OPUS_MULTISTREAM_GET_DECODER_STATE(x,y) OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST, __opus_check_int(x), __opus_check_decstate_ptr(y) (**@}*) (** @defgroup opus_multistream Opus Multistream API * @{ * * The multistream API allows individual Opus streams to be combined into a * single packet, enabling support for up to 255 channels. Unlike an * elementary Opus stream, the encoder and decoder must negotiate the channel * configuration before the decoder can successfully interpret the data in the * packets produced by the encoder. Some basic information, such as packet * duration, can be computed without any special negotiation. * * The format for multistream Opus packets is defined in * <a href="https://tools.ietf.org/html/rfc7845">RFC 7845</a> * and is based on the self-delimited Opus framing described in Appendix B of * <a href="https://tools.ietf.org/html/rfc6716">RFC 6716</a>. * Normal Opus packets are just a degenerate case of multistream Opus packets, * and can be encoded or decoded with the multistream API by setting * <code>streams</code> to <code>1</code> when initializing the encoder or * decoder. * * Multistream Opus streams can contain up to 255 elementary Opus streams. * These may be either "uncoupled" or "coupled", indicating that the decoder * is configured to decode them to either 1 or 2 channels, respectively. * The streams are ordered so that all coupled streams appear at the * beginning. * * A <code>mapping</code> table defines which decoded channel <code>i</code> * should be used for each input/output (I/O) channel <code>j</code>. This table is * typically provided as an unsigned char array. * Let <code>i = mapping[j]</code> be the index for I/O channel <code>j</code>. * If <code>i < 2*coupled_streams</code>, then I/O channel <code>j</code> is * encoded as the left channel of stream <code>(i/2)</code> if <code>i</code> * is even, or as the right channel of stream <code>(i/2)</code> if * <code>i</code> is odd. Otherwise, I/O channel <code>j</code> is encoded as * mono in stream <code>(i - coupled_streams)</code>, unless it has the special * value 255, in which case it is omitted from the encoding entirely (the * decoder will reproduce it as silence). Each value <code>i</code> must either * be the special value 255 or be less than <code>streams + coupled_streams</code>. * * The output channels specified by the encoder * should use the * <a href="https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-810004.3.9">Vorbis * channel ordering</a>. A decoder may wish to apply an additional permutation * to the mapping the encoder used to achieve a different output channel * order (e.g. for outputing in WAV order). * * Each multistream packet contains an Opus packet for each stream, and all of * the Opus packets in a single multistream packet must have the same * duration. Therefore the duration of a multistream packet can be extracted * from the TOC sequence of the first stream, which is located at the * beginning of the packet, just like an elementary Opus stream: * * @code * int nb_samples; * int nb_frames; * nb_frames = opus_packet_get_nb_frames(data, len); * if (nb_frames < 1) * return nb_frames; * nb_samples = opus_packet_get_samples_per_frame(data, 48000) * nb_frames; * @endcode * * The general encoding and decoding process proceeds exactly the same as in * the normal @ref opus_encoder and @ref opus_decoder APIs. * See their documentation for an overview of how to use the corresponding * multistream functions. *) (** Opus multistream encoder state. * This contains the complete state of a multistream Opus encoder. * It is position independent and can be freely copied. * @see opus_multistream_encoder_create * @see opus_multistream_encoder_init *) type POpusMSEncoder = ^OpusMSEncoder; OpusMSEncoder = record end; (** Opus multistream decoder state. * This contains the complete state of a multistream Opus decoder. * It is position independent and can be freely copied. * @see opus_multistream_decoder_create * @see opus_multistream_decoder_init *) POpusMSDecoder = ^OpusMSDecoder; OpusMSDecoder = record end; (**\name Multistream encoder functions *) (**@{*) (** Gets the size of an OpusMSEncoder structure. * @param streams <tt>int</tt>: The total number of streams to encode from the * input. * This must be no more than 255. * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams * to encode. * This must be no larger than the total * number of streams. * Additionally, The total number of * encoded channels (<code>streams + * coupled_streams</code>) must be no * more than 255. * @returns The size in bytes on success, or a negative error code * (see @ref opus_errorcodes) on error. *) function opus_multistream_encoder_get_size(streams: cint; coupled_streams: cint): opus_int32; cdecl; external LIB_OPUS; function opus_multistream_surround_encoder_get_size(channels: cint; mapping_family: cint): opus_int32; cdecl; external LIB_OPUS; (** Allocates and initializes a multistream encoder state. * Call opus_multistream_encoder_destroy() to release * this object when finished. * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz). * This must be one of 8000, 12000, 16000, * 24000, or 48000. * @param channels <tt>int</tt>: Number of channels in the input signal. * This must be at most 255. * It may be greater than the number of * coded channels (<code>streams + * coupled_streams</code>). * @param streams <tt>int</tt>: The total number of streams to encode from the * input. * This must be no more than the number of channels. * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams * to encode. * This must be no larger than the total * number of streams. * Additionally, The total number of * encoded channels (<code>streams + * coupled_streams</code>) must be no * more than the number of input channels. * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from * encoded channels to input channels, as described in * @ref opus_multistream. As an extra constraint, the * multistream encoder does not allow encoding coupled * streams for which one channel is unused since this * is never a good idea. * @param application <tt>int</tt>: The target encoder application. * This must be one of the following: * <dl> * <dt>#OPUS_APPLICATION_VOIP</dt> * <dd>Process signal for improved speech intelligibility.</dd> * <dt>#OPUS_APPLICATION_AUDIO</dt> * <dd>Favor faithfulness to the original input.</dd> * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt> * <dd>Configure the minimum possible coding delay by disabling certain modes * of operation.</dd> * </dl> * @param[out] error <tt>int *</tt>: Returns #OPUS_OK on success, or an error * code (see @ref opus_errorcodes) on * failure. *) function opus_multistream_encoder_create(Fs: opus_int32; channels: cint; streams: cint; coupled_streams: cint; const mapping: pcuchar; application: cint; error: pcint): POpusMSEncoder; cdecl; external LIB_OPUS; function opus_multistream_surround_encoder_create(Fs: opus_int32; channels: cint; mapping_family: cint; streams: pcint; coupled_streams: pcint; mapping: pcuchar; application: cint; error: pcint): POpusMSEncoder; cdecl; external LIB_OPUS; (** Initialize a previously allocated multistream encoder state. * The memory pointed to by \a st must be at least the size returned by * opus_multistream_encoder_get_size(). * This is intended for applications which use their own allocator instead of * malloc. * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. * @see opus_multistream_encoder_create * @see opus_multistream_encoder_get_size * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize. * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz). * This must be one of 8000, 12000, 16000, * 24000, or 48000. * @param channels <tt>int</tt>: Number of channels in the input signal. * This must be at most 255. * It may be greater than the number of * coded channels (<code>streams + * coupled_streams</code>). * @param streams <tt>int</tt>: The total number of streams to encode from the * input. * This must be no more than the number of channels. * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams * to encode. * This must be no larger than the total * number of streams. * Additionally, The total number of * encoded channels (<code>streams + * coupled_streams</code>) must be no * more than the number of input channels. * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from * encoded channels to input channels, as described in * @ref opus_multistream. As an extra constraint, the * multistream encoder does not allow encoding coupled * streams for which one channel is unused since this * is never a good idea. * @param application <tt>int</tt>: The target encoder application. * This must be one of the following: * <dl> * <dt>#OPUS_APPLICATION_VOIP</dt> * <dd>Process signal for improved speech intelligibility.</dd> * <dt>#OPUS_APPLICATION_AUDIO</dt> * <dd>Favor faithfulness to the original input.</dd> * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt> * <dd>Configure the minimum possible coding delay by disabling certain modes * of operation.</dd> * </dl> * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) * on failure. *) function opus_multistream_encoder_init(st: POpusMSEncoder; Fs: opus_int32; channels: cint; streams: cint; coupled_streams: cint; const mapping: pcuchar; application: cint): cint; cdecl; external LIB_OPUS; function opus_multistream_surround_encoder_init(st: POpusMSEncoder; Fs: opus_int32; channels: cint; mapping_family: cint; streams: pcint; coupled_streams: pcint; mapping: pcuchar; application: cint): cint; cdecl; external LIB_OPUS; (** Encodes a multistream Opus frame. * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state. * @param[in] pcm <tt>const opus_int16*</tt>: The input signal as interleaved * samples. * This must contain * <code>frame_size*channels</code> * samples. * @param frame_size <tt>int</tt>: Number of samples per channel in the input * signal. * This must be an Opus frame size for the * encoder's sampling rate. * For example, at 48 kHz the permitted values * are 120, 240, 480, 960, 1920, and 2880. * Passing in a duration of less than 10 ms * (480 samples at 48 kHz) will prevent the * encoder from using the LPC or hybrid modes. * @param[out] data <tt>unsigned char*</tt>: Output payload. * This must contain storage for at * least \a max_data_bytes. * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated * memory for the output * payload. This may be * used to impose an upper limit on * the instant bitrate, but should * not be used as the only bitrate * control. Use #OPUS_SET_BITRATE to * control the bitrate. * @returns The length of the encoded packet (in bytes) on success or a * negative error code (see @ref opus_errorcodes) on failure. *) function opus_multistream_encode(st: POpusMSEncoder; const pcm: Popus_int16; frame_size: cint; data: pcuchar; max_data_bytes: opus_int32): cint; cdecl; external LIB_OPUS; (** Encodes a multistream Opus frame from floating point input. * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state. * @param[in] pcm <tt>const float*</tt>: The input signal as interleaved * samples with a normal range of * +/-1.0. * Samples with a range beyond +/-1.0 * are supported but will be clipped by * decoders using the integer API and * should only be used if it is known * that the far end supports extended * dynamic range. * This must contain * <code>frame_size*channels</code> * samples. * @param frame_size <tt>int</tt>: Number of samples per channel in the input * signal. * This must be an Opus frame size for the * encoder's sampling rate. * For example, at 48 kHz the permitted values * are 120, 240, 480, 960, 1920, and 2880. * Passing in a duration of less than 10 ms * (480 samples at 48 kHz) will prevent the * encoder from using the LPC or hybrid modes. * @param[out] data <tt>unsigned char*</tt>: Output payload. * This must contain storage for at * least \a max_data_bytes. * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated * memory for the output * payload. This may be * used to impose an upper limit on * the instant bitrate, but should * not be used as the only bitrate * control. Use #OPUS_SET_BITRATE to * control the bitrate. * @returns The length of the encoded packet (in bytes) on success or a * negative error code (see @ref opus_errorcodes) on failure. *) function opus_multistream_encode_float(st: POpusMSEncoder; const pcm: pcfloat; frame_size: cint; data: pcuchar; max_data_bytes: opus_int32): cint; cdecl; external LIB_OPUS; (** Frees an <code>OpusMSEncoder</code> allocated by * opus_multistream_encoder_create(). * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to be freed. *) procedure opus_multistream_encoder_destroy(st: POpusMSEncoder); cdecl; external LIB_OPUS; (** Perform a CTL function on a multistream Opus encoder. * * Generally the request and subsequent arguments are generated by a * convenience macro. * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state. * @param request This and all remaining parameters should be replaced by one * of the convenience macros in @ref opus_genericctls, * @ref opus_encoderctls, or @ref opus_multistream_ctls. * @see opus_genericctls * @see opus_encoderctls * @see opus_multistream_ctls *) function opus_multistream_encoder_ctl(st: POpusMSEncoder; request: cint; args: array of const): cint; cdecl; external LIB_OPUS; (**@}*) (**\name Multistream decoder functions *) (**@{*) (** Gets the size of an <code>OpusMSDecoder</code> structure. * @param streams <tt>int</tt>: The total number of streams coded in the * input. * This must be no more than 255. * @param coupled_streams <tt>int</tt>: Number streams to decode as coupled * (2 channel) streams. * This must be no larger than the total * number of streams. * Additionally, The total number of * coded channels (<code>streams + * coupled_streams</code>) must be no * more than 255. * @returns The size in bytes on success, or a negative error code * (see @ref opus_errorcodes) on error. *) function opus_multistream_decoder_get_size(streams: cint; coupled_streams: cint): opus_int32; cdecl; external LIB_OPUS; (** Allocates and initializes a multistream decoder state. * Call opus_multistream_decoder_destroy() to release * this object when finished. * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz). * This must be one of 8000, 12000, 16000, * 24000, or 48000. * @param channels <tt>int</tt>: Number of channels to output. * This must be at most 255. * It may be different from the number of coded * channels (<code>streams + * coupled_streams</code>). * @param streams <tt>int</tt>: The total number of streams coded in the * input. * This must be no more than 255. * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled * (2 channel) streams. * This must be no larger than the total * number of streams. * Additionally, The total number of * coded channels (<code>streams + * coupled_streams</code>) must be no * more than 255. * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from * coded channels to output channels, as described in * @ref opus_multistream. * @param[out] error <tt>int *</tt>: Returns #OPUS_OK on success, or an error * code (see @ref opus_errorcodes) on * failure. *) function opus_multistream_decoder_create(Fs: opus_int32; channels: cint; streams: cint; coupled_streams: cint; const mapping: pcuchar; error: pcint): POpusMSDecoder; cdecl; external LIB_OPUS; (** Intialize a previously allocated decoder state object. * The memory pointed to by \a st must be at least the size returned by * opus_multistream_encoder_get_size(). * This is intended for applications which use their own allocator instead of * malloc. * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. * @see opus_multistream_decoder_create * @see opus_multistream_deocder_get_size * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize. * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz). * This must be one of 8000, 12000, 16000, * 24000, or 48000. * @param channels <tt>int</tt>: Number of channels to output. * This must be at most 255. * It may be different from the number of coded * channels (<code>streams + * coupled_streams</code>). * @param streams <tt>int</tt>: The total number of streams coded in the * input. * This must be no more than 255. * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled * (2 channel) streams. * This must be no larger than the total * number of streams. * Additionally, The total number of * coded channels (<code>streams + * coupled_streams</code>) must be no * more than 255. * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from * coded channels to output channels, as described in * @ref opus_multistream. * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) * on failure. *) function opus_multistream_decoder_init(st: POpusMSDecoder; Fs: opus_int32; channels: cint; streams: cint; coupled_streams: cint; const mapping: pcuchar): cint; cdecl; external LIB_OPUS; (** Decode a multistream Opus packet. * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state. * @param[in] data <tt>const unsigned char*</tt>: Input payload. * Use a <code>NULL</code> * pointer to indicate packet * loss. * @param len <tt>opus_int32</tt>: Number of bytes in payload. * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved * samples. * This must contain room for * <code>frame_size*channels</code> * samples. * @param frame_size <tt>int</tt>: The number of samples per channel of * available space in \a pcm. * If this is less than the maximum packet duration * (120 ms; 5760 for 48kHz), this function will not be capable * of decoding some packets. In the case of PLC (data==NULL) * or FEC (decode_fec=1), then frame_size needs to be exactly * the duration of audio that is missing, otherwise the * decoder will not be in the optimal state to decode the * next incoming packet. For the PLC and FEC cases, frame_size * <b>must</b> be a multiple of 2.5 ms. * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band * forward error correction data be decoded. * If no such data is available, the frame is * decoded as if it were lost. * @returns Number of samples decoded on success or a negative error code * (see @ref opus_errorcodes) on failure. *) function opus_multistream_decode(st: POpusMSDecoder; const data: pcuchar; len: opus_int32; pcm: Popus_int16; frame_size: cint; decode_fec: cint): cint; cdecl; external LIB_OPUS; (** Decode a multistream Opus packet with floating point output. * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state. * @param[in] data <tt>const unsigned char*</tt>: Input payload. * Use a <code>NULL</code> * pointer to indicate packet * loss. * @param len <tt>opus_int32</tt>: Number of bytes in payload. * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved * samples. * This must contain room for * <code>frame_size*channels</code> * samples. * @param frame_size <tt>int</tt>: The number of samples per channel of * available space in \a pcm. * If this is less than the maximum packet duration * (120 ms; 5760 for 48kHz), this function will not be capable * of decoding some packets. In the case of PLC (data==NULL) * or FEC (decode_fec=1), then frame_size needs to be exactly * the duration of audio that is missing, otherwise the * decoder will not be in the optimal state to decode the * next incoming packet. For the PLC and FEC cases, frame_size * <b>must</b> be a multiple of 2.5 ms. * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band * forward error correction data be decoded. * If no such data is available, the frame is * decoded as if it were lost. * @returns Number of samples decoded on success or a negative error code * (see @ref opus_errorcodes) on failure. *) function opus_multistream_decode_float(st: POpusMSDecoder; const data: pcuchar; len: opus_int32; pcm: pcfloat; frame_size: cint; decode_fec: cint): cint; cdecl; external LIB_OPUS; (** Perform a CTL function on a multistream Opus decoder. * * Generally the request and subsequent arguments are generated by a * convenience macro. * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state. * @param request This and all remaining parameters should be replaced by one * of the convenience macros in @ref opus_genericctls, * @ref opus_decoderctls, or @ref opus_multistream_ctls. * @see opus_genericctls * @see opus_decoderctls * @see opus_multistream_ctls *) function opus_multistream_decoder_ctl(st: POpusMSDecoder; request: cint; args: array of const): cint; cdecl; external LIB_OPUS; (** Frees an <code>OpusMSDecoder</code> allocated by * opus_multistream_decoder_create(). * @param st <tt>OpusMSDecoder</tt>: Multistream decoder state to be freed. *) procedure opus_multistream_decoder_destroy(st: POpusMSDecoder); cdecl; external LIB_OPUS; (**@}*) (**@}*) // #ifdef __cplusplus // } // #endif // #endif (* OPUS_MULTISTREAM_H *) implementation end.
unit UClasses; interface uses SysUtils, Dialogs; const TabLinhas :integer = 22; TabColunas :integer = 22; type TTipoObj = (toAgenteP, toAgenteV, toCasaP, toCasaV); TTabuleiro = class(TObject) private tTab:array [1..22,1..22] of integer; // codigoPeca = ocupado; 0 = vazio; public constructor Create(); procedure SetOcupado(posX,posY, ocupado:integer);// ocupado = codAgente; 0 = vazio; 99 = casa function GetPosXY(posX,posY:integer):integer; end; TAgente = class(TObject) private aCodigo, aX, aY, aOldX, aOldY :integer; aTipo : TTipoObj; aEncontrouCasa :boolean; public constructor Create; procedure SetCodigo(cod:integer); function GetCodigo:integer; procedure SetPosicao(x,y:integer); function GetPosX:integer; function GetPosY:integer; procedure SetTipo(tipo:TTipoObj); function GetTipo:TTipoObj; procedure SetCasaEncontrada; function GetCasaEncontrada:boolean; function VerificaLados(tabuleiro:TTabuleiro):boolean; end; implementation { TTabuleiro } constructor TTabuleiro.Create(); var i,j:integer; begin for i := 1 to TabColunas do begin for j := 1 to TabLinhas do begin tTab[i,j] := 0; end; end; end; function TTabuleiro.GetPosXY(posX, posY: integer): integer; begin if ((posX < 22) and (posY < 22) and (posX > 0) and (posY > 0)) then Result := tTab[posX,posY] else Result := 1; end; procedure TTabuleiro.SetOcupado(posX, posY, ocupado: integer); begin if ((posX < 22) and (posY < 22) and (posX > 0) and (posY > 0)) then tTab[posX,posY] := ocupado; end; { TAgente } constructor TAgente.Create; begin aCodigo := 0; aX := 0; aY := 0; aOldX := 0; aOldY := 0; aEncontrouCasa := False; end; function TAgente.GetCasaEncontrada: boolean; begin result := aEncontrouCasa; end; function TAgente.GetCodigo: integer; begin Result := aCodigo; end; function TAgente.GetPosX: integer; begin Result := aX; end; function TAgente.GetPosY: integer; begin Result := aY; end; function TAgente.GetTipo: TTipoObj; begin Result := aTipo; end; procedure TAgente.SetCasaEncontrada; begin aEncontrouCasa := True; MessageDlg('Agente nš ' + IntToStr(aCodigo) + ' encontrou sua casa',mtInformation,[mbOK],0); end; procedure TAgente.SetCodigo(cod: integer); begin aCodigo := cod; end; procedure TAgente.SetPosicao(x, y: integer); begin if ((x < 22) and (y < 22) and (x >= 0) and (y >= 0)) then begin aOldX := aX; aOldY := aY; aX := x; aY := y; end; end; procedure TAgente.SetTipo(tipo: TTipoObj); begin aTipo := tipo; end; function TAgente.VerificaLados(tabuleiro:TTabuleiro): boolean; var // um agente encherga apenas ao seu redor. aux: integer; begin Result := False; if not aEncontrouCasa then begin if (((tabuleiro.GetPosXY(aX-1,aY) = 99) and (aTipo = toAgenteP)) or ((tabuleiro.GetPosXY(aX-1,aY) = 98) and (aTipo = toAgenteV))) then begin SetPosicao(aX-1,aY); tabuleiro.SetOcupado(aOldX,aOldY,0); Result := True; SetCasaEncontrada; end else if (((tabuleiro.GetPosXY(aX+1,aY) = 99) and (aTipo = toAgenteP)) or ((tabuleiro.GetPosXY(aX+1,aY) = 98) and (aTipo = toAgenteV))) then begin SetPosicao(aX+1,aY); tabuleiro.SetOcupado(aOldX,aOldY,0); Result := True; SetCasaEncontrada; end else if (((tabuleiro.GetPosXY(aX,aY+1) = 99) and (aTipo = toAgenteP)) or ((tabuleiro.GetPosXY(aX,aY+1) = 98) and (aTipo = toAgenteV))) then begin SetPosicao(aX,aY+1); tabuleiro.SetOcupado(aOldX,aOldY,0); Result := True; SetCasaEncontrada; end else if (((tabuleiro.GetPosXY(aX,aY-1) = 99) and (aTipo = toAgenteP)) or ((tabuleiro.GetPosXY(aX,aY-1) = 98) and (aTipo = toAgenteV))) then begin SetPosicao(aX,aY-1); tabuleiro.SetOcupado(aOldX,aOldY,0); Result := True; SetCasaEncontrada; end else begin aux := Random(4); case aux of 0: begin if ((tabuleiro.GetPosXY(aX-1,aY) = 0) and (aX-1 <> aOldX)) then begin tabuleiro.SetOcupado(aX-1,aY,aCodigo); SetPosicao(aX-1,aY); tabuleiro.SetOcupado(aOldX,aOldY,0); end; end; 1: begin if ((tabuleiro.GetPosXY(aX+1,aY) = 0) and (aX+1 <> aOldX)) then begin tabuleiro.SetOcupado(aX+1,aY,aCodigo); SetPosicao(aX+1,aY); tabuleiro.SetOcupado(aOldX,aOldY,0); end; end; 2: begin if ((tabuleiro.GetPosXY(aX,aY+1) = 0) and (aY+1 <> aOldY)) then begin tabuleiro.SetOcupado(aX,aY+1,aCodigo); SetPosicao(aX,aY+1); tabuleiro.SetOcupado(aOldX,aOldY,0); end; end; 3: begin if ((tabuleiro.GetPosXY(aX,aY-1) = 0) and (aY-1 <> aOldY)) then begin tabuleiro.SetOcupado(aX,aY-1,aCodigo); SetPosicao(aX,aY-1); tabuleiro.SetOcupado(aOldX,aOldY,0); end; end; end; end; end; end; end.
unit uFrmListaContasReceber; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFrmLista, Data.DB, Vcl.Menus, JvComponentBase, JvEnterTab, Vcl.Grids, Vcl.DBGrids, JvExDBGrids, JvDBGrid, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, JvExButtons, JvBitBtn, ACBrUtil, JvADOQuery; type TFrmListaContasReceber = class(TFrmLista) btnMovimentos: TJvBitBtn; pmMovimentos: TPopupMenu; Baixarttulo1: TMenuItem; Estornarttulo1: TMenuItem; Centralderelatrio1: TMenuItem; procedure FormCreate(Sender: TObject); procedure Baixarttulo1Click(Sender: TObject); procedure Estornarttulo1Click(Sender: TObject); procedure JvBitBtn5Click(Sender: TObject); procedure Centralderelatrio1Click(Sender: TObject); procedure btnRemoverClick(Sender: TObject); procedure dbgrdConsultaDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btnNovoClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); private FTPLANCAMENTO: string; procedure SetTPLANCAMENTO(const Value: string); { Private declarations } public // valores CR=Receber, CP=Pagar property TPLANCAMENTO : string read FTPLANCAMENTO write SetTPLANCAMENTO; end; var FrmListaContasReceber: TFrmListaContasReceber; implementation uses krnVarGlobais, UfrmFormularioBaixa, Funcoes, udmAcesso, uFrmCentralRelatorios, uFrmCadastroTitulos; {$R *.dfm} procedure TFrmListaContasReceber.Baixarttulo1Click(Sender: TObject); begin inherited; { TODO -oJanilson -c : Baixar de titulo 19/03/2019 11:02:13 } if dsConsulta.DataSet.RecordCount > 0 then begin if dsConsulta.DataSet.FieldByName('SITUACAO').AsString='Aberto' then begin try Application.CreateForm(TfrmFormularioBaixa,frmFormularioBaixa); frmFormularioBaixa.Tag := dsConsulta.DataSet.FieldByName('ID').AsInteger; frmFormularioBaixa.edtDocumento.Text := dsConsulta.DataSet.FieldByName('DOCUMENTO').AsString; frmFormularioBaixa.edtParcela.Text := dsConsulta.DataSet.FieldByName('PARCELA').AsString; frmFormularioBaixa.edtContato.Text := dsConsulta.DataSet.FieldByName('NOME_CONTATO').AsString; frmFormularioBaixa.edtValorTitulo.Value := dsConsulta.DataSet.FieldByName('VALOR').AsFloat; frmFormularioBaixa.edtMulta.Value := 0; frmFormularioBaixa.edtJuros.Value := 0; frmFormularioBaixa.edtDesconto.Value:= 0; frmFormularioBaixa.edtVlrPago.Value := frmFormularioBaixa.edtValorTitulo.Value; frmFormularioBaixa.ShowModal; finally if frmFormularioBaixa.ModalResult = mrOk then begin proc_UpdateTitulo(Estabelecimento, dsConsulta.DataSet.FieldByName('ID').AsInteger, frmFormularioBaixa.clkID_CONTACORRENTE.KeyValue, frmFormularioBaixa.edtMulta.Value, frmFormularioBaixa.edtJuros.Value, frmFormularioBaixa.edtDesconto.Value, frmFormularioBaixa.edtVlrPago.Value, frmFormularioBaixa.edtBaixa.Date, 'LQ', dsConsulta.DataSet.FieldByName('TIPO_LANCAMENTO').AsString ); end; FreeAndNil(frmFormularioBaixa); dsConsulta.DataSet.Refresh; end; end; end; end; procedure TFrmListaContasReceber.btnEditarClick(Sender: TObject); begin inherited; if dsConsulta.DataSet.RecordCount>0 then begin if dsConsulta.DataSet.FieldByName('SITUACAO').AsString <> 'Aberto' then raise Exception.Create('Edição somente de títulos em aberto.'); try dmAcesso.inicializaNovoRegistro(Self.Tabela, dsConsulta.DataSet.FieldByName('ID').AsInteger); Application.CreateForm(tFrmCadastroTitulos, FrmCadastroTitulos); FrmCadastroTitulos.Tag:=1; openDetGrupoContatos(dsConsulta.DataSet.FieldByName('ID').AsInteger); FrmCadastroTitulos.dsCadastro.DataSet.Edit; if TPLANCAMENTO = 'CR' then begin FrmCadastroTitulos.dsLkpNatureza.DataSet := dmAcesso.QyLkpNaturezaCR; FrmCadastroTitulos.dsLkpContatos.DataSet := dmAcesso.QyLKPClientes; if dsConsulta.DataSet.FieldByName('ID_VENDA').AsInteger <> 0 then begin with FrmCadastroTitulos do begin clkID_CONTATO.Enabled := False; dbedtDOCUMENTO.Enabled := False; dbedtPARCELA.Enabled := False; edtEMISSAO.Enabled := False; cbbTIPO_PAGAMENTO.Enabled := False; end; end; end else begin FrmCadastroTitulos.dsLkpNatureza.DataSet := dmAcesso.QyLkpNaturezaCP; FrmCadastroTitulos.dsLkpContatos.DataSet := dmAcesso.QyLKPFornecedores; if dsConsulta.DataSet.FieldByName('ID_COMPRA').AsInteger <> 0 then begin with FrmCadastroTitulos do begin clkID_CONTATO.Enabled := False; dbedtDOCUMENTO.Enabled := False; dbedtPARCELA.Enabled := False; edtEMISSAO.Enabled := False; cbbTIPO_PAGAMENTO.Enabled := False; end; end; end; FrmCadastroTitulos.ShowModal; finally dsConsulta.DataSet.Refresh; FreeAndNil(FrmCadastroTitulos); end; end; end; procedure TFrmListaContasReceber.btnNovoClick(Sender: TObject); begin inherited; try dmAcesso.inicializaNovoRegistro(Self.Tabela); Application.CreateForm(TFrmCadastroTitulos,FrmCadastroTitulos); FrmCadastroTitulos.dsCadastro.DataSet.Insert; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('ID_FILIAL').AsInteger := Estabelecimento; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('EMISSAO').AsDateTime := Date; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('VENCIMENTO').AsDateTime := Date; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('VALOR').AsFloat := 0; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('SITUACAO').AsString := 'AB'; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('ORIGEM').AsString := 'AU'; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('PARCELA').AsInteger:=1; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('BLOQUEADO').AsInteger:=0; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('TIPO_PAGTO').AsString := 'ESP'; FrmCadastroTitulos.cbbTIPO_PAGAMENTO.ItemIndex:=0; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('ID_CONDICAOPAGAMENTO').AsInteger := dmAcesso.QyLkpContaCorrente.FieldByName('ID').AsInteger; FrmCadastroTitulos.clkID_CONTACORRENTE.KeyValue:=dmAcesso.QyLkpContaCorrente.FieldByName('ID').AsInteger; if TPLANCAMENTO = 'CR' then begin FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('TIPO_LANCAMENTO').AsString := 'C'; FrmCadastroTitulos.dsLkpNatureza.DataSet := dmAcesso.QyLkpNaturezaCR; FrmCadastroTitulos.clkID_NATUREZA.KeyValue := dmAcesso.QyLkpNaturezaCR.FieldByName('ID').AsInteger; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('ID_CONTATO').AsInteger := dmAcesso.QyLKPClientes.FieldByName('ID').AsInteger; FrmCadastroTitulos.clkID_CONTATO.KeyValue := dmAcesso.QyLKPClientes.FieldByName('ID').AsInteger; end else begin FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('TIPO_LANCAMENTO').AsString := 'D'; FrmCadastroTitulos.dsLkpNatureza.DataSet := dmAcesso.QyLkpNaturezaCP; FrmCadastroTitulos.clkID_NATUREZA.KeyValue := dmAcesso.QyLkpNaturezaCP.FieldByName('ID').AsInteger; FrmCadastroTitulos.dsLkpContatos.DataSet := dmAcesso.QyLKPFornecedores; FrmCadastroTitulos.dsCadastro.DataSet.FieldByName('ID_CONTATO').AsInteger := dmAcesso.QyLKPClientes.FieldByName('ID').AsInteger; FrmCadastroTitulos.clkID_CONTATO.KeyValue := dmAcesso.QyLKPFornecedores.FieldByName('ID').AsInteger; end; FrmCadastroTitulos.ShowModal; finally FreeAndNil(FrmCadastroTitulos); dsConsulta.DataSet.Refresh; end; end; procedure TFrmListaContasReceber.btnRemoverClick(Sender: TObject); begin if dsConsulta.DataSet.FieldByName('SITUACAO').AsString <> 'Aberto' then AlertaInfo('Lançamento não pode ser removido.') else begin if TPLANCAMENTO = 'CR' then begin if dsConsulta.DataSet.FieldByName('ID_VENDA').AsInteger <> 0 then begin AlertaInfo(PChar('Título vinculado a venda nº ' +dsConsulta.DataSet.FieldByName('ID_VENDA').AsString +#13+ 'É necessário estornar o pedido.')); end else inherited; end else begin if dsConsulta.DataSet.FieldByName('ID_COMPRA').AsInteger <> 0 then begin AlertaInfo(PChar( 'Título vinculado a compra nº ' +dsConsulta.DataSet.FieldByName('ID_COMPRA').AsString +#13+ 'É necessário remover a compra.') ); end else inherited; end; end; end; procedure TFrmListaContasReceber.Centralderelatrio1Click(Sender: TObject); begin inherited; try Application.CreateForm(TFrmCentralRelatorios,FrmCentralRelatorios); FrmCentralRelatorios.Hint := 'LANCAMENTO'; if TPLANCAMENTO = 'CR' then FrmCentralRelatorios.cbbTipoLancamento.ItemIndex := 0 else FrmCentralRelatorios.cbbTipoLancamento.ItemIndex := 1; FrmCentralRelatorios.cbbTipoLancamento.Enabled:=False; FrmCentralRelatorios.ShowModal; finally FreeAndNil(FrmCentralRelatorios); end; end; procedure TFrmListaContasReceber.dbgrdConsultaDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin inherited; if Assigned(dsConsulta.DataSet.FindField('SITUACAO')) then begin if (Column.Field.FieldName = 'SITUACAO') then begin if (dsConsulta.DataSet.FieldByName('SITUACAO').AsString = 'Baixado') or (dsConsulta.DataSet.FieldByName('SITUACAO').AsString = 'Liquidado') then begin // dbgrdConsulta.Canvas.Brush.Color:= clRed; //"pinta" a celula inteira dbgrdConsulta.Canvas.Font.Color:= clBlue; //"Pinta" a letra dbgrdConsulta.Canvas.FillRect(Rect); dbgrdConsulta.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; if (dsConsulta.DataSet.FieldByName('VENCIMENTO').AsDateTime < Date) and ((dsConsulta.DataSet.FieldByName('SITUACAO').AsString = 'Aberto'))then begin dbgrdConsulta.Canvas.Font.Color:= clRed; //"Pinta" a letra dbgrdConsulta.Canvas.FillRect(Rect); dbgrdConsulta.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end; end; end; procedure TFrmListaContasReceber.Estornarttulo1Click(Sender: TObject); begin inherited; { TODO -oJanilson -c : Estorno de titulo 19/03/2019 11:02:32 } if dsConsulta.DataSet.FieldByName('SITUACAO').AsString <> 'Aberto' then begin proc_UpdateTitulo(Estabelecimento, dsConsulta.DataSet.FieldByName('ID').AsInteger, dsConsulta.DataSet.FieldByName('ID_CONTACORRENTE').AsInteger, 0, 0, 0, 0, now, 'AB', dsConsulta.DataSet.FieldByName('TIPO_LANCAMENTO').AsString ); { TODO -oJanilson -c : Imprimir recibo? 21/03/2019 10:41:05 } dsConsulta.DataSet.Refresh; end; end; procedure TFrmListaContasReceber.FormCreate(Sender: TObject); begin inherited; paginate := 30; end; procedure TFrmListaContasReceber.JvBitBtn5Click(Sender: TObject); begin if TPLANCAMENTO = 'CR' then begin if trim(edtBusca.Text) <> '' then begin self.Where := ' WHERE LANCAMENTO.TIPO_LANCAMENTO = "C" AND LANCAMENTO.ID_FILIAL = ' + IntToStr(Estabelecimento) + ' AND CONTATO.NOME LIKE ' + QuotedStr('%'+ Trim(edtBusca.Text) +'%') + ' OR LANCAMENTO.DOCUMENTO LIKE '+QuotedStr('%'+ Trim(edtBusca.Text) +'%') ; end else self.Where :=' WHERE LANCAMENTO.TIPO_LANCAMENTO = "C" AND LANCAMENTO.ID_FILIAL = ' + IntToStr(Estabelecimento); inherited; end else begin if trim(edtBusca.Text) <> '' then begin self.Where := ' WHERE LANCAMENTO.TIPO_LANCAMENTO = "D" AND LANCAMENTO.ID_FILIAL = ' + IntToStr(Estabelecimento) + ' AND CONTATO.NOME LIKE ' + QuotedStr('%'+ Trim(edtBusca.Text) +'%') + ' OR LANCAMENTO.DOCUMENTO LIKE '+QuotedStr('%'+ Trim(edtBusca.Text) +'%') ; end else self.Where :=' WHERE LANCAMENTO.TIPO_LANCAMENTO = "D" AND LANCAMENTO.ID_FILIAL = ' + IntToStr(Estabelecimento); inherited; end; end; procedure TFrmListaContasReceber.SetTPLANCAMENTO(const Value: string); begin FTPLANCAMENTO := Value; end; end.
program demo1; uses glr_render, glr_render2d, glr_scene, glr_core, glr_filesystem, glr_math, glr_utils, glr_resload; type { TGame } TGame = class(TglrGame) protected dx, dy: Integer; Camera, CameraHud: TglrCamera; Material: TglrMaterial; meshData: array of TglrVertexP3T2C4; meshBuffer: TglrVertexBuffer; meshIBuffer: TglrIndexBuffer; Sprites: array of TglrSprite; Batch: TglrSpriteBatch; Font: TglrFont; Text: TglrText; FontBatch: TglrFontBatch; atlas: TglrTextureAtlas; procedure PrepareMesh(); procedure RenderMesh(); procedure CreateSprites(); procedure CreateFont(); public procedure OnFinish; override; procedure OnInput(Event: PglrInputEvent); override; procedure OnPause; override; procedure OnRender; override; procedure OnResume; override; procedure OnResize(aNewWidth, aNewHeight: Integer); override; procedure OnStart; override; procedure OnUpdate(const dt: Double); override; end; { TGame } procedure TGame.PrepareMesh; const CubeSize = 4; indices: array[0..35] of byte = (0, 1, 3, //back 0, 3, 2, 4, 6, 7, //front 7, 5, 4, 9, 8, 10, //right 8, 11, 10, 15, 12, 14, //left 15, 13, 12, 19, 17, 16, //top 19, 16, 18, 23, 20, 21, //bottom 23, 22, 20); var i: Integer; begin SetLength(meshData, 24); meshData[0].vec := Vec3f(CubeSize/2, CubeSize/2, CubeSize/2); meshData[1].vec := Vec3f(-CubeSize/2, CubeSize/2, CubeSize/2); meshData[2].vec := Vec3f(CubeSize/2, -CubeSize/2, CubeSize/2); meshData[3].vec := Vec3f(-CubeSize/2, -CubeSize/2, CubeSize/2); meshData[4].vec := Vec3f(CubeSize/2, CubeSize/2, -CubeSize/2); meshData[5].vec := Vec3f(-CubeSize/2, CubeSize/2, -CubeSize/2); meshData[6].vec := Vec3f(CubeSize/2, -CubeSize/2, -CubeSize/2); meshData[7].vec := Vec3f(-CubeSize/2, -CubeSize/2, -CubeSize/2); meshData[8].vec := Vec3f(CubeSize/2, CubeSize/2, CubeSize/2); //0 meshData[9].vec := Vec3f(CubeSize/2, CubeSize/2, -CubeSize/2); //4 meshData[10].vec := Vec3f(CubeSize/2, -CubeSize/2, -CubeSize/2); //6 meshData[11].vec := Vec3f(CubeSize/2, -CubeSize/2, CubeSize/2); //2 meshData[12].vec := Vec3f(-CubeSize/2, CubeSize/2, CubeSize/2); //1 meshData[13].vec := Vec3f(-CubeSize/2, -CubeSize/2, CubeSize/2); //3 meshData[14].vec := Vec3f(-CubeSize/2, CubeSize/2, -CubeSize/2); //5 meshData[15].vec := Vec3f(-CubeSize/2, -CubeSize/2, -CubeSize/2); //7 meshData[16].vec := Vec3f(CubeSize/2, CubeSize/2, CubeSize/2); //0 meshData[17].vec := Vec3f(-CubeSize/2, CubeSize/2, CubeSize/2); //1 meshData[18].vec := Vec3f(CubeSize/2, CubeSize/2, -CubeSize/2); //4 meshData[19].vec := Vec3f(-CubeSize/2, CubeSize/2, -CubeSize/2); //5 meshData[20].vec := Vec3f(CubeSize/2, -CubeSize/2, CubeSize/2); //2 meshData[21].vec := Vec3f(-CubeSize/2, -CubeSize/2, CubeSize/2); //3 meshData[22].vec := Vec3f(CubeSize/2, -CubeSize/2, -CubeSize/2); //6 meshData[23].vec := Vec3f(-CubeSize/2, -CubeSize/2, -CubeSize/2); //7 for i := 0 to 23 do meshData[i].col := Vec4f(1, 1, 1, 1); meshData[0].tex := Vec2f(1, 1); meshData[1].tex := Vec2f(0, 1); meshData[2].tex := Vec2f(1, 0); meshData[3].tex := Vec2f(0, 0); meshData[4].tex := Vec2f(0, 1); meshData[5].tex := Vec2f(1, 1); meshData[6].tex := Vec2f(0, 0); meshData[7].tex := Vec2f(1, 0); meshData[8].tex := Vec2f(0, 1); meshData[9].tex := Vec2f(1, 1); meshData[10].tex := Vec2f(1, 0); meshData[11].tex := Vec2f(0, 0); meshData[12].tex := Vec2f(1, 1); meshData[13].tex := Vec2f(1, 0); meshData[14].tex := Vec2f(0, 1); meshData[15].tex := Vec2f(0, 0); meshData[16].tex := Vec2f(1, 0); meshData[17].tex := Vec2f(0, 0); meshData[18].tex := Vec2f(1, 1); meshData[19].tex := Vec2f(0, 1); meshData[20].tex := Vec2f(1, 1); meshData[21].tex := Vec2f(0, 1); meshData[22].tex := Vec2f(1, 0); meshData[23].tex := Vec2f(0, 0); meshBuffer := TglrVertexBuffer.Create(@meshData[0], 24, vfPos3Tex2Col4, uStaticDraw); meshIBuffer := TglrIndexBuffer.Create(@indices[0], 36, ifByte); end; procedure TGame.RenderMesh; begin Render.DrawTriangles(meshBuffer, meshIBuffer, 0, 36); end; procedure TGame.CreateSprites; const count = 30; var i: Integer; begin atlas := TglrTextureAtlas.Create(FileSystem.ReadResource('data/atlas.tga'), FileSystem.ReadResource('data/atlas.atlas'), extTga, aextCheetah); Batch := TglrSpriteBatch.Create(); SetLength(Sprites, count); for i := 0 to count - 1 do begin Sprites[i] := TglrSprite.Create(30, 30, Vec2f(0.5, 0.5)); Sprites[i].Position := Vec3f(Random(800), Random(600), Random(15)); Sprites[i].SetVerticesColor(Vec4f(Random(), Random(), Random, 1)); Sprites[i].SetTextureRegion(atlas.GetRegion('goodline.png')); end; end; procedure TGame.CreateFont; begin Font := TglrFont.Create(FileSystem.ReadResource('data/AmazingGrotesk19.fnt')); Text := TglrText.Create(UTF8Decode('Hello, world! / Привет, мир! ' + #13#10 + 'This time it will go over platforms... / На этот раз все будет кроссплатформенно...')); Text.LetterSpacing := 1; Text.Position := Vec3f(10, 150, 90); FontBatch := TglrFontBatch.Create(Font); end; procedure TGame.OnFinish; var i: Integer; begin for i := 0 to Length(Sprites) - 1 do Sprites[i].Free(); Font.Free(); Text.Free(); FontBatch.Free(); Batch.Free(); atlas.Free(); Material.Free(); Camera.Free(); CameraHud.Free(); WriteLn('End'); end; procedure TGame.OnInput(Event: PglrInputEvent); begin if (Event.InputType = itTouchDown) and (Event.Key = kLeftButton) then begin dx := Event.X; dy := Event.Y; end; if (Event.InputType = itTouchMove) and (Event.Key = kLeftButton) then begin Camera.Rotate((Event.X - dx) * deg2rad * 0.2, Vec3f(0, 1, 0)); Camera.Rotate((Event.Y - dy) * deg2rad * 0.2, Camera.Right); dx := Event.X; dy := Event.Y; end; if (Event.InputType = itTouchMove) and (Event.Key = kNoInput) then begin Sprites[1].Up := (Sprites[1].Position - Vec3f(Core.Input.Touch[0].Pos, 0)).Normal; Sprites[1].Direction := Vec3f(0, 0.0, 1.0); end; if (Event.InputType = itWheel) then Camera.Translate(0, 0, -Sign(Event.W)); if (Event.InputType = itKeyUp) and (Event.Key = kU) then Log.Write(lInformation, 'Camera.Mat: '#13#10 + Convert.ToString(Camera.Matrix, 2)); end; procedure TGame.OnPause; begin WriteLn('Pause'); end; procedure TGame.OnRender; begin Camera.Update(); Material.Bind(); RenderMesh(); CameraHud.Update(); Material.Bind(); Batch.Start(); Batch.Draw(Sprites); Batch.Finish(); FontBatch.Start(); FontBatch.Draw(Text); FontBatch.Finish(); end; procedure TGame.OnResume; begin WriteLn('Resume'); end; procedure TGame.OnResize(aNewWidth, aNewHeight: Integer); begin WriteLn('Resize'); end; procedure TGame.OnStart; begin WriteLn('Start'); Render.SetCullMode(cmBack); Camera := TglrCamera.Create(); Camera.SetProjParams(0, 0, Render.Width, Render.Height, 35, 0.1, 1000, pmPerspective, pTopLeft); Camera.SetViewParams(Vec3f(5, 0, 5), Vec3f(0, 0, 0), Vec3f(0, 1, 0)); CameraHud := TglrCamera.Create(); CameraHud.SetProjParams(0, 0, Render.Width, Render.Height, 45, 0.1, 1000, pmOrtho, pTopLeft); CameraHud.SetViewParams(Vec3f(0, 0, 100), Vec3f(0, 0, 0), Vec3f(0, 1, 0)); Material := TglrMaterial.Create(Default.SpriteShader); // Material.AddTexture(TglrTexture.Create(FileSystem.ReadResource('Arial12b.bmp'), 'bmp'), 'uDiffuse'); // Material.AddTexture(TglrTexture.Create(FileSystem.ReadResource('data/box.tga'), 'tga'), 'uDiffuse'); // Material.Color := dfVec4f(0.7, 0.2, 0.1, 1); PrepareMesh(); CreateSprites(); CreateFont(); Material.AddTexture(atlas, 'uDiffuse'); end; procedure TGame.OnUpdate(const dt: Double); var i: Integer; begin for i := 0 to Length(Sprites) - 1 do Sprites[i].Rotation := Sprites[i].Rotation + dt * Sprites[i].Position.y / 10; end; var Game: TGame; InitParams: TglrInitParams; begin with InitParams do begin Width := 800; Height := 600; X := 100; Y := 100; Caption := 'tiny glr [' + TINYGLR_VERSION + ']'; vSync := True; PackFilesPath := ''; UseDefaultAssets := True; end; Game := TGame.Create(); Core.Init(Game, InitParams); Core.Loop(); Core.DeInit(); Game.Free(); end.
unit ColorTbl; { Exports type TColorTable and a few subroutines that work on/with it. The TColorTable is meant to be used for palette like data structures of max. 256 entries, which are used in GIF files and BMP files. The entries in the TColorTable (TColorItem) are three bytes with r,g,b values. Reinier Sterkenburg, Delft, The Netherlands March 97: - created 22 Apr 97: - corrected a very stupid bug: the shifts for DecodeColor were wrong (4, 2 in stead of 16, 8) 30 Aug 97: - Made TColorTable a class again. If I keep using a packed record (RColorTable) for the storage and I/O of the colors this works. 31 Aug 97: - Added use of RFastColorTable. This complicatest things a bit but it improves the performance of GetColorIndex. See also GifUnit.BitmapToPixelmatrix 2 Dec 97: - added function TColorTable.GetColor } interface uses Graphics; { Imports TColor } type TColorItem = packed record { one item a a color table } Red: byte; Green: byte; Blue: byte; end; { TColorItem } RColorTable = packed record Count: Integer; { Actual number of colors } Colors: packed array[0..255] of TColorItem; { the color table } end; { TColorTable } RFastColorTable = record Colors: array[0..255] of TColor; end; { RFastColorTable } TColorTable = class(TObject) private function GetCount: Integer; procedure SetCount(NewValue: Integer); public CT: RColorTable; FCT: RFastColorTable; constructor Create(NColors: Word); procedure AdjustColorCount; procedure CompactColors; function GetColor(Index: Byte): TColor; function GetColorIndex(Color: TColor): Integer; property Count: Integer read GetCount write SetCount; end; { TColorTable } implementation function DecodeColor(Color: TColor): TColorItem; begin { DecodeColor } Result.Blue := (Color shr 16) and $FF; Result.Green := (Color shr 8) and $FF; Result.Red := Color and $FF; end; { DecodeColor } function EncodeColorItem(r, g, b: Byte): TColorItem; begin { EncodeColorItem } Result.Red := r; Result.Green := g; Result.Blue := b; end; { EncodeColorItem } (***** RColorTable *****) procedure TColorTable_CreateBW(var CT: RColorTable); begin { TColorTable_CreateBW } CT.Count := 2; CT.Colors[0] := EncodeColorItem(0, 0, 0); CT.Colors[1] := EncodeColorItem($FF, $FF, $FF); end; { TColorTable_CreateBW } procedure TColorTable_Create16(var CT: RColorTable); begin { TColorTable_Create16 } CT.Count := 16; CT.Colors[ 0] := EncodeColorItem($00, $00, $00); { black } CT.Colors[ 1] := EncodeColorItem($80, $00, $00); { maroon } CT.Colors[ 2] := EncodeColorItem($00, $80, $00); { darkgreen } CT.Colors[ 3] := EncodeColorItem($80, $80, $00); { army green } CT.Colors[ 4] := EncodeColorItem($00, $00, $80); { dark blue } CT.Colors[ 5] := EncodeColorItem($80, $00, $80); { purple } CT.Colors[ 6] := EncodeColorItem($00, $80, $80); { blue green } CT.Colors[ 7] := EncodeColorItem($80, $80, $80); { dark gray } CT.Colors[ 8] := EncodeColorItem($C0, $C0, $C0); { light gray } CT.Colors[ 9] := EncodeColorItem($FF, $00, $00); { red } CT.Colors[10] := EncodeColorItem($00, $FF, $00); { green } CT.Colors[11] := EncodeColorItem($FF, $FF, $00); { yellow } CT.Colors[12] := EncodeColorItem($00, $00, $FF); { blue } CT.Colors[13] := EncodeColorItem($FF, $00, $FF); { magenta } CT.Colors[14] := EncodeColorItem($00, $FF, $FF); { lt blue green } CT.Colors[15] := EncodeColorItem($FF, $FF, $FF); { white } end; { TColorTable_Create16 } procedure TColorTable_Create256(var CT: RColorTable); var ColorNo: Byte; begin { TColorTable_Create256 } CT.Count := 256; for ColorNo := 0 to 255 do CT.Colors[ColorNo] := EncodeColorItem(ColorNo, ColorNo, ColorNo); end; { TColorTable_Create256 } (***** TColorTable *****) constructor TColorTable.Create(NColors: Word); begin { TColorTable.Create } inherited Create; case NColors of 0, 2: TColorTable_CreateBW(CT); 16: TColorTable_Create16(CT); 256: TColorTable_Create256(CT); end; CT.Count := NColors; end; { TColorTable.Create } procedure TColorTable.AdjustColorCount; begin { TColorTable.AdjustColorCount } if CT.Count > 2 then if CT.Count <= 4 then CT.Count := 4 else if CT.Count <= 8 then CT.Count := 8 else if CT.Count <= 16 then CT.Count := 16 else if CT.Count <= 32 then CT.Count := 32 else if CT.Count <= 64 then CT.Count := 64 else if CT.Count <= 128 then CT.Count := 128 else if CT.Count < 256 then CT.Count := 256; end; { TColorTable.AdjustColorCount } procedure TColorTable.CompactColors; var i: integer; begin { TColorTable.CompactColors } for i := 0 to CT.Count-1 do CT.Colors[i] := DecodeColor(FCT.Colors[i]); end; { TColorTable.CompactColors } function TColorTable.GetColor(Index: Byte): TColor; begin with CT.Colors[Index] do Result := Blue shl 16 + Green shl 8 + Red; end; function TColorTable.GetColorIndex(Color: TColor): Integer; begin { GetColorIndex } Result := CT.Count - 1; while Result >= 0 do begin if Color = FCT.Colors[Result] then exit else Dec(Result); end; end; { TColorTable.GetColorIndex } function TColorTable.GetCount: Integer; begin Result := CT.Count; end; { TColorTable.GetCount } procedure TColorTable.SetCount(NewValue: Integer); begin CT.Count := NewValue; end; { TColorTable.SetCount } end.
unit UFormViewToolbar; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Menus, ATxToolbarList; type TFormViewToolbar = class(TForm) ListAvail: TListView; labAvail: TLabel; btnOk: TButton; btnCancel: TButton; ListCurrent: TListView; labCurrent: TLabel; btnAdd: TButton; btnRemove: TButton; btnReset: TButton; btnUp: TButton; btnDown: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure ListAvailSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure ListCurrentSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure FormShow(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure btnUpClick(Sender: TObject); procedure btnDownClick(Sender: TObject); procedure btnResetClick(Sender: TObject); private { Private declarations } FButtons: TToolbarList; procedure UpdateLists; public { Public declarations } end; function CustomizeToolbarDialog(AButtons: TToolbarList): boolean; implementation uses ATxMsgProc, ATxUtils; {$R *.DFM} procedure ListSelect(List: TListView; n: integer); begin with List do begin if n>Items.Count-1 then Dec(n); if n>=0 then begin ItemFocused:= Items[n]; Selected:= ItemFocused; Selected.MakeVisible(false); end; end; end; procedure ListSwapItems(List: TListView; n1, n2: integer); var s: string; en: boolean; begin with List do begin Items.BeginUpdate; s:= Items[n1].Caption; Items[n1].Caption:= Items[n2].Caption; Items[n2].Caption:= s; en:= Items[n1].Checked; Items[n1].Checked:= Items[n2].Checked; Items[n2].Checked:= en; Items.EndUpdate; end; end; function CustomizeToolbarDialog(AButtons: TToolbarList): boolean; begin with TFormViewToolbar.Create(nil) do try AButtons.CopyTo(FButtons); Result:= ShowModal=mrOk; if Result then FButtons.CopyTo(AButtons); finally Release; end; end; procedure TFormViewToolbar.FormCreate(Sender: TObject); begin FButtons:= TToolbarList.Create; end; procedure TFormViewToolbar.FormDestroy(Sender: TObject); begin FreeAndNil(FButtons); end; procedure TFormViewToolbar.UpdateLists; var Index1, Index2: integer; i, N: integer; Rec: PToolbarButtonRec; begin with ListAvail do if Assigned(Selected) then Index1:= Selected.Index else Index1:= 0; with ListCurrent do if Assigned(Selected) then Index2:= Selected.Index else Index2:= 0; ListAvail.Items.BeginUpdate; ListAvail.Items.Clear; for i:= 1 to cToolbarButtonsMax do begin if not FButtons.GetAvail(i, Rec) then Break; if (FButtons.IsAvailCurrent(i)) and (Rec^.FMenuItem.Caption<>'-') then Continue; with Rec^ do with ListAvail.Items.Add do begin if FMenuItem.Caption='-' then begin Caption:= sMsgButtonSeparator; ImageIndex:= -1; end else begin Caption:= GetToolbarButtonId(Rec^); ImageIndex:= FMenuItem.ImageIndex; end; Data:= pointer(i); end; end; ListSelect(ListAvail, Index1); ListAvail.Items.EndUpdate; ListCurrent.Items.BeginUpdate; ListCurrent.Items.Clear; for i:= 1 to cToolbarButtonsMax do begin if not FButtons.GetCurrent(i, N) then Break; if not FButtons.GetAvail(N, Rec) then Break; with Rec^ do with ListCurrent.Items.Add do begin if FMenuItem.Caption='-' then begin Caption:= sMsgButtonSeparator; ImageIndex:= -1; end else begin Caption:= GetToolbarButtonId(Rec^); ImageIndex:= FMenuItem.ImageIndex; end; Data:= pointer(N); end; end; ListSelect(ListCurrent, Index2); ListCurrent.Items.EndUpdate; end; procedure TFormViewToolbar.btnAddClick(Sender: TObject); var N: integer; OK: boolean; begin with ListAvail do if Assigned(Selected) then begin with ListCurrent do if Assigned(Selected) then N:= Selected.Index+1 else N:= 0; OK:= FButtons.AddCurrentAfter(integer(Selected.Data), N); UpdateLists; if OK then ListSelect(ListCurrent, N); end; end; procedure TFormViewToolbar.btnRemoveClick(Sender: TObject); begin with ListCurrent do if Assigned(Selected) then begin FButtons.RemoveCurrent(Selected.Index+1); UpdateLists; end; end; procedure TFormViewToolbar.ListAvailSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin btnAdd.Enabled:= Assigned(ListAvail.Selected); end; procedure TFormViewToolbar.ListCurrentSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin btnRemove.Enabled:= Assigned(ListCurrent.Selected); end; procedure TFormViewToolbar.FormShow(Sender: TObject); begin {$I Lang.FormViewToolbar.inc} ListAvail.SmallImages:= FButtons.ImageList; ListCurrent.SmallImages:= FButtons.ImageList; UpdateLists; end; procedure TFormViewToolbar.btnUpClick(Sender: TObject); begin with ListCurrent do if Assigned(Selected) then begin if FButtons.MoveCurrentUp(Selected.Index+1) then if Selected.Index>0 then ListSelect(ListCurrent, Selected.Index-1); UpdateLists; end; end; procedure TFormViewToolbar.btnDownClick(Sender: TObject); begin with ListCurrent do if Assigned(Selected) then begin if FButtons.MoveCurrentDown(Selected.Index+1) then if Selected.Index<Items.Count-1 then ListSelect(ListCurrent, Selected.Index+1); UpdateLists; end; end; procedure TFormViewToolbar.btnResetClick(Sender: TObject); begin FButtons.ResetCurrents; UpdateLists; end; end.
unit uvFrmTileFolder; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Buttons, StdCtrls, uvITileView; type TFrameTileFolder = class(TFrame, ITileView) pnlTile: TPanel; lblNameText: TLabel; imgFolder: TImage; imgClose: TImage; procedure imgCloseClick(Sender: TObject); private fTileData : TObject; fOnCloseClick : TCloseTileProc; public procedure setPosition(aLeft, aTop, aWidth : integer); function getHeight : integer; function getWidth : integer; procedure setTileData(aTileData : TObject); function getTileData : TObject; function getOwner : TComponent; procedure setParent(aParent : TWinControl); function getParent : TWinControl; procedure setControlName(aName : String); function getControlName : String; procedure setOnCloseClick(aProc : TCloseTileProc); function getTileMinWidth : integer; function getTileMinHeight : integer; end; implementation {$R *.dfm} procedure TFrameTileFolder.setPosition(aLeft, aTop, aWidth : integer); begin Left := aLeft; Top := aTop; Width := aWidth; end; function TFrameTileFolder.getHeight : integer; begin result := Height; end; function TFrameTileFolder.getWidth : integer; begin result := Width; end; procedure TFrameTileFolder.setTileData(aTileData : TObject); begin fTileData := aTileData; end; function TFrameTileFolder.getTileData : TObject; begin result := fTileData; end; function TFrameTileFolder.getOwner : TComponent; begin result := owner; end; procedure TFrameTileFolder.setParent(aParent : TWinControl); begin parent := aParent; end; function TFrameTileFolder.getParent : TWinControl; begin result := parent; end; procedure TFrameTileFolder.setControlName(aName : String); begin name := aName; end; function TFrameTileFolder.getControlName : String; begin result := name; end; procedure TFrameTileFolder.setOnCloseClick(aProc : TCloseTileProc); begin fOnCloseClick := aProc; end; procedure TFrameTileFolder.imgCloseClick(Sender: TObject); begin if assigned(fOnCloseClick) then fOnCloseClick(self); end; function TFrameTileFolder.getTileMinWidth : integer; begin result := Constraints.MinWidth; end; function TFrameTileFolder.getTileMinHeight : integer; begin result := Constraints.MinHeight; end; end.
{$IfNDef HyperlinkProcessor_imp} // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\HyperlinkProcessor.imp.pas" // Стереотип: "VCMForm" // Элемент модели: "HyperlinkProcessor" MUID: (4A815C200111) // Имя типа: "_HyperlinkProcessor_" {$Define HyperlinkProcessor_imp} {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} _HyperlinkProcessor_ = {abstract} class(_HyperlinkProcessor_Parent_, IbsHyperLinkProcessorHelper) {* Обработчик гиперссылок } protected function pm_GetHyperlinkText: TevCustomEditorWindow; virtual; abstract; function JumpTo(Sender: TObject; anEffects: TafwJumpToEffects; const aMoniker: IevMoniker): Boolean; {* Обработчик гиперссылки } procedure GetHotSpotInfo(Sender: TObject; const aHotSpot: IevHotSpot; const aKeys: TafwCursorState; var theInfo: TafwCursorInfo); {* Обработчик события OnGetHotSpotInfo } procedure DoSetHyperlinkCallStatus(aValue: Boolean); virtual; {* Выставляет флаг, определяющий произведенный переход по ссылке } function NeedJumpTo(const aHyperlink: IevHyperlink): Boolean; virtual; function GetBehaviourFromEffects(anEffects: TafwJumpToEffects): TbsProcessHyperLinkBehaviour; virtual; function MakeContainerForBehaviour(aBehaviour: TbsProcessHyperLinkBehaviour): IvcmContainer; procedure BeforeJumpTo(const aHyperlink: IevHyperlink); virtual; function DoProcessExternalOperation(const anOperation: IExternalOperation): Boolean; virtual; abstract; {* Обработчик внешней операции } function DoMakeLinkDocInfo(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal): IdeDocInfo; virtual; function DoProcessLocalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; virtual; {* Обработка локальных ссылок } function DoProcessGlobalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; virtual; procedure GotoPoint(aPointID: Cardinal; aPointType: TDocumentPositionType = bsTypesNew.dptSub); virtual; abstract; {* Переход на точку в документе } procedure OpenRedactionLocalLink(const aDocument: IDocument; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour); virtual; abstract; {* Открывает локальную ссылку на другую редакцию } procedure OpenRedactionGlobalLink(const aDocument: IDocument; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour); virtual; abstract; function HyperlinkDocument: IDocument; virtual; abstract; {* Документ ИЗ которого ведёт ссылка } procedure GetNonHyperlinkInfo(Sender: TObject; const aHotSpot: IevHotSpot; const aKeys: TafwCursorState; var theInfo: TafwCursorInfo); virtual; {* Возвращает информацию о курсоре НЕ НАД ССЫЛКОЙ } function IsFloating: Boolean; virtual; abstract; {* Форма плавающая } procedure DoCheckLinkInfo(const aLink: IevHyperlink); virtual; function MakeContainer: IvcmContainer; {* Создать параметры на которых будут делаться вызовы операций } function MakeNewMainWindow: IvcmContainer; {* Открыть новое главное окно и вернуть параметры для него } function ProcessExternalOperation(const anOperation: IExternalOperation): Boolean; procedure CheckLinkInfo(const aLink: IevHyperlink); function MakeLinkDocInfo(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal): IdeDocInfo; function ProcessLocalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; function ProcessGlobalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; function MakeTabbedContainer(aNeedActivate: Boolean): IvcmContainer; {$If NOT Defined(NoVCM)} procedure InitControls; override; {* Процедура инициализации контролов. Для перекрытия в потомках } {$IfEnd} // NOT Defined(NoVCM) protected property HyperlinkText: TevCustomEditorWindow read pm_GetHyperlinkText; {* Текст, содержащий гиперссылку } end;//_HyperlinkProcessor_ {$Else NOT Defined(Admin) AND NOT Defined(Monitorings)} _HyperlinkProcessor_ = _HyperlinkProcessor_Parent_; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) {$Else HyperlinkProcessor_imp} {$IfNDef HyperlinkProcessor_imp_impl} {$Define HyperlinkProcessor_imp_impl} {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} function _HyperlinkProcessor_.JumpTo(Sender: TObject; anEffects: TafwJumpToEffects; const aMoniker: IevMoniker): Boolean; {* Обработчик гиперссылки } var l_Hyperlink: IevHyperlink; //#UC START# *4A8199EE00F2_4A815C200111_var* //#UC END# *4A8199EE00F2_4A815C200111_var* begin //#UC START# *4A8199EE00F2_4A815C200111_impl* Result := False; if Supports(aMoniker, IevHyperlink, l_HyperLink) then try BeforeJumpTo(l_HyperLink); HyperlinkText.SetFocus; // http://mdp.garant.ru/pages/viewpage.action?pageId=460286108 if not NeedJumpTo(l_Hyperlink) then begin Result := True; Exit; end; // http://mdp.garant.ru/pages/viewpage.action?pageId=352452629 DoSetHyperlinkCallStatus(True); Result := nsProcessHyperLink(l_HyperLink, GetBehaviourFromEffects(anEffects), Self, Aggregate, HyperlinkDocument); // - http://mdp.garant.ru/pages/viewpage.action?pageId=340174500 (* Result := nsProcessHyperLink(l_HyperLink, (afw_jteRequestNewWindow in anEffects) or afw.Settings.LoadBoolean(pi_Document_OpenInNewWindow, dv_Document_OpenInNewWindow), Self, Aggregate, HyperlinkDocument); *) if not Result then DoSetHyperlinkCallStatus(False); finally l_HyperLink := nil; end;//try..finally //#UC END# *4A8199EE00F2_4A815C200111_impl* end;//_HyperlinkProcessor_.JumpTo procedure _HyperlinkProcessor_.GetHotSpotInfo(Sender: TObject; const aHotSpot: IevHotSpot; const aKeys: TafwCursorState; var theInfo: TafwCursorInfo); {* Обработчик события OnGetHotSpotInfo } var l_Hyperlink: IevHyperlink; //#UC START# *4A82C02701E4_4A815C200111_var* //#UC END# *4A82C02701E4_4A815C200111_var* begin //#UC START# *4A82C02701E4_4A815C200111_impl* if Supports(aHotSpot, IevHyperlink, l_Hyperlink) then nsCheckHyperLinkInfo(l_Hyperlink, Self, theInfo, HyperlinkDocument) else GetNonHyperlinkInfo(Sender, aHotSpot, aKeys, theInfo); //#UC END# *4A82C02701E4_4A815C200111_impl* end;//_HyperlinkProcessor_.GetHotSpotInfo procedure _HyperlinkProcessor_.DoSetHyperlinkCallStatus(aValue: Boolean); {* Выставляет флаг, определяющий произведенный переход по ссылке } //#UC START# *4F382E2D01C1_4A815C200111_var* //#UC END# *4F382E2D01C1_4A815C200111_var* begin //#UC START# *4F382E2D01C1_4A815C200111_impl* // - ничего, не делаем, пусть потомки перекрывают, если хотят //#UC END# *4F382E2D01C1_4A815C200111_impl* end;//_HyperlinkProcessor_.DoSetHyperlinkCallStatus function _HyperlinkProcessor_.NeedJumpTo(const aHyperlink: IevHyperlink): Boolean; //#UC START# *520234BD015B_4A815C200111_var* //#UC END# *520234BD015B_4A815C200111_var* begin //#UC START# *520234BD015B_4A815C200111_impl* Result := True; //#UC END# *520234BD015B_4A815C200111_impl* end;//_HyperlinkProcessor_.NeedJumpTo function _HyperlinkProcessor_.GetBehaviourFromEffects(anEffects: TafwJumpToEffects): TbsProcessHyperLinkBehaviour; //#UC START# *53A95A1A0073_4A815C200111_var* function lp_CorrectBehaviour(aBehaviour: TnsProcessHyperLinkBehaviour): TnsProcessHyperLinkBehaviour; var l_OpenKind: TvcmMainFormOpenKind; begin Result := aBehaviour; l_OpenKind := nsLinksFromDocumentOpenKind; if (aBehaviour = phbInSameContainer) then begin case l_OpenKind of vcm_okInCurrentTab: Result := phbInSameContainer; vcm_okInNewTab: if (anEffects = []) then Result := phbInNewTabActivate else if (anEffects = [afw_jteRequestNewTab]) then Result := phbInNewTabNoActivate; vcm_okInNewWindow: Result := phbInNewWindow; end; end else if (aBehaviour = phbInNewTabNoActivate) then Result := aBehaviour; end;//lp_CorrectBehaviour const cBehaviourToEffectsArr: array[TnsProcessHyperLinkBehaviour] of TafwJumpToEffects = ([], //phbInSameContainer [afw_jteRequestNewTab, afw_jteRequestNoActivate], //phbInNewTabNoActivate [afw_jteRequestNewTab], //phbInNewTabActivate [afw_jteRequestNewWindow]);//phpInNewWindow var l_Index: TnsProcessHyperLinkBehaviour; l_BehaviourFromEffects: TnsProcessHyperLinkBehaviour; //#UC END# *53A95A1A0073_4A815C200111_var* begin //#UC START# *53A95A1A0073_4A815C200111_impl* l_BehaviourFromEffects := phbInSameContainer; for l_Index := Low(TnsProcessHyperLinkBehaviour) to High(TnsProcessHyperLinkBehaviour) do if (cBehaviourToEffectsArr[l_Index] = anEffects) then begin l_BehaviourFromEffects := l_Index; Break; end; Result := lp_CorrectBehaviour(l_BehaviourFromEffects); //#UC END# *53A95A1A0073_4A815C200111_impl* end;//_HyperlinkProcessor_.GetBehaviourFromEffects function _HyperlinkProcessor_.MakeContainerForBehaviour(aBehaviour: TbsProcessHyperLinkBehaviour): IvcmContainer; //#UC START# *54D3144F0227_4A815C200111_var* //#UC END# *54D3144F0227_4A815C200111_var* begin //#UC START# *54D3144F0227_4A815C200111_impl* case aBehaviour of phbInSameContainer: Result := nil; phbInNewTabNoActivate: Result := MakeTabbedContainer(False); phbInNewTabActivate: Result := MakeTabbedContainer(True); phbInNewWindow: Result := MakeNewMainWindow; else Assert(False); end;//case aBehaviour //#UC END# *54D3144F0227_4A815C200111_impl* end;//_HyperlinkProcessor_.MakeContainerForBehaviour procedure _HyperlinkProcessor_.BeforeJumpTo(const aHyperlink: IevHyperlink); //#UC START# *5767DF4D033E_4A815C200111_var* //#UC END# *5767DF4D033E_4A815C200111_var* begin //#UC START# *5767DF4D033E_4A815C200111_impl* // для перекрытия в потомках //#UC END# *5767DF4D033E_4A815C200111_impl* end;//_HyperlinkProcessor_.BeforeJumpTo function _HyperlinkProcessor_.DoMakeLinkDocInfo(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal): IdeDocInfo; //#UC START# *4A815FB3005D_4A815C200111_var* //#UC END# *4A815FB3005D_4A815C200111_var* begin //#UC START# *4A815FB3005D_4A815C200111_impl* Result := TdeDocInfo.Make(aDocument, TbsDocPos_C(aPointType, aSub)); //#UC END# *4A815FB3005D_4A815C200111_impl* end;//_HyperlinkProcessor_.DoMakeLinkDocInfo function _HyperlinkProcessor_.DoProcessLocalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; {* Обработка локальных ссылок } //#UC START# *4A8160720125_4A815C200111_var* //#UC END# *4A8160720125_4A815C200111_var* begin //#UC START# *4A8160720125_4A815C200111_impl* Result := true; if aDocument.IsSameRedaction(HyperlinkDocument) then begin // Переход по локальной ссылке в текущей редакции документа if (aBehaviour = phbInSameContainer) then // - http://mdp.garant.ru/pages/viewpage.action?pageId=569213206 begin Dispatcher.History.SaveState(Self.As_IvcmEntityForm, vcm_stPosition); GoToPoint(aSub); end else Result := False; end//aDocument.IsSameRedaction(HyperlinkDocument) else // Переход по локальной ссылке на другую редакцию документа OpenRedactionLocalLink(aDocument, aSub, aBehaviour); //#UC END# *4A8160720125_4A815C200111_impl* end;//_HyperlinkProcessor_.DoProcessLocalLink function _HyperlinkProcessor_.DoProcessGlobalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; //#UC START# *53A2F4B30119_4A815C200111_var* //#UC END# *53A2F4B30119_4A815C200111_var* begin //#UC START# *53A2F4B30119_4A815C200111_impl* Result := //(aBehaviour = phbInNewWindow) and // это сделано для открытия СР в новом окне aDocument.IsSameDocument(HyperlinkDocument) and not aDocument.IsSameRedaction(HyperlinkDocument); if Result then OpenRedactionGlobalLink(aDocument, aSub, aBehaviour); //#UC END# *53A2F4B30119_4A815C200111_impl* end;//_HyperlinkProcessor_.DoProcessGlobalLink procedure _HyperlinkProcessor_.GetNonHyperlinkInfo(Sender: TObject; const aHotSpot: IevHotSpot; const aKeys: TafwCursorState; var theInfo: TafwCursorInfo); {* Возвращает информацию о курсоре НЕ НАД ССЫЛКОЙ } //#UC START# *4A890E81030B_4A815C200111_var* //#UC END# *4A890E81030B_4A815C200111_var* begin //#UC START# *4A890E81030B_4A815C200111_impl* // - ничего не делаем //#UC END# *4A890E81030B_4A815C200111_impl* end;//_HyperlinkProcessor_.GetNonHyperlinkInfo procedure _HyperlinkProcessor_.DoCheckLinkInfo(const aLink: IevHyperlink); //#UC START# *4A8A9E2A004F_4A815C200111_var* //#UC END# *4A8A9E2A004F_4A815C200111_var* begin //#UC START# *4A8A9E2A004F_4A815C200111_impl* // - ничего не делаем //#UC END# *4A8A9E2A004F_4A815C200111_impl* end;//_HyperlinkProcessor_.DoCheckLinkInfo function _HyperlinkProcessor_.MakeContainer: IvcmContainer; {* Создать параметры на которых будут делаться вызовы операций } //#UC START# *4A7687C702C8_4A815C200111_var* //#UC END# *4A7687C702C8_4A815C200111_var* begin //#UC START# *4A7687C702C8_4A815C200111_impl* if IsFloating then Result := vcmDispatcher.FormDispatcher.CurrentMainForm.AsContainer else Result := NativeMainForm; //#UC END# *4A7687C702C8_4A815C200111_impl* end;//_HyperlinkProcessor_.MakeContainer function _HyperlinkProcessor_.MakeNewMainWindow: IvcmContainer; {* Открыть новое главное окно и вернуть параметры для него } //#UC START# *4A7687F0016D_4A815C200111_var* //#UC END# *4A7687F0016D_4A815C200111_var* begin //#UC START# *4A7687F0016D_4A815C200111_impl* if TvcmTabbedContainerFormDispatcher.Instance.NeedUseTabs then Result := nsOpenNewWindowTabbed(MakeContainer, vcm_okInNewWindow) else if IsFloating then Result := nsOpenNewWindowParams(vcmDispatcher.FormDispatcher.CurrentMainForm.AsContainer) else Result := nsOpenNewWindowParams(NativeMainForm); //#UC END# *4A7687F0016D_4A815C200111_impl* end;//_HyperlinkProcessor_.MakeNewMainWindow function _HyperlinkProcessor_.ProcessExternalOperation(const anOperation: IExternalOperation): Boolean; //#UC START# *4A76CDFA014B_4A815C200111_var* //#UC END# *4A76CDFA014B_4A815C200111_var* begin //#UC START# *4A76CDFA014B_4A815C200111_impl* Result := DoProcessExternalOperation(anOperation); //#UC END# *4A76CDFA014B_4A815C200111_impl* end;//_HyperlinkProcessor_.ProcessExternalOperation procedure _HyperlinkProcessor_.CheckLinkInfo(const aLink: IevHyperlink); //#UC START# *4A780EBF00CD_4A815C200111_var* //#UC END# *4A780EBF00CD_4A815C200111_var* begin //#UC START# *4A780EBF00CD_4A815C200111_impl* DoCheckLinkInfo(aLink); //#UC END# *4A780EBF00CD_4A815C200111_impl* end;//_HyperlinkProcessor_.CheckLinkInfo function _HyperlinkProcessor_.MakeLinkDocInfo(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal): IdeDocInfo; //#UC START# *4A79216102C6_4A815C200111_var* //#UC END# *4A79216102C6_4A815C200111_var* begin //#UC START# *4A79216102C6_4A815C200111_impl* Result := DoMakeLinkDocInfo(aDocument, aPointType, aSub); //#UC END# *4A79216102C6_4A815C200111_impl* end;//_HyperlinkProcessor_.MakeLinkDocInfo function _HyperlinkProcessor_.ProcessLocalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; //#UC START# *4A7928E80375_4A815C200111_var* //#UC END# *4A7928E80375_4A815C200111_var* begin //#UC START# *4A7928E80375_4A815C200111_impl* Result := DoProcessLocalLink(aDocument, aPointType, aSub, aBehaviour); //#UC END# *4A7928E80375_4A815C200111_impl* end;//_HyperlinkProcessor_.ProcessLocalLink function _HyperlinkProcessor_.ProcessGlobalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal; aBehaviour: TbsProcessHyperLinkBehaviour): Boolean; //#UC START# *53A2EF1B036C_4A815C200111_var* //#UC END# *53A2EF1B036C_4A815C200111_var* begin //#UC START# *53A2EF1B036C_4A815C200111_impl* Result := DoProcessGlobalLink(aDocument, aPointType, aSub, aBehaviour); //#UC END# *53A2EF1B036C_4A815C200111_impl* end;//_HyperlinkProcessor_.ProcessGlobalLink function _HyperlinkProcessor_.MakeTabbedContainer(aNeedActivate: Boolean): IvcmContainer; //#UC START# *53A812BE013E_4A815C200111_var* //#UC END# *53A812BE013E_4A815C200111_var* begin //#UC START# *53A812BE013E_4A815C200111_impl* Result := nsOpenNewWindowTabbed(MakeContainer, vcm_okInNewTab, aNeedActivate); //#UC END# *53A812BE013E_4A815C200111_impl* end;//_HyperlinkProcessor_.MakeTabbedContainer {$If NOT Defined(NoVCM)} procedure _HyperlinkProcessor_.InitControls; {* Процедура инициализации контролов. Для перекрытия в потомках } //#UC START# *4A8E8F2E0195_4A815C200111_var* //#UC END# *4A8E8F2E0195_4A815C200111_var* begin //#UC START# *4A8E8F2E0195_4A815C200111_impl* inherited; with HyperlinkText do begin OnJumpTo := Self.JumpTo; OnGetHotSpotInfo := Self.GetHotSpotInfo; end;//with HyperlinkText //#UC END# *4A8E8F2E0195_4A815C200111_impl* end;//_HyperlinkProcessor_.InitControls {$IfEnd} // NOT Defined(NoVCM) {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) {$EndIf HyperlinkProcessor_imp_impl} {$EndIf HyperlinkProcessor_imp}
unit fb2iSilo_dispatch; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, FB2_to_iSilo_TLB, StdVcl,fb2iSilo_engine,MSXML2_TLB,Windows; type TFB2iSiloExport = class(TAutoObject, IFB2iSiloExport) procedure BeforeDestruction; override; private ConverterVar:TFB2iSiloConverter; Function GetConverter:TFB2iSiloConverter; protected procedure AfterConstruction; Override; function Get_SkipImages: WordBool; safecall; function Get_TOCLevels: Integer; safecall; function Get_XSL: IDispatch; safecall; procedure Convert(const document: IDispatch; filename: OleVariant); safecall; procedure ConvertInteractive(hWnd: Integer; filename: OleVariant; const document: IDispatch); safecall; procedure Set_SkipImages(Value: WordBool); safecall; procedure Set_TOCLevels(Value: Integer); safecall; procedure Set_XSL(const Value: IDispatch); safecall; function Get_IXLXSL: IDispatch; safecall; procedure Set_IXLXSL(const Value: IDispatch); safecall; property Converter:TFB2iSiloConverter read GetConverter write ConverterVar; { Protected declarations } end; implementation uses ComServ,SysUtils,save_iSilo_dialog,Dialogs; procedure TFB2iSiloExport.BeforeDestruction; Begin inherited BeforeDestruction; if ConverterVar<>Nil then ConverterVar.Free; end; Function TFB2iSiloExport.GetConverter; Begin if ConverterVar=Nil then ConverterVar:=TFB2iSiloConverter.Create; Result:=ConverterVar; end; procedure TFB2iSiloExport.AfterConstruction; Begin Converter:=Nil; end; function TFB2iSiloExport.Get_SkipImages: WordBool; begin Result:=Converter.SkipImg; end; function TFB2iSiloExport.Get_TOCLevels: Integer; begin Result:=Converter.TocDeep; end; function TFB2iSiloExport.Get_XSL: IDispatch; begin Result:=Converter.DocumentXSL; end; procedure TFB2iSiloExport.Convert(const document: IDispatch; filename: OleVariant); Var DOM:IXMLDOMDocument2; begin if document.QueryInterface(IID_IXMLDOMDocument2,DOM) <> S_OK then Raise Exception.Create('Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2'); Converter.Convert(DOM,filename); end; procedure TFB2iSiloExport.ConvertInteractive(hWnd: Integer; filename: OleVariant; const document: IDispatch); Var DOM:IXMLDOMDocument2; DLG:TOpenPictureDialog; FN:String; begin FN:=filename; if Document=Nil then With TOpenDialog.Create(Nil) do try Filter:='FictionBook 2.0 documents (*.fb2)|*.fb2|All files (*.*)|*.*'; If not Execute then Exit; DOM:=CoFreeThreadedDOMDocument40.Create; if not DOM.load(FileName) then Raise Exception.Create('Opening fb2 file:'#10+DOM.parseError.reason); FN:=FileName; Finally Free; end else if document.QueryInterface(IID_IXMLDOMDocument2,DOM) <> S_OK then Raise Exception.Create('Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2'); try DLG:=TOpenPictureDialog.Create(Nil); if FN<>'' then DLG.FileName:=copy(FN,1,Length(FN)-Length(ExtractFileExt(FN)))+'.pdb'; with DLG do Begin if Execute then ExportDOM(DOM,DLG.FileName,DLG.TocDepth,DLG.DoSkipImages); Free; end; except on E: Exception do MessageBox(hWnd,PChar(E.Message),'Error',MB_OK or MB_ICONERROR); end; end; procedure TFB2iSiloExport.Set_SkipImages(Value: WordBool); begin Converter.SkipImg:=Value; end; procedure TFB2iSiloExport.Set_TOCLevels(Value: Integer); begin Converter.TocDeep:=Value; end; procedure TFB2iSiloExport.Set_XSL(const Value: IDispatch); Var OutVar:IXMLDOMDocument2; begin if Value.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR) else Converter.DocumentXSL:=OutVar; end; function TFB2iSiloExport.Get_IXLXSL: IDispatch; begin Result:=Converter.IXLXSL; end; procedure TFB2iSiloExport.Set_IXLXSL(const Value: IDispatch); Var OutVar:IXMLDOMDocument2; begin if Value.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR) else Converter.IXLXSL:=OutVar; end; initialization TAutoObjectFactory.Create(ComServer, TFB2iSiloExport, CLASS_FB2iSiloExport, ciMultiInstance, tmApartment); end.
unit viewer_thtmlcomp; {$mode delphi} interface uses Classes, SysUtils, // browserviewer, // HtmlMisc, HTMLsubs, Htmlview, HTMLun2; type { THtmlCompViewer } THtmlCompViewer = class(TBrowserViewer) private Viewer: THTMLViewer; FoundObject: TImageObj; procedure ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ViewerProgress(Sender: TObject; Stage: TProgressStage; PercentDone: Integer); procedure ViewerPrintHTMLFooter(Sender: TObject; HFViewer: THTMLViewer; NumPage: Integer; LastPage: Boolean; var XL, XR: Integer; var StopPrinting: Boolean); procedure ViewerPrintHTMLHeader(Sender: TObject; HFViewer: THTMLViewer; NumPage: Integer; LastPage: Boolean; var XL, XR: Integer; var StopPrinting: Boolean); procedure HotSpotChange(Sender: TObject; const URL: string); procedure HotSpotClick(Sender: TObject; const URL: string; var Handled: boolean); procedure RightClick(Sender: TObject; Parameters: TRightClickParameters); procedure ViewerImageRequest(Sender: TObject; const SRC: string; var Stream: TMemoryStream); public procedure CreateViewer(AParent, AOwner: TWinControl); override; procedure LoadFromFile(AFilename: string); override; // procedure LoadFromURL(AURL: string); override; function GetDocumentTitle: string; override; procedure SetShowImages(AValue: Boolean); override; procedure HandlePageLoaderTerminated(Sender: TObject); override; procedure Reload; override; end; implementation { THtmlCompViewer } procedure THtmlCompViewer.ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var TitleStr: string; begin if not Timer1.Enabled and Assigned(ActiveControl) and ActiveControl.Focused then {9.25} begin TitleStr := Viewer.TitleAttr; if TitleStr = '' then OldTitle := '' else if TitleStr <> OldTitle then begin TimerCount := 0; Timer1.Enabled := True; OldTitle := TitleStr; end; end; end; procedure THtmlCompViewer.ViewerProgress(Sender: TObject; Stage: TProgressStage; PercentDone: Integer); begin ProgressBar.Position := PercentDone; case Stage of psStarting: ProgressBar.Visible := True; psRunning:; psEnding: ProgressBar.Visible := False; end; ProgressBar.Update; end; procedure THtmlCompViewer.ViewerPrintHTMLFooter(Sender: TObject; HFViewer: THTMLViewer; NumPage: Integer; LastPage: Boolean; var XL, XR: Integer; var StopPrinting: Boolean); var S: string; begin S := ReplaceStr(HFText, '#left', Viewer.DocumentTitle); S := ReplaceStr(S, '#right', Viewer.CurrentFile); HFViewer.LoadFromString(S); end; procedure THtmlCompViewer.ViewerPrintHTMLHeader(Sender: TObject; HFViewer: THTMLViewer; NumPage: Integer; LastPage: Boolean; var XL, XR: Integer; var StopPrinting: Boolean); var S: string; begin S := ReplaceStr(HFText, '#left', DateToStr(Date)); S := ReplaceStr(S, '#right', 'Page '+IntToStr(NumPage)); HFViewer.LoadFromString(S); end; procedure THtmlCompViewer.HotSpotChange(Sender: TObject; const URL: string); {mouse moved over or away from a hot spot. Change the status line} var Caption: string; begin Caption := ''; if URL <> '' then Caption := Caption+'URL: '+URL+' '; if Viewer.TitleAttr <> '' then Caption := Caption+'Title: '+Viewer.TitleAttr; panelBottom.Caption := Caption; end; {This routine handles what happens when a hot spot is clicked. The assumption is made that DOS filenames are being used. .EXE, .WAV, .MID, and .AVI files are handled here, but other file types could be easily added. If the URL is handled here, set Handled to True. If not handled here, set it to False and ThtmlViewer will handle it.} procedure THtmlCompViewer.HotSpotClick(Sender: TObject; const URL: string; var Handled: boolean); const snd_Async = $0001; { play asynchronously } var PC: array[0..255] of char; {$IFDEF LCL} PC2: array[0..255] of char; {$ENDIF} S, Params: string[255]; Ext: string[5]; ID: string; AbsURL: string; I, J, K: integer; begin Handled := False; {The following looks for a link of the form, "IDExpand_XXX". This is interpreted as meaning a block with an ID="XXXPlus" or ID="XXXMinus" attribute should have its Display property toggled. } I := Pos('IDEXPAND_', Uppercase(URL)); if I=1 then begin ID := Copy(URL, 10, Length(URL)-9); Viewer.IDDisplay[ID+'Plus'] := not Viewer.IDDisplay[ID+'Plus']; Viewer.IDDisplay[ID+'Minus'] := not Viewer.IDDisplay[ID+'Minus']; Viewer.Reformat; Handled := True; Exit; end; AbsURL := MyPageLoader.URLToAbsoluteURL(URL); J := Pos('HTTP:', UpperCase(AbsURL)); if (J > 0) then begin LoadURL(AbsURL); Handled := True; Exit; end; I := Pos(':', URL); J := Pos('FILE:', UpperCase(URL)); if (I <= 2) or (J > 0) then begin {apparently the URL is a filename} S := URL; K := Pos(' ', S); {look for parameters} if K = 0 then K := Pos('?', S); {could be '?x,y' , etc} if K > 0 then begin Params := Copy(S, K+1, 255); {save any parameters} S[0] := chr(K-1); {truncate S} end else Params := ''; S := Viewer.HTMLExpandFileName(S); Ext := Uppercase(ExtractFileExt(S)); if Ext = '.WAV' then begin Handled := True; {$IFNDEF LCL} sndPlaySound(StrPCopy(PC, S), snd_ASync); {$ENDIF} end else if Ext = '.EXE' then begin Handled := True; {$IFNDEF LCL} WinExec(StrPCopy(PC, S+' '+Params), sw_Show); {$ELSE} {$IFDEF MSWINDOWS} ShellExecute(Handle, nil, StrPCopy(PC, S), StrPCopy(PC2, Params), nil, SW_SHOWNORMAL); {$ELSE} //Not sure if this makes any sense since executable won't have .exe. {$IFDEF DARWIN} Shell('open -n "' + S + '" --args "' + Params + '"'); {$ELSE} Shell('"' + S + '" "' + Params + '"'); {$ENDIF} {$ENDIF} {$ENDIF} end else if (Ext = '.MID') or (Ext = '.AVI') then begin Handled := True; {$IFNDEF LCL} WinExec(StrPCopy(PC, 'MPlayer.exe /play /close '+S), sw_Show); {$ELSE} {$IFDEF MSWINDOWS} ShellExecute(Handle, nil, 'MPlayer.exe', '/play /close', nil, SW_SHOWNORMAL); {$ELSE} //No equivalent to MPlayer? {$ENDIF} {$ENDIF} end; {else ignore other extensions} editURL.Text := URL; Exit; end; I := Pos('MAILTO:', UpperCase(URL)); if (I > 0) then begin {$IFDEF MSWINDOWS} ShellExecute(0, nil, pchar(URL), nil, nil, SW_SHOWNORMAL); {$ELSE} {$IFDEF DARWIN} Shell('open "' + URL + '"'); {$ELSE} Shell('"' + URL + '"'); //use LCL's OpenURL? {$ENDIF} {$ENDIF} Handled := True; Exit; end; editURL.Text := URL; {other protocall} end; procedure THtmlCompViewer.RightClick(Sender: TObject; Parameters: TRightClickParameters); var Pt: TPoint; S, Dest: string; I: integer; HintWindow: THintWindow; ARect: TRect; begin with Parameters do begin FoundObject := Image; ViewImage.Enabled := (FoundObject <> Nil) and (FoundObject.Bitmap <> Nil); CopyImageToClipboard.Enabled := (FoundObject <> Nil) and (FoundObject.Bitmap <> Nil); if URL <> '' then begin S := URL; I := Pos('#', S); if I >= 1 then begin Dest := System.Copy(S, I, 255); {local destination} S := System.Copy(S, 1, I-1); {the file name} end else Dest := ''; {no local destination} if S = '' then S := Viewer.CurrentFile else S := Viewer.HTMLExpandFileName(S); NewWindowFile := S+Dest; OpenInNewWindow.Enabled := FileExists(S); end else OpenInNewWindow.Enabled := False; GetCursorPos(Pt); if Length(CLickWord) > 0 then begin HintWindow := THintWindow.Create(Self); try ARect := Rect(0,0,0,0); DrawTextW(HintWindow.Canvas.Handle, @ClickWord[1], Length(ClickWord), ARect, DT_CALCRECT); with ARect do HintWindow.ActivateHint(Rect(Pt.X+20, Pt.Y-(Bottom-Top)-15, Pt.x+30+Right, Pt.Y-15), ClickWord); PopupMenu.Popup(Pt.X, Pt.Y); finally HintWindow.Free; end; end else PopupMenu.Popup(Pt.X, Pt.Y); end; end; { In this event we should provide images for the html component } procedure THtmlCompViewer.ViewerImageRequest(Sender: TObject; const SRC: string; var Stream: TMemoryStream); var J: Integer; URL: string; begin URL := MyPageLoader.URLToAbsoluteURL(SRC); J := Pos('http:', LowerCase(URL)); if (J > 0) then begin MyPageLoader.LoadBinaryResource(URL, Stream); Exit; end; end; procedure THtmlCompViewer.CreateViewer(AParent, AOwner: TWinControl); begin ViewerName := 'THTMLComp written in Pascal'; Viewer := THTMLViewer.Create(AOwner); Viewer.Left := 1; Viewer.Height := 358; Viewer.Top := 1; Viewer.Width := 611; Viewer.OnHotSpotCovered := HotSpotChange; Viewer.OnHotSpotClick := HotSpotClick; Viewer.OnImageRequest := ViewerImageRequest; Viewer.OnFormSubmit := SubmitEvent; Viewer.OnHistoryChange := HistoryChange; Viewer.OnProgress := ViewerProgress; Viewer.TabStop := True; Viewer.TabOrder := 0; Viewer.Align := alClient; Viewer.DefBackground := clWindow; Viewer.BorderStyle := htFocused; Viewer.HistoryMaxCount := 6; Viewer.DefFontName := 'Times New Roman'; Viewer.DefPreFontName := 'Courier New'; Viewer.DefFontColor := clWindowText; Viewer.DefOverLinkColor := clFuchsia; Viewer.ImageCacheCount := 6; Viewer.NoSelect := False; Viewer.CharSet := DEFAULT_CHARSET; Viewer.PrintMarginLeft := 2; Viewer.PrintMarginRight := 2; Viewer.PrintMarginTop := 2; Viewer.PrintMarginBottom := 2; Viewer.PrintScale := 1; Viewer.OnMouseMove := ViewerMouseMove; Viewer.OnProcessing := ProcessingHandler; Viewer.OnPrintHTMLHeader := ViewerPrintHTMLHeader; Viewer.OnPrintHTMLFooter := ViewerPrintHTMLFooter; Viewer.OnInclude := ViewerInclude; //Viewer.OnSoundRequest := SoundRequest; Viewer.OnMetaRefresh := MetaRefreshEvent; Viewer.OnObjectClick := ObjectClick; Viewer.OnRightClick := RightClick; Viewer.Parent := AParent; // ShowImages.Checked := Viewer.ViewImages; Viewer.HistoryMaxCount := MaxHistories; {defines size of history list} end; procedure THtmlCompViewer.LoadFromFile(AFilename: string); begin Viewer.LoadFromFile(HtmlToDos(Trim(AFilename))); end; function THtmlCompViewer.GetDocumentTitle: string; begin Result := Viewer.DocumentTitle; end; procedure THtmlCompViewer.SetShowImages(AValue: Boolean); begin Viewer.ViewImages := AValue; end; procedure THtmlCompViewer.HandlePageLoaderTerminated(Sender: TObject); begin inherited HandlePageLoaderTerminated(Sender); Viewer.LoadFromString(MyPageLoader.Contents); Caption := Viewer.DocumentTitle; end; procedure THtmlCompViewer.Reload; begin Viewer.ReLoad; Viewer.SetFocus; end; initialization SetBrowserViewerClass(THtmlCompViewer); end.
unit https; interface {$I DelphiDefs.inc} {$IFDEF MSWINDOWS} uses MSXML2_TLB, sysutils, variants, typex, commandprocessor, classes, debug, IdSSLOpenSSL, systemx, IdSSLOpenSSLHeaders, betterobject, helpers_stream; const DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'; type TExtraHeader = record name: string; value: string; class function make(n,v: string): TExtraHeader;static; end; THttpsMethod = (mGet, mPost); THTTPSRequest = record addHead: string; addHeadValue: string; method: ThttpsMethod; acceptranges: string; contentlength: int64; range: string; url: string; PostData: string; Referer: string; Cookie: string; ContentType: string; PostBody: string; end; THTTPResults = record ResultCode: ni; Body: string; Success: boolean; contentType: string; contentRange: string; error: string; cookie_headers: array of string; bodystream: IHolder<TStream>; procedure AddCookieHeader(s: string); end; Tcmd_HTTPS = class(TCommand) private public Request: THTTPSRequest; Results: THTTPResults; procedure DoExecute; override; procedure Init; override; end; Tcmd_HTTPsToFile = class(Tcmd_HTTPS) public UrL: string; IgnoreIftargetExists: boolean; LocalFile: String; procedure DoExecute; override; end; //function QuickHTTPSGet(sURL: ansistring): ansistring; function QuickHTTPSGet(sURL: ansistring; out sOutREsponse: string; addHead: string =''; addHeadValue: string = ''): boolean;overload; function QuickHTTPSGet(sURL: ansistring; out sOutREsponse: string; addHeaders: TArray<TExtraHeader>): boolean;overload; function QuickHTTPSPost(sURL: ansistring; sPostBody: ansistring; out sOutREsponse: string; contentType: string = DEFAULT_CONTENT_TYPE; addHead: string =''; addHeadValue: string = ''; method: string = 'POST'): boolean; function QuickHTTPSPostOld(sURL: ansistring; PostData: ansistring; ContentType: ansistring = 'application/x-www-form-urlencoded'): ansistring; function HTTPSGet(sURL: string; referer: string = ''): THTTPResults; function HTTPSPost(sURL: string; PostData: string; ContentType: string = 'application/x-www-form-urlencoded'): THTTPResults; procedure https_SetHeaderIfSet(htp: IXMLHttpRequest; sheader: string; sValue: string); {$ENDIF} implementation {$IFDEF MSWINDOWS} function QuickHTTPSPost(sURL: ansistring; sPostBody: ansistring; out sOutREsponse: string; contentType: string = DEFAULT_CONTENT_TYPE; addHead: string =''; addHeadValue: string = ''; method: string = 'POST'): boolean; var htp: IXMLhttprequest; begin {$IFDEF LOG_HTTP} Debug.Log(sURL); {$ENDIF} htp := ComsXMLHTTP30.create(); try htp.open(method, sURL, false, null, null); htp.setRequestHeader('Content-Type', ContentType); if addHead <> '' then htp.setRequestHeader(addHead, addHeadValue); htp.send(sPostBody); result := htp.status = 200; if result then sOutREsponse := htp.responsetext else begin soutResponse := htp.responsetext; end; except on e: Exception do begin result := false; sOutResponse := 'error '+e.message; end; end; end; function QuickHTTPSGet(sURL: ansistring; out sOutREsponse: string; addHeaders: TArray<TExtraHeader>): boolean; var t: ni; htp: IXMLhttprequest; begin {$IFDEF LOG_HTTP} Debug.Log(sURL); {$ENDIF} htp := ComsXMLHTTP30.create(); try htp.open('GET', sURL, false, null, null); for t := 0 to high(addHeaders) do begin htp.setRequestHeader(addHeaders[t].name, addHeaders[t].value); end; htp.send(''); result := htp.status = 200; if result then sOutREsponse := htp.responsetext else begin soutResponse := htp.responsetext; end; except on e: Exception do begin result := false; sOutResponse := 'error '+e.message; end; end; end; function QuickHTTPSGet(sURL: ansistring; out sOutREsponse: string; addHead: string =''; addHeadValue: string = ''): boolean; var htp: IXMLhttprequest; begin {$IFDEF LOG_HTTP} Debug.Log(sURL); {$ENDIF} htp := ComsXMLHTTP30.create(); try htp.open('GET', sURL, false, null, null); if addHead <> '' then htp.setRequestHeader(addHead, addHeadValue); htp.send(''); result := htp.status = 200; if result then sOutREsponse := htp.responsetext else begin soutResponse := htp.responsetext; end; except on e: Exception do begin result := false; sOutResponse := 'error '+e.message; end; end; end; function QuickHTTPSPostOld(sURL: ansistring; PostData: ansistring; ContentType: ansistring = 'application/x-www-form-urlencoded'): ansistring; var htp: IXMLhttprequest; begin // raise Exception.create('carry forward'); htp := ComsXMLHTTP30.create(); try htp.open('POST', sURL, false,null,null); htp.setRequestHeader('Accept-Language', 'en'); //htp.setRequestHeader('Connection:', 'Keep-Alive'); htp.setRequestHeader('Content-Type', ContentType); htp.setRequestHeader('Content-Length', inttostr(length(PostData))); htp.send(PostData); result := ansistring(htp.responsetext); finally // htp.free; end; end; function HTTPSGet(sURL: string; referer: string = ''): THTTPResults; var htp: IXMLhttprequest; begin // raise Exception.create('carry forward'); result.error := ''; htp := ComsXMLHTTP30.create(); try try htp.open('GET', sURL, false, null, null); htp.setRequestHeader('Referer', referer); htp.send(''); result.ResultCode := htp.status; result.Body := htp.responseText; result.contentType := htp.getResponseHeader('Content-type'); result.Success := true; result.bodystream := THolder<TStream>.create; Result.bodystream.o := olevarianttomemoryStream(htp.responsebody); except on e: Exception do begin result.success := false; result.error := e.message; end; end; finally // htp.free; end; end; function HTTPSPost(sURL: string; PostData: string; ContentType: string = 'application/x-www-form-urlencoded'): THTTPResults; var htp: IXMLhttprequest; begin // raise Exception.create('carry forward'); result.error := ''; htp := ComsXMLHTTP30.create(); try htp.open('POST', sURL, false,null,null); htp.setRequestHeader('Accept-Language', 'en'); htp.setRequestHeader('Connection:', 'Keep-Alive'); htp.setRequestHeader('Content-Type', ContentType); htp.setRequestHeader('Content-Length', inttostr(length(PostData))); htp.send(PostData); result.ResultCode := htp.status; result.Body := htp.responsetext; finally // htp.free; end; end; { Tcmd_HTTPS } procedure Tcmd_HTTPS.DoExecute; var htp: IXMLhttprequest; sMeth: string; begin inherited; if request.method = mGet then begin try {$IFDEF LOG_HTTP} Debug.Log(sURL); {$ENDIF} htp := ComsXMLHTTP30.create(); try if self.request.method = THttpsMethod.mPost then sMeth := 'POST' else sMeth := 'GET'; htp.open(sMeth, self.request.url, false, null, null); https_setheaderifset(htp, 'Content-Length', inttostr(request.contentlength)); https_setheaderifset(htp, 'Content-Type', request.contenttype); https_setheaderifset(htp, 'Accept-Ranges', request.acceptranges); https_setheaderifset(htp, 'Range', request.range); https_setheaderifset(htp, 'Referer', request.referer); https_setheaderifset(htp, 'Cookie', request.Cookie); https_setheaderifset(htp, 'CookieEx', request.Cookie); https_setheaderifset(htp, request.addHead, request.addHeadValue); if self.request.method = mGet then htp.send('') else htp.send(request.postBody); results.ResultCode := htp.status; results.contentRange := htp.getResponseHeader('Content-Range'); results.contentType := htp.getResponseHeader('Content-Type'); var s := htp.getResponseHeader('Set-Cookie'); if s <> '' then begin results.AddCookieHeader(s); end; results.bodystream := THolder<TStream>.create; self.Results.bodystream.o := olevarianttomemoryStream(htp.responsebody); // results.Body := htp.responsetext; except on e: Exception do begin ErrorMessage := e.message; results.Body := 'error '+e.message; end; end; finally end; end else if request.method = mPost then begin results := HTTPSPost(request.url, request.PostData, request.contenttype); end; end; procedure Tcmd_HTTPS.Init; begin inherited; request.ContentType := 'application/x-www-form-urlencoded'; end; procedure https_SetHeaderIfSet(htp: IXMLHttpRequest; sheader: string; sValue: string); begin if sValue = '' then exit; htp.setRequestHeader(sHeader, sValue); end; { THTTPSRequest } { TExtraHeader } class function TExtraHeader.make(n, v: string): TExtraHeader; begin result.name := n; result.value := v; end; { THTTPResults } procedure THTTPResults.AddCookieHeader(s: string); begin setlength(self.cookie_headers, length(self.cookie_headers)+1); cookie_headers[high(cookie_headers)] := s; end; { Tcmd_HTTPsToFile } procedure Tcmd_HTTPsToFile.DoExecute; begin //inherited; request.url := URL; if (not IgnoreIftargetExists) or (not FileExists(LocalFile)) then begin inherited; var fs := TfileStream.create(LocalFile, fmCreate); try Stream_GuaranteeCopy(self.Results.bodystream.o, fs); finally fs.free; end; end; end; initialization if fileexists(dllpath+'ssleay32.dll') then begin IdOpenSSLSetLibPath(DLLPath); IdSSLOpenSSL.LoadOpenSSLLibrary; end; {$ENDIF} end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, DPF.iOS.BaseControl, System.Math, System.DateUtils, DPF.iOS.Common, DPF.iOS.UIFont, DPF.iOS.UITableView, DPF.iOS.UITableViewItems, DPF.iOS.UILabel, DPF.iOS.UIImageView, DPF.iOS.UIView, DPF.iOS.UIButton, DPF.iOS.UISwitch; type TFTableViewCustomView = class( TForm ) DPFUITableView1: TDPFUITableView; DPFUIView1: TDPFUIView; DPFUIView2: TDPFUIView; DPFSwitch1: TDPFSwitch; DPFButton1: TDPFButton; DPFButton2: TDPFButton; procedure FormCreate( Sender: TObject ); procedure DPFUITableView1DrawCell( Sender: TObject; Section, RowNo: Integer; TableItem: TTableItem; var Objects: TArray<DPF.iOS.BaseControl.TDPFiOSBaseControl>; var Handled: Boolean ); procedure DPFSwitch1Changed( Sender: TObject; ISON: Boolean ); procedure DPFButton1Click( Sender: TObject ); procedure DPFUITableView1GetRowHeight( Sender: TObject; Section, RowNo: Integer; var RowHeight: Single ); procedure DPFButton2Click( Sender: TObject ); procedure DPFUITableView1ItemSelect( Sender: TObject; Section, RowNo: Integer; var CellAccessory: TTableViewCellAccessory ); private { Private declarations } protected procedure PaintRects( const UpdateRects: array of TRectF ); override; public { Public declarations } end; var FTableViewCustomView: TFTableViewCustomView; implementation {$R *.fmx} procedure TFTableViewCustomView.DPFButton1Click( Sender: TObject ); begin FormCreate( nil ); end; procedure TFTableViewCustomView.DPFButton2Click( Sender: TObject ); begin DPFUITableView1.ClearAll( true, true ); end; procedure TFTableViewCustomView.DPFSwitch1Changed( Sender: TObject; ISON: Boolean ); begin DPFUITableView1.AutoScroll := ISON; end; // ------------------------------------------------------------------------------ // Notes: // Dont create again objects, if length( Objects ) > 0 // ------------------------------------------------------------------------------ procedure TFTableViewCustomView.DPFUITableView1DrawCell( Sender: TObject; Section, RowNo: Integer; TableItem: TTableItem; var Objects: TArray<DPF.iOS.BaseControl.TDPFiOSBaseControl>; var Handled: Boolean ); const icons: array [0 .. 24] of string = ( 'admin', 'businessman', 'businessmen', 'calendar', 'flag_iran', 'flower_blue', 'flower_red', 'flower_white', 'flower_yellow', 'lock', 'lock_open', 'loudspeaker', 'mail', 'news', 'shield_green', 'table', 'trafficlight_green', 'trafficlight_off', 'trafficlight_on', 'trafficlight_red', 'trafficlight_red_yellow', 'trafficlight_yellow', 'user_headphones', 'users2', 'users4' ); var MustBeCreate: Boolean; begin Handled := true; MustBeCreate := length( Objects ) = 0; if MustBeCreate then SetLength( Objects, 5 ); if MustBeCreate then begin TDPFImageView( Objects[0] ) := TDPFImageView.Create( nil ); TDPFImageView( Objects[0] ).Position.X := 0; TDPFImageView( Objects[0] ).Position.X := 0; TDPFImageView( Objects[0] ).Width := 64; TDPFImageView( Objects[0] ).Shadow := false; TDPFImageView( Objects[0] ).Height := 64; TDPFImageView( Objects[0] ).CacheImage := true; end; TDPFImageView( Objects[0] ).ClearImage; TDPFImageView( Objects[0] ).ImageList.text := '/Documents/' + icons[RandomRange( 0, 25 )] + '.png'; TDPFImageView( Objects[0] ).ReloadImage; if MustBeCreate then begin TDPFLabel( Objects[1] ) := TDPFLabel.Create( nil ); TDPFLabel( Objects[1] ).TextColor := TAlphaColors.Steelblue; TDPFLabel( Objects[1] ).Font.FontName := ios_Verdana_Bold; TDPFLabel( Objects[1] ).Width := 50; TDPFLabel( Objects[1] ).Height := 15; TDPFLabel( Objects[1] ).Position.x := DPFUITableView1.Width - TDPFImageView( Objects[1] ).Width - 1; TDPFLabel( Objects[1] ).Position.Y := 0; end; TDPFLabel( Objects[1] ).Text := FormatDateTime( 'hh:mm', IncSecond( now, RandomRange( 1, 10000 ) ) ); if MustBeCreate then begin TDPFSwitch( Objects[2] ) := TDPFSwitch.Create( nil ); TDPFSwitch( Objects[2] ).Font.FontName := ios_Verdana_Bold; TDPFSwitch( Objects[2] ).Width := 50; TDPFSwitch( Objects[2] ).Height := 15; TDPFSwitch( Objects[2] ).Position.x := DPFUITableView1.Width - TDPFImageView( Objects[1] ).Width - 15; TDPFSwitch( Objects[2] ).Position.Y := 32; end; if MustBeCreate then begin TDPFLabel( Objects[3] ) := TDPFLabel.Create( nil ); TDPFLabel( Objects[3] ).TextColor := TAlphaColors.Black; TDPFLabel( Objects[3] ).Font.FontName := ios_Verdana_Bold; TDPFLabel( Objects[3] ).Width := 200; TDPFLabel( Objects[3] ).Height := 15; TDPFLabel( Objects[3] ).Position.x := TDPFImageView( Objects[0] ).Position.X + TDPFImageView( Objects[0] ).Width + 1; TDPFLabel( Objects[3] ).Position.Y := 10; end; TDPFLabel( Objects[3] ).Text := 'Custom Label ' + TableItem.ItemText.Text; if MustBeCreate then begin TDPFLabel( Objects[4] ) := TDPFLabel.Create( nil ); TDPFLabel( Objects[4] ).TextColor := TAlphaColors.Gray; TDPFLabel( Objects[4] ).Font.FontName := ios_Verdana_Bold; TDPFLabel( Objects[4] ).Width := 200; TDPFLabel( Objects[4] ).Height := 15; TDPFLabel( Objects[4] ).Position.x := TDPFImageView( Objects[0] ).Position.X + TDPFImageView( Objects[0] ).Width + 1; TDPFLabel( Objects[4] ).Position.Y := 40; end; TDPFLabel( Objects[4] ).Text := 'Custom Detail Label'; end; procedure TFTableViewCustomView.DPFUITableView1GetRowHeight( Sender: TObject; Section, RowNo: Integer; var RowHeight: Single ); begin RowHeight := 80; end; procedure TFTableViewCustomView.DPFUITableView1ItemSelect( Sender: TObject; Section, RowNo: Integer; var CellAccessory: TTableViewCellAccessory ); var Objects: TArray<DPF.iOS.BaseControl.TDPFiOSBaseControl>; begin Objects := DPFUITableView1.GetRowCustomViews( Section, RowNo ); // TDPFImageView( Objects[0] ) // TDPFLabel( Objects[1] ) // TDPFSwitch( Objects[2] ) // TDPFSwitch( Objects[2] ) // TDPFLabel( Objects[3] ) // TDPFLabel( Objects[4] ) end; procedure TFTableViewCustomView.FormCreate( Sender: TObject ); var I: Integer; begin GetSharedApplication.setStatusBarHidden( true ); DPFUITableView1.ClearAll( true, true ); with DPFUITableView1.Sections.Add do begin for I := 0 to 150 do begin with TableItems.Add do begin BackgroundColor := TAlphaColors.white; ItemText.Text := 'Item ' + IntToStr( i ); ImageName := '/Documents/admin.png'; end; end; end; DPFUITableView1.RefreshNeeded; end; procedure TFTableViewCustomView.PaintRects( const UpdateRects: array of TRectF ); begin { } end; end.
unit ServiceReceiverU; interface uses FMX.Types, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, ServiceU; type JServiceReceiverClass = interface(JBroadcastReceiverClass) ['{177320F8-F933-4E10-8106-7A5119603383}'] {Methods} // function init: JServiceReceiver; cdecl; end; [JavaSignature('com/blong/test/ServiceReceiver')] JServiceReceiver = interface(JBroadcastReceiver) ['{A1F1C3CF-7C02-4B8F-8AB2-E4B552286B35}'] {Methods} end; TJServiceReceiver = class(TJavaGenericImport<JServiceReceiverClass, JServiceReceiver>) private [weak]FOwningService: TSampleService; protected constructor _Create(Service: TSampleService); public class function Create(Service: TSampleService): JServiceReceiver; procedure OnReceive(Context: JContext; ReceivedIntent: JIntent); end; implementation uses System.Classes, System.SysUtils, FMX.Helpers.Android, Androidapi.NativeActivity, Androidapi.JNI, Androidapi.JNI.JavaTypes, Androidapi.JNI.Toast; {$REGION 'JNI setup code and callback'} var ServiceReceiver: TJServiceReceiver; //This is called from the Java activity's onReceiveNative() method procedure ServiceReceiverOnReceiveNative(PEnv: PJNIEnv; This: JNIObject; JNIContext, JNIReceivedIntent: JNIObject); cdecl; begin Log.d('+ServiceReceiverOnReceiveNative'); Log.d('Thread: Main: %.8x, Current: %.8x, Java:%.8d (%2:.8x)', [MainThreadID, TThread.CurrentThread.ThreadID, TJThread.JavaClass.CurrentThread.getId]); TThread.Queue(nil, procedure begin Log.d('+ThreadSwitcher'); Log.d('Thread: Main: %.8x, Current: %.8x, Java:%.8d (%2:.8x)', [MainThreadID, TThread.CurrentThread.ThreadID, TJThread.JavaClass.CurrentThread.getId]); ServiceReceiver.OnReceive(TJContext.Wrap(JNIContext), TJIntent.Wrap(JNIReceivedIntent)); Log.d('-ThreadSwitcher'); end); Log.d('-ServiceReceiverOnReceiveNative'); end; procedure RegisterDelphiNativeMethods; var PEnv: PJNIEnv; ReceiverClass: JNIClass; NativeMethod: JNINativeMethod; begin Log.d('Starting the Service Receiver JNI stuff'); PEnv := TJNIResolver.GetJNIEnv; Log.d('Registering interop methods'); NativeMethod.Name := 'serviceReceiverOnReceiveNative'; NativeMethod.Signature := '(Landroid/content/Context;Landroid/content/Intent;)V'; NativeMethod.FnPtr := @ServiceReceiverOnReceiveNative; ReceiverClass := TJNIResolver.GetJavaClassID('com.blong.test.ServiceReceiver'); PEnv^.RegisterNatives(PEnv, ReceiverClass, @NativeMethod, 1); PEnv^.DeleteLocalRef(PEnv, ReceiverClass); end; {$ENDREGION} { TServiceReceiver } constructor TJServiceReceiver._Create(Service: TSampleService); begin inherited; Log.d('TJServiceReceiver._Create constructor'); FOwningService := Service; end; class function TJServiceReceiver.Create(Service: TSampleService): JServiceReceiver; begin Log.d('TJServiceReceiver.Create class function'); Result := inherited Create; ServiceReceiver := TJServiceReceiver._Create(Service); end; procedure TJServiceReceiver.OnReceive(Context: JContext; ReceivedIntent: JIntent); var Cmd: Integer; begin Log.d('Service receiver received a message'); Cmd := receivedIntent.getIntExtra(StringToJString(TSampleService.ID_INT_COMMAND), 0); if Cmd = TSampleService.CMD_STOP_SERVICE then begin Log.d('It was a STOP message'); FOwningService.Running := false; Log.d('Service receiver is stopping service'); FOwningService.GetJService.stopSelf; Toast('Service stopped by main activity', TToastLength.LongToast) end; end; initialization RegisterDelphiNativeMethods end.
unit LogisticsBreakdown; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, History,DB, CopyFile; type TLogisticsBreakdown_Form = class(TForm) OK_Button: TButton; Hist: THistory; CopyFile: TCopyFile; procedure FormShow(Sender: TObject); procedure OK_ButtonClick(Sender: TObject); private { Private declarations } fFileName:string; public { Public declarations } procedure Execute; property filename:string read fFilename write fFilename; end; var LogisticsBreakdown_Form: TLogisticsBreakdown_Form; implementation uses DataModule; const InTransit = 'INTRANSIT'; ArrivedNUMMI = 'ARRIVEDNUMMI'; ArrivedMAN = 'ARRIVEDMANUF'; ArrivedUnion = 'ARRIVEDUNION'; ArrivedCONS = 'ARRIVEDCONS'; Terminated = 'TERMINATED'; Renban = 1; Equipment = 9; DT = 20; Status = 28; Lot = 40; Renbanl = 8; Equipmentl = 11; DTl = 8; Statusl = 12; Lotl = 5; {$R *.dfm} procedure TLogisticsBreakdown_Form.Execute; begin ShowModal; end; procedure TLogisticsBreakdown_Form.FormShow(Sender: TObject); var fcf:Textfile; fcl:string; begin Hist.Append('Start File Process'); Data_Module.LogActLog('LOGISTICS','Start processing file,'+fFileNAme); try AssignFile(fcf, fFileName); Reset(fcf); //count records while not Seekeof(fcf) do begin Readln(fcf, fcl); // //Process record // // check length // break out data and update DB try With Data_Module.Inv_StoredProc do Begin Close; ProcedureName := 'dbo.SELECT_OrderOpenOrderLog;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := copy(fcl,Renban,Renbanl); Open; if Data_Module.Inv_Connection.Errors.Count > 0 then begin ShowMessage('Unable to get Logistics in Order data, '+Data_Module.Inv_Connection.Errors.Item[0].Get_Description); Data_Module.LogActLog('ERROR','Unable to get Logistics in Order data, '+Data_Module.Inv_Connection.Errors.Item[0].Get_Description); raise EDatabaseError.Create('Unable to get Logistics in Order data'); end; if not IsEmpty then begin Close; if trim(copy(fcl,status,statusl)) = InTransit then begin ProcedureName := 'dbo.UPDATE_OrderShipping;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := trim(copy(fcl,Renban,Renbanl)); Parameters.AddParameter.Name := '@Shipping'; Parameters.ParamValues['@Shipping'] := trim(copy(fcl,DT,DTl)); Parameters.AddParameter.Name := '@Trailer'; Parameters.ParamValues['@Trailer'] := trim(copy(fcl,Equipment,Equipmentl)); Data_Module.LogActLog('LOGISTICS','Update InTransit, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Update InTransit, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end else if trim(copy(fcl,status,statusl)) = ArrivedMAN then begin ProcedureName := 'dbo.UPDATE_OrderPLANT;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := trim(copy(fcl,Renban,Renbanl)); Parameters.AddParameter.Name := '@PLANT'; Parameters.ParamValues['@PLANT'] := trim(copy(fcl,DT,DTl)); Parameters.AddParameter.Name := '@Trailer'; Parameters.ParamValues['@Trailer'] := trim(copy(fcl,Equipment,Equipmentl)); Parameters.AddParameter.Name := '@Lot'; if (length(fcl) = 44) then begin //test:=trim(copy(fcl,lot,lotl+1)); Parameters.ParamValues['@Lot'] := trim(copy(fcl,Lot,Lotl)); Data_Module.LogActLog('LOGISTICS','Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)+' PK:'+copy(fcl,Lot,Lotl)); Hist.Append('Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)+' PK:'+copy(fcl,Lot,Lotl)); end else if (length(fcl) = 43) then begin //test:=trim(copy(fcl,lot,lotl+1)); Parameters.ParamValues['@Lot'] := trim(copy(fcl,Lot,Lotl)); Data_Module.LogActLog('LOGISTICS','Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)+' PK:'+copy(fcl,Lot,Lotl)); Hist.Append('Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)+' PK:'+copy(fcl,Lot,Lotl)); end else begin Parameters.ParamValues['@Lot'] := ''; Data_Module.LogActLog('LOGISTICS','Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end; end else if trim(copy(fcl,status,statusl)) = ArrivedNUMMI then begin ProcedureName := 'dbo.UPDATE_OrderPLANT;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := trim(copy(fcl,Renban,Renbanl)); Parameters.AddParameter.Name := '@PLANT'; Parameters.ParamValues['@PLANT'] := trim(copy(fcl,DT,DTl)); Parameters.AddParameter.Name := '@Trailer'; Parameters.ParamValues['@Trailer'] := trim(copy(fcl,Equipment,Equipmentl)); Parameters.AddParameter.Name := '@Lot'; if (length(fcl) = 44) then begin //test:=trim(copy(fcl,lot,lotl+1)); Parameters.ParamValues['@Lot'] := trim(copy(fcl,Lot,Lotl)); Data_Module.LogActLog('LOGISTICS','Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)+' PK:'+copy(fcl,Lot,Lotl)); Hist.Append('Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)+' PK:'+copy(fcl,Lot,Lotl)); end else begin Parameters.ParamValues['@Lot'] := ''; Data_Module.LogActLog('LOGISTICS','Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Update Arrived'+Data_Module.fiPlantName.AsString+', R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end; end else if trim(copy(fcl,status,statusl)) = ArrivedCONS then begin ProcedureName := 'dbo.UPDATE_OrderWarehouse;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := trim(copy(fcl,Renban,Renbanl)); Parameters.AddParameter.Name := '@Warehouse'; Parameters.ParamValues['@Warehouse'] := trim(copy(fcl,DT,DTl)); Parameters.AddParameter.Name := '@Trailer'; Parameters.ParamValues['@Trailer'] := trim(copy(fcl,Equipment,Equipmentl)); Data_Module.LogActLog('LOGISTICS','Update CONS, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Update CONS, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end else if trim(copy(fcl,status,statusl)) = ArrivedUnion then begin ProcedureName := 'dbo.UPDATE_OrderWarehouse;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := trim(copy(fcl,Renban,Renbanl)); Parameters.AddParameter.Name := '@Warehouse'; Parameters.ParamValues['@Warehouse'] := trim(copy(fcl,DT,DTl)); Parameters.AddParameter.Name := '@Trailer'; Parameters.ParamValues['@Trailer'] := trim(copy(fcl,Equipment,Equipmentl)); Data_Module.LogActLog('LOGISTICS','Update Warehouse, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Update Warehouse, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end else if trim(copy(fcl,status,statusl)) = Terminated then begin ProcedureName := 'dbo.UPDATE_OrderTerminated;1'; Parameters.Clear; Parameters.AddParameter.Name := '@RenbanNumber'; Parameters.ParamValues['@RenbanNumber'] := trim(copy(fcl,Renban,Renbanl)); Parameters.AddParameter.Name := '@Terminated'; Parameters.ParamValues['@Terminated'] := trim(copy(fcl,DT,DTl)); Parameters.AddParameter.Name := '@Trailer'; Parameters.ParamValues['@Trailer'] := trim(copy(fcl,Equipment,Equipmentl)); Data_Module.LogActLog('LOGISTICS','Update Terminated, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Update Terminated, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end; ExecProc; if Data_Module.Inv_Connection.Errors.Count > 0 then begin ShowMessage('Unable to get Logistics in Order data, '+Data_Module.Inv_Connection.Errors.Item[0].Get_Description); Data_Module.LogActLog('ERROR','Unable to get Logistics in Order data, '+Data_Module.Inv_Connection.Errors.Item[0].Get_Description); raise EDatabaseError.Create('Unable to get Logistics in Order data'); end; end else begin Data_Module.LogActLog('LOGISTICS','Renban not in database, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); Hist.Append('Renban not in database, R:'+copy(fcl,Renban,Renbanl)+' DT:'+copy(fcl,DT,DTl)); end; end; except on e:exception do begin Hist.Append('Unable to update Order record, '+e.Message); Data_Module.LogActLog('ERROR','Unable to update Order record, '+e.Message); // // Create Error report<<<< end; end; end; CloseFile(fcf); // Move the file to Archive CopyFile.CopyFrom:=filename except on e:exception do begin Data_Module.LogActLog('ERROR','Unable to load logistics, '+e.message); Hist.Append('Unable to load logistics, '+e.message); CloseFile(fcf); end; end; Hist.Append('End File Process'); Data_Module.LogActLog('LOGISTICS','Finished processing file,'+fFileNAme); OK_Button.Visible:=True; end; procedure TLogisticsBreakdown_Form.OK_ButtonClick(Sender: TObject); begin Close; end; end.
unit BaseRuleData; interface type (*// PArrayDoubleNode = ^TArrayDoubleNode; TArrayDoubleNode = packed record Size : Byte; Length : Byte; NodeIndex : Byte; Status : Byte; PrevSibling : PArrayDoubleNode; NextSibling : PArrayDoubleNode; Value : array[0..64 - 1] of double; end; PArrayInt64Node = ^TArrayInt64Node; TArrayInt64Node = packed record Size : Byte; Length : Byte; NodeIndex : Byte; Status : Byte; PrevSibling : PArrayInt64Node; NextSibling : PArrayInt64Node; Value : array[0..64 - 1] of int64; end; //*) PArrayDouble = ^TArrayDouble; TArrayDouble = packed record Length : integer; Size : integer; MaxValue : double; MinValue : double; //FirstValueNode : PArrayDoubleNode; //LastValueNode : PArrayDoubleNode; Value : array of double; end; PArrayInt64 = ^TArrayInt64; TArrayInt64 = packed record Length : integer; Size : integer; MaxValue : Int64; MinValue : Int64; //FirstValueNode : PArrayInt64Node; //LastValueNode : PArrayInt64Node; Value : array of int64; end; function CheckOutArrayDouble(ADataLength: integer = 0): PArrayDouble; procedure CheckInArrayDouble(var ArrayDouble: PArrayDouble); // function CheckOutArrayDoubleNode(ArrayDouble: PArrayDouble): PArrayDoubleNode; // procedure CheckInArrayDoubleNode(ArrayDouble: PArrayDouble; var ANode: PArrayDoubleNode); procedure SetArrayDoubleLength(ArrayDouble: PArrayDouble; ALength: integer); procedure SetArrayDoubleValue(ArrayDouble: PArrayDouble; AIndex: integer; AValue: double); function GetArrayDoubleValue(ArrayDouble: PArrayDouble; AIndex: integer): double; // procedure SetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer; AValue: double); // function GetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer): double; function CheckOutArrayInt64(ADataLength: integer = 0): PArrayInt64; procedure CheckInArrayInt64(var ArrayInt64: PArrayInt64); // function CheckOutArrayInt64Node(ArrayInt64: PArrayInt64): PArrayInt64Node; // procedure CheckInArrayInt64Node(ArrayInt64: PArrayInt64; var ANode: PArrayInt64Node); procedure SetArrayInt64Length(ArrayInt64: PArrayInt64; ALength: integer); procedure SetArrayInt64Value(ArrayInt64: PArrayInt64; AIndex: integer; AValue: Int64); function GetArrayInt64Value(ArrayInt64: PArrayInt64; AIndex: integer): Int64; // procedure SetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer; AValue: Int64); // function GetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer): Int64; implementation function CheckOutArrayDouble(ADataLength: integer = 0): PArrayDouble; begin Result := System.New(PArrayDouble); FillChar(Result^, SizeOf(TArrayDouble), 0); if 0 < ADataLength then begin SetArrayDoubleLength(Result, ADataLength); end; end; procedure CheckInArrayDouble(var ArrayDouble: PArrayDouble); begin if nil = ArrayDouble then exit; SetArrayDoubleLength(ArrayDouble, 0); FreeMem(ArrayDouble); ArrayDouble := nil; end; (*// function CheckOutArrayDoubleNode(ArrayDouble: PArrayDouble): PArrayDoubleNode; begin Result := System.New(PArrayDoubleNode); FillChar(Result^, SizeOf(TArrayDoubleNode), 0); if nil <> ArrayDouble then begin if nil = ArrayDouble.FirstValueNode then ArrayDouble.FirstValueNode := Result; if nil <> ArrayDouble.LastValueNode then begin Result.PrevSibling := ArrayDouble.LastValueNode; ArrayDouble.LastValueNode.NextSibling := Result; end; ArrayDouble.LastValueNode := Result; ArrayDouble.Size := ArrayDouble.Size + Length(Result.Value); end; end; procedure CheckInArrayDoubleNode(ArrayDouble: PArrayDouble; var ANode: PArrayDoubleNode); begin end; //*) procedure SetArrayDoubleLength(ArrayDouble: PArrayDouble; ALength: integer); begin if nil = ArrayDouble then exit; SetLength(ArrayDouble.Value, ALength); ArrayDouble.Size := ALength; ArrayDouble.Length := ALength; (*// if ArrayDouble.Size < ALength then begin while ArrayDouble.Size < ALength do begin CheckOutArrayDoubleNode(ArrayDouble); end; ArrayDouble.Length := ALength; end else begin if 0 = ALength then begin end else begin end; end; //*) end; (*// function GetArrayDoubleNode(ArrayDouble: PArrayDouble; AIndex: integer): PArrayDoubleNode; var tmpNode: PArrayDoubleNode; tmpIndex: Integer; begin Result := nil; tmpNode := ArrayDouble.FirstValueNode; tmpIndex := AIndex; while nil <> tmpNode do begin if tmpIndex < Length(tmpNode.Value) then begin if 0 <= tmpIndex then begin Result := tmpNode; Result.NodeIndex := tmpIndex; end; exit; end; tmpNode := tmpNode.NextSibling; tmpIndex := tmpIndex - Length(tmpNode.Value); end; end; //*) procedure SetArrayDoubleValue(ArrayDouble: PArrayDouble; AIndex: integer; AValue: double); //var // tmpNode: PArrayDoubleNode; // tmpIndex: Integer; begin ArrayDouble.value[AIndex] := AValue; (*// tmpNode := ArrayDouble.FirstValueNode; tmpIndex := AIndex; while nil <> tmpNode do begin if tmpIndex < Length(tmpNode.Value) then begin tmpNode.Value[tmpIndex] := AValue; end; tmpNode := tmpNode.NextSibling; tmpIndex := tmpIndex - Length(tmpNode.Value); end; //*) end; (*// procedure SetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer; AValue: double); begin ArrayDoubleNode.value[ANodeIndex] := AValue; end; //*) function GetArrayDoubleValue(ArrayDouble: PArrayDouble; AIndex: integer): double; begin //Result := 0; Result := ArrayDouble.value[AIndex]; end; (*// function GetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer): double; begin Result := ArrayDoubleNode.value[ANodeIndex]; end; //*) function CheckOutArrayInt64(ADataLength: integer = 0): PArrayInt64; begin Result := System.New(PArrayInt64); FillChar(Result^, SizeOf(TArrayInt64), 0); if 0 < ADataLength then begin SetArrayInt64Length(Result, ADataLength); end; end; procedure CheckInArrayInt64(var ArrayInt64: PArrayInt64); begin if nil = ArrayInt64 then exit; SetArrayInt64Length(ArrayInt64, 0); FreeMem(ArrayInt64); ArrayInt64 := nil; end; (*// function CheckOutArrayInt64Node(ArrayInt64: PArrayInt64): PArrayInt64Node; begin Result := System.New(PArrayInt64Node); FillChar(Result^, SizeOf(TArrayInt64Node), 0); if nil <> ArrayInt64 then begin if nil = ArrayInt64.FirstValueNode then ArrayInt64.FirstValueNode := Result; if nil <> ArrayInt64.LastValueNode then begin Result.PrevSibling := ArrayInt64.LastValueNode; ArrayInt64.LastValueNode.NextSibling := Result; end; ArrayInt64.LastValueNode := Result; ArrayInt64.Size := ArrayInt64.Size + Length(Result.Value); end; end; procedure CheckInArrayInt64Node(ArrayInt64: PArrayInt64; var ANode: PArrayInt64Node); begin end; //*) procedure SetArrayInt64Length(ArrayInt64: PArrayInt64; ALength: integer); begin if nil = ArrayInt64 then exit; SetLength(ArrayInt64.Value, ALength); ArrayInt64.Size := ALength; ArrayInt64.Length := ALength; (*// if ArrayInt64.Size < ALength then begin while ArrayInt64.Size < ALength do begin CheckOutArrayInt64Node(ArrayInt64); end; ArrayInt64.Length := ALength; end else begin if 0 = ALength then begin end else begin end; end; //*) end; procedure SetArrayInt64Value(ArrayInt64: PArrayInt64; AIndex: integer; AValue: Int64); begin ArrayInt64.value[AIndex] := AValue; end; (*// procedure SetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer; AValue: Int64); begin ArrayInt64Node.value[ANodeIndex] := AValue; end; //*) function GetArrayInt64Value(ArrayInt64: PArrayInt64; AIndex: integer): Int64; begin //Result := 0; Result := ArrayInt64.value[AIndex]; end; (*// function GetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer): Int64; begin Result := ArrayInt64Node.value[ANodeIndex]; end; //*) end.
unit ConversionForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls; type TFormConversion = class(TForm) rgADCRange: TRadioGroup; GroupBoxDst: TGroupBox; edXa: TEdit; edXb: TEdit; Label6: TLabel; Label7: TLabel; GroupBoxSrc: TGroupBox; pcSource: TPageControl; tsCurrent: TTabSheet; Label3: TLabel; Label1: TLabel; Label2: TLabel; edR: TEdit; edIa: TEdit; edIb: TEdit; tsVoltage: TTabSheet; Label4: TLabel; Label5: TLabel; edUa: TEdit; edUb: TEdit; BtnOk: TButton; BtnCancel: TButton; BtnApply: TButton; edXm: TEdit; Label8: TLabel; procedure FormShow(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure BtnApplyClick(Sender: TObject); private function GetVolatageMode: Boolean; procedure SetVoltageMode(const Value: Boolean); function Validate:Boolean; function GetADCRange: Integer; procedure SetADCRange(const Value: Integer); public Ia,Ib,R:Double; Ua,Ub:Double; Xm,Xa,Xb:Double; public property ADCRange:Integer read GetADCRange write SetADCRange; property VoltageMode:Boolean read GetVolatageMode write SetVoltageMode; end; function getADCRangeParams(Range:Integer; var PhysScale,VoltsScale:Double ):Boolean; var FormConversion: TFormConversion; implementation {$R *.DFM} function getADCRangeParams(Range:Integer; var PhysScale,VoltsScale:Double ):Boolean; begin Result:=True; case Range of 0: begin PhysScale:=15.000; VoltsScale:=0.001; end; // 15 mV 1: begin PhysScale:=50.000; VoltsScale:=0.001; end; // 50 mV 2: begin PhysScale:=100.00; VoltsScale:=0.001; end; // 100 mV 3: begin PhysScale:=150.00; VoltsScale:=0.001; end; // 150 mV 4: begin PhysScale:=500.00; VoltsScale:=0.001; end; // 500 mV 5: begin PhysScale:=1.0000; VoltsScale:=1.000; end; // 1 V 6: begin PhysScale:=2.5000; VoltsScale:=1.000; end; // 2.5 V 7: begin PhysScale:=5.0000; VoltsScale:=1.000; end; // 5 V 8: begin PhysScale:=10.000; VoltsScale:=1.000; end; // 10 V 9: begin PhysScale:=20.000; VoltsScale:=0.125; end; // 20 mA (with R=125 Ohm, U=2.5V) else Result:=False; end; end; procedure TFormConversion.FormShow(Sender: TObject); begin rgADCRange.ItemIndex:=ADCRange; edIa.Text:=FloatToStr(Ia); edIb.Text:=FloatToStr(Ib); edR.Text:=FloatToStr(R); edUa.Text:=FloatToStr(Ua); edUb.Text:=FloatToStr(Ub); edXm.Text:=FloatToStr(Xm); edXa.Text:=FloatToStr(Xa); edXb.Text:=FloatToStr(Xb); end; function TFormConversion.GetVolatageMode: Boolean; begin Result:=pcSource.ActivePageIndex=1; end; procedure TFormConversion.SetVoltageMode(const Value: Boolean); begin if Value then pcSource.ActivePageIndex:=1 else pcSource.ActivePageIndex:=0 end; function TFormConversion.Validate: Boolean; { var VoltsRange:Double; PhysScale,VoltsScale:Double; } begin Result:=False; try if VoltageMode then begin // "Voltage" page checking try Ua:=StrToFloat(edUa.Text); except edUa.SetFocus; raise; end; try Ub:=StrToFloat(edUb.Text); except edUb.SetFocus; raise; end; end else begin // "Current" page checking try Ia:=StrToFloat(edIa.Text); except edIa.SetFocus; raise; end; try Ib:=StrToFloat(edIb.Text); except edIb.SetFocus; raise; end; try R:=StrToFloat(edR.Text); if R<=0 then raise Exception.Create( 'Величина шунтирующего сопротивления должна быть больше 0' ); except edR.SetFocus; raise; end; end; // "Result value" checking try Xm:=StrToFloat(edXm.Text); except edXm.SetFocus; raise; end; try Xa:=StrToFloat(edXa.Text); except edXa.SetFocus; raise; end; try Xb:=StrToFloat(edXb.Text); except edXb.SetFocus; raise; end; if Xa=Xb then raise Exception.Create('Значение Xa должно отличаться от Xb'); except on E:Exception do begin Application.MessageBox(PChar(E.Message),'Ошибка',MB_ICONERROR or MB_OK); exit; end; end; if not VoltageMode then begin Ua:=Ia*R; Ub:=Ib*R; end; { getADCRangeParams(ADCRange,PhysScale,VoltsScale); VoltsRange:=PhysScale*VoltsScale; if (Ua<=-VoltsRange) or (+VoltsRange<=Ub) } Result:=True; end; procedure TFormConversion.BtnOkClick(Sender: TObject); begin if Validate then ModalResult:=mrOK; end; procedure TFormConversion.BtnApplyClick(Sender: TObject); begin if Validate then ModalResult:=mrYes; end; function TFormConversion.GetADCRange: Integer; begin Result:=rgADCRange.ItemIndex; end; procedure TFormConversion.SetADCRange(const Value: Integer); begin rgADCRange.ItemIndex:=Value; if rgADCRange.ItemIndex=-1 then rgADCRange.ItemIndex:=9; end; { (Application.MessageBox( 'Вы действительно хотите изменить настройки?', 'Подтверждение', MB_ICONQUESTION or MB_YESNO or MB_TOPMOST or MB_DEFBUTTON2 )<>ID_YES); } end.
{ Copyright (C) <2005> <Andrew Haines> chmls.lpr This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } { See the file COPYING, included in this distribution, for details about the copyright. } program chmls; {$IFDEF MSWINDOWS} {$apptype console} {$ENDIF} {$mode objfpc}{$H+} uses Classes, chmreader, chmbase, Sysutils { add your units here }; type { TJunkObject } TJunkObject = class procedure OnFileEntry(Name: String; Offset, UncompressedSize, ASection: Integer); end; var ITS: TITSFReader; Stream: TFileStream; I : Integer; Section: Integer = -1; JunkObject: TJunkObject; procedure WriteStr(Str: String; CharWidth: Integer); var OutString: String; Len: Integer; begin Len := Length(Str); SetLength(OutString, CharWidth-Len); FillChar(OutString[1], CharWidth-Len, ' '); Write(OutString + Str); // to sdtout end; { TJunkObject } procedure TJunkObject.OnFileEntry(Name: String; Offset, UncompressedSize, ASection: Integer); begin Inc(I); if (Section > -1) and (ASection <> Section) then Exit; if (I = 1) or (I mod 40 = 0) then WriteLn(StdErr, '<Section> <Offset> <UnCompSize> <Name>'); Write(' '); Write(ASection); Write(' '); WriteStr(IntToStr(Offset), 10); Write(' '); WriteStr(IntToStr(UncompressedSize), 11); Write(' '); WriteLn(Name); end; Procedure Usage; begin WriteLn(' Usage: chmls filename.chm [section number]'); Halt(1); end; // Start of program begin if (Paramcount < 1) or (Paramstr(1)='-h') or (Paramstr(1)='-?') then begin usage; end; if ParamCount > 1 then begin Section := StrToIntDef(ParamStr(2),-1); If (Section=-1) then begin Usage; Halt(1); end; end; Stream := TFileStream.Create(ParamStr(1), fmOpenRead); JunkObject := TJunkObject.Create; ITS:= TITSFReader.Create(Stream, True); I := 0; ITS.GetCompleteFileList(@JunkObject.OnFileEntry); WriteLn('Total Files in chm: ', I); ITS.Free; JunkObject.Free; end.
{ Tyler Galske } program Main; Uses sysutils; var strIn: string; numShifts, MIN_CHAR, MAX_CHAR : integer; procedure encrypt(strIn: string; numShifts: integer); var i: integer; begin strIn := AnsiUpperCase(strIn); writeln('ENCRYPT'); writeln(strIn); for i := 0 to Length(strIn) do if (ord(strIn[i]) >= MIN_CHAR) and (ord(strIn[i]) <= MAX_CHAR) then begin strIn[i] := chr(ord(strIn[i]) + numShifts); if (ord(strIn[i]) > MAX_CHAR) then begin strIn[i] := chr(ord(strIn[i]) - 26); end; end; writeln(strIn); end; procedure decrypt(strIn: string; numShifts: integer); var i: integer; begin strIn := AnsiUpperCase(strIn); writeln('DECRYPT'); writeln(strIn); for i := 0 to Length(strIn) do begin if (ord(strIn[i]) >= MIN_CHAR) and (ord(strIn[i]) <= MAX_CHAR) then begin strIn[i] := chr(ord(strIn[i]) - numShifts); if (ord(strIn[i]) < MIN_CHAR) then begin strIn[i] := chr(ord(strIn[i]) + 26); end; end; end; writeln(strIn); end; procedure solve(strIn: string; maxShiftValue: integer); var i: integer; begin strIn := AnsiUpperCase(strIn); writeln('SOLVE'); writeln(strIn); while maxShiftValue > -1 do begin writeln('Caesar ', maxShiftValue, ': ', strIn); for i := 0 to Length(strIn) do begin if (ord(strIn[i]) >= MIN_CHAR) and (ord(strIn[i]) <= MAX_CHAR) then begin strIn[i] := chr(ord(strIn[i]) - 1); if (ord(strIn[i]) < MIN_CHAR) then begin strIn[i] := chr(ord(strIn[i]) + 26); end; end; end; maxShiftValue := maxShiftValue -1; end; end; begin MIN_CHAR := 65; MAX_CHAR := 90; strIn := 'the quick brown fox jumped over the lazy dog'; numShifts := 15; encrypt(strIn, numShifts); numShifts := 12; strIn := 'xqfe sa kmzwqqe'; decrypt(strIn, numShifts); numShifts := 26; strIn := 'hal'; solve(strIn, numShifts); readln() end.
//////////////////////////////////////////////////////////////////////////////// // MTBusb.pas // MTB communication library // Main MTB technology // (c) Petr Travnik (petr.travnik@kmz-brno.cz), // Jan Horacek (jan.horacek@kmz-brno.cz), // Michal Petrilak (engineercz@gmail.com) //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2015-2019 Petr Travnik, Michal Petrilak, Jan Horacek 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. } { DESCRIPTION: This is main MTB technology unit. TMTBusb class operates with MTB. Methods can be called to the class and events can be handled from the class. This class does almost everything: it creates messages for MTB-USB, parses it, cares about modules, ... } unit MTBusb; interface uses Windows, SysUtils, Classes, IniFiles, ExtCtrls, Forms, math, MTBD2XXUnit, Version; // Verze komponenty const MIN_FW_VERSION: Integer = 920; // verze pro FW 0.9.6 a vyšší const _ADDR_MAX_NUM = 191; // maximalni pocet adres; _PORT_MAX_NUM = 4095; // 256*16-1; _PORTOVER_MAX_NUM = 255; // 32*8-1; _DEFAULT_USB_NAME = 'MTB03001'; _DEFAULT_ERR_ADDR = 255; // konstanty pro MTB-USB modul const _USB_SET = $0C8; _MTB_SET = $0D0; _FB_LIST = $0D0; _USB_RST = $0D8; _SEND_CMD = $0E0; _SCAN_MTB = $0E8; _COM_OFF = $0F0; _COM_ON = $0F8; {konstanty odpovedi} _RST_OK = $040; _LIST_OK = $050; _MTB_CFG = $060; _MTB_DATA = $070; _MTB_ID = $0A0; _MTB_SEARCH_END = $0B0; _ERR_CODE = $0C0; _USB_CFGQ = $0F0; // konstanty pro MTB moduly // prikazy: const __PWR_ON = $1*8; __PWR_OFF = $2*8; __BYPASS_RST = $4*8; __IDLE = $8*8; __SEND_ID = $9*8; __SET_CFG = $a*8; __SET_OUTB = $10*8; {nastaveni jednoho bitu} __READ_FEED = $11*8; __SET_REG_U = $12*8; __SET_OUTW = $13*8; {nastaveni vsech 16 vystupu- puvodni OPkod = 12h!!!, novy=13h} __FLICK_OUT = $14*8; __SET_NAVEST = $15*8; {nastaveni kodu navesti S-com} __READ_POT = $16*8; {cteni stavu potenciometru} // ID modulu const MTB_POT_ID = $10; MTB_REGP_ID = $30; MTB_UNI_ID = $40; MTB_UNIOUT_ID = $50; MTB_TTL_ID = $60; MTB_TTLOUT_ID = $70; const _REG_ADDR = $80; // 128..159 REG 32 adres _POT_ADDR = $a0; // 160..175 POT 16 adres _REG_CHANN = 256; _POT_CHANN = 64; _END_BYTE = 11; // hodnota posledniho byte v paketu type // Ranges & sub-types: TAddr = 0.._ADDR_MAX_NUM; // Rozsah povolenych adres TIOaddr = 0.._ADDR_MAX_NUM; // Rozsah adres UNI, TTL TIOchann = 0..15; // Rozsah kanalu UNI,TTL TregAddr = 128..159; // Rezsah Reg adres TRegChann = 0..255; // Rozsah kanalu regulatoru TRegOut = 0..7; // Rozsah vystupu regulatoru TRegSpeed = 0..15; // Rychlost regulatoru TRegDirect = 0..1; // Smer Regulatoru TRegAcctime = 0..20; // Casova rampa regulatoru TPotAddr = 160..175; // Rozsah pro adresy POT TPotChann = 0..63; // Hodnota kanálu potenciometru TPotInp = 0..3; // Rozsah pro vstupy POT TPotValue = 0..15; // Hodnota potenciometru TPotDirect = 0..1; // Smer potenciometru TPortValue = 0..4095; // Hodnota Portu // Exceptions EAlreadyOpened = class(Exception); ECannotOpenPort = class(Exception); EFirmwareTooLog = class(Exception); ENotOpened = class(Exception); EAlreadyStarted = class(Exception); EOpeningNotFinished = class(Exception); ENoModules = class(Exception); ENotStarted = class(Exception); TLogLevel = (llNo = 0, llError = 1, llWarning = 2, llInfo = 3, llCmd = 4, llRawCmd = 5, llDebug = 6); TModulType = (idNone = $0, idMTB_POT_ID = $10, idMTB_REGP_ID = $30, idMTB_UNI_ID = $40, idMTB_UNIOUT_ID = $50, idMTB_TTL_ID = $60, idMTB_TTLOUT_ID = $70); TFlickType = (flOff = 0, fl33 = 1, fl55 = 2); TTimerInterval = (ti50 = 50, ti100 = 100, ti200 = 200, ti250 = 250); TMtbSpeed = (sp38400 = 2, sp57600 = 3, sp115200 = 4); TModulConfigGet = record CFGdata: array[0..3] of byte; CFGnum: byte; CFGpopis : string; CFGfw : string; end; TModulConfigSet = record CFGdata: array[0..3] of byte; CFGpopis : string; end; TPort = record value: word; PortName: Array[0..15] of string; changed: boolean; end; TPortIn = record value : boolean; inUp : boolean; inDn : boolean; end; TPortOut = record value : boolean; flick : TFlickType; flickChange : boolean; end; TReg = record RegSpeed : TRegSpeed; RegDirect : TRegDirect; RegAcctime : TRegAcctime; end; TPortRegOver = record value : boolean; inUp : boolean; end; TPot = record PotValue : TPotValue; PotDirect: TPotDirect; end; TScom = record ScomCode: Array[0..7] of byte; // kod vystupu ScomName: Array[0..15] of string; // nazev vystupu ScomActive: array[0..7] of Boolean; // true, pokud je Scom vystup aktivni changed: array[0..7] of Boolean; // nastavi priznak pri zmene end; TModule = object name: string; popis: string; Input: TPort; Output: TPort; Status : byte; Sum : Byte; Scom: TScom; OPData: Array[0..3] of byte; CFData: Array[0..3] of byte; // konfigurace CFGnum: byte; // počet konfig. dat ErrTX: byte; // poslední chyba ID: byte; // (ID + cfg num) typ: TModulType; //(ID only) firmware: string; // verze FW setting : byte; available: boolean; failure : Boolean; // vypadek modulu - porucha - neodpovida revived : Boolean; // modul oziven po vypadku - zacal odpovidat inputStateKnown : Boolean; end; TNotifyEventError = procedure (Sender: TObject; errValue: word; errAddr: byte) of object; TNotifyEventLog = procedure (Sender: TObject; logLevel: TLogLevel; msg:string) of object; TNotifyEventChange = procedure (Sender: TObject; module: byte) of object; TMTBusb = class(TComponent) private FTimer: TTimer; FSpeed: TMtbSpeed; FScanInterval: TTimerInterval; FConfigFn : String; FOpenned: boolean; FScanning: boolean; FusbName: String; FModule: Array[0..255] of TModule; FPot : array[TPotChann] of TPot; FPortIn : array[0.._PORT_MAX_NUM] of TPortIn; FPortOut: array[0.._PORT_MAX_NUM] of TPortOut; FRegOver: array[0.._PORTOVER_MAX_NUM] of TPortRegOver; FReg: Array[0..255] of TReg; FPotChanged : Boolean; // zmena vstupu POT FOverChanged : Boolean; // zmena vstupu REG - pretizeni FInputChanged : Boolean; // zmena vstupu IO - UNI/TTL FModuleCount: Cardinal; // pocet nalezenych modulu na sbernici FScan_flag: boolean; FSeznam_flag: boolean; FDataInputErr: Boolean; // chyba posledniho byte paketu FHWVersion: string; FHWVersion_Major: byte; FHWVersion_Minor: byte; FHWVersion_Release: byte; FHWVersionInt : Integer; // verze FW ve tvaru int, bez teček FCmdCount: word; // pocet cmd/sec FCmdCountCounter: word; // citac 1 sec v timeru FCmdCounter_flag : boolean; // priznak zmeny poctu cmd FCmdSecCycleNum : word; FCyclesFbData : Byte; // hodnota pro opakovane zasilani FB dat do PC v sec // 0 .. data se zasilaji jen pri zmene // 1 .. 25 = 1sec .. 25sec // do modulu se zasila x*10 FXRamAddr : Word; // Adresa XRAM FXRamValue : Byte; // Hodnota bunky FLogLevel : TLogLevel; FWaitingOnScan : boolean; FErrAddress: byte; FBeforeOpen, FAfterOpen, FBeforeClose, FBeforeStart, FAfterStart, FBeforeStop, FAfterStop, FAfterClose, FOnScanned : TNotifyEvent; FOnError : TNotifyEventError; FOnLog : TNotifyEventLog; FOnScan : TNotifyEvent; FOnChange : TNotifyEvent; FOnInputChange : TNotifyEventChange; FOnOutputChange : TNotifyEventChange; function MT_send_packet(buf: array of byte; count:byte): integer; function GetSpeedStr: cardinal; procedure SetScanInterval(interval: TTimerInterval); procedure MtbScan(Sender: TObject); procedure LogWrite(ll:TLogLevel; msg:string); procedure WriteError(errValue: word; errAddr: byte); procedure GetCmdNum; procedure SendCyclesData; function GetPotValue(chann: TPotChann): TPot; function GetInPortDifUp(Port: TPortValue): boolean; function GetInPortDifDn(Port: TPortValue): boolean; function GetInPort(Port: TPortValue): boolean; procedure SetOutPort(Port: TPortValue; state: boolean); procedure SetInPort(Port: TPortValue; state: boolean); function GetRegOverValue(Port: TRegChann): TPortRegOver; function GetModuleStatus(addr :TAddr): byte; procedure ResetPortsStatus(); procedure LogDataOut(bufLen:Integer); procedure LogDataIn(bufLen:Integer; bufStart:Integer = 0); protected { Protected declarations } public { Public declarations } WrCfgData: TModulConfigSet; RdCfgdata: TModulConfigGet; constructor Create(AOwner: TComponent; ConfigFn:string); reintroduce; destructor Destroy; override; function GetDeviceCount: Integer; function GetDeviceSerial(index: Integer): string; procedure Open(serial_num: String); procedure Close(); procedure Start(); procedure Stop(); function GetPortNum(addr : TIOaddr; channel: TIOchann): word; function GetChannel(Port: TPortValue): byte; function GetPotChannel(potAddr: TPotAddr; potInp: TPotInp): word; function GetRegChannel(regAddr: TregAddr; regOut: TRegOut): word; function GetExistsInPort(Port: TPortValue): boolean; function GetExistsOutPort(Port: TPortValue): boolean; function GetAdrr(Port: TPortValue): byte; function IsModule(addr: TAddr): boolean; function IsModuleConfigured(addr: TAddr): boolean; // modul ma konfiguracni data function IsModuleRevived(addr: TAddr): boolean; // modul oziven po vypadku function IsModuleFailure(addr: TAddr): boolean; // modul v poruse function IsModuleScanned(addr: TAddr): boolean; function AreAllModulesScanned(): boolean; function GetModuleInfo(addr: TAddr): TModule; // informace o modulu function GetModuleType(addr: TAddr): TModulType; // Typ modulu function GetModuleTypeName(addr: TAddr): string; // Typ modulu - nazev function GetModuleCfg(addr: TAddr): TModulConfigGet; // Vrati cfg data procedure SetModuleCfg(addr: TAddr); // Vlozi cfg data z pole FSetCfg[] function GetModuleEnable(addr: TIOaddr):boolean; procedure SetModuleEnable(addr: TIOaddr; enable:Boolean); // On/off modulu procedure SetCfg(addr: TAddr; config: cardinal); function GetCfg(addr: TAddr): cardinal; procedure SetPortIName(Port: TPortValue; name: string); function GetPortIName(Port: TPortValue): string; procedure SetPortOName(Port: TPortValue; name: string); function GetPortOName(Port: TPortValue): string; function GetErrString(err: word): string; procedure SetOutputIO(addr : TIOaddr; channel: TIOchann; value: boolean); function GetInputIO(addr : TIOaddr; channel: TIOchann): boolean; function GetIModule(addr: TIOaddr): word; function GetOModule(addr: TIOaddr): word; procedure SetOModule(addr: TIOaddr; state: word); function GetOutPort(Port: TPortValue): boolean; procedure SetOutPortFlick(Port: TPortValue; state: TFlickType); function GetOutPortFlick(Port: TPortValue): TFlickType; function IsIRIn(Port: TPortValue): Boolean; function IsScomOut(Port: TPortValue): Boolean; procedure SetScomCode(Port: TPortValue; code: byte); function GetScomCode(Port: TPortValue): byte; procedure SetRegSpeed(Rchan: TRegChann; Rspeed: TRegSpeed; Rdirect: TRegDirect; AccTime : TRegAcctime); function GetRegSpeed(Rchan: TRegChann): TReg; procedure GetFbData; // zadost o FB data procedure SetCyclesData(value: Byte); procedure XMemWr(mAddr: word; mData : Byte); procedure XMemRd(mAddr: word); procedure LoadConfig(fn:string); procedure SaveConfig(fn:string); procedure CheckAllScannedEvent(); property ModuleCount: Cardinal read FModuleCount; property Openned: boolean read FOpenned; property Scanning: boolean read FScanning; property ErrAddres: byte read FErrAddress; property OpeningScanning: boolean read FScan_flag; property CmdCounter_flag: boolean read FCmdCounter_flag; property CmdCount : word read FCmdCount; property HWVersion: string read FHWVersion; property HWVersionInt: Integer read FHWVersionInt; property InputChanged : boolean read FInputChanged; property PotChanged: boolean read FPotChanged; property OverChanged: boolean read FOverChanged; property Pot[chann : TPotChann]: TPot read GetPotValue; property InPortDifUp[port : TPortValue]: boolean read GetInPortDifUp; property InPortDifDn[port : TPortValue]: boolean read GetInPortDifDn; property InPortValue[port : TPortValue]: boolean read GetInPort write SetInPort; property OutPortValue[port : TPortValue]: boolean read GetOutPort write SetOutPort; property ModuleStatus[addr : TAddr]: byte read GetModuleStatus; property RegOver[chann : TRegChann]: TPortRegOver read GetRegOverValue; property LogLevel: TLogLevel read FLogLevel write FLogLevel; property ConfigFn: string read FConfigFn write FConfigFn; published { Published declarations } property UsbSerial: string read FusbName write FusbName; property MtbSpeed: TMtbSpeed read FSpeed write FSpeed default sp38400; property ScanInterval: TTimerInterval read FScanInterval write SetScanInterval default ti100; property OnError : TNotifyEventError read FOnError write FOnError; property OnLog : TNotifyEventLog read FOnLog write FOnLog; property OnChange : TNotifyEvent read FOnChange write FOnChange; property OnScan : TNotifyEvent read FOnScan write FOnScan; property OnInputChange : TNotifyEventChange read FOnInputChange write FOnInputChange; property OnOutputChange : TNotifyEventChange read FOnOutputChange write FOnOutputChange; property BeforeOpen : TNotifyEvent read FBeforeOpen write FBeforeOpen; property AfterOpen : TNotifyEvent read FAfterOpen write FAfterOpen; property BeforeClose : TNotifyEvent read FBeforeClose write FBeforeClose; property AfterClose : TNotifyEvent read FAfterClose write FAfterClose; property BeforeStart : TNotifyEvent read FBeforeStart write FBeforeStart; property AfterStart : TNotifyEvent read FAfterStart write FAfterStart; property BeforeStop : TNotifyEvent read FBeforeStop write FBeforeStop; property AfterStop : TNotifyEvent read FAfterStop write FAfterStop; property OnScanned : TNotifyEvent read FOnScanned write FOnScanned; end; implementation uses Variants, Errors; function TMTBusb.GetPotValue(chann: TPotChann): TPot; begin Result.PotValue := FPot[chann].PotValue; Result.PotDirect := FPot[chann].PotDirect; end; procedure TMTBusb.LogWrite(ll:TLogLevel; msg:string); begin if ((ll <= Self.LogLevel) and (Assigned(OnLog))) then OnLog(Self, ll, msg); end; procedure TMTBusb.WriteError(errValue: word; errAddr: byte); begin if (Assigned(OnError)) then OnError(Self, errValue, errAddr); end; // Vrati pocet pripojenych zarizeni function TMTBusb.GetDeviceCount: Integer; begin try GetFTDeviceCount; Result := FT_Device_Count; except on E:Exception do begin Self.LogWrite(llError, 'GetDeviceCount exception: '+E.ClassName+' - '+E.Message); raise; end; end; end; // Vrati seriove cislo modulu function TMTBusb.GetDeviceSerial(index: Integer): string; begin try GetFTDeviceSerialNo(index); Result := FT_Device_String; except on E:Exception do begin Self.LogWrite(llError, 'GetDeviceSerial exception: '+E.ClassName+' - '+E.Message); raise; end; end; end; // vrati stav vsech vstupu jako word function TMTBusb.GetIModule(addr: TIOaddr): word; begin if (FModule[addr].available) then begin Result := FModule[addr].Input.value; end else begin Result := 0; end; end; //Chybove zpravy function TMTBusb.GetErrString(err: word): string; begin case err of MTB_GENERAL_EXCEPTION: Result := 'Kritická chyba'; MTB_FT_EXCEPTION: Result := 'Výjimka FTdriver'; MTB_FILE_CANNOT_ACCESS: Result := 'Nelze přitoupit k souboru'; MTB_FILE_DEVICE_OPENED: Result := 'Zařízení již otevřeno'; MTB_MODULE_INVALID_ADDR: Result := 'Naplatná adresa'; MTB_MODULE_FAILED: Result := 'Modul v poruše'; MTB_PORT_INVALID_NUMBER: Result := 'Neplatné číslo portu'; MTB_MODULE_UNKNOWN_TYPE: Result := 'Neznámý typ modulu'; MTB_INVALID_SPEED: Result := 'Neplatná rychlost'; MTB_INVALID_SCOM_CODE: Result := 'Neplatný kód S-SCOM návěsti'; MTB_INVALID_MODULES_COUNT: Result := 'Neplatný počet modulů'; MTB_INPUT_NOT_YET_SCANNED: Result := 'Vstupy zatím nenaskenovány'; MTB_INVALID_PACKET: Result := 'Neplatný paket'; MTB_MODULE_NOT_ANSWERED_CMD: Result := 'Modul neodpověděl na příkaz - CMD'; MTB_MODULE_NOT_ANSWERED_CMD_GIVING_UP: Result := 'Modul neodpověděl na příkaz - CMD, poslední pokus'; MTB_MODULE_OUT_SUM_ERROR: Result := 'Chybný SUM přijatých dat - CMD'; MTB_MODULE_OUT_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM přijatých dat - CMD, poslední pokus'; MTB_MODULE_IN_SUM_ERROR: Result := 'Chybný SUM odeslaných dat - CMD'; MTB_MODULE_IN_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM odeslaných dat - CMD, poslední pokus'; MTB_MODULE_NOT_RESPONDED_FB: Result := 'Modul neodpověděl na příkaz - FB'; MTB_MODULE_NOT_RESPONDED_FB_GIVING_UP: Result := 'Modul neodpověděl na příkaz - FB, poslední pokus'; MTB_MODULE_IN_FB_SUM_ERROR: Result := 'Chybný SUM přijatých dat - FB'; MTB_MODULE_IN_FB_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM přijatých dat - FB, poslední pokus'; MTB_MODULE_OUT_FB_SUM_ERROR: Result := 'Chybný SUM odeslaných dat - FB'; MTB_MODULE_OUT_FB_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM odeslaných dat - FB, poslední pokus'; MTB_MODULE_INVALID_FB_SUM: Result := 'Chybný SUM - FB'; MTB_MODULE_NOT_RESPONDING_PWR_ON: Result := 'Modul neodpovídá - PWR_ON'; MTB_MODULE_PWR_ON_IN_SUM_ERROR: Result := 'Chybný SUM přijatých dat - POWER ON - konfigurace'; MTB_MODULE_PWR_ON_IN_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM přijatých dat - POWER ON - konfigurace, posledni pokus'; MTB_MODULE_PWR_ON_OUT_SUM_ERROR: Result := 'Chybný SUM odeslaných dat - POWER ON - konfigurace'; MTB_MODULE_PWR_ON_OUT_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM odeslaných dat - POWER ON - konfigurace, posledni pokus'; MTB_MODULE_FAIL: Result := 'Modul nekomunikuje'; MTB_MODULE_RESTORED: Result := 'Modul obnoven'; MTB_MODULE_INVALID_DATA: Result := 'Chybný SUM - Modul obdržel chybná data'; MTB_MODULE_REWIND_IN_SUM_ERROR: Result := 'Chybný SUM přijatých dat - oživení modulu'; MTB_MODULE_REWIND_OUT_SUM_ERROR: Result := 'Chybný SUM odeslaných dat - oživení modulu'; MTB_MODULE_SCAN_IN_SUM_ERROR: Result := 'Chybný SUM přijatých dat - SCAN sběrnice'; MTB_MODULE_SCAN_IN_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM přijatých dat - SCAN sběrnice - posledni pokus'; MTB_MODULE_SCAN_OUT_SUM_ERROR: Result := 'Chybný SUM odeslaných dat - SCAN sběrnice'; MTB_MODULE_SCAN_OUT_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM odeslaných dat - SCAN sběrnice - posledni pokus'; MTB_MODULE_SC_IN_SUM_ERROR: Result := 'Chybný SUM přijatých dat - SC konfigurace'; MTB_MODULE_SC_IN_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM přijatých dat - SC konfigurace - posledni pokus'; MTB_MODULE_SC_OUT_SUM_ERROR: Result := 'Chybný SUM odeslaných dat - SC konfigurace'; MTB_MODULE_SC_OUT_SUM_ERROR_GIVING_UP: Result := 'Chybný SUM odeslaných dat - SC konfigurace - posledni pokus'; else Result := 'Neznámá chyba'; end; end; // odesle paket pro modul function TMTBusb.MT_send_packet(buf: array of byte; count:byte): integer; var i, sum: word; s : string; begin s := ' '; Result := 1; FT_Out_Buffer[0] := _SEND_CMD + count + 1; FT_Out_Buffer[1] := buf[0]; FT_Out_Buffer[2] := buf[1] or (count-2); // přidá počet dat sum := FT_Out_Buffer[1]+FT_Out_Buffer[2]; for i := 2 to count-1 do begin FT_Out_Buffer[i+1] := buf[i]; s := s + IntToHex(buf[i],2) + ' '; sum := sum + buf[i]; end; FT_Out_Buffer[count+1] := Lo($8000-sum); s := s + IntToHex(FT_Out_Buffer[count+1],2); LogDataOut(count+2); Write_USB_Device_Buffer(count+2); end; function TMTBusb.IsIRIn(Port: TPortValue): Boolean; var adresa : Byte; begin Result := False; adresa := GetAdrr(Port); if (adresa < 1) or (adresa > _ADDR_MAX_NUM) then Exit; if not IsModule(adresa) then Exit; if (GetModuleType(adresa) <> TModulType.idMTB_UNI_ID) then Exit; Result := ((FModule[adresa].CFData[2] shr (GetChannel(Port) div 4)) and $1 > 0); end; // pokud je vystupu prirazen Scom port tak True, 15.1.2012 function TMTBusb.IsScomOut(Port: TPortValue): Boolean; var adresa : Byte; begin Result := False; adresa := GetAdrr(Port); if (adresa < 1) or (adresa > _ADDR_MAX_NUM) then Exit; if not IsModule(adresa) then Exit; if GetChannel(Port) > 7 then Exit; Result := FModule[adresa].Scom.ScomActive[GetChannel(Port)]; end; // nastavi Scom kod pro vysilani procedure TMTBusb.SetScomCode(Port: TPortValue; code: byte); begin if not IsScomOut(Port) then Exit; FModule[GetAdrr(Port)].Scom.ScomCode[GetChannel(Port)] := code; FModule[GetAdrr(Port)].Scom.changed[GetChannel(Port)] := True; end; // vrati hodnotu Scom kodu, kdery je nastaven na vystup function TMTBusb.GetScomCode(Port: TPortValue): byte; var adresa, channel : Byte; begin Result := 0; if not IsScomOut(Port) then Exit; adresa := GetAdrr(Port); channel := GetChannel(Port); Result := FModule[adresa].Scom.ScomCode[channel]; end; // ziska adresu modulu z cisla portu function TMTBusb.GetAdrr(Port: TPortValue): byte; begin Result := Port DIV 16; end; // ziska cislo kanalu z cisla portu function TMTBusb.GetChannel(Port: TPortValue): byte; begin Result := Port MOD 16; end; function TMTBusb.GetPotChannel(potAddr: TPotAddr;potInp : TPotInp): word; begin Result := ((potAddr - _POT_ADDR)*4)+potInp; end; function TMTBusb.GetRegChannel(regAddr: TregAddr;regOut : TRegOut): word; begin Result := ((regAddr - _REG_ADDR)*8)+regOut; end; // ziska nazev inp portu function TMTBusb.GetPortIName(Port: TPortValue): string; begin Result := FModule[Port DIV 16].Input.PortName[Port MOD 16] end; // nastavi nazev inp portu procedure TMTBusb.SetPortIName(Port: TPortValue; name: string); begin FModule[Port DIV 16].Input.PortName[Port MOD 16] := name; end; // ziska nazev out portu function TMTBusb.GetPortOName(Port: TPortValue): string; begin Result := FModule[Port DIV 16].Output.PortName[Port MOD 16] end; // vlozi nazev out portu procedure TMTBusb.SetPortOName(Port: TPortValue; name: string); begin FModule[Port DIV 16].Output.PortName[Port MOD 16] := name; end; // spocita adresu portu z adresy a kanalu function TMTBusb.GetPortNum(addr: TIOaddr; channel: TIOchann): word; begin Result := 0; if addr > 0 then Result := addr*16+channel; end; // vlozi konfigurace pro modul - cardinal procedure TMTBusb.SetCfg(addr: TAddr; config: cardinal); begin FModule[addr].CFData[0] := (config AND $000000FF); FModule[addr].CFData[1] := (config AND $0000FF00) div $100; FModule[addr].CFData[2] := (config AND $00FF0000) div $10000; FModule[addr].CFData[3] := (config AND $FF000000) div $1000000; end; // ziska konfiguraci modulu - cardinal function TMTBusb.GetCfg(addr: TAddr): cardinal; begin Result := 0; Result := Result OR (FModule[addr].CFData[0]); Result := Result OR (FModule[addr].CFData[1] * $100); Result := Result OR (FModule[addr].CFData[2] * $10000); Result := Result OR (FModule[addr].CFData[3] * $1000000); end; // nastavi in port na hodnotu - pouze pro testovani procedure TMTBusb.SetInPort(Port: TPortValue; state: boolean); var X: word; last: word; begin X := Round(Power(2,Port MOD 16)); last := FModule[Port DIV 16].Input.value; if state then begin FModule[Port DIV 16].Input.value := FModule[Port DIV 16].Input.value OR X; end else begin FModule[Port DIV 16].Input.value := FModule[Port DIV 16].Input.value AND ($FFFF-X); end; if (last <> FModule[Port DIV 16].Input.value) then FModule[Port DIV 16].Input.changed := true; end; // nastavi out port na hodnotu procedure TMTBusb.SetOutPort(Port: TPortValue; state: boolean); var X: word; last: word; begin X := Round(Power(2,Port MOD 16)); last := FModule[Port DIV 16].Output.value; if state then begin FModule[Port DIV 16].Output.value := FModule[Port DIV 16].Output.value OR X; end else begin FModule[Port DIV 16].Output.value := FModule[Port DIV 16].Output.value AND ($FFFF-X); end; if (last <> FModule[Port DIV 16].Output.value) then FModule[Port DIV 16].Output.changed := true; end; // nastavi blikani pro out port procedure TMTBusb.SetOutPortFlick(Port: TPortValue; state: TFlickType); var adresa : word; begin adresa := Port div 16; if (adresa in [1.._ADDR_MAX_NUM]) and (IsModule(adresa)) then begin if FPortOut[Port].flick <> state then begin FPortOut[Port].flick := state; FPortOut[Port].flickChange := True; end; end; end; // vrati hodnotu nastaveni blikani function TMTBusb.GetOutPortFlick(Port: TPortValue): TFlickType; begin Result := FPortOut[Port].flick; end; // nastavi vystupy vsech kanalu 0-15 pro dany modul (adresu) procedure TMTBusb.SetOModule(addr: TIOaddr; state: Word); begin if IsModule(addr) then begin if (state <> FModule[addr].Output.value) then begin FModule[addr].Output.changed := True; FModule[addr].Output.value := state; end; end; end; // ziska stav vystupu vsech out kanalu dane adresy modulu function TMTBusb.GetOModule(addr: TIOaddr): word; begin Result := FModule[addr].Output.value; end; // ziska stav vstupu dane adresy a kanalu function TMTBusb.GetInputIO(addr : TIOaddr; channel: TIOchann): boolean; var X: word; Port : word; begin Port := addr*16+channel; X := Round(Power(2,Port MOD 16)); Result := (X = (FModule[Port DIV 16].Input.value AND X)); end; // nastavi out adresu a channel na hodnotu procedure TMTBusb.SetOutputIO(addr : TIOaddr; channel: TIOchann; value: boolean); var X: word; last: word; Port: word; begin Port := addr*16+channel; X := Round(Power(2,Port MOD 16)); last := FModule[Port DIV 16].Output.value; if value then begin FModule[Port DIV 16].Output.value := FModule[Port DIV 16].Output.value OR X; end else begin FModule[Port DIV 16].Output.value := FModule[Port DIV 16].Output.value AND ($FFFF-X); end; if (last <> FModule[Port DIV 16].Output.value) then FModule[Port DIV 16].Output.changed := true; end; // ziska stav vstupu daneho inp portu function TMTBusb.GetInPort(Port: TPortValue): boolean; var X: word; begin X := Round(Power(2,Port MOD 16)); //Result := (X = (FModule[Port DIV 16].Input.value AND X)); if (X = (FModule[Port DIV 16].Input.value AND X)) then Result := true else Result :=false; end; // ziska stav vystupu daneho out portu function TMTBusb.GetOutPort(Port: TPortValue): boolean; var X: word; begin X := Round(Power(2,Port MOD 16)); if (X = (FModule[Port DIV 16].Output.value AND X)) then Result := true else Result :=false; end; // Vrati True, pokud prave prisel signal na vstup function TMTBusb.GetInPortDifUp(Port: TPortValue): boolean; begin If FPortIn[Port].inUp then Result := True else Result := False; end; // Vrati True, pokud prave zmizel signal na vstupu function TMTBusb.GetInPortDifDn(Port: TPortValue): boolean; begin If FPortIn[Port].inDn then Result := True else Result := False; end; // Vrati stav pretizeni daneho kanalu regulatoru function TMTBusb.GetRegOverValue(Port: TRegChann): TPortRegOver; begin Result.value := FRegOver[Port].value; Result.inUp := FRegOver[Port].inUp; end; // vrati, zda je adresa obsazena function TMTBusb.IsModule(addr: TAddr): boolean; begin Result := False; if addr in [1.._ADDR_MAX_NUM] then begin if FModule[addr].typ <> idNone then begin Result := True; end; end; end; // vrati status modulu 19.4.2007 function TMTBusb.GetModuleStatus(addr :TAddr): byte; begin Result:= FModule[addr].status; end; // vrati, zda in port existuje function TMTBusb.GetExistsInPort(Port: TPortValue): boolean; begin case GetModuleType(Port div 16) of idMTB_POT_ID: Result := False; idMTB_REGP_ID: Result := True; idMTB_UNI_ID: Result := True; idMTB_UNIOUT_ID: Result := False; idMTB_TTL_ID: Result := True; idMTB_TTLOUT_ID: Result := False; else Result := False; end; end; // modul ma konfiguracni data - true function TMTBusb.IsModuleConfigured(addr: TAddr): boolean; begin Result := False; if IsModule(addr) then begin Result := FModule[addr].Status and $FA = $40; //Result := not FModule[addr].Status and $2 = $2; end; end; // modul oziven po vypadku function TMTBusb.IsModuleRevived(addr: TAddr): boolean; begin Result := False; if IsModule(addr) then begin Result := FModule[addr].revived; end; end; // modul v poruse function TMTBusb.IsModuleFailure(addr: TAddr): boolean; begin Result := False; if IsModule(addr) then begin Result := FModule[addr].failure; end; end; function TMTBusb.IsModuleScanned(addr: TAddr): boolean; begin Result := False; if IsModule(addr) then begin Result := FModule[addr].inputStateKnown; end; end; // vrati, zda out port existuje function TMTBusb.GetExistsOutPort(Port: TPortValue): boolean; begin case GetModuleType(Port div 16) of idMTB_POT_ID: Result := False; idMTB_REGP_ID: Result := False; idMTB_UNI_ID: Result := True; idMTB_UNIOUT_ID: Result := True; idMTB_TTL_ID: Result := True; idMTB_TTLOUT_ID: Result := True; else Result := False; end; end; function TMTBusb.GetModuleType(addr: TAddr): TModulType; // Typ modulu begin result := idNone; if GetModuleInfo(addr).ID <> 0 then begin case GetModuleInfo(addr).typ of idMTB_POT_ID: Result := idMTB_POT_ID; idMTB_REGP_ID: Result := idMTB_REGP_ID; idMTB_UNI_ID: Result := idMTB_UNI_ID; idMTB_UNIOUT_ID: Result := idMTB_UNIOUT_ID; idMTB_TTL_ID: Result := idMTB_TTL_ID; idMTB_TTLOUT_ID: Result := idMTB_TTLOUT_ID; else Result := idNone; end; end; end; // nastavi rychlost MTB-REG procedure TMTBusb.SetRegSpeed(Rchan: TRegChann; Rspeed: TRegSpeed; Rdirect: TRegDirect; AccTime: TRegAcctime); var adresa : byte; mdata: Array[0..7] of byte; begin if AccTime > 20 then AccTime := 20; adresa := (Rchan DIV 8)+ _REG_ADDR; if (IsModule(adresa)) then begin if (GetModuleType(adresa) = idMTB_REGP_ID) then begin // kontrola zmeny parametru if (FReg[Rchan].RegSpeed <> Rspeed) or (FReg[Rchan].RegDirect <> Rdirect) then begin // odeslat data pro REG FReg[Rchan].RegSpeed := Rspeed; FReg[Rchan].RegDirect := Rdirect; mdata[0] := adresa; mdata[1] := __SET_REG_U; mdata[2] := (Rchan shl 5) + (Rdirect shl 4) + Rspeed; mdata[3] := AccTime; MT_send_packet(mdata, 4); end else begin // parametry beze zmen end; end else begin // adresa neobsahuje REG end; end else begin // adresa neni obsazena end; end; // vrati hodnoty regulatoru (odeslane???) function TMTBusb.GetRegSpeed(Rchan: TRegChann): TReg; begin Result.RegSpeed := FReg[Rchan].RegSpeed; Result.RegDirect := FReg[Rchan].RegDirect; Result.RegAcctime := FReg[Rchan].RegAcctime; end; // vrati informace o modulu v Tmodule function TMTBusb.GetModuleInfo(addr: TAddr): TModule; begin Result := FModule[addr]; end; // vrati informace o modulu v Tmodule function TMTBusb.GetModuleCfg(addr: TAddr): TModulConfigGet; begin RdCfgdata.CFGnum := GetModuleInfo(addr).CFGnum; RdCfgdata.CFGdata[0] := GetModuleInfo(addr).CFdata[0]; RdCfgdata.CFGdata[1] := GetModuleInfo(addr).CFdata[1]; RdCfgdata.CFGdata[2] := GetModuleInfo(addr).CFdata[2]; RdCfgdata.CFGdata[3] := GetModuleInfo(addr).CFdata[3]; RdCfgdata.CFGfw := GetModuleInfo(addr).firmware; RdCfgdata.CFGpopis := GetModuleInfo(addr).popis; Result := RdCfgdata; end; // Vlozi cfg data z pole FSetCfg[] procedure TMTBusb.SetModuleCfg(addr: TAddr); begin FModule[addr].CFData[0] := WrCfgData.CFGdata[0]; FModule[addr].CFData[1] := WrCfgData.CFGdata[1]; FModule[addr].CFData[2] := WrCfgData.CFGdata[2]; FModule[addr].CFData[3] := WrCfgData.CFGdata[3]; FModule[addr].popis := WrCfgData.CFGpopis; end; // zaradi nebo vyradi modul z cinnosti - nutno pred spustenim komunikace procedure TMTBusb.SetModuleEnable(addr: TIOaddr; enable:Boolean); // On/off modulu begin if enable then FModule[addr].setting := FModule[addr].setting or 1 else FModule[addr].setting := FModule[addr].setting and ($FF-1); end; // zjisti, zda je modul zařazen nebo vyřazen function TMTBusb.GetModuleEnable(addr: TIOaddr): boolean; begin if (FModule[addr].setting and 1)=1 then Result := True else Result := False; end; // vrátí název modul dle typu function TMTBusb.GetModuleTypeName(addr: TAddr): string; begin Result := ''; if GetModuleInfo(addr).ID <> 0 then begin case GetModuleInfo(addr).typ of idMTB_POT_ID: Result := 'MTB-POT'; idMTB_REGP_ID: Result := 'MTB-REG puls'; idMTB_UNI_ID: Result := 'MTB-UNI'; idMTB_UNIOUT_ID: Result := 'MTB-UNI out'; idMTB_TTL_ID: Result := 'MTB-TTL'; idMTB_TTLOUT_ID: Result := 'MTB-TTL out'; else Result := 'Neznamý modul'; end; end; end; // vrati rychlost v str function TMTBusb.GetSpeedStr: Cardinal; begin Case FSpeed of sp38400: Result := 38400; sp57600: Result := 57600; sp115200: Result := 115200; else Result := 0; end; end; // nastavi rychlost kontroly prijatych dat - timer procedure TMTBusb.SetScanInterval(interval: TTimerInterval); begin // Kontrola rychlosti FScanInterval := interval; case interval of ti50: FCmdSecCycleNum := 20; ti100: FCmdSecCycleNum := 10; ti200: FCmdSecCycleNum := 5; ti250: FCmdSecCycleNum := 4; end; FTimer.Interval := ord(FScanInterval); end; // pozadavek na zaslani FB data procedure TMTBusb.GetFbData; begin if FScanning then begin FT_Out_Buffer[0] := _USB_SET + 1; FT_Out_Buffer[1] := 5; LogDataOut(2); Write_USB_Device_Buffer(2); end; end; // pozadavek na zaslani CMD count -pocet prikazu procedure TMTBusb.GetCmdNum; begin if FScanning then begin FT_Out_Buffer[0] := _USB_SET + 1; FT_Out_Buffer[1] := 21; LogDataOut(2); Write_USB_Device_Buffer(2); end; end; // Nastavi hodnotu poctu cyklu pro refresh FB dat do PC procedure TMTBusb.SetCyclesData(value: Byte); begin FCyclesFbData := 0; if value > 25 then FCyclesFbData := 25 else FCyclesFbData := value; end; // Odesle hodnotu poctu cyklu pro refresh FB dat do PC procedure TMTBusb.SendCyclesData; begin if FOpenned then begin FT_Out_Buffer[0] := _USB_SET + 2; FT_Out_Buffer[1] := 31; FT_Out_Buffer[2] := FCyclesFbData * 10; LogWrite(llCmd, 'Cycles FB Data'); LogDataOut(3); Write_USB_Device_Buffer(3); // Nastavi CyclesData end; end; // Ulozit data do pameti procedure TMTBusb.XMemWr(mAddr: word; mData : Byte); begin if FOpenned then begin FT_Out_Buffer[0] := _USB_SET + 4; FT_Out_Buffer[1] := 10; FT_Out_Buffer[2] := Hi(mAddr); FT_Out_Buffer[3] := Lo(mAddr); FT_Out_Buffer[4] := mData; LogDataOut(5); Write_USB_Device_Buffer(5); // Data do XRAM end; end; // Nacist data z pameti procedure TMTBusb.XMemRd(mAddr: word); begin if FOpenned then begin FT_Out_Buffer[0] := _USB_SET + 3; FT_Out_Buffer[1] := 11; FT_Out_Buffer[2] := Hi(mAddr); FT_Out_Buffer[3] := Lo(mAddr); LogDataOut(4); Write_USB_Device_Buffer(4); // Data do XRAM end; end; // Scan sbernice, zjisteni pripojenych modulu procedure TMTBusb.MtbScan(Sender: TObject); var i,j,channel,x: word; adresa: byte; port : TPortValue; changed: boolean; odpoved: boolean; paketNum, datNum: byte; mdata: Array[0..7] of byte; potValue : TPotValue; potDirect :TPotDirect; inDataNew1 : word; inDataOld1 : word; pocetModulu : Word; errId : Word; begin try odpoved := false; Get_USB_Device_QueueStatus; // open if (FScan_flag) then begin while (FT_Q_Bytes>=8) do begin Read_USB_Device_Buffer(8); if FT_In_Buffer[7] = _END_BYTE then begin Self.LogDataIn(8); case (FT_In_Buffer[0]) and $F0 of _MTB_ID: begin if (FModuleCount = 256) then begin // something went wrong FModuleCount := 0; WriteError(MTB_INVALID_MODULES_COUNT, _DEFAULT_ERR_ADDR); LogWrite(llError, 'MTB-USB deska odpovídá opakovaným nalezením modulů!'); Self.Close(); end; Inc(FModuleCount); adresa := FT_In_Buffer[1]; FModule[adresa].ID := FT_In_Buffer[2]; FModule[adresa].firmware := IntToHex(FT_In_Buffer[3],2); FModule[adresa].Status := FT_In_Buffer[4]; FModule[adresa].Sum := FT_In_Buffer[5]; FModule[adresa].available := true; case FModule[adresa].ID and $F0 of MTB_POT_ID:FModule[adresa].typ := idMTB_POT_ID; MTB_REGP_ID: FModule[adresa].typ := idMTB_REGP_ID; MTB_UNI_ID: FModule[adresa].typ := idMTB_UNI_ID; MTB_UNIOUT_ID: FModule[adresa].typ := idMTB_UNIOUT_ID; MTB_TTL_ID: FModule[adresa].typ := idMTB_TTL_ID; MTB_TTLOUT_ID: FModule[adresa].typ := idMTB_TTLOUT_ID; else FModule[adresa].typ := idNone; end; FModule[adresa].CFGnum := FModule[adresa].ID and $0F; LogWrite(llInfo, 'Nalezen modul - adresa: '+ IntToStr(adresa) + ' - ' + GetModuleTypeName(adresa) + ' FW: ' + FModule[adresa].firmware); end; _MTB_SEARCH_END: begin pocetModulu := FT_In_Buffer[1]; FScan_flag := false; FSeznam_flag := True; FOpenned := True; LogWrite(llInfo, 'Ukončeno hledání modulů'); if FModuleCount <> pocetModulu then begin FModuleCount := 0; WriteError(MTB_INVALID_MODULES_COUNT, _DEFAULT_ERR_ADDR); LogWrite(llError, 'Nespravný počet nalezených modulů'); Self.Close(); end else if Assigned(AfterOpen) then AfterOpen(Self); end; _RST_OK: begin end; _USB_CFGQ: begin case FT_In_Buffer[2] of 1:begin FHWVersion_Major := FT_In_Buffer[3]; FHWVersion_Minor := FT_In_Buffer[4]; FHWVersion_Release := FT_In_Buffer[5]; FHWVersion := IntToStr(FHWVersion_Major)+'.'+IntToStr(FHWVersion_Minor)+'.'+IntToStr(FHWVersion_Release); FHWVersionInt := StrToInt(Format('%d%.2d%.2d',[FHWVersion_Major, FHWVersion_Minor, FHWVersion_Release])); LogWrite(llInfo, 'Verze FW: '+FHWVersion); end; 11:begin FXRamAddr := (FT_In_Buffer[3]*256)+FT_In_Buffer[4]; FXRamValue := FT_In_Buffer[5]; LogWrite(llInfo, 'XRamRD: '+IntToStr(FXRamAddr)+':'+IntToStr(FXRamValue)); end; end; end; _ERR_CODE: begin FErrAddress := (FT_In_Buffer[1]); errId := (FT_In_Buffer[2]); Self.WriteError(3000+errId, FErrAddress); Self.LogWrite(llError, 'Chyba '+intToStr(errId)+ ' modulu '+IntToStr(FErrAddress)+': '+Self.GetErrString(3000+errId)); end; end; Get_USB_Device_QueueStatus; end else begin // kontrola paketu FDataInputErr := True; // prisel chybný paket LogWrite(llWarning, 'Chyba přijmutého paketu: '+IntToHex(FT_In_Buffer[0],2) +' '+IntToHex(FT_In_Buffer[1],2)+' '+IntToHex(FT_In_Buffer[2],2) +' '+IntToHex(FT_In_Buffer[3],2)+' '+IntToHex(FT_In_Buffer[4],2) +' '+IntToHex(FT_In_Buffer[5],2)+' '+IntToHex(FT_In_Buffer[6],2) +' '+IntToHex(FT_In_Buffer[7],2)); end; end; // while if FDataInputErr then begin FScan_flag := false; LogWrite(llWarning, 'Chyba paketu pri scan modulu'); FOpenned := False; FScan_flag := False; Purge_USB_Device_Out; // ?? vymazat buffer??? FDataInputErr := false; end; end; // ######################################################################### // spustena komunikace if (FScanning) then begin FDataInputErr := False; if FCmdCounter_flag then FCmdCounter_flag := False; if FInputChanged then begin for i := 0 to _PORT_MAX_NUM do begin FPortIn[i].inUp := false; FPortIn[i].inDn := false; end; end; FInputChanged := False; if FOverChanged then begin for i := 0 to _PORTOVER_MAX_NUM do begin FRegOver[i].inUp := false; end; end; FOverChanged := False; Get_USB_Device_QueueStatus; if (FT_Q_Bytes >= 8) then begin paketNum := FT_Q_Bytes div 8; Read_USB_Device_Buffer(paketNum * 8); for i := 0 to paketNum-1 do begin if FT_In_Buffer[i*8+7] = _END_BYTE then begin if ((FT_In_Buffer[i*8] and $F0) <> _USB_CFGQ) and (FT_In_Buffer[i*8+2] <> 21) then begin LogDataIn(8, i*8); end; case (FT_In_Buffer[i*8] and $F0) of _USB_CFGQ: begin case FT_In_Buffer[i*8+2] of 1:begin // verze FW FHWVersion_Major := FT_In_Buffer[i*8+3]; FHWVersion_Minor := FT_In_Buffer[i*8+4]; FHWVersion_Release := FT_In_Buffer[i*8+5]; FHWVersion := IntToStr(FHWVersion_Major)+'.'+IntToStr(FHWVersion_Minor)+'.'+IntToStr(FHWVersion_Release); LogWrite(llInfo, 'Verze FW: '+FHWVersion); LogWrite(llRawCmd, '_USB_CFGQ: '+' - '+ IntToHex(FT_In_Buffer[i*8],2)+' '+ IntToHex(FT_In_Buffer[i*8+1],2)+' '+IntToHex(FT_In_Buffer[i*8+2],2) +' '+IntToHex(FT_In_Buffer[i*8+3],2)+' '+IntToHex(FT_In_Buffer[i*8+4],2)+' '+IntToHex(FT_In_Buffer[i*8+5],2) +' '+IntToHex(FT_In_Buffer[i*8+6],2)+' '+IntToHex(FT_In_Buffer[i*8+7],2)); end; 21:begin // Pocet prikazu FCmdCount := FT_In_Buffer[i*8+4] OR FT_In_Buffer[i*8+3] * $100; FCmdCounter_flag := True; end else begin LogWrite(llRawCmd, '_USB_CFGQ ?: '+' - '+ IntToHex(FT_In_Buffer[i*8],2)+' '+ IntToHex(FT_In_Buffer[i*8+1],2)+' '+IntToHex(FT_In_Buffer[i*8+2],2) +' '+IntToHex(FT_In_Buffer[i*8+3],2)+' '+IntToHex(FT_In_Buffer[i*8+4],2)+' '+IntToHex(FT_In_Buffer[i*8+5],2) +' '+IntToHex(FT_In_Buffer[i*8+6],2)+' '+IntToHex(FT_In_Buffer[i*8+7],2)); end; end; // ostatni navratove hodnoty doplnit pozdeji //Beep; end; _MTB_DATA: begin datNum := FT_In_Buffer[i*8] and $0F; adresa := FT_In_Buffer[i*8+1]; mdata[0] := FT_In_Buffer[i*8+2]; mdata[1] := FT_In_Buffer[i*8+3]; mdata[2] := FT_In_Buffer[i*8+4]; mdata[3] := FT_In_Buffer[i*8+5]; FModule[adresa].Sum := FT_In_Buffer[i*8+datNum]; FModule[adresa].Status := FT_In_Buffer[i*8+datNum-1]; if (datNum>3) then begin case (FModule[adresa].typ) of // vyhodnoceni prijatych dat // moduly I/O idMTB_UNI_ID,idMTB_TTL_ID: begin inDataOld1 := FModule[adresa].Input.value; FModule[adresa].inputStateKnown := true; Self.CheckAllScannedEvent(); inDataNew1 := FT_In_Buffer[i*8+2] OR FT_In_Buffer[i*8+3] * $100; if inDataNew1 <> inDataOld1 then begin FModule[adresa].Input.changed := true; for j := 0 to 15 do begin x := Round(Power(2,j)); if (inDataOld1 and x) <> (inDataNew1 and x) then begin if (inDataNew1 and x) = 0 then begin // 1 -> 0 FPortIn[adresa*16+j].value := False; FPortIn[adresa*16+j].inUp := False; FPortIn[adresa*16+j].inDn := True; end else begin // 0 -> 1 FPortIn[adresa*16+j].value := True; FPortIn[adresa*16+j].inUp := True; FPortIn[adresa*16+j].inDn := False; end; end; end; FModule[adresa].Input.value := inDataNew1; end; end; // potenciometry idMTB_POT_ID: begin // channel n+0 channel := (adresa - _POT_ADDR)*4; // vypocita channel potValue := (mdata[0] and 15); potDirect:= (mdata[2] and 1); if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; // channel n+1 Inc(channel); potValue := (mdata[0] shr 4)and 15; potDirect:= (mdata[2] shr 1)and 1; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; // channel n+2 Inc(channel); potValue := (mdata[1] and 15); potDirect:= (mdata[2] shr 2)and 1; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; // channel n+3 Inc(channel); potValue := (mdata[1] shr 4)and 15; potDirect:= (mdata[2] shr 3)and 1; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; end; // regulatory idMTB_REGP_ID: begin channel := (adresa - _REG_ADDR)*8; inDataOld1 := FModule[adresa].Input.value; inDataNew1 := FT_In_Buffer[i*8+2] OR FT_In_Buffer[i*8+3] * $100; if inDataNew1 <> inDataOld1 then begin FModule[adresa].Input.changed := true; for j := 0 to 7 do begin x := Round(Power(2,j)); if (inDataOld1 and x) <> (inDataNew1 and x) then begin if (inDataNew1 and x) = 0 then begin // 1 -> 0 FRegOver[channel+j].value := False; FRegOver[channel+j].inUp := False; end else begin // 0 -> 1 FRegOver[channel+j].value := True; FRegOver[channel+j].inUp := True; end; end; end; FModule[adresa].Input.value := inDataNew1 end; end; end; // case module typ end else if datNum = 3 then begin // upravit po zmene FW // jen odpoved po prikazu (adresa, status a SUM) odpoved := true; // doplnit kontrolu statusu end else begin // doslo mene nez 3 data LogWrite(llCmd, 'Status <3B addr: '+IntToStr(adresa)+' status: '+IntToStr(FModule[adresa].Status)); end; end; _ERR_CODE: begin FErrAddress := (FT_In_Buffer[(i*8)+1]); errId := (FT_In_Buffer[(i*8)+2]); Self.WriteError(3000+errId, FErrAddress); Self.LogWrite(llWarning, 'Chyba '+intToStr(errId)+ ' modulu '+IntToStr(FErrAddress)+': '+Self.GetErrString(3000+errId)); case errId of 141:begin // modul nekomunikuje FModule[FErrAddress].revived := False; FModule[FErrAddress].failure := True; FModule[FErrAddress].Status := 0; FModule[FErrAddress].inputStateKnown := false; // nastaveni null hodnot do mudulu, ktere jsou v poruse adresa := FErrAddress; case (FModule[adresa].typ) of // vyhodnoceni prijatych dat // moduly I/O idMTB_UNI_ID,idMTB_TTL_ID: begin inDataOld1 := FModule[adresa].Input.value; //inDataNew1 := FT_In_Buffer[i*8+2] OR FT_In_Buffer[i*8+3] * $100; inDataNew1 := 0; if inDataNew1 <> inDataOld1 then begin FModule[adresa].Input.changed := true; for j := 0 to 15 do begin x := Round(Power(2,j)); if (inDataOld1 and x) <> (inDataNew1 and x) then begin if (inDataNew1 and x) = 0 then begin // 1 -> 0 FPortIn[adresa*16+j].value := False; FPortIn[adresa*16+j].inUp := False; FPortIn[adresa*16+j].inDn := True; end else begin // 0 -> 1 FPortIn[adresa*16+j].value := True; FPortIn[adresa*16+j].inUp := True; FPortIn[adresa*16+j].inDn := False; end; end; end; FModule[adresa].Input.value := inDataNew1 end; end; // potenciometry idMTB_POT_ID: begin // channel n+0 channel := (adresa - _POT_ADDR)*4; // vypocita channel potValue := 0; potDirect:= 0; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; // channel n+1 Inc(channel); potValue := 0; potDirect:= 0; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; // channel n+2 Inc(channel); potValue := 0; potDirect:= 0; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; // channel n+3 Inc(channel); potValue := 0; potDirect:= 0; if (FPot[channel].PotValue <> potValue) or (FPot[channel].PotDirect <> potDirect) then begin FPot[channel].PotValue := potValue; FPot[channel].PotDirect:= potDirect; FModule[adresa].Input.changed := true; end; end; // regulatory - overit funkcnost idMTB_REGP_ID: begin channel := (adresa - _REG_ADDR)*8; inDataOld1 := FModule[adresa].Input.value; inDataNew1 := 0; if inDataNew1 <> inDataOld1 then begin FModule[adresa].Input.changed := true; for j := 0 to 7 do begin x := Round(Power(2,j)); if (inDataOld1 and x) <> (inDataNew1 and x) then begin if (inDataNew1 and x) = 0 then begin // 1 -> 0 FRegOver[channel+j].value := False; FRegOver[channel+j].inUp := False; end else begin // 0 -> 1 FRegOver[channel+j].value := True; FRegOver[channel+j].inUp := True; end; end; end; FModule[adresa].Input.value := inDataNew1 end; end; end; // case module typ end; 142:begin // modul oziven FModule[FErrAddress].revived := True; end; end; if FHWVersionInt = 905 then begin case errId of 11:errId := 101; 1:errId := 102; 2:errId := 103; else errId := 200; end; Self.WriteError(3000+errId, FErrAddress); end; end; end; // case end else begin FDataInputErr := True; LogWrite(llWarning, 'Chyba přijmutého paketu: '+IntToHex(FT_In_Buffer[i*8+0],2) +' '+IntToHex(FT_In_Buffer[i*8+1],2)+' '+IntToHex(FT_In_Buffer[i*8+2],2) +' '+IntToHex(FT_In_Buffer[i*8+3],2)+' '+IntToHex(FT_In_Buffer[i*8+4],2) +' '+IntToHex(FT_In_Buffer[i*8+5],2)+' '+IntToHex(FT_In_Buffer[i*8+6],2) +' '+IntToHex(FT_In_Buffer[i*8+7],2)); end; // if kontrola posledniho byte paketu end; end; // priprava pro odeslani dat pri oziveni modulu for i := 1 to _ADDR_MAX_NUM do begin if IsModule(i) then begin if IsModuleRevived(i) then begin if IsModuleConfigured(i) then begin case FModule[i].typ of idMTB_UNI_ID,idMTB_UNIOUT_ID,idMTB_TTL_ID,idMTB_TTLOUT_ID:begin LogWrite(llCmd, 'obnovit data na vystup adr:'+IntToStr(i)); FModule[i].revived := False; FModule[i].failure := False; // uni - vystup FModule[i].Output.changed := True; // uni - blikani vystupu for j := 0 to 15 do begin port := GetPortNum(i,j); if FPortOut[port].flick in [fl33, fl55] then FPortOut[port].flickChange := True; end; // Scom for j := 0 to 7 do begin if FModule[i].Scom.ScomActive[j] then FModule[i].Scom.changed[j] := True; end; end; end; end else begin // poslat idle - ziskat config mdata[0] := i; mdata[1] := __IDLE; MT_send_packet(mdata, 2); end; end; end; end; // odeslani pri zmene dat na vystupu for i := 1 to _ADDR_MAX_NUM do begin if IsModule(i) then begin if FModule[i].Output.changed then begin case (FModule[i].ID AND $F0) of MTB_UNI_ID, MTB_UNIOUT_ID, MTB_TTL_ID, MTB_TTLOUT_ID: begin mdata[0] := i; mdata[1] := __SET_OUTW + 2; mdata[2] := Lo(FModule[i].Output.value); mdata[3] := Hi(FModule[i].Output.value); MT_send_packet(mdata, 4); FModule[i].Output.changed := false; if (Assigned(OnOutputChange)) then OnOutputChange(Self, i); end; end; end; end; end; if FCmdCountCounter > 1 then begin dec(FCmdCountCounter) end else begin FCmdCountCounter := FCmdSecCycleNum; GetCmdNum; end; // nastaveni blikani vystupu for i := 0 to _PORT_MAX_NUM do begin if FModule[i div 16].typ in [idMTB_UNI_ID,idMTB_TTL_ID,idMTB_UNIOUT_ID,idMTB_TTLOUT_ID] then begin if FPortOut[i].flickChange then begin mdata[0] := (i div 16); mdata[1] := __FLICK_OUT; channel := GetChannel(i); mdata[2] := (channel and 7) or ((channel and 8)shl 1); case FPortOut[i].flick of fl33:mdata[2] := mdata[2] or $20; fl55:mdata[2] := mdata[2] or $40; else mdata[2] := mdata[2] or $0; end; MT_send_packet(mdata, 3); FPortOut[i].flickChange := False; end; end; end; // Scom data for i := 1 to _ADDR_MAX_NUM do begin if IsModule(i) then begin if FModule[i].typ in [idMTB_UNI_ID,idMTB_TTL_ID,idMTB_UNIOUT_ID,idMTB_TTLOUT_ID] then begin for j := 0 to 7 do begin if (FModule[i].Scom.ScomActive[j]) and (FModule[i].Scom.changed[j]) then begin mdata[0] := i; // adresa mdata[1] := __SET_NAVEST; // CMD mdata[2] := j; // port mdata[3] := FModule[i].Scom.ScomCode[j]; // Scom code MT_send_packet(mdata, 4); FModule[i].Scom.changed[j] := False; if (Assigned(OnOutputChange)) then OnOutputChange(Self, i); end; end; end; end; end; // kontrola vstupu changed := false; FPotChanged := false; FOverChanged := false; FInputChanged := false; for i := 1 to _ADDR_MAX_NUM do begin if IsModule(i) then begin if (FModule[i].Input.changed) then begin changed := true; Case FModule[i].typ of idMTB_UNI_ID,idMTB_TTL_ID : FInputChanged := True; // Nastavi pri zmene na vstupech I/O idMTB_POT_ID : FPotChanged := True; // Nastavi pri zmene POT idMTB_REGP_ID : FOverChanged := True; // Nastavi pri pretizeni REG end; FModule[i].Input.changed := false; if (Assigned(OnInputChange)) then OnInputChange(Self, i); if ((FModule[i].failure) and (Assigned(OnOutputChange))) then OnOutputChange(Self, i); end; end; end; if FCmdCounter_flag then changed := True; if FDataInputErr then begin Get_USB_Device_QueueStatus; if (FT_Q_Bytes > 0) then begin x := FT_Q_Bytes; Read_USB_Device_Buffer(x); end; GetFbData; // znovu zaslat FB data Self.WriteError(MTB_INVALID_PACKET, _DEFAULT_ERR_ADDR); LogWrite(llWarning, 'Neplatný paket!'); end; if odpoved then changed := True; // Při změně vyvolá událost if (changed AND Assigned(OnChange)) then OnChange(Self); end; // FScaning if Assigned(OnScan) then OnScan(Self); except on E:EFtGeneral do begin Self.LogWrite(llError, 'EXCEPTION (mtbScan): '+e.ClassName+' - '+e.Message); Self.WriteError(MTB_FT_EXCEPTION, _DEFAULT_ERR_ADDR); LogWrite(llError, 'FTDI výjimka!'); try if FScanning then Stop; except end; try if FOpenned then Close; except end; end; on e:Exception do Self.LogWrite(llError, 'EXCEPTION (mtbScan): '+e.ClassName+' - '+e.Message); end; end; // otevre zarizeni procedure TMTBusb.Open(serial_num: String); var i: word; begin if ((FOpenned) or (FScan_flag)) then raise EAlreadyOpened.Create('MTB already opened'); LogWrite(llCmd, 'Otevírám zařízení ' + UsbSerial); if Assigned(BeforeOpen) then BeforeOpen(Self); try Open_USB_Device_By_Serial_Number(serial_num); except on E:EFtDeviceNotFound do raise ECannotOpenPort.Create('Cannot open port'); on E:Exception do begin Self.LogWrite(llError, 'Open exception: '+E.ClassName+' - '+E.Message); raise; end; end; try // Nulovat poc. hodnoty FModuleCount := 0; for i:= 1 to _ADDR_MAX_NUM do begin FModule[i].CFGnum := 0; FModule[i].ID := 0; FModule[i].typ := idNone; FModule[i].available := false; FModule[i].firmware := ''; end; FTimer.Enabled := true; // set FIFO timeout Set_USB_Device_TimeOuts(20,200); Purge_USB_Device_Out; // get FW version FT_Out_Buffer[0] := _USB_SET + 1; FT_Out_Buffer[1] := 1; Self.LogDataOut(2); Write_USB_Device_Buffer(2); FScan_flag := true; FDataInputErr := false; // begin scanning FT_Out_Buffer[0]:= _SCAN_MTB; Self.LogDataOut(1); Write_USB_Device_Buffer(1); LogWrite(llCmd, 'Otevřeno zařízení ' + UsbSerial); LogWrite(llCmd, 'Library v' + Version.GetLibVersion()); except on E:Exception do begin Self.LogWrite(llError, 'Open exception, closing: '+E.ClassName+' - '+E.Message); Self.Close(); raise; end; end; end; // uzavre zarizeni procedure TMTBusb.Close(); var i:Integer; begin try if Assigned(BeforeClose) then BeforeClose(Self); // Reset MTB-USB try FT_Out_Buffer[0] := _USB_RST; LogDataOut(1); Write_USB_Device_Buffer(1); except end; Close_USB_Device; FTimer.Enabled := false; FOpenned := false; FScanning := false; FWaitingOnScan := false; LogWrite(llCmd, 'Uzavření zařízení'); for i:= 1 to _ADDR_MAX_NUM do begin FModule[i].Status := 0; FModule[i].CFGnum := 0; FModule[i].ID := 0; FModule[i].typ := idNone; FModule[i].available := false; FModule[i].firmware := ''; end; if Assigned(AfterClose) then AfterClose(Self); except on E:Exception do begin Self.LogWrite(llError, 'Close exception: '+E.ClassName+' - '+E.Message); raise; end; end; end; // spusti komunikaci procedure TMTBusb.Start(); var i: word; begin if (not FOpenned) then raise ENotOpened.Create('Device not opened, cannot start!'); if (FScanning) then raise EAlreadyStarted.Create('Scanning already started!'); if (FHWVersionInt < MIN_FW_VERSION) then raise EFirmwareTooLog.Create('FW < 0.9.20, cannot start!'); if (FModuleCount = 0) then raise ENoModules.Create('No modules found on bus, cannot start!'); if (Assigned(BeforeStart)) then BeforeStart(Self); try Purge_USB_Device_Out; // vyprazdnit FIFO out Self.ResetPortsStatus(); FT_Out_Buffer[0] := _MTB_SET + 1; FT_Out_Buffer[1] := 0; LogDataOut(2); Write_USB_Device_Buffer(2); // Reset XRAM // send configuration to modules for i := 1 to _ADDR_MAX_NUM do begin if (FModule[i].available) then begin FT_Out_Buffer[0] := _MTB_SET + 7; FT_Out_Buffer[1] := i; FT_Out_Buffer[2] := FModule[i].ID; FT_Out_Buffer[3] := FModule[i].setting; // Bit 0 ==> používat modul? FT_Out_Buffer[4] := FModule[i].CFData[0]; FT_Out_Buffer[5] := FModule[i].CFData[1]; FT_Out_Buffer[6] := FModule[i].CFData[2]; FT_Out_Buffer[7] := FModule[i].CFData[3]; LogDataOut(8); Write_USB_Device_Buffer(8); end; end; SendCyclesData; FT_Out_Buffer[0] := _USB_SET + 1; FT_Out_Buffer[1] := Ord(FSpeed); LogDataOut(2); Write_USB_Device_Buffer(2); // Nastavit rychlost komunikace FT_Out_Buffer[0] := _COM_ON; // spuštění skenování LogDataOut(1); Write_USB_Device_Buffer(1); FScanning := true; FWaitingOnScan := true; LogWrite(llInfo, 'Spuštění komunikace'); LogWrite(llInfo, 'Speed: '+ IntToStr(GetSpeedStr)+'bd ScanInterval: ' + IntToStr(ord(ScanInterval))); GetCmdNum; if (Assigned(AfterStart)) then AfterStart(Self); except on E:Exception do begin Self.LogWrite(llError, 'Start exception, closing: '+E.ClassName+' - '+E.Message); Self.Close(); raise; end; end; end; // zastavi komunikaci procedure TMTBusb.Stop(); var i : word; begin if (not FScanning) then raise ENotStarted.Create('Communication not started, cannot close!'); if (not FOpenned) then raise ENotOpened.Create('Device not opened, cannot stop communication!'); if (Assigned(BeforeStop)) then BeforeStop(Self); try Self.ResetPortsStatus(); FT_Out_Buffer[0] := _COM_OFF; // zastavení skenování LogDataOut(1); Write_USB_Device_Buffer(1); FScanning := false; FWaitingOnScan := false; LogWrite(llInfo, 'Zastavení komunikace'); for i := 1 to _ADDR_MAX_NUM do begin FModule[i].Status := 0; end; if (Assigned(AfterStop)) then AfterStop(Self); except on E:Exception do begin Self.LogWrite(llError, 'Stop exception, closing: '+E.ClassName+' - '+E.Message); Self.Close(); raise; end; end; end; constructor TMTBusb.Create(AOwner: TComponent; ConfigFn:string); begin inherited Create(AOwner); // Default hodnoty FLogLevel := logLevel; FOpenned := false; FScanning := false; FWaitingOnScan := false; FModuleCount := 0; FCmdSecCycleNum := 10; FCyclesFbData := 0; FTimer := TTimer.Create(self); FTimer.Enabled := false; FTimer.Interval := ord(FScanInterval); FTimer.OnTimer := MtbScan; FTimer.SetSubComponent(True); FConfigFn := ConfigFn; try Self.LoadConfig(FConfigFn); except on E:Exception do Self.LogWrite(llError, 'Nelze načíst konfiguraci : ' + E.Message); end; end; destructor TMTBusb.Destroy; begin if (FScanning and FOpenned) then begin try Self.Stop(); except end; end; if (FOpenned) then begin try Self.Close(); except end; end; try Self.SaveConfig(Self.FConfigFn); except on E:Exception do Self.LogWrite(llError, 'Nelze uložit konfiguraci : ' + E.Message); end; inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TMTBusb.LogDataOut(bufLen:Integer); var s:string; i:Integer; begin for i := 0 to bufLen-1 do s := s + IntToHex(FT_Out_Buffer[i], 2) + ' '; Self.LogWrite(llRawCmd, 'DATA OUT: '+s); end; procedure TMTBusb.LogDataIn(bufLen:Integer; bufStart:Integer = 0); var s:string; i:Integer; begin for i := 0 to bufLen-1 do s := s + IntToHex(FT_In_Buffer[i], 2) + ' '; Self.LogWrite(llRawCmd, 'DATA IN: '+s); end; //////////////////////////////////////////////////////////////////////////////// procedure TMTBusb.LoadConfig(fn:string); var ini:TMemIniFile; i:Integer; name:string; begin ini := TMemIniFile.Create(fn, TEncoding.UTF8); for i := 1 to _ADDR_MAX_NUM do begin name := 'Modul '+intToStr(i); Self.SetCfg(i, ini.ReadInteger(name, 'cfg', 0)); FModule[i].setting := ini.ReadInteger(name, 'setting', 1); FModule[i].popis := ini.ReadString(name, 'popis', ''); end; Self.FSpeed := TMtbSpeed(ini.ReadInteger('MTB', 'speed', 4)); Self.FScanInterval := TTimerInterval(ini.ReadInteger('MTB', 'timer', 100)); Self.FusbName := ini.ReadString('MTB', 'device', _DEFAULT_USB_NAME); Self.FLogLevel := TLogLevel(ini.ReadInteger('MTB', 'LogLevel', Integer(llNo))); ini.Free; end; procedure TMTBusb.SaveConfig(fn:string); var ini:TMemIniFile; i:Integer; name:string; begin ini := TMemIniFile.Create(fn, TEncoding.UTF8); for i := 1 to _ADDR_MAX_NUM do begin name := 'Modul '+intToStr(i); ini.WriteInteger(name, 'cfg', Self.GetCfg(i)); ini.WriteInteger(name, 'setting', FModule[i].Setting); ini.WriteString(name, 'popis', FModule[i].popis); end; ini.WriteInteger('MTB', 'speed', Integer(Self.FSpeed)); ini.WriteInteger('MTB', 'timer', Integer(Self.FScanInterval)); ini.WriteString('MTB', 'device', Self.FusbName); ini.WriteInteger('MTB', 'LogLevel', Integer(Self.FLogLevel)); ini.UpdateFile; ini.Free; end; //////////////////////////////////////////////////////////////////////////////// procedure TMTBusb.ResetPortsStatus(); var i, j:Integer; begin for i := 1 to _ADDR_MAX_NUM do begin FModule[i].revived := False; FModule[i].failure := False; FModule[i].inputStateKnown := false; FModule[i].Input.value := 0; FModule[i].Input.changed := False; FModule[i].Output.value := 0; FModule[i].Output.changed := False; for j := 0 to 7 do begin FModule[i].Scom.ScomCode[j] := 0; FModule[i].Scom.changed[j] := False; FModule[i].Scom.ScomActive[j] := False; end; if FModule[i].CFData[0] and $1 = 1 then begin FModule[i].Scom.ScomActive[0] := True; FModule[i].Scom.ScomActive[1] := True; end; if FModule[i].CFData[0] and $2 = 2 then begin FModule[i].Scom.ScomActive[2] := True; FModule[i].Scom.ScomActive[3] := True; end; if FModule[i].CFData[0] and $4 = 4 then begin FModule[i].Scom.ScomActive[4] := True; FModule[i].Scom.ScomActive[5] := True; end; if FModule[i].CFData[0] and $8 = 8 then begin FModule[i].Scom.ScomActive[6] := True; FModule[i].Scom.ScomActive[7] := True; end; end; for i := 0 to _PORT_MAX_NUM do begin FPortIn[i].value := False; FPortIn[i].inUp := False; FPortIn[i].inDn := False; end; for i := 0 to _POT_CHANN-1 do begin FPot[i].PotValue := 0; FPot[i].PotDirect := 0; end; end; //////////////////////////////////////////////////////////////////////////////// function TMTBusb.AreAllModulesScanned(): boolean; var i:Integer; begin for i := 1 to _ADDR_MAX_NUM do begin if ((IsModule(i)) and (not IsModuleFailure(i)) and ((not IsModuleConfigured(i)) or (not IsModuleScanned(i)))) then Exit(false); end; Result := true; end; //////////////////////////////////////////////////////////////////////////////// procedure TMTBusb.CheckAllScannedEvent(); begin if ((Self.FWaitingOnScan) and (AreAllModulesScanned())) then begin Self.FWaitingOnScan := false; if (Assigned(Self.FOnScanned)) then Self.FOnScanned(Self); end; end; //////////////////////////////////////////////////////////////////////////////// end.
unit UPaths; interface function DataFolder: string; implementation uses System.SysUtils; function DataFolder: string; begin {$IFDEF MSWINDOWS} Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + '..\..\'; {$ELSE} Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); {$ENDIF} end; end.
unit eInterestSimulator.Model.Sistema; interface uses eInterestSimulator.Model.Interfaces; type TModelSistema = class(TInterfacedObject, iSistema) private FDescricao: String; FHabilitado: Boolean; FTipoSistema: TTypeSistema; function Descricao(Value: String): iSistema; overload; function Descricao: String; overload; function Habilitado(Value: Boolean): iSistema; overload; function Habilitado: Boolean; overload; function TipoSistema(Value: TTypeSistema): iSistema; overload; function TipoSistema: TTypeSistema; overload; public constructor Create; destructor Destroy; override; class function New: iSistema; end; implementation { TModelSistema } constructor TModelSistema.Create; begin end; function TModelSistema.Descricao(Value: String): iSistema; begin Result := Self; FDescricao := Value; end; function TModelSistema.Descricao: String; begin Result := FDescricao; end; destructor TModelSistema.Destroy; begin inherited; end; function TModelSistema.Habilitado: Boolean; begin Result := FHabilitado; end; function TModelSistema.Habilitado(Value: Boolean): iSistema; begin Result := Self; FHabilitado := Value; end; class function TModelSistema.New: iSistema; begin Result := Self.Create; end; function TModelSistema.TipoSistema: TTypeSistema; begin Result := FTipoSistema; end; function TModelSistema.TipoSistema(Value: TTypeSistema): iSistema; begin Result := Self; FTipoSistema := Value; end; end.
unit SplashDesigner; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, SpeedImage, ComCtrls, ExtDlgs; type TfmSplashDesigner = class( TForm ) btOK: TButton; pcExpertContainer: TPageControl; tsExpertPage1: TTabSheet; llIntro: TLabel; tsExpertPage2: TTabSheet; paSplashPreview: TPanel; siSplashPreview: TSpeedImage; btBrowseSplashImage: TButton; odSplashImage: TOpenPictureDialog; btCancel : TButton; bvSep1 : TBevel; gbSplashOptions: TGroupBox; cbUseTransparent: TCheckBox; cbUseRegistry: TCheckBox; cbStayOnTop: TCheckBox; procedure btOKClick(Sender: TObject); procedure btBrowseSplashImageClick(Sender: TObject); procedure btCancelClick(Sender: TObject); end; var fmSplashDesigner : TfmSplashDesigner; implementation {$R *.DFM} uses Buffer, SpeedBmp; procedure TfmSplashDesigner.btOKClick(Sender: TObject); begin if pcExpertContainer.ActivePage = tsExpertPage1 then pcExpertContainer.ActivePage := tsExpertPage2 else {}; end; procedure TfmSplashDesigner.btBrowseSplashImageClick(Sender: TObject); begin with odSplashImage do if Execute then siSplashPreview.Picture := LoadBitmapFile( Filename ); end; procedure TfmSplashDesigner.btCancelClick(Sender: TObject); begin Close; end; end.
unit Unit_drawing_with_firemonkey; interface uses System.SysUtils, System.Types, System.UITypes, System.UIConsts, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, System.Math.Vectors; type TRadioGroupHelper = class helper for TGroupBox // Setzt voraus, dass die TAG-Werte der TRadioButton manuell zuvor auf 0..x durchnumeriert wurden function ItemIndex: Integer; procedure SetItemIndex(NewIndex: Integer); end; type TForm1 = class(TForm) image1: TImage; rctngl_left1: TRectangle; btn__draw_filledpolygon: TButton; btn_draw_arc: TButton; btn_draw_ellipse: TButton; btn_draw_lines: TButton; btn_draw_Polygon: TButton; clear_color: TButton; trckbr_opacity: TTrackBar; lbl_opacity: TLabel; rb_blue: TRadioButton; grp_Radio: TGroupBox; rb_black: TRadioButton; rb_white: TRadioButton; btn_draw_circles: TButton; btn_draw_rect: TButton; btn_draw_datapath: TButton; procedure btn_draw_arcClick(Sender: TObject); procedure btn_draw_ellipseClick(Sender: TObject); procedure btn_draw_circlesClick(Sender: TObject); procedure btn_draw_PolygonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn__draw_filledpolygonClick(Sender: TObject); procedure clear_colorClick(Sender: TObject); procedure trckbr_opacityChange(Sender: TObject); procedure btn_draw_linesClick(Sender: TObject); procedure btn_draw_rectClick(Sender: TObject); procedure btn_draw_datapathClick(Sender: TObject); private { Private declarations } FOpacity: Single; FPolygonArray: array of TPolygon; procedure MakeRandomPolygons(Sender: TObject); public { Public declarations } localBMP: TBitmap; procedure LoadBMP2GUI(Sender: TObject); end; var Form1: TForm1; implementation {$R *.fmx} function TRadioGroupHelper.ItemIndex: Integer; var L: Integer; begin Result := -1; for L := 0 to ChildrenCount - 1 do begin if Children[L] is TRadioButton then begin if (Children[L] as TRadioButton).IsChecked then begin Result := (Children[L] as TRadioButton).Tag; end; end; end; end; procedure TRadioGroupHelper.SetItemIndex(NewIndex: Integer); var L: Integer; begin for L := 0 to ChildrenCount - 1 do begin if Children[L] is TRadioButton then begin if (Children[L] as TRadioButton).Tag = NewIndex then begin (Children[L] as TRadioButton).IsChecked := True; end; end; end; end; function randomColor: TColor; var rec: TAlphaColorRec; begin with rec do begin A := random(255); R := random(255); G := random(255); B := random(255); end; Result := rec.Color; end; procedure TForm1.MakeRandomPolygons(Sender: TObject); var i: Integer; MyPolygon: TPolygon; p1, p2, p3, p4, p5: TPointF; begin SetLength(FPolygonArray, 10); for i := Low(FPolygonArray) to High(FPolygonArray) do begin // sets the points that define the polygon p1 := TPointF.Create(200 + Random(150), 220 + Random(150)); p2 := TPointF.Create(250 + Random(150), 360 + Random(150)); p3 := TPointF.Create(280 + Random(150), 260 + Random(150)); p4 := TPointF.Create(200 + Random(150), 180 + Random(150)); p5 := TPointF.Create(100 + Random(150), 160 + Random(150)); // creates the polygon SetLength(MyPolygon, 5); MyPolygon[0] := p1; MyPolygon[1] := p2; MyPolygon[2] := p3; MyPolygon[3] := p4; MyPolygon[4] := p5; FPolygonArray[i] := MyPolygon; end; end; procedure TForm1.trckbr_opacityChange(Sender: TObject); begin FOpacity := trckbr_opacity.Value; lbl_opacity.Text := 'opacity:' + FloatToStr(FOpacity); end; procedure TForm1.LoadBMP2GUI(Sender: TObject); var p1, p2, p3, p4, p5: TPointF; begin image1.Bitmap.Assign(localBMP); end; procedure TForm1.btn_draw_arcClick(Sender: TObject); var p1, p2: TPointF; begin // Sets the center of the arc p1 := TPointF.Create(200, 200); // sets the radius of the arc p2 := TPointF.Create(150, 150); localBMP.Canvas.BeginScene; // draws the arc on the canvas localBMP.Canvas.DrawArc(p1, p2, 90, 230, FOpacity); // updates the bitmap to show the arc localBMP.Canvas.EndScene; // Image1.Bitmap.BitmapChanged; LoadBMP2GUI(nil); end; procedure TForm1.btn_draw_ellipseClick(Sender: TObject); var MyRect: TRectF; begin // set the circumscribed rectangle of the ellipse MyRect := TRectF.Create(50, 40, 200, 270); // draws the ellipse om the canvas localBMP.Canvas.BeginScene; localBMP.Canvas.DrawEllipse(MyRect, FOpacity); localBMP.Canvas.EndScene; // updates the bitmap // Image1.Bitmap.BitmapChanged; LoadBMP2GUI(nil); end; procedure TForm1.btn_draw_linesClick(Sender: TObject); var p1, p2: TPointF; i, j: Integer; Brush: TStrokeBrush; begin for i := 1 to 100 do begin Brush := TStrokeBrush.Create(TBrushKind.Solid, randomColor); Brush.Thickness := 2; // Brush.Kind := Solid; p1 := TPointF.Create(2, 2); p2 := TPointF.Create(Random(400), Random(400)); localBMP.Canvas.BeginScene; // draw lines on the canvas localBMP.Canvas.DrawLine(p1, p2, 1, Brush); localBMP.Canvas.EndScene; LoadBMP2GUI(nil); Brush.Free; end end; procedure TForm1.btn_draw_circlesClick(Sender: TObject); var p1, p2: TPointF; i, j: Integer; Brush: TStrokeBrush; MyRect: TRectF; begin /// 5 circles /// localBMP.Canvas.BeginScene; MyRect := TRectF.Create(25, 100, 125, 200); // draws the ellipse om the canvas localBMP.Canvas.DrawEllipse(MyRect, FOpacity); localBMP.Canvas.Stroke.Color := Randomcolor; MyRect := TRectF.Create(150, 100, 250, 200); // draws the ellipse om the canvas localBMP.Canvas.DrawEllipse(MyRect, FOpacity); localBMP.Canvas.Stroke.Color := Randomcolor; MyRect := TRectF.Create(275, 100, 375, 200); // draws the ellipse om the canvas localBMP.Canvas.DrawEllipse(MyRect, FOpacity); localBMP.Canvas.Stroke.Color := Randomcolor; MyRect := TRectF.Create(75, 150, 175, 250); // draws the ellipse om the canvas localBMP.Canvas.DrawEllipse(MyRect, FOpacity); localBMP.Canvas.Stroke.Color := Randomcolor; MyRect := TRectF.Create(200, 150, 300, 250); // draws the ellipse om the canvas localBMP.Canvas.DrawEllipse(MyRect, FOpacity); localBMP.Canvas.Stroke.Color := Randomcolor; localBMP.Canvas.EndScene; // updates the bitmap // Image1.Bitmap.BitmapChanged; LoadBMP2GUI(nil); end; procedure TForm1.btn_draw_datapathClick(Sender: TObject); var path: TPathData; MyRect1, MyRect2: TRectF; begin // set the circumscribed rectangle of the ellipse to be add in the path MyRect1 := TRectF.Create(90, 100, 230, 300); /// sets the rectangle to be add in the path MyRect2 := TRectF.Create(70, 90, 220, 290); // initializes and creates the path to be drawn path := TPathData.Create; path.AddEllipse(MyRect1); path.AddRectangle(MyRect2, 0, 0, AllCorners); localBMP.Canvas.BeginScene; // draws the path on the canvas localBMP.Canvas.DrawPath(path, 200); localBMP.Canvas.EndScene; LoadBMP2GUI(nil); end; procedure TForm1.clear_colorClick(Sender: TObject); begin case grp_Radio.ItemIndex of 1: localBMP.Canvas.Clear(clawhite); 2: localBMP.Canvas.Clear(clablack); 3: localBMP.Canvas.Clear(clablue); else localBMP.Canvas.Clear(clawhite); end; LoadBMP2GUI(nil); end; procedure TForm1.btn_draw_PolygonClick(Sender: TObject); var MyPolygon: TPolygon; i: Integer; Brush: TStrokeBrush; begin for i := Low(FPolygonArray) to High(FPolygonArray) do begin MyPolygon := FPolygonArray[i]; Brush := TStrokeBrush.Create(TBrushKind.Solid, randomColor); Brush.Thickness := 2; // localBMP.Canvas.Stroke := Brush; localBMP.Canvas.BeginScene; // draws the polygon on the canvas localBMP.Canvas.DrawPolygon(MyPolygon, FOpacity); localBMP.Canvas.EndScene; // updates the bitmap // Image1.Bitmap.BitmapChanged; LoadBMP2GUI(nil); Brush.Free; end; end; procedure TForm1.btn_draw_rectClick(Sender: TObject); begin /// /// /// localBMP.Canvas.BeginScene; localBMP.Canvas.Stroke.Color := claBlue; localBMP.Canvas.Stroke.Kind:= TBrushKind.bkSolid; localBMP.Canvas.DrawRect(RectF(0,0,50,50),0,0,AllCorners,1); localBMP.Canvas.EndScene; // updates the bitmap // Image1.Bitmap.BitmapChanged; LoadBMP2GUI(nil); end; procedure TForm1.btn__draw_filledpolygonClick(Sender: TObject); var i: Integer; MyPolygon: TPolygon; Brush: TBrush; begin Brush := TBrush.Create(TBrushKind.Solid, TAlphaColors.red); for i := Low(FPolygonArray) to High(FPolygonArray) do begin MyPolygon := FPolygonArray[i]; Brush.Color := randomColor; localBMP.Canvas.BeginScene; // draws the polygon on the canvas localBMP.Canvas.Fill := Brush; localBMP.Canvas.FillPolygon(MyPolygon, FOpacity); localBMP.Canvas.EndScene; // updates the bitmap // Image1.Bitmap.BitmapChanged; end; LoadBMP2GUI(nil); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin localBMP.Free; end; procedure TForm1.FormCreate(Sender: TObject); begin localBMP := TBitmap.Create; localBMP.Width := 500; localBMP.Height := 500; localBMP.Clear(clawhite); LoadBMP2GUI(nil); MakeRandomPolygons(nil); FOpacity := 50; trckbr_opacity.Value := FOpacity; end; end.
{!DOCTOPIC}{ Type » TIntArray } {!DOCREF} { @method: function TIntArray.Len(): Int32; @desc: Returns the length of the array. Same as 'Length(arr)' } function TIntArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TIntArray.IsEmpty(): Boolean; @desc: Returns True if the array is empty. Same as 'Length(arr) = 0' } function TIntArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure TIntArray.Append(const Value:Int32); @desc: Add another item to the array } {$IFNDEF SRL6} procedure TIntArray.Append(const Value:Int32); {$ELSE} procedure TIntArray.Append(const Value:Int32); override; {$ENDIF} var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := Value; end; {!DOCREF} { @method: procedure TIntArray.Insert(idx:Int32; Value:Int32); @desc: Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length, it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br] `Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`. } procedure TIntArray.Insert(idx:Int32; Value:Int32); var l:Int32; begin l := Length(Self); if (idx < 0) then idx := math.modulo(idx,l); if (l <= idx) then begin self.append(value); Exit(); end; SetLength(Self, l+1); MemMove(Self[idx], self[idx+1], (L-Idx)*SizeOf(Int32)); Self[idx] := value; end; {!DOCREF} { @method: procedure TIntArray.Del(idx:Int32); @desc: Removes the element at the given index c'idx' } procedure TIntArray.Del(idx:Int32); var i,l:Int32; begin l := Length(Self); if (l <= idx) or (idx < 0) then Exit(); if (L-1 <> idx) then MemMove(Self[idx+1], self[idx], (L-Idx)*SizeOf(Int32)); SetLength(Self, l-1); end; {!DOCREF} { @method: procedure TIntArray.Remove(Value:Int32); @desc: Removes the first element from left which is equal to c'Value' } procedure TIntArray.Remove(Value:Int32); begin Self.Del( Self.Find(Value) ); end; {!DOCREF} { @method: function TIntArray.Pop(): Int32; @desc: Removes and returns the last item in the array } function TIntArray.Pop(): Int32; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function TIntArray.PopLeft(): Int32; @desc: Removes and returns the first item in the array } function TIntArray.PopLeft(): Int32; begin Result := Self[0]; MemMove(Self[1], Self[0], SizeOf(Int32)*Length(Self)); SetLength(Self, High(self)); end; {!DOCREF} { @method: function TIntArray.Slice(Start,Stop: Int32; Step:Int32=1): TIntArray; @desc: Slicing similar to slice in Python, tho goes from 'start to and including stop' Can be used to eg reverse an array, and at the same time allows you to `step` past items. You can give it negative start, and stop, then it will wrap around based on length(..) If c'Start >= Stop', and c'Step <= -1' it will result in reversed output. [b]Examples:[/b] [code=pascal] TIA := [0,1,2,3,4,5,6,7,8,9]; TIA.Slice(,,-1) = [9,8,7,6,5,4,3,2,1,0] //Copies from 9 downto 0, with a step-size of 1. TIA.Slice(,,-2) = [9,7,5,3,1] //Copies from 9 downto 0, with a step-size of 2. TIA.Slice(3,7) = [3,4,5,6,7] //Copies from 2 to 7 TIA.Slice(,-2) = [0,1,2,3,4,5,6,7,8] //Copies from 1 to Len-2 [/code] [note]Don't pass positive `Step`, combined with `Start > Stop`, that is undefined[/note] } function TIntArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TIntArray; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 0; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 0; if Step = 0 then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result,0) end; end; {!DOCREF} { @method: procedure TIntArray.Extend(Arr:TIntArray); @desc: Extends the array with an array } procedure TIntArray.Extend(Arr:TIntArray); var L:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(Int32)); end; {!DOCREF} { @method: function TIntArray.Find(Value:Int32): Int32; @desc: Searces for the given value and returns the first position from the left. } function TIntArray.Find(Value:Int32): Int32; begin Result := exp_Find(Self,[Value]); end; {!DOCREF} { @method: function TIntArray.Find(Sequence:TIntArray): Int32; overload; @desc: Searces for the given sequence and returns the first position from the left. } function TIntArray.Find(Sequence:TIntArray): Int32; overload; begin Result := exp_Find(Self,Sequence); end; {!DOCREF} { @method: function TIntArray.FindAll(Value:Int32): TIntArray; @desc: Searces for the given value and returns all the position where it was found. } function TIntArray.FindAll(Value:Int32): TIntArray; overload; begin Result := exp_FindAll(Self,[value]); end; {!DOCREF} { @method: function TIntArray.FindAll(Sequence:TIntArray): TIntArray; overload; @desc: Searces for the given sequence and returns all the position where it was found. } function TIntArray.FindAll(Sequence:TIntArray): TIntArray; overload; begin Result := exp_FindAll(Self,sequence); end; {!DOCREF} { @method: function TIntArray.Contains(val:Int32): Boolean; @desc: Checks if the arr contains the given value c'val' } function TIntArray.Contains(val:Int32): Boolean; begin Result := Self.Find(val) <> -1; end; {!DOCREF} { @method: function TIntArray.Count(val:Int32): Int32; @desc: Counts all the occurances of the given value c'val' } function TIntArray.Count(val:Int32): Int32; begin Result := Length(Self.FindAll(val)); end; {!DOCREF} { @method: procedure TIntArray.Sort(key:TSortKey=sort_Default); @desc: Sorts the array Supports the keys: c'sort_Default' } procedure TIntArray.Sort(key:TSortKey=sort_Default); begin case key of sort_default: se.SortTIA(Self); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TIntArray.Sorted(key:TSortKey=sort_Default): TIntArray; @desc: Returns a new sorted array from the input array. Supports the keys: c'sort_Default' } function TIntArray.Sorted(Key:TSortKey=sort_Default): TIntArray; begin Result := Copy(Self); case key of sort_default: se.SortTIA(Result); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TIntArray.Reversed(): TIntArray; @desc: Creates a reversed copy of the array } function TIntArray.Reversed(): TIntArray; begin Result := Self.Slice(,,-1); end; {!DOCREF} { @method: procedure TIntArray.Reverse(); @desc: Reverses the array } procedure TIntArray.Reverse(); begin Self := Self.Slice(,,-1); end; {=============================================================================} // The functions below this line is not in the standard array functionality // // By "standard array functionality" I mean, functions that all standard // array types should have. {=============================================================================} {!DOCREF} { @method: function TIntArray.Sum(): Int64; @desc: Adds up the TIA and returns the sum } {$IFNDEF SRL6} function TIntArray.Sum(): Int64; {$ELSE} function TIntArray.Sum(): Int32; override; {$ENDIF} begin Result := exp_SumPtr(PChar(Self),SizeOf(Int32),Length(Self),False); end; {!DOCREF} { @method: function TIntArray.Mean(): Extended; @desc:Returns the mean value of the array. Use round, trunc or floor to get an c'Int' value. } function TIntArray.Mean(): Extended; begin Result := Self.Sum() / Length(Self); end; {!DOCREF} { @method: function TIntArray.Stdev(): Extended; @desc: Returns the standard deviation of the array } function TIntArray.Stdev(): Extended; var i:Int32; avg:Extended; square:TExtArray; begin avg := Self.Mean(); SetLength(square,Length(Self)); for i:=0 to High(self) do Square[i] := Sqr(Self[i] - avg); Result := sqrt(square.Mean()); end; {!DOCREF} { @method: function TIntArray.Variance(): Extended; @desc: Return the sample variance. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the array. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. } function TIntArray.Variance(): Extended; var avg:Extended; i:Int32; begin avg := Self.Mean(); for i:=0 to High(Self) do Result := Result + Sqr(Self[i] - avg); Result := Result / length(self); end; {!DOCREF} { @method: function TIntArray.Mode(): Int32; @desc: Returns the sample mode of the array, which is the most frequently occurring value in the array. When there are multiple values occurring equally frequently, mode returns the smallest of those values. } function TIntArray.Mode(): Int32; var arr:TIntArray; i,cur,hits,best: Int32; begin arr := self.sorted(); cur := arr[0]; hits := 1; best := 0; for i:=1 to High(Arr) do begin if (cur <> arr[i]) then begin if (hits > best) then begin best := hits; Result := cur; end; hits := 0; cur := Arr[I]; end; Inc(hits); end; if (hits > best) then Result := cur; end; {!DOCREF} { @method: function TIntArray.VarMin(): Int32; @desc: Returns the minimum value in the array } function TIntArray.VarMin(): Int32; var _:Int32; begin se.MinMaxTIA(Self,Result,_); end; {!DOCREF} { @method: function TIntArray.VarMax(): Int32; @desc: Returns the maximum value in the array } function TIntArray.VarMax(): Int32; var _:Int32; begin se.MinMaxTIA(Self,_,Result); end; {!DOCREF} { @method: function TIntArray.ArgMin(): Int32; @desc: Returns the index containing the smallest element in the array. } function TIntArray.ArgMin(): Int32; var mat:TIntMatrix; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMin(mat).x; end; {!DOCREF} { @method: function TIntArray.ArgMin(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the smallest element in the array. } function TIntArray.ArgMin(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TIntMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMin(n), Result, _); end; {!DOCREF} { @method: function TIntArray.ArgMin(Lo,Hi:int32): Int32; overload; @desc: Returns the index containing the smallest element in the array within the lower and upper bounds c'lo, hi'. } function TIntArray.ArgMin(lo,hi:Int32): Int32; overload; var B: TBox; mat:TIntMatrix; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMin(mat,B).x; end; {!DOCREF} { @method: function TIntArray.ArgMax(): Int32; @desc: Returns the index containing the largest element in the array. } function TIntArray.ArgMax(): Int32; var mat:TIntMatrix; begin SetLength(Mat,1); mat[0] := Self; Result := exp_ArgMax(mat).x; end; {!DOCREF} { @method: function TIntArray.ArgMax(n:int32): TIntArray; overload; @desc: Returns the n-indices containing the largest element in the array. } function TIntArray.ArgMax(n:Int32): TIntArray; overload; var i: Int32; _:TIntArray; mat:TIntMatrix; begin SetLength(Mat,1); mat[0] := Self; se.TPASplitAxis(mat.ArgMax(n), Result, _); end; {!DOCREF} { @method: function TIntArray.ArgMax(Lo,Hi:int32): Int32; overload; @desc: Returns the index containing the largest element in the array within the lower and upper bounds c'lo, hi'. } function TIntArray.ArgMax(lo,hi:Int32): Int32; overload; var B: TBox; mat:TIntMatrix; begin SetLength(Mat,1); mat[0] := Self; B := [lo,0,hi,0]; Result := exp_ArgMax(mat,B).x; end;
unit evToolPanel; // Модуль: "w:\common\components\gui\Garant\Everest\evToolPanel.pas" // Стереотип: "UtilityPack" // Элемент модели: "evToolPanel" MUID: (547CB3B5032B) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , vtPanel , evVisualInterfaces , l3Interfaces ; type TevCustomToolPanel = class(TvtCustomPanel, IevToolWindow) {* базовый класс для инструментальных панелей } private f_Orientation: Tl3Orientation1; protected procedure pm_SetOrientation(aValue: Tl3Orientation1); procedure OrientationChanged; virtual; procedure Scroll(iD: Tl3Inch); procedure Invalidate; function pm_GetVisible: Boolean; procedure pm_SetVisible(aValue: Boolean); public procedure DoScroll(iD: Tl3Inch); virtual; public property Orientation: Tl3Orientation1 read f_Orientation write pm_SetOrientation; end;//TevCustomToolPanel implementation uses l3ImplUses {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *547CB3B5032Bimpl_uses* //#UC END# *547CB3B5032Bimpl_uses* ; procedure TevCustomToolPanel.pm_SetOrientation(aValue: Tl3Orientation1); //#UC START# *547CB49A021A_547CB3C6025Eset_var* //#UC END# *547CB49A021A_547CB3C6025Eset_var* begin //#UC START# *547CB49A021A_547CB3C6025Eset_impl* if (f_Orientation <> aValue) then begin f_Orientation := aValue; case Orientation of ev_orHorizontal: Align := alTop; ev_orVertical: Align := alLeft; end;{Case Orientation} OrientationChanged; end;{f_Delta <> Value} //#UC END# *547CB49A021A_547CB3C6025Eset_impl* end;//TevCustomToolPanel.pm_SetOrientation procedure TevCustomToolPanel.OrientationChanged; //#UC START# *547CB4C800EA_547CB3C6025E_var* //#UC END# *547CB4C800EA_547CB3C6025E_var* begin //#UC START# *547CB4C800EA_547CB3C6025E_impl* Invalidate; //#UC END# *547CB4C800EA_547CB3C6025E_impl* end;//TevCustomToolPanel.OrientationChanged procedure TevCustomToolPanel.DoScroll(iD: Tl3Inch); //#UC START# *547CC36E00D5_547CB3C6025E_var* //#UC END# *547CC36E00D5_547CB3C6025E_var* begin //#UC START# *547CC36E00D5_547CB3C6025E_impl* //#UC END# *547CC36E00D5_547CB3C6025E_impl* end;//TevCustomToolPanel.DoScroll procedure TevCustomToolPanel.Scroll(iD: Tl3Inch); //#UC START# *547CA089003C_547CB3C6025E_var* //#UC END# *547CA089003C_547CB3C6025E_var* begin //#UC START# *547CA089003C_547CB3C6025E_impl* DoScroll(iD); //#UC END# *547CA089003C_547CB3C6025E_impl* end;//TevCustomToolPanel.Scroll procedure TevCustomToolPanel.Invalidate; //#UC START# *547CA0940115_547CB3C6025E_var* //#UC END# *547CA0940115_547CB3C6025E_var* begin //#UC START# *547CA0940115_547CB3C6025E_impl* inherited Invalidate; //#UC END# *547CA0940115_547CB3C6025E_impl* end;//TevCustomToolPanel.Invalidate function TevCustomToolPanel.pm_GetVisible: Boolean; //#UC START# *547CA0B40252_547CB3C6025Eget_var* //#UC END# *547CA0B40252_547CB3C6025Eget_var* begin //#UC START# *547CA0B40252_547CB3C6025Eget_impl* Result := Visible; //#UC END# *547CA0B40252_547CB3C6025Eget_impl* end;//TevCustomToolPanel.pm_GetVisible procedure TevCustomToolPanel.pm_SetVisible(aValue: Boolean); //#UC START# *547CA0B40252_547CB3C6025Eset_var* //#UC END# *547CA0B40252_547CB3C6025Eset_var* begin //#UC START# *547CA0B40252_547CB3C6025Eset_impl* Visible := aValue; //#UC END# *547CA0B40252_547CB3C6025Eset_impl* end;//TevCustomToolPanel.pm_SetVisible initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TevCustomToolPanel); {* Регистрация TevCustomToolPanel } {$IfEnd} // NOT Defined(NoScripts) end.
unit NewNotebookReg; { Inno Setup Copyright (C) 1997-2005 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. TNewNotebook design-time registration $jrsoftware: issrc/Components/NewNotebookReg.pas,v 1.3 2005/10/11 18:23:37 jr Exp $ } interface uses Classes; procedure Register; implementation {$IFNDEF VER80} { if it's not Delphi 1.0 } {$IFNDEF VER90} { if it's not Delphi 2.0 } {$IFNDEF VER93} { and it's not C++Builder 1.0 } {$IFNDEF VER100} { if it's not Delphi 3.0 } {$IFNDEF VER110} { and it's not C++Builder 3.0 } {$IFNDEF VER120} {$IFNDEF VER125} { if it's not Delphi 4 or C++Builder 4 } {$IFNDEF VER130} { if it's not Delphi 5 or C++Builder 5 } {$DEFINE IS_D6} { then it must be at least Delphi 6 or C++Builder 6 } {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} uses NewNotebook, {$IFNDEF IS_D6} DsgnIntf {$ELSE} DesignIntf, DesignEditors {$ENDIF}; { TNewNotebookEditor } type TNewNotebookEditor = class(TComponentEditor) public procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): String; override; function GetVerbCount: Integer; override; end; procedure TNewNotebookEditor.Edit; var Notebook: TNewNotebook; begin { When a page is double-clicked, select the parent notebook } if Component is TNewNotebookPage then begin Notebook := TNewNotebookPage(Component).Notebook; if Assigned(Notebook) then Designer.SelectComponent(Notebook); end end; procedure TNewNotebookEditor.ExecuteVerb(Index: Integer); var Notebook: TNewNotebook; Page: TNewNotebookPage; begin { Find the notebook component to operate on. Note that this same editor class is used for both TNewNotebook and TNewNotebookPage. } if Component is TNewNotebookPage then begin Notebook := TNewNotebookPage(Component).Notebook; if Notebook = nil then Exit; { just in case } end else Notebook := Component as TNewNotebook; case Index of 0, 1: begin Page := Notebook.FindNextPage(Notebook.ActivePage, Index = 0); Notebook.ActivePage := Page; Designer.Modified; Designer.SelectComponent(Page); end; 3: begin Page := TNewNotebookPage.Create(Notebook.Owner); Page.Name := Designer.UniqueName(Page.ClassName); Page.Notebook := Notebook; Notebook.ActivePage := Page; Designer.Modified; Designer.SelectComponent(Page); end; end; end; function TNewNotebookEditor.GetVerbCount: Integer; begin Result := 4; end; function TNewNotebookEditor.GetVerb(Index: Integer): String; begin case Index of 0: Result := 'Next Page'; 1: Result := 'Previous Page'; 2: Result := '-'; 3: Result := 'New Page'; else Result := ''; end; end; procedure Register; begin RegisterComponents('JR', [TNewNotebook]); RegisterClass(TNewNotebookPage); RegisterComponentEditor(TNewNotebook, TNewNotebookEditor); RegisterComponentEditor(TNewNotebookPage, TNewNotebookEditor); end; end.
Unit MultiLinePanel; Interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls,ExtCtrls, WinTypes, Graphics; Type THeightAlign = (taTop, taCenter, taBottom); TGradientStyle = (gsLeft, gsTop, gsRight, gsBottom, gsLRCenter, gsTBCenter); TGradientColors = 2..255; //TComponentState = (csLoading, csReading, csWriting, csDestroying, csDesigning, csAncestor, csUpdating, csFixups, csFreeNotification, csInline, csDesignInstance); type TMultiLinePanel = class(TPanel) private FBgGradient: TBitmap; FMultiCanvas: TControlCanvas; FMultiLine : Boolean; FDefaultHeight: Integer; FOnChange: TNotifyEvent; FHeightAlign: THeightAlign; FSpaceLineFeed: Boolean; FBorderLineColor : TColor; FBorderRound : Byte; FBorderLine : Boolean; FBorderLineWidth : Integer; FCaptionList: TStringList; FDefHeight: Integer; FDefWidth: Integer; FGradientFromColor : TColor; FGradientToColor : TColor; FGradientStyle : TGradientStyle; FDisplayFormat: String; procedure SetMultiLine(Value: Boolean); procedure SetDefaultHeight(Value: Integer); procedure SetHeightAlign(Value: THeightAlign); procedure SetSpaceLineFeed(Value: Boolean); procedure SetBorderLineColor(Value: TColor); procedure SetBorderRound(const Value: Byte); procedure SetBorderLine(Value: Boolean); procedure SetBorderLineWidth(Value: Integer); procedure SetGradientFromColor(Value: TColor); procedure SetGradientToColor(Value: TColor); procedure SetGradientStyle(Value: TGradientStyle); virtual; procedure CreateGradientRect(const AWidth, AHeight: Integer; const StartColor, EndColor: TColor; const Colors: TGradientColors; const Style: TGradientStyle; const Dithered: Boolean; var Bitmap: TBitmap); function IsResized: Boolean; function IsSpecialDrawState(IgnoreDefault: Boolean = False): Boolean; protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure HookResized; //override; published property DisplayFormat: String read FDisplayFormat write FDisplayFormat; property MultiLine: Boolean read FMultiLine write SetMultiLine default TRUE; property DefaultHeight : Integer read FDefaultHeight write SetDefaultHeight default 41; property HeightAlign: THeightAlign read FHeightAlign write SetHeightAlign; property SpaceLineFeed: Boolean read FSpaceLineFeed write SetSpaceLineFeed default FALSE; property BorderLineColor: TColor read FBorderLineColor write SetBorderLineColor default $00733800; property BorderRound: Byte read FBorderRound write SetBorderRound default 5; property BorderLine: Boolean read FBorderLine write SetBorderLine default FALSE; property BorderLineWidth: Integer read FBorderLineWidth write SetBorderLineWidth; property GradientFromColor: TColor read FGradientFromColor write SetGradientFromColor; property GradientToColor: TColor read FGradientToColor write SetGradientToColor; property GradientStyle: TGradientStyle read FGradientStyle write SetGradientStyle default gsLeft; end; procedure Register; implementation constructor TMultiLinePanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FBgGradient := TBitmap.Create; // background gradient FCaptionList := TStringList.Create; ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csSetCaption, csOpaque, csDoubleClicks, csReplicatable]; FDefHeight := 0; FDefWidth := 0; Width := 185; Height := 41; DefaultHeight := 41; MultiLine := TRUE; SpaceLineFeed := FALSE; FBorderLineColor := $00733800; FBorderRound := 5; FBorderLine := FALSE; FBorderLineWidth := 1; FGradientFromColor := clBtnFace; FGradientToColor := clWhite; FGradientStyle := gsLeft; end; destructor TMultiLinePanel.Destroy; begin FCaptionList.Free; FBgGradient.Free; inherited Destroy; end; procedure TMultiLinePanel.SetMultiLine(Value: Boolean); begin if FMultiLine <> Value then begin FMultiLine := Value; RecreateWnd; end; end; procedure TMultiLinePanel.SetDefaultHeight(Value: Integer); begin if FDefaultHeight <> Value then begin FDefaultHeight := Value; Height := Value; RecreateWnd; end; end; procedure TMultiLinePanel.SetHeightAlign(Value: THeightAlign); begin if FHeightAlign <> Value then begin FHeightAlign := Value; RecreateWnd; end; end; procedure TMultiLinePanel.SetSpaceLineFeed(Value: Boolean); begin if FSpaceLineFeed <> Value then begin FSpaceLineFeed := Value; RecreateWnd; end; end; procedure TMultiLinePanel.SetBorderLineColor(Value: TColor); begin if FBorderLineColor <> Value then begin FBorderLineColor := Value; invalidate; end; end; procedure TMultiLinePanel.SetBorderRound(const Value: Byte); begin if FBorderRound <> Value then begin FBorderRound := Value; invalidate; end; end; procedure TMultiLinePanel.SetBorderLine(Value: Boolean); begin if FBorderLine <> Value then begin FBorderLine := Value; invalidate; end; end; procedure TMultiLinePanel.SetBorderLineWidth(Value: Integer); begin if FBorderLineWidth <> Value then begin FBorderLineWidth := Value; invalidate; end; end; procedure TMultiLinePanel.SetGradientFromColor(Value: TColor); begin if FGradientFromColor <> Value then begin FGradientFromColor := Value; HookResized; RecreateWnd; end; end; procedure TMultiLinePanel.SetGradientToColor(Value: TColor); begin if FGradientToColor <> Value then begin FGradientToColor := Value; HookResized; RecreateWnd; end; end; procedure TMultiLinePanel.SetGradientStyle(Value: TGradientStyle); //virtual; begin if FGradientStyle <> Value then begin FGradientStyle := Value; RecreateWnd; HookResized; end; end; procedure TMultiLinePanel.HookResized; const ColSteps = 64; Dithering = True; var Offset: Integer; begin inherited; CreateGradientRect(Width, Height, FGradientFromColor, FGradientToColor, ColSteps, FGradientStyle, Dithering, FBgGradient); end; procedure TMultiLinePanel.CreateGradientRect(const AWidth, AHeight: Integer; const StartColor, EndColor: TColor; const Colors: TGradientColors; const Style: TGradientStyle; const Dithered: Boolean; var Bitmap: TBitmap); const PixelCountMax = 32768; type TGradientBand = array[0..255] of TColor; TRGBMap = packed record case boolean of True: (RGBVal: DWord); False: (R, G, B, D: Byte); end; PRGBTripleArray = ^TRGBTripleArray; TRGBTripleArray = array[0..PixelCountMax-1] of TRGBTriple; const DitherDepth = 16; var iLoop, xLoop, yLoop, XX, YY: Integer; iBndS, iBndE: Integer; GBand: TGradientBand; Row: pRGBTripleArray; procedure CalculateGradientBand; var rR, rG, rB: Real; lCol, hCol: TRGBMap; iStp: Integer; begin if Style in [gsLeft, gsTop] then begin lCol.RGBVal := ColorToRGB(StartColor); hCol.RGBVal := ColorToRGB(EndColor); end else begin lCol.RGBVal := ColorToRGB(EndColor); hCol.RGBVal := ColorToRGB(StartColor); end; rR := (hCol.R - lCol.R) / (Colors - 1); rG := (hCol.G - lCol.G) / (Colors - 1); rB := (hCol.B - lCol.B) / (Colors - 1); for iStp := 0 to (Colors - 1) do GBand[iStp] := RGB( lCol.R + Round(rR * iStp), lCol.G + Round(rG * iStp), lCol.B + Round(rB * iStp) ); end; begin Bitmap.Height := AHeight; Bitmap.Width := AWidth; if Bitmap.PixelFormat <> pf24bit then Bitmap.PixelFormat := pf24bit; CalculateGradientBand; with Bitmap.Canvas do begin Brush.Color := StartColor; FillRect(Bounds(0, 0, AWidth, AHeight)); if Style in [gsLeft, gsRight] then begin for iLoop := 0 to Colors - 1 do begin iBndS := MulDiv(iLoop, AWidth, Colors); iBndE := MulDiv(iLoop + 1, AWidth, Colors); Brush.Color := GBand[iLoop]; PatBlt(Handle, iBndS, 0, iBndE, AHeight, PATCOPY); if (iLoop > 0) and (Dithered) then for yLoop := 0 to DitherDepth - 1 do if (yLoop < AHeight) then begin Row := Bitmap.Scanline[yLoop]; for xLoop := 0 to AWidth div (Colors - 1) do begin XX:= iBndS + Random(xLoop); if (XX < AWidth) and (XX > -1) then with Row[XX] do begin rgbtRed := GetRValue(GBand[iLoop - 1]); rgbtGreen := GetGValue(GBand[iLoop - 1]); rgbtBlue := GetBValue(GBand[iLoop - 1]); end; end; end; end; for yLoop := 1 to AHeight div DitherDepth do CopyRect(Bounds(0, yLoop * DitherDepth, AWidth, DitherDepth), Bitmap.Canvas, Bounds(0, 0, AWidth, DitherDepth)); end else begin for iLoop := 0 to Colors - 1 do begin iBndS := MulDiv(iLoop, AHeight, Colors); iBndE := MulDiv(iLoop + 1, AHeight, Colors); Brush.Color := GBand[iLoop]; PatBlt(Handle, 0, iBndS, AWidth, iBndE, PATCOPY); if (iLoop > 0) and (Dithered) then for yLoop := 0 to AHeight div (Colors - 1) do begin YY:=iBndS + Random(yLoop); if (YY < AHeight) and (YY > -1) then begin Row := Bitmap.Scanline[YY]; for xLoop := 0 to DitherDepth - 1 do if (xLoop < AWidth) then with Row[xLoop] do begin rgbtRed := GetRValue(GBand[iLoop - 1]); rgbtGreen := GetGValue(GBand[iLoop - 1]); rgbtBlue := GetBValue(GBand[iLoop - 1]); end; end; end; end; for xLoop := 0 to AWidth div DitherDepth do CopyRect(Bounds(xLoop * DitherDepth, 0, DitherDepth, AHeight), Bitmap.Canvas, Bounds(0, 0, DitherDepth, AHeight)); end; end; end; function TMultiLinePanel.IsSpecialDrawState(IgnoreDefault: Boolean = False): Boolean; begin end; procedure Register; begin RegisterComponents('Standard', [TMultiLinePanel]); end; function TMultiLinePanel.IsResized: Boolean; begin Result := FALSE; if FDefWidth <> Width then begin FDefWidth := Width; Result := TRUE; end; if FDefHeight <> Height then begin FDefHeight := Height; Result := TRUE; end; end; procedure TMultiLinePanel.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var Rect: TRect; TopColor, BottomColor: TColor; FontHeight: Integer; Flags: Longint; pCaption: PChar; MaxWidth, i, sHeight: Integer; tCaption: String; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; procedure AddCaptionList; begin FCaptionList.Add( tCaption ); tCaption := ''; end; begin Rect := GetClientRect; with Canvas do begin Brush.Color := Color; FillRect(Rect); Brush.Style := bsClear; Font := Self.Font; FCaptionList.Clear; MaxWidth := ClientWidth - 4; sHeight := ClientHeight; FontHeight := TextHeight( Caption ); if csDesigning in ComponentState then FDefaultHeight := Height; if (Align = AlClient) or (Align = AlRight) or (Align = AlLeft) then FDefaultHeight := Height; Flags := DT_EXPANDTABS or DT_VCENTER or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); BitBlt(Handle, 1, 1, Width, Height, FBgGradient.Canvas.Handle, 2, 2, SRCCOPY); if FBorderLine then//and (BevelOuter = bvNone) and (BevelInner = bvNone) then begin Pen.Width := FBorderLineWidth; Pen.Color := FBorderLineColor; Brush.Style := bsClear; RoundRect(0, 0, Width, Height, FBorderRound, FBorderRound); end else begin if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, Rect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; end; if FMultiLine then begin pCaption := PChar( Caption ); tCaption := ''; for i := 1 to Length( Caption ) do begin if ( pCaption[ 0 ] <> #13 ) and ( pCaption[ 0 ] <> #10 ) then begin if MaxWidth < ( TextWidth( tCaption ) + TextWidth( pCaption[ 0 ] ) ) then AddCaptionList; tCaption := tCaption + pCaption[ 0 ] end else if pCaption[ 0 ] = #13 then AddCaptionList; inc( pCaption ); end; if tCaption <> '' then AddCaptionList; if FCaptionList.Count <= 1 then begin ClientHeight := FDefaultHeight; Height := FDefaultHeight; end else begin if FDefaultHeight < ( ( FontHeight * FCaptionList.Count ) + 6 ) then ClientHeight := ( ( FontHeight * FCaptionList.Count ) + 6 ); end; if FCaptionList.Count > 0 then begin with Rect do begin for i := 0 to FCaptionList.Count - 1 do begin if FCaptionList.Count = 1 then Top := ((Bottom + Top) - FontHeight) div 2 else begin if ClientHeight = ( ( FontHeight * FCaptionList.Count ) + 6 ) then Top := ( FontHeight * i ) + 3 else Top := ( ClientHeight - ( FontHeight * FCaptionList.Count ) ) div 2 + ( FontHeight * i ); end; Bottom := Top + FontHeight; case Alignments[Alignment] of DT_LEFT: Left := 3; DT_RIGHT: Right := Right - 3; end; DrawText( Handle, PChar( FCaptionList.Strings[ i ]), Length( FCaptionList.Strings[ i ] ), Rect, Flags ); end; end; end; end else begin ClientHeight := FDefaultHeight; Height := FDefaultHeight; with Rect do begin Top := ((Bottom + Top) - FontHeight) div 2; Bottom := Top + FontHeight; end; DrawText(Handle, PChar(Caption), -1, Rect, Flags); end; if sHeight <> ClientHeight then begin if FHeightAlign = taCenter then Top := Top - (ClientHeight - sHeight) div 2 else if FHeightAlign = taBottom then Top := Top - (ClientHeight - sHeight); end; end; end; end.
unit nsPrimeSettings; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Settings\nsPrimeSettings.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsPrimeSettings" MUID: (4C99AEBC01B3) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If Defined(nsWithoutLogin)} uses l3IntfUses , nsSettingsPrim , afwInterfaces , bsInterfaces , PrimeUnit , SettingsUnit ; type TnsPrimeSettings = class(TnsSettingsPrim, IafwSettings, InsSettingsNotify, InsSettings) private f_State: TafwSettingsState; protected function pm_GetState: TafwSettingsState; procedure pm_SetState(aValue: TafwSettingsState); procedure AddListener(const aListener: InsUserSettingsEditListener); overload; procedure RemoveListener(const aListener: InsUserSettingsEditListener); overload; procedure AddListener(const aListener: InsUserSettingsListener); overload; procedure RemoveListener(const aListener: InsUserSettingsListener); overload; procedure StartEdit; {* вызывается перед началом редактирования } procedure UserSettingsChanged; {* при изменении\восстановлении пользовательских настроек } procedure StartReplace; {* вызывается перед переключением конфигурации } procedure FinishReplace; {* вызывается по окончании переключения конфигурации } function pm_GetSettingsNotify: InsSettingsNotify; function pm_GetData: ISettingsManager; procedure pm_SetData(const aValue: ISettingsManager); function LoadDouble(const aSettingId: TafwSettingId; aDefault: Double = 0; aRestoreDefault: Boolean = False): Double; procedure SaveDouble(const aSettingId: TafwSettingId; aValue: Double; aDefault: Double = 0; aSetAsDefault: Boolean = False); public class function Make(const aSettings: IPrimeSettingsManager): IafwSettings; reintroduce; constructor Create(const aSettings: IPrimeSettingsManager); reintroduce; end;//TnsPrimeSettings {$IfEnd} // Defined(nsWithoutLogin) implementation {$If Defined(nsWithoutLogin)} uses l3ImplUses //#UC START# *4C99AEBC01B3impl_uses* //#UC END# *4C99AEBC01B3impl_uses* ; class function TnsPrimeSettings.Make(const aSettings: IPrimeSettingsManager): IafwSettings; var l_Inst : TnsPrimeSettings; begin l_Inst := Create(aSettings); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsPrimeSettings.Make constructor TnsPrimeSettings.Create(const aSettings: IPrimeSettingsManager); //#UC START# *4C99BA8A0231_4C99AEBC01B3_var* //#UC END# *4C99BA8A0231_4C99AEBC01B3_var* begin //#UC START# *4C99BA8A0231_4C99AEBC01B3_impl* inherited Create(aSettings); f_State := afw_ssNone; //#UC END# *4C99BA8A0231_4C99AEBC01B3_impl* end;//TnsPrimeSettings.Create function TnsPrimeSettings.pm_GetState: TafwSettingsState; //#UC START# *48896A7B0311_4C99AEBC01B3get_var* //#UC END# *48896A7B0311_4C99AEBC01B3get_var* begin //#UC START# *48896A7B0311_4C99AEBC01B3get_impl* Result := f_State; //#UC END# *48896A7B0311_4C99AEBC01B3get_impl* end;//TnsPrimeSettings.pm_GetState procedure TnsPrimeSettings.pm_SetState(aValue: TafwSettingsState); //#UC START# *48896A7B0311_4C99AEBC01B3set_var* //#UC END# *48896A7B0311_4C99AEBC01B3set_var* begin //#UC START# *48896A7B0311_4C99AEBC01B3set_impl* f_State := aValue; //#UC END# *48896A7B0311_4C99AEBC01B3set_impl* end;//TnsPrimeSettings.pm_SetState procedure TnsPrimeSettings.AddListener(const aListener: InsUserSettingsEditListener); //#UC START# *4914446E0280_4C99AEBC01B3_var* //#UC END# *4914446E0280_4C99AEBC01B3_var* begin //#UC START# *4914446E0280_4C99AEBC01B3_impl* // Do nothing //#UC END# *4914446E0280_4C99AEBC01B3_impl* end;//TnsPrimeSettings.AddListener procedure TnsPrimeSettings.RemoveListener(const aListener: InsUserSettingsEditListener); //#UC START# *4914447B01C4_4C99AEBC01B3_var* //#UC END# *4914447B01C4_4C99AEBC01B3_var* begin //#UC START# *4914447B01C4_4C99AEBC01B3_impl* // Do nothing //#UC END# *4914447B01C4_4C99AEBC01B3_impl* end;//TnsPrimeSettings.RemoveListener procedure TnsPrimeSettings.AddListener(const aListener: InsUserSettingsListener); //#UC START# *491444880189_4C99AEBC01B3_var* //#UC END# *491444880189_4C99AEBC01B3_var* begin //#UC START# *491444880189_4C99AEBC01B3_impl* // Do nothing //#UC END# *491444880189_4C99AEBC01B3_impl* end;//TnsPrimeSettings.AddListener procedure TnsPrimeSettings.RemoveListener(const aListener: InsUserSettingsListener); //#UC START# *4914449202EA_4C99AEBC01B3_var* //#UC END# *4914449202EA_4C99AEBC01B3_var* begin //#UC START# *4914449202EA_4C99AEBC01B3_impl* // Do nothing //#UC END# *4914449202EA_4C99AEBC01B3_impl* end;//TnsPrimeSettings.RemoveListener procedure TnsPrimeSettings.StartEdit; {* вызывается перед началом редактирования } //#UC START# *491444D00360_4C99AEBC01B3_var* //#UC END# *491444D00360_4C99AEBC01B3_var* begin //#UC START# *491444D00360_4C99AEBC01B3_impl* // Do nothing //#UC END# *491444D00360_4C99AEBC01B3_impl* end;//TnsPrimeSettings.StartEdit procedure TnsPrimeSettings.UserSettingsChanged; {* при изменении\восстановлении пользовательских настроек } //#UC START# *491444E70109_4C99AEBC01B3_var* //#UC END# *491444E70109_4C99AEBC01B3_var* begin //#UC START# *491444E70109_4C99AEBC01B3_impl* // Do nothing //#UC END# *491444E70109_4C99AEBC01B3_impl* end;//TnsPrimeSettings.UserSettingsChanged procedure TnsPrimeSettings.StartReplace; {* вызывается перед переключением конфигурации } //#UC START# *491444FB0228_4C99AEBC01B3_var* //#UC END# *491444FB0228_4C99AEBC01B3_var* begin //#UC START# *491444FB0228_4C99AEBC01B3_impl* // Do nothing //#UC END# *491444FB0228_4C99AEBC01B3_impl* end;//TnsPrimeSettings.StartReplace procedure TnsPrimeSettings.FinishReplace; {* вызывается по окончании переключения конфигурации } //#UC START# *4914450A01D2_4C99AEBC01B3_var* //#UC END# *4914450A01D2_4C99AEBC01B3_var* begin //#UC START# *4914450A01D2_4C99AEBC01B3_impl* // Do nothing //#UC END# *4914450A01D2_4C99AEBC01B3_impl* end;//TnsPrimeSettings.FinishReplace function TnsPrimeSettings.pm_GetSettingsNotify: InsSettingsNotify; //#UC START# *4914451B03BB_4C99AEBC01B3get_var* //#UC END# *4914451B03BB_4C99AEBC01B3get_var* begin //#UC START# *4914451B03BB_4C99AEBC01B3get_impl* Result := Self; //#UC END# *4914451B03BB_4C99AEBC01B3get_impl* end;//TnsPrimeSettings.pm_GetSettingsNotify function TnsPrimeSettings.pm_GetData: ISettingsManager; //#UC START# *49144567028A_4C99AEBC01B3get_var* //#UC END# *49144567028A_4C99AEBC01B3get_var* begin //#UC START# *49144567028A_4C99AEBC01B3get_impl* Assert(False); Result := nil; //#UC END# *49144567028A_4C99AEBC01B3get_impl* end;//TnsPrimeSettings.pm_GetData procedure TnsPrimeSettings.pm_SetData(const aValue: ISettingsManager); //#UC START# *49144567028A_4C99AEBC01B3set_var* //#UC END# *49144567028A_4C99AEBC01B3set_var* begin //#UC START# *49144567028A_4C99AEBC01B3set_impl* Assert(False); //#UC END# *49144567028A_4C99AEBC01B3set_impl* end;//TnsPrimeSettings.pm_SetData function TnsPrimeSettings.LoadDouble(const aSettingId: TafwSettingId; aDefault: Double = 0; aRestoreDefault: Boolean = False): Double; //#UC START# *4AB729980069_4C99AEBC01B3_var* //#UC END# *4AB729980069_4C99AEBC01B3_var* begin //#UC START# *4AB729980069_4C99AEBC01B3_impl* LoadParam(aSettingId, vtExtended, Result, aDefault, aRestoreDefault); //#UC END# *4AB729980069_4C99AEBC01B3_impl* end;//TnsPrimeSettings.LoadDouble procedure TnsPrimeSettings.SaveDouble(const aSettingId: TafwSettingId; aValue: Double; aDefault: Double = 0; aSetAsDefault: Boolean = False); //#UC START# *4AB729A702A2_4C99AEBC01B3_var* //#UC END# *4AB729A702A2_4C99AEBC01B3_var* begin //#UC START# *4AB729A702A2_4C99AEBC01B3_impl* SaveParam(aSettingId, vtExtended, aValue, aDefault, aSetAsDefault); //#UC END# *4AB729A702A2_4C99AEBC01B3_impl* end;//TnsPrimeSettings.SaveDouble {$IfEnd} // Defined(nsWithoutLogin) end.
unit UserParametersUnit; interface uses REST.Json.Types, System.Generics.Collections, SysUtils, Classes, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, EnumsUnit; type TUserParameters = class(TGenericParameters) private [JSONName('member_id')] [Nullable] FMemberId: NullableInteger; [JSONName('HIDE_ROUTED_ADDRESSES')] [Nullable] FHideRoutedAddresses: NullableString; [JSONName('member_phone')] [Nullable] FPhoneNumber: NullableString; [JSONName('member_zipcode')] [Nullable] FZip: NullableString; [JSONName('route_count')] [Nullable] FRouteCount: NullableInteger; [JSONName('member_email')] [Nullable] FEmail: NullableString; [JSONName('HIDE_VISITED_ADDRESSES')] [Nullable] FHideVisitedAddresses: NullableString; [JSONName('READONLY_USER')] [Nullable] FReadonlyUser: NullableString; [JSONName('member_type')] [Nullable] FMemberType: NullableString; [JSONName('date_of_birth')] [Nullable] FDateOfBirth: NullableString; [JSONName('member_first_name')] [Nullable] FFirstName: NullableString; [JSONName('member_last_name')] [Nullable] FLastName: NullableString; [JSONName('member_password')] [Nullable] FPassword: NullableString; [JSONName('HIDE_NONFUTURE_ROUTES')] [Nullable] FHideNonFutureRoutes: NullableString; [JSONName('SHOW_ALL_VEHICLES')] [Nullable] FShowAllVehicles: NullableString; [JSONName('SHOW_ALL_DRIVERS')] [Nullable] FShowAllDrivers: NullableString; function GetMemberType: TMemberType; procedure SetMemberType(const Value: TMemberType); function GetHideRoutedAddresses: NullableBoolean; function GetHideNonFutureRoutes: NullableBoolean; function GetHideVisitedAddresses: NullableBoolean; function GetShowAllDrivers: NullableBoolean; function GetShowAllVehicles: NullableBoolean; function GetReadonlyUser: NullableBoolean; procedure SetHideRoutedAddresses(const Value: NullableBoolean); procedure SetHideNonFutureRoutes(const Value: NullableBoolean); procedure SetHideVisitedAddresses(const Value: NullableBoolean); procedure SetShowAllDrivers(const Value: NullableBoolean); procedure SetShowAllVehicles(const Value: NullableBoolean); procedure SetReadonlyUser(const Value: NullableBoolean); public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; override; property MemberId: NullableInteger read FMemberId write FMemberId; /// <summary> /// A first name of the member /// </summary> property FirstName: NullableString read FFirstName write FFirstName; /// <summary> /// A last name of the member /// </summary> property LastName: NullableString read FLastName write FLastName; /// <summary> /// An email of the member /// </summary> property Email: NullableString read FEmail write FEmail; /// <summary> /// A phone number of the member /// </summary> property PhoneNumber: NullableString read FPhoneNumber write FPhoneNumber; /// <summary> /// A type of the member /// </summary> property MemberType: TMemberType read GetMemberType write SetMemberType; /// <summary> /// Zip /// </summary> property Zip: NullableString read FZip write FZip; /// <summary> /// Zip /// </summary> property RouteCount: NullableInteger read FRouteCount write FRouteCount; /// <summary> /// Date of user birth /// </summary> property DateOfBirth: NullableString read FDateOfBirth write FDateOfBirth; /// <summary> /// Password /// </summary> property Password: NullableString read FPassword write FPassword; /// <summary> /// /// </summary> property ReadonlyUser: NullableBoolean read GetReadonlyUser write SetReadonlyUser; /// <summary> /// /// </summary> property HideRoutedAddresses: NullableBoolean read GetHideRoutedAddresses write SetHideRoutedAddresses; /// <summary> /// /// </summary> property HideVisitedAddresses: NullableBoolean read GetHideVisitedAddresses write SetHideVisitedAddresses; /// <summary> /// /// </summary> property HideNonFutureRoutes: NullableBoolean read GetHideNonFutureRoutes write SetHideNonFutureRoutes; /// <summary> /// /// </summary> property ShowAllVehicles: NullableBoolean read GetShowAllVehicles write SetShowAllVehicles; /// <summary> /// /// </summary> property ShowAllDrivers: NullableBoolean read GetShowAllDrivers write SetShowAllDrivers; end; implementation constructor TUserParameters.Create; begin Inherited Create; FMemberId := NullableInteger.Null; FFirstName := NullableString.Null; FLastName := NullableString.Null; FEmail := NullableString.Null; FPhoneNumber := NullableString.Null; FMemberType := NullableString.Null; FReadonlyUser := NullableString.Null; FZip := NullableString.Null; FRouteCount := NullableInteger.Null; FDateOfBirth := NullableString.Null; FPassword := NullableString.Null; FHideRoutedAddresses := NullableString.Null; FHideVisitedAddresses := NullableString.Null; FHideNonFutureRoutes := NullableString.Null; FShowAllVehicles := NullableString.Null; FShowAllDrivers := NullableString.Null; end; function TUserParameters.GetHideNonFutureRoutes: NullableBoolean; begin if FHideNonFutureRoutes.IsNotNull then Result := StrToBool(FHideNonFutureRoutes.Value) else Result := NullableBoolean.Null; end; function TUserParameters.GetHideRoutedAddresses: NullableBoolean; begin if FHideRoutedAddresses.IsNotNull then Result := StrToBool(FHideRoutedAddresses.Value) else Result := NullableBoolean.Null; end; function TUserParameters.GetHideVisitedAddresses: NullableBoolean; begin if FHideVisitedAddresses.IsNotNull then Result := StrToBool(FHideVisitedAddresses.Value) else Result := NullableBoolean.Null; end; function TUserParameters.GetMemberType: TMemberType; var MemberType: TMemberType; begin Result := TMemberType.mtUnknown; if FMemberType.IsNotNull then for MemberType := Low(TMemberType) to High(TMemberType) do if (FMemberType = TMemberTypeDescription[MemberType]) then Exit(MemberType); end; function TUserParameters.GetReadonlyUser: NullableBoolean; begin if FReadonlyUser.IsNotNull then Result := StrToBool(FReadonlyUser.Value) else Result := NullableBoolean.Null; end; function TUserParameters.GetShowAllDrivers: NullableBoolean; begin if FShowAllDrivers.IsNotNull then Result := StrToBool(FShowAllDrivers.Value) else Result := NullableBoolean.Null; end; function TUserParameters.GetShowAllVehicles: NullableBoolean; begin if FShowAllVehicles.IsNotNull then Result := StrToBool(FShowAllVehicles.Value) else Result := NullableBoolean.Null; end; procedure TUserParameters.SetHideNonFutureRoutes( const Value: NullableBoolean); begin if Value.IsNull then FHideNonFutureRoutes := NullableString.Null else FHideNonFutureRoutes := UpperCase(BoolToStr(Value, True)); end; procedure TUserParameters.SetHideRoutedAddresses( const Value: NullableBoolean); begin if Value.IsNull then FHideRoutedAddresses := NullableString.Null else FHideRoutedAddresses := UpperCase(BoolToStr(Value, True)); end; procedure TUserParameters.SetHideVisitedAddresses( const Value: NullableBoolean); begin if Value.IsNull then FHideVisitedAddresses := NullableString.Null else FHideVisitedAddresses := UpperCase(BoolToStr(Value, True)); end; procedure TUserParameters.SetMemberType(const Value: TMemberType); begin FMemberType := TMemberTypeDescription[Value]; end; procedure TUserParameters.SetReadonlyUser(const Value: NullableBoolean); begin if Value.IsNull then FReadonlyUser := NullableString.Null else FReadonlyUser := UpperCase(BoolToStr(Value, True)); end; procedure TUserParameters.SetShowAllDrivers(const Value: NullableBoolean); begin if Value.IsNull then FShowAllDrivers := NullableString.Null else FShowAllDrivers := UpperCase(BoolToStr(Value, True)); end; procedure TUserParameters.SetShowAllVehicles( const Value: NullableBoolean); begin if Value.IsNull then FShowAllVehicles := NullableString.Null else FShowAllVehicles := UpperCase(BoolToStr(Value, True)); end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clFormChooser; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Forms, Classes, Controls, StdCtrls, Windows, Messages, {$ELSE} Vcl.Forms, System.Classes, Vcl.Controls, Vcl.StdCtrls, Winapi.Windows, Winapi.Messages, {$ENDIF} clHtmlParser; type THttpFormChooser = class(TForm) btnOK: TButton; lblCaption: TLabel; ListBox: TListBox; Label1: TLabel; procedure ListBoxDblClick(Sender: TObject); public class function ChooseForm(AParser: TclHtmlParser): Integer; end; implementation {$R *.DFM} { THttpFormChooser } class function THttpFormChooser.ChooseForm(AParser: TclHtmlParser): Integer; var i, ScrollWidth: Integer; Dlg: THttpFormChooser; s: string; begin Dlg := THttpFormChooser.Create(nil); try ScrollWidth := 0; for i := 0 to AParser.Forms.Count - 1 do begin if (AParser.Forms[i].Controls.Count > 0) then begin s := AParser.Forms[i].FormName; if (s <> '') then begin s := s + ', '; end; s := s + AParser.Forms[i].Action; if Dlg.ListBox.Canvas.TextWidth(s) > ScrollWidth then begin ScrollWidth := Dlg.ListBox.Canvas.TextWidth(s); end; Dlg.ListBox.Items.Add(s); end; end; if (Dlg.ListBox.Items.Count > 1) then begin Dlg.ListBox.ItemIndex := 0; if (Dlg.ListBox.Width < ScrollWidth) then begin SendMessage(Dlg.ListBox.Handle, LB_SETHORIZONTALEXTENT, ScrollWidth + 10, 0); end; Dlg.ShowModal(); Result := Dlg.ListBox.ItemIndex; end else begin Result := 0; end; finally Dlg.Free(); end; end; procedure THttpFormChooser.ListBoxDblClick(Sender: TObject); begin ModalResult := mrOK; Close(); end; end.
unit Benjamim.Header.Interfaces; interface uses {$IF DEFINED(FPC)} fpjson, {$ELSE} System.JSON, {$ENDIF} Benjamim.Utils; Type iHeader = interface ['{A14B0231-CAB9-40BF-A0D1-91552D33FEA6}'] function Algorithm: string; overload; function Algorithm(const aAlgorithm: TJwtAlgorithm): iHeader; overload; function AsJson(const AsBase64: boolean = false): string; function AsJsonObject: TJSONObject; end; implementation end.
program Ch1; {$mode objfpc} uses SysUtils,Types,Math; procedure QuickSort(var A:TIntegerDynArray;Left,Right:Integer); var I,J:Integer; Pivot,Temp:Integer; begin I := Left; J := Right; Pivot := A[(Left + Right) div 2]; repeat while Pivot > A[I] do Inc(I); while Pivot < A[J] do Dec(J); if I <= J then begin Temp := A[I]; A[I] := A[J]; A[J] := Temp; Inc(I); Dec(J); end; until I > J; if Left < J then QuickSort(A, Left, J); if I < Right then QuickSort(A, I, Right); end; function TwiceLargest(Arr:TIntegerDynArray):Integer; begin QuickSort(Arr,Low(Arr),High(Arr)); Result := IfThen(Arr[High(Arr)] >= (2 * Arr[High(Arr)-1]), 1, -1); end; begin WriteLn(Format('%2d',[TwiceLargest([1,2,3,4])])); WriteLn(Format('%2d',[TwiceLargest([1,2,0,5])])); WriteLn(Format('%2d',[TwiceLargest([2,6,3,1])])); WriteLn(Format('%2d',[TwiceLargest([4,5,2,3])])); end.
unit InfoBBALTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoBBALRecord = record PLender: String[4]; PTranDate: String[8]; PModCount: String[1]; PTotalBalance: Currency; PIndirectBalance: Currency; End; TInfoBBALClass2 = class public PLender: String[4]; PTranDate: String[8]; PModCount: String[1]; PTotalBalance: Currency; PIndirectBalance: Currency; End; // function CtoRInfoBBAL(AClass:TInfoBBALClass):TInfoBBALRecord; // procedure RtoCInfoBBAL(ARecord:TInfoBBALRecord;AClass:TInfoBBALClass); TInfoBBALBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoBBALRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoBBAL = (InfoBBALPrimaryKey); TInfoBBALTable = class( TDBISAMTableAU ) private FDFLender: TStringField; FDFTranDate: TStringField; FDFModCount: TStringField; FDFTotalBalance: TCurrencyField; FDFIndirectBalance: TCurrencyField; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPTranDate(const Value: String); function GetPTranDate:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPTotalBalance(const Value: Currency); function GetPTotalBalance:Currency; procedure SetPIndirectBalance(const Value: Currency); function GetPIndirectBalance:Currency; procedure SetEnumIndex(Value: TEIInfoBBAL); function GetEnumIndex: TEIInfoBBAL; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoBBALRecord; procedure StoreDataBuffer(ABuffer:TInfoBBALRecord); property DFLender: TStringField read FDFLender; property DFTranDate: TStringField read FDFTranDate; property DFModCount: TStringField read FDFModCount; property DFTotalBalance: TCurrencyField read FDFTotalBalance; property DFIndirectBalance: TCurrencyField read FDFIndirectBalance; property PLender: String read GetPLender write SetPLender; property PTranDate: String read GetPTranDate write SetPTranDate; property PModCount: String read GetPModCount write SetPModCount; property PTotalBalance: Currency read GetPTotalBalance write SetPTotalBalance; property PIndirectBalance: Currency read GetPIndirectBalance write SetPIndirectBalance; published property Active write SetActive; property EnumIndex: TEIInfoBBAL read GetEnumIndex write SetEnumIndex; end; { TInfoBBALTable } TInfoBBALQuery = class( TDBISAMQueryAU ) private FDFLender: TStringField; FDFTranDate: TStringField; FDFModCount: TStringField; FDFTotalBalance: TCurrencyField; FDFIndirectBalance: TCurrencyField; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPTranDate(const Value: String); function GetPTranDate:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPTotalBalance(const Value: Currency); function GetPTotalBalance:Currency; procedure SetPIndirectBalance(const Value: Currency); function GetPIndirectBalance:Currency; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoBBALRecord; procedure StoreDataBuffer(ABuffer:TInfoBBALRecord); property DFLender: TStringField read FDFLender; property DFTranDate: TStringField read FDFTranDate; property DFModCount: TStringField read FDFModCount; property DFTotalBalance: TCurrencyField read FDFTotalBalance; property DFIndirectBalance: TCurrencyField read FDFIndirectBalance; property PLender: String read GetPLender write SetPLender; property PTranDate: String read GetPTranDate write SetPTranDate; property PModCount: String read GetPModCount write SetPModCount; property PTotalBalance: Currency read GetPTotalBalance write SetPTotalBalance; property PIndirectBalance: Currency read GetPIndirectBalance write SetPIndirectBalance; published property Active write SetActive; end; { TInfoBBALTable } procedure Register; implementation procedure TInfoBBALTable.CreateFields; begin FDFLender := CreateField( 'Lender' ) as TStringField; FDFTranDate := CreateField( 'TranDate' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFTotalBalance := CreateField( 'TotalBalance' ) as TCurrencyField; FDFIndirectBalance := CreateField( 'IndirectBalance' ) as TCurrencyField; end; { TInfoBBALTable.CreateFields } procedure TInfoBBALTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoBBALTable.SetActive } procedure TInfoBBALTable.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TInfoBBALTable.GetPLender:String; begin result := DFLender.Value; end; procedure TInfoBBALTable.SetPTranDate(const Value: String); begin DFTranDate.Value := Value; end; function TInfoBBALTable.GetPTranDate:String; begin result := DFTranDate.Value; end; procedure TInfoBBALTable.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TInfoBBALTable.GetPModCount:String; begin result := DFModCount.Value; end; procedure TInfoBBALTable.SetPTotalBalance(const Value: Currency); begin DFTotalBalance.Value := Value; end; function TInfoBBALTable.GetPTotalBalance:Currency; begin result := DFTotalBalance.Value; end; procedure TInfoBBALTable.SetPIndirectBalance(const Value: Currency); begin DFIndirectBalance.Value := Value; end; function TInfoBBALTable.GetPIndirectBalance:Currency; begin result := DFIndirectBalance.Value; end; procedure TInfoBBALTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Lender, String, 4, N'); Add('TranDate, String, 8, N'); Add('ModCount, String, 1, N'); Add('TotalBalance, Currency, 0, N'); Add('IndirectBalance, Currency, 0, N'); end; end; procedure TInfoBBALTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Lender;TranDate, Y, Y, N, N'); end; end; procedure TInfoBBALTable.SetEnumIndex(Value: TEIInfoBBAL); begin case Value of InfoBBALPrimaryKey : IndexName := ''; end; end; function TInfoBBALTable.GetDataBuffer:TInfoBBALRecord; var buf: TInfoBBALRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLender := DFLender.Value; buf.PTranDate := DFTranDate.Value; buf.PModCount := DFModCount.Value; buf.PTotalBalance := DFTotalBalance.Value; buf.PIndirectBalance := DFIndirectBalance.Value; result := buf; end; procedure TInfoBBALTable.StoreDataBuffer(ABuffer:TInfoBBALRecord); begin DFLender.Value := ABuffer.PLender; DFTranDate.Value := ABuffer.PTranDate; DFModCount.Value := ABuffer.PModCount; DFTotalBalance.Value := ABuffer.PTotalBalance; DFIndirectBalance.Value := ABuffer.PIndirectBalance; end; function TInfoBBALTable.GetEnumIndex: TEIInfoBBAL; var iname : string; begin result := InfoBBALPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoBBALPrimaryKey; end; procedure TInfoBBALQuery.CreateFields; begin FDFLender := CreateField( 'Lender' ) as TStringField; FDFTranDate := CreateField( 'TranDate' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFTotalBalance := CreateField( 'TotalBalance' ) as TCurrencyField; FDFIndirectBalance := CreateField( 'IndirectBalance' ) as TCurrencyField; end; { TInfoBBALQuery.CreateFields } procedure TInfoBBALQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoBBALQuery.SetActive } procedure TInfoBBALQuery.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TInfoBBALQuery.GetPLender:String; begin result := DFLender.Value; end; procedure TInfoBBALQuery.SetPTranDate(const Value: String); begin DFTranDate.Value := Value; end; function TInfoBBALQuery.GetPTranDate:String; begin result := DFTranDate.Value; end; procedure TInfoBBALQuery.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TInfoBBALQuery.GetPModCount:String; begin result := DFModCount.Value; end; procedure TInfoBBALQuery.SetPTotalBalance(const Value: Currency); begin DFTotalBalance.Value := Value; end; function TInfoBBALQuery.GetPTotalBalance:Currency; begin result := DFTotalBalance.Value; end; procedure TInfoBBALQuery.SetPIndirectBalance(const Value: Currency); begin DFIndirectBalance.Value := Value; end; function TInfoBBALQuery.GetPIndirectBalance:Currency; begin result := DFIndirectBalance.Value; end; function TInfoBBALQuery.GetDataBuffer:TInfoBBALRecord; var buf: TInfoBBALRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLender := DFLender.Value; buf.PTranDate := DFTranDate.Value; buf.PModCount := DFModCount.Value; buf.PTotalBalance := DFTotalBalance.Value; buf.PIndirectBalance := DFIndirectBalance.Value; result := buf; end; procedure TInfoBBALQuery.StoreDataBuffer(ABuffer:TInfoBBALRecord); begin DFLender.Value := ABuffer.PLender; DFTranDate.Value := ABuffer.PTranDate; DFModCount.Value := ABuffer.PModCount; DFTotalBalance.Value := ABuffer.PTotalBalance; DFIndirectBalance.Value := ABuffer.PIndirectBalance; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoBBALTable, TInfoBBALQuery, TInfoBBALBuffer ] ); end; { Register } function TInfoBBALBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('LENDER','TRANDATE','MODCOUNT','TOTALBALANCE','INDIRECTBALANCE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TInfoBBALBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftCurrency; 5 : result := ftCurrency; end; end; function TInfoBBALBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLender; 2 : result := @Data.PTranDate; 3 : result := @Data.PModCount; 4 : result := @Data.PTotalBalance; 5 : result := @Data.PIndirectBalance; end; end; end.