text
stringlengths
14
6.51M
{ *********************************************************************************** } { * 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 ClpAsn1Encodable; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpAsn1OutputStream, ClpDerOutputStream, ClpIProxiedInterface, ClpCryptoLibTypes; type TAsn1Encodable = class abstract(TInterfacedObject, IAsn1Encodable, IAsn1Convertible) public const Der: String = 'DER'; Ber: String = 'BER'; function GetEncoded(): TCryptoLibByteArray; overload; function GetEncoded(const encoding: String): TCryptoLibByteArray; overload; /// <summary> /// Return the DER encoding of the object, null if the DER encoding can /// not be made. /// </summary> /// <returns> /// return a DER byte array, null otherwise. /// </returns> function GetDerEncoded(): TCryptoLibByteArray; function Equals(const other: IAsn1Convertible): Boolean; reintroduce; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI}override; function ToAsn1Object(): IAsn1Object; virtual; abstract; end; implementation { TAsn1Encodable } function TAsn1Encodable.Equals(const other: IAsn1Convertible): Boolean; var o1, o2: IAsn1Object; begin if (other = Self as IAsn1Convertible) then begin Result := true; Exit; end; if (other = Nil) then begin Result := false; Exit; end; o1 := ToAsn1Object(); o2 := other.ToAsn1Object(); Result := ((o1 = o2) or o1.CallAsn1Equals(o2)); end; function TAsn1Encodable.GetDerEncoded: TCryptoLibByteArray; begin try Result := GetEncoded(Der); except on e: EIOCryptoLibException do begin Result := Nil; end; end; end; function TAsn1Encodable.GetEncoded: TCryptoLibByteArray; var bOut: TMemoryStream; aOut: TAsn1OutputStream; begin bOut := TMemoryStream.Create(); aOut := TAsn1OutputStream.Create(bOut); try aOut.WriteObject(Self as IAsn1Encodable); System.SetLength(Result, bOut.Size); bOut.Position := 0; bOut.Read(Result[0], System.Length(Result)); finally bOut.Free; aOut.Free; end; end; function TAsn1Encodable.GetEncoded(const encoding: String): TCryptoLibByteArray; var bOut: TMemoryStream; dOut: TDerOutputStream; begin if (encoding = Der) then begin bOut := TMemoryStream.Create(); dOut := TDerOutputStream.Create(bOut); try dOut.WriteObject(Self as IAsn1Encodable); System.SetLength(Result, bOut.Size); bOut.Position := 0; bOut.Read(Result[0], System.Length(Result)); finally bOut.Free; dOut.Free; end; Exit; end; Result := GetEncoded(); end; function TAsn1Encodable.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} begin Result := ToAsn1Object().CallAsn1GetHashCode(); end; end.
unit frmHousingUseCase; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Controls.Presentation, FMX.StdCtrls; type TDistrictRecord = record longitude: Single; latitude: Single; housing_median_age: Single; total_rooms: Single; total_bedrooms: Single; population: Single; households: Single; median_income: Single; median_house_value: Single; ocean_proximity: String; end; THousingForm = class(TForm) ListView1: TListView; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } tmpFilePath : string; HousingCSVdata : TStringList; tmpStrAry : TArray<string>; tmpRecord : TDistrictRecord; targetArray: array of TDistrictRecord; tmpListItem : TListViewItem; myFormatSettings : TFormatSettings; public { Public declarations } procedure execHousing(); end; var HousingForm: THousingForm; implementation procedure THousingForm.execHousing(); var I, J: integer; begin {TODO: ask user for path to file } tmpFilePath := 'D:\workspace\Delphi\DelphiAI\data\houseprices\housing.csv'; { setup the settings according to used format in our csv-files } myFormatSettings := TFormatSettings.Create; myFormatSettings.DecimalSeparator := '.'; try HousingCSVdata := TStringList.Create; try HousingCSVdata.LoadFromFile(tmpFilePath); except On E : Exception Do Begin ShowMessage(E.Message); raise E; { since we cant continue in meaningful way } End; end; { use length of StringList to reserve memory for data structure } SetLength(targetArray, HousingCSVdata.Count); for I := 1 to HousingCSVdata.Count - 1 do { Index 0 = Header row } begin tmpStrAry := HousingCSVdata[I].Split([',']); J := 0; with tmpRecord do begin longitude := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); latitude := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); housing_median_age := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); total_rooms := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); if tmpStrAry[J] <> '' then total_bedrooms := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings) else total_bedrooms := 0.0; Inc(J); population := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); median_income := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); median_house_value := StrToFloatDef(tmpStrAry[J], 0.0, myFormatSettings); Inc(J); ocean_proximity := tmpStrAry[J]; targetArray[I] := tmpRecord; tmpListItem := ListView1.Items.Add; tmpListItem.Text := HousingCSVdata[I]; end; end; finally HousingCSVdata.Free; end; end; {$R *.fmx} procedure THousingForm.Button1Click(Sender: TObject); begin execHousing(); end; end.
program chapter6assignment(INPUT,OUTPUT); { Alberto Villalobos February 19, 2014 Chapter 6 assignment Description: A use enters space separated values in pairs and the program must read those pairs, one being class id and the other being class size. Then, the program identifies the smallest sized class and the biggest sized classed. Then in the end, the program outputs the id and size of the largest and smallest class, as well as an everage size per class. Input pairs of classids and classids Output smallest class id and size largest class id and size average class size level 0 initialize variables while more classes get classid & size see if largest or smallest compute totals print results level 1 initialize variables set count to 0 set total to 0 set smallsize to maxint set largesize to 0 see if largest or smallest if classsize > largesize set largesize to classsize set largeid to classid if classize < smallsize set smallsize to classize set smallid to classid computer totals add classize to total add 1 to count print results print smallid & smallsize print largeid and largesize print total/count } var count, total, classid, classsize, smallsize, smallid, largesize, largeid : integer; begin writeln('Please enter calls ids and class size in pairs, eg: 001 15'); writeln('Press ctrl+D when you are done'); count := 0; total := 0; largeid := 0; largesize := 0; smallsize := 200000; smallid := 0; while not eof do begin {read two vars} read(classid); read(classsize); {check if largest} if (classsize > largesize) then begin largesize := classsize; largeid := classid; end; if (classsize < smallsize) then begin smallsize := classsize; smallid := classid; end; {sums} total := total + classsize; count := count + 1; if eoln then readln end; writeln('The smallest class is: ',smallid, ' with ', smallsize, ' students'); writeln('The largest class is: ',largeid, ' with ', largesize, ' students'); writeln('The average size per class is: ', (total/count):5:2); end.
unit OptimizationActionsUnit; interface uses SysUtils, BaseActionUnit, DataObjectUnit, OptimizationParametersUnit, RouteParametersQueryUnit, AddOrderToOptimizationRequestUnit; type TOptimizationActions = class(TBaseAction) public function Run(OptimizationParameters: TOptimizationParameters; out ErrorString: String): TDataObject; function Get(OptimizationProblemId: String; out ErrorString: String): TDataObject; overload; function Get(Limit, Offset: integer; out ErrorString: String): TDataObjectList; overload; function Update(OptimizationParameters: TOptimizationParameters; out ErrorString: String): TDataObject; function Remove(OptimizationId: String; out ErrorString: String): boolean; function RemoveDestination(OptimizationId: String; DestinationId: integer; out ErrorString: String): boolean; /// <summary> /// Insert an existing order into an existing optimization. /// </summary> function AddOrder(Parameters: TAddOrderToOptimizationRequest; out ErrorString: String): TDataObjectRoute; end; implementation { TOptimizationActions } uses SettingsUnit, DataObjectOptimizationsResponseUnit, RemoveDestinationFromOptimizationResponseUnit, GenericParametersUnit, CommonTypesUnit, RemoveOptimizationResponseUnit; function TOptimizationActions.AddOrder( Parameters: TAddOrderToOptimizationRequest; out ErrorString: String): TDataObjectRoute; begin Result := FConnection.Put(TSettings.EndPoints.Optimization, Parameters, TDataObjectRoute, ErrorString) as TDataObjectRoute; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Order to an optimization not added'; end; function TOptimizationActions.Get(Limit, Offset: integer; out ErrorString: String): TDataObjectList; var Response: TDataObjectOptimizationsResponse; Request: TRouteParametersQuery; i: integer; begin Result := TDataObjectList.Create; Request := TRouteParametersQuery.Create; try Request.Limit := Limit; Request.Offset := Offset; Response := FConnection.Get(TSettings.EndPoints.Optimization, Request, TDataObjectOptimizationsResponse, ErrorString) as TDataObjectOptimizationsResponse; try if (Response <> nil) then for i := 0 to Length(Response.Optimizations) - 1 do Result.Add(Response.Optimizations[i]); finally FreeAndNil(Response); end; finally FreeAndNil(Request) end; end; function TOptimizationActions.Get(OptimizationProblemId: String; out ErrorString: String): TDataObject; var OptimizationParameters: TOptimizationParameters; begin OptimizationParameters := TOptimizationParameters.Create; try OptimizationParameters.OptimizationProblemID := OptimizationProblemId; Result := FConnection.Get(TSettings.EndPoints.Optimization, OptimizationParameters, TDataObject, ErrorString) as TDataObject; // Result := Get(OptimizationParameters, ErrorString); finally FreeAndNil(OptimizationParameters); end; end; function TOptimizationActions.Remove(OptimizationId: String; out ErrorString: String): boolean; var GenericParameters: TGenericParameters; Response: TRemoveOptimizationResponse; begin GenericParameters := TGenericParameters.Create(); try GenericParameters.AddParameter('optimization_problem_id', OptimizationId); Response := FConnection.Delete(TSettings.EndPoints.Optimization, GenericParameters, TRemoveOptimizationResponse, ErrorString) as TRemoveOptimizationResponse; try Result := (Response <> nil) and (Response.Status) and (Response.Removed); if (not Result) and (ErrorString = EmptyStr) then ErrorString := 'Error removing optimization'; finally FreeAndNil(Response); end; finally FreeAndNil(GenericParameters); end; end; function TOptimizationActions.RemoveDestination(OptimizationId: String; DestinationId: integer; out ErrorString: String): boolean; var Response: TRemoveDestinationFromOptimizationResponse; GenericParameters: TGenericParameters; begin GenericParameters := TGenericParameters.Create(); try GenericParameters.AddParameter('optimization_problem_id', OptimizationId); GenericParameters.AddParameter('route_destination_id', IntToStr(DestinationId)); Response := FConnection.Delete(TSettings.EndPoints.GetAddress, GenericParameters, TRemoveDestinationFromOptimizationResponse, ErrorString) as TRemoveDestinationFromOptimizationResponse; try Result := (Response <> nil) and (Response.Deleted); finally FreeAndNil(Response); end; finally FreeAndNil(GenericParameters); end; end; function TOptimizationActions.Run( OptimizationParameters: TOptimizationParameters; out ErrorString: String): TDataObject; begin Result := FConnection.Post(TSettings.EndPoints.Optimization, OptimizationParameters, TDataObject, ErrorString) as TDataObject; end; function TOptimizationActions.Update( OptimizationParameters: TOptimizationParameters; out ErrorString: String): TDataObject; begin Result := FConnection.Put(TSettings.EndPoints.Optimization, OptimizationParameters, TDataObject, ErrorString) as TDataObject; end; end.
unit uFuncoes; interface uses System.Classes, Firedac.Comp.Client, System.SysUtils, System.MaskUtils, Firedac.Stan.Param, System.IniFiles, uDM, Horse; function DataSql(Data1, Data2: TDateTime): string; overload; function DataSql(Data: TDateTime): string; overload; function Formatar(Texto: string; TamanhoDesejado: Integer; AcrescentarADireita: Boolean = True; CaracterAcrescentar: char = ' '): string; function ValidaCPF(Num: string): Boolean; function ValidaCNPJ(Num: string): Boolean; function SomenteNumero(Texto: string): string; function RemoveAcento(Str: string; ARemoverApostrofo: Boolean = False): string; function StrZero(Num, Size: Integer): string; function GUIDToString2(const Guid: TGUID): string; function ValorExtenso(Valor: Extended; Moeda: Boolean): string; function FormatarTelefone(ATelefone: String): String; function DirSistema: String; function NomeArquivoValido(Nome: string): string; function LerIni(ATabela, ACampo: string; ADefault: string = ''): string; procedure GerarErro(Res: THorseResponse; AMensagem: String; AMensagemInterna: string = ''); function GetClaims(Req: THorseRequest; AClaim: String): String; function ValidarData(AData: String): TDateTime; implementation uses Horse.Commons, uLogArquivo, System.JSON; function DataSql(Data1, Data2: TDateTime): string; begin Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', Data1)) + ' and ' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', Data2)); end; function DataSql(Data: TDateTime): string; begin Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', Data)); end; function Formatar(Texto: string; TamanhoDesejado: Integer; AcrescentarADireita: Boolean = True; CaracterAcrescentar: char = ' '): string; var QuantidadeAcrescentar, TamanhoTexto, PosicaoInicial, i: Integer; begin case CaracterAcrescentar of '0' .. '9', 'a' .. 'z', 'A' .. 'Z': ; { Não faz nada } else CaracterAcrescentar := ' '; end; Texto := Trim(AnsiUpperCase(Texto)); TamanhoTexto := Length(Texto); for i := 1 to (TamanhoTexto) do begin if Pos(Texto[i], ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~''"!@#$%^&*()_-+=|/\{}[]:;,.<>') = 0 then begin case Texto[i] of 'Á', 'À', 'Â', 'Ä', 'Ã': Texto[i] := 'A'; 'É', 'È', 'Ê', 'Ë': Texto[i] := 'E'; 'Í', 'Ì', 'Î', 'Ï': Texto[i] := 'I'; 'Ó', 'Ò', 'Ô', 'Ö', 'Õ': Texto[i] := 'O'; 'Ú', 'Ù', 'Û', 'Ü': Texto[i] := 'U'; 'Ç': Texto[i] := 'C'; 'Ñ': Texto[i] := 'N'; else Texto[i] := ' '; end; end; end; QuantidadeAcrescentar := TamanhoDesejado - TamanhoTexto; if QuantidadeAcrescentar < 0 then QuantidadeAcrescentar := 0; if CaracterAcrescentar = '' then CaracterAcrescentar := ' '; if TamanhoTexto >= TamanhoDesejado then PosicaoInicial := TamanhoTexto - TamanhoDesejado + 1 else PosicaoInicial := 1; if AcrescentarADireita then Texto := Copy(Texto, 1, TamanhoDesejado) + StringOfChar(CaracterAcrescentar, QuantidadeAcrescentar) else Texto := StringOfChar(CaracterAcrescentar, QuantidadeAcrescentar) + Copy(Texto, PosicaoInicial, TamanhoDesejado); Result := AnsiUpperCase(Texto); end; function ValidaCPF(Num: string): Boolean; var n1, n2, n3, n4, n5, n6, n7, n8, n9: Integer; d1, d2: Integer; digitado, calculado: string; i: Integer; Repetido: Boolean; begin Num := SomenteNumero(Num); if Length(Num) <> 11 then begin Result := False; exit; end; Repetido := True; for i := 1 to 11 do begin if Num[1] <> Num[i] then begin Repetido := False; break; end; end; if Repetido then begin Result := False; exit; end; try n1 := StrToInt(Num[1]); n2 := StrToInt(Num[2]); n3 := StrToInt(Num[3]); n4 := StrToInt(Num[4]); n5 := StrToInt(Num[5]); n6 := StrToInt(Num[6]); n7 := StrToInt(Num[7]); n8 := StrToInt(Num[8]); n9 := StrToInt(Num[9]); d1 := n9 * 2 + n8 * 3 + n7 * 4 + n6 * 5 + n5 * 6 + n4 * 7 + n3 * 8 + n2 * 9 + n1 * 10; d1 := 11 - (d1 mod 11); if d1 >= 10 then d1 := 0; d2 := d1 * 2 + n9 * 3 + n8 * 4 + n7 * 5 + n6 * 6 + n5 * 7 + n4 * 8 + n3 * 9 + n2 * 10 + n1 * 11; d2 := 11 - (d2 mod 11); if d2 >= 10 then d2 := 0; calculado := IntToStr(d1) + IntToStr(d2); digitado := Num[10] + Num[11]; if calculado = digitado then ValidaCPF := True else ValidaCPF := False; except Result := False; end; end; function ValidaCNPJ(Num: string): Boolean; var n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12: Integer; d1, d2: Integer; digitado, calculado: string; begin Num := SomenteNumero(Num); if length(Num) <> 14 then begin Result := False; exit; end; n1 := StrToInt(Num[1]); n2 := StrToInt(Num[2]); n3 := StrToInt(Num[3]); n4 := StrToInt(Num[4]); n5 := StrToInt(Num[5]); n6 := StrToInt(Num[6]); n7 := StrToInt(Num[7]); n8 := StrToInt(Num[8]); n9 := StrToInt(Num[9]); n10 := StrToInt(Num[10]); n11 := StrToInt(Num[11]); n12 := StrToInt(Num[12]); d1 := n12 * 2 + n11 * 3 + n10 * 4 + n9 * 5 + n8 * 6 + n7 * 7 + n6 * 8 + n5 * 9 + n4 * 2 + n3 * 3 + n2 * 4 + n1 * 5; d1 := 11 - (d1 mod 11); if d1 >= 10 then d1 := 0; d2 := d1 * 2 + n12 * 3 + n11 * 4 + n10 * 5 + n9 * 6 + n8 * 7 + n7 * 8 + n6 * 9 + n5 * 2 + n4 * 3 + n3 * 4 + n2 * 5 + n1 * 6; d2 := 11 - (d2 mod 11); if d2 >= 10 then d2 := 0; calculado := IntToStr(d1) + IntToStr(d2); digitado := Num[13] + Num[14]; if calculado = digitado then Result := true else Result := False; end; function SomenteNumero(Texto: string): string; var i: Integer; Aux: string; begin Aux := ''; for i := 1 to Length(Texto) do begin if Texto[i] in ['0' .. '9'] then Aux := Aux + Texto[i]; end; Result := Aux; end; function RemoveAcento(Str: string; ARemoverApostrofo: Boolean = False): string; { Remove caracteres acentuados de uma string } const ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ&'; SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU@'; var xx, Tam, x: Integer; Str2: string; begin for x := 1 to Length(Str) do begin if Pos(Str[x], ComAcento) <> 0 then begin Str[x] := SemAcento[Pos(Str[x], ComAcento)]; end; end; Str := Trim(Str); Str2 := ''; Tam := Length(Str); for xx := 1 to Tam do begin if Copy(Str, xx, 1) <> '@' then begin Str2 := Str2 + Copy(Str, xx, 1); end; end; if ARemoverApostrofo then Str := StringReplace(Str2, #39, '', []) else Str := Str2; Result := Str; end; function StrZero(Num, Size: Integer): string; var Text: string; i, Tam: Integer; begin Text := IntToStr(Num); Tam := Length(Text); for i := 1 to (Size - Tam) do Text := '0' + Text; Result := Text; end; function GUIDToString2(const Guid: TGUID): string; begin SetLength(Result, 36); StrLFmt(PChar(Result), 36, '%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x', [Guid.d1, Guid.d2, Guid.D3, Guid.D4[0], Guid.D4[1], Guid.D4[2], Guid.D4[3], Guid.D4[4], Guid.D4[5], Guid.D4[6], Guid.D4[7]]); end; function VersaoExe: string; begin Result := '1.0.0.0'; end; function ValorExtenso(Valor: Extended; Moeda: Boolean): string; var Centavos, centena, Milhar, Milhao, Bilhao, Texto: string; vValorAux: Extended; const Unidades: array [1 .. 9] of string = ('um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove'); Dez: array [1 .. 9] of string = ('onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove'); Dezenas: array [1 .. 9] of string = ('dez', 'vinte', 'trinta', 'quarenta', 'cinqüenta', 'sessenta', 'setenta', 'oitenta', 'noventa'); Centenas: array [1 .. 9] of string = ('cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seiscentos', 'setecentos', 'oitocentos', 'novecentos'); function ifs(Expressao: Boolean; CasoVerdadeiro, CasoFalso: string): string; begin if Expressao then Result := CasoVerdadeiro else Result := CasoFalso; end; function MiniExtenso(Valor: ShortString): string; var unidade, dezena, centena: string; begin if (Valor[2] = '1') and (Valor[3] <> '0') then begin unidade := Dez[StrToInt(Valor[3])]; dezena := ''; end else begin if Valor[2] <> '0' then dezena := Dezenas[StrToInt(Valor[2])]; if Valor[3] <> '0' then unidade := Unidades[StrToInt(Valor[3])]; end; if (Valor[1] = '1') and (unidade = '') and (dezena = '') then centena := 'cem' else if Valor[1] <> '0' then centena := Centenas[StrToInt(Valor[1])] else centena := ''; Result := centena + ifs((centena <> '') and ((dezena <> '') or (unidade <> '')), ' e ', '') + dezena + ifs((dezena <> '') and (unidade <> ''), ' e ', '') + unidade; end; begin vValorAux := 0; if Valor = 0 then begin if Moeda then Result := '' else Result := 'zero'; exit; end else if Valor < 0 then begin vValorAux := Valor; Valor := Valor * -1; end; Texto := FormatFloat('000000000000.00', Valor); Centavos := MiniExtenso('0' + Copy(Texto, 14, 2)); centena := MiniExtenso(Copy(Texto, 10, 3)); Milhar := MiniExtenso(Copy(Texto, 7, 3)); if Milhar <> '' then Milhar := Milhar + ' mil'; Milhao := MiniExtenso(Copy(Texto, 4, 3)); if Milhao <> '' then Milhao := Milhao + ifs(Copy(Texto, 4, 3) = '001', ' milhão', ' milhões'); Bilhao := MiniExtenso(Copy(Texto, 1, 3)); if Bilhao <> '' then Bilhao := Bilhao + ifs(Copy(Texto, 1, 3) = '001', ' bilhão', ' bilhões'); Result := Bilhao + ifs((Bilhao <> '') and (Milhao + Milhar + centena <> ''), ifs((Pos(' e ', Bilhao) > 0) or (Pos(' e ', Milhao + Milhar + centena) > 0), ', ', ' e '), '') + Milhao + ifs((Milhao <> '') and (Milhar + centena <> ''), ifs((Pos(' e ', Milhao) > 0) or (Pos(' e ', Milhar + centena) > 0), ', ', ' e '), '') + Milhar + ifs((Milhar <> '') and (centena <> ''), ifs(Pos(' e ', centena) > 0, ', ', ' e '), '') + centena; if Moeda then begin if (Bilhao <> '') and (Milhao + Milhar + centena = '') then Result := Bilhao + ' de reais' else if (Milhao <> '') and (Milhar + centena = '') then Result := Milhao + ' de reais' else Result := Bilhao + ifs((Bilhao <> '') and (Milhao + Milhar + centena <> ''), ifs((Pos(' e ', Bilhao) > 0) or (Pos(' e ', Milhao + Milhar + centena) > 0), ', ', ' e '), '') + Milhao + ifs((Milhao <> '') and (Milhar + centena <> ''), ifs((Pos(' e ', Milhao) > 0) or (Pos(' e ', Milhar + centena) > 0), ', ', ' e '), '') + Milhar + ifs((Milhar <> '') and (centena <> ''), ifs(Pos(' e ', centena) > 0, ', ', ' e '), '') + centena + ifs(Int(Valor) = 1, ' real', ' reais'); if Centavos <> '' then begin if Valor > 1 then Result := Result + ' e ' + Centavos + ifs(Copy(Texto, 14, 2) = '01', ' centavo', ' centavos') else Result := Centavos + ifs(Copy(Texto, 14, 2) = '01', ' centavo', ' centavos'); end; end; if vValorAux < 0 then Result := Result + ' negativo'; end; function FormatarTelefone(ATelefone: String): String; begin if ATelefone.Length = 8 then Result := FormatMaskText('0000\-0000;0;', ATelefone.Trim) else if ATelefone.Length = 10 then Result := FormatMaskText('\(00\) 0000\-0000;0;', ATelefone.Trim) else if ATelefone.Length = 11 then Result := FormatMaskText('\(00\) 00000\-0000;0;', ATelefone.Trim) else Result := ATelefone; end; function DirSistema: String; begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); end; function NomeArquivoValido(Nome: string): string; var I: Integer; begin Result := ''; for I := 1 to length(Nome) do begin if Nome[I] in ['<', '>', '"', '[', ']', '|', '/'] then Result := Result + '_' else Result := Result + Nome[I]; end; end; function LerIni(ATabela, ACampo: string; ADefault: string = ''): string; var ServerIni: TIniFile; sNomeArquivo: String; begin sNomeArquivo := ParamStr(0); sNomeArquivo := ChangeFileExt(sNomeArquivo, '.ini'); ServerIni := TIniFile.Create(sNomeArquivo); Result := ServerIni.ReadString(ATabela, ACampo, ADefault); ServerIni.Free; end; procedure GerarErro(Res: THorseResponse; AMensagem: String; AMensagemInterna: string = ''); begin if AMensagemInterna.IsEmpty then Log.Erro(AMensagem) else Log.Erro(AMensagem + sLineBreak + AMensagemInterna); Res.Send<TJSONObject>(TJSONObject.Create(TJSONPair.Create('error', AMensagem))).Status(THTTPStatus.BadRequest); raise EHorseCallbackInterrupted.Create; end; function GetClaims(Req: THorseRequest; AClaim: String): String; var JO: TJSONObject; begin // Função para pegar valor do claim da chave JWT da requisição. JO := Req.Session<TJSONObject>; Result := JO.GetValue<string>(AClaim); end; function ValidarData(AData: String): TDateTime; var Formato: TFormatSettings; begin Formato.DateSeparator := '-'; Formato.ShortDateFormat := 'yyyy-mm-dd'; try Result := StrToDate(AData, Formato); except raise Exception.Create('Data inválida.'); end; end; end.
unit Unit1; interface uses System.Generics.Collections, Unit2, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; BtnAdd: TButton; BtnDel: TButton; BtnFind: TButton; BtnUpdate: TButton; BtnClean: TButton; edtUName: TEdit; procedure FormCreate(Sender: TObject); procedure BtnFindClick(Sender: TObject); procedure BtnAddClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; //学生列表 StudentList: TList<TStudent>; implementation {$R *.dfm} procedure TForm1.BtnAddClick(Sender: TObject); var Stu: TStudent; begin if edtUName.Text <> '' then StudentList.add(TStudent.Create(edtUName.Text)) else MessageBox(Self.Handle, '姓名不能为空', '温馨提示', MB_OK); Memo1.Lines.Clear; for Stu in StudentList do begin Memo1.Lines.Add(Stu.Name); end; end; procedure TForm1.BtnFindClick(Sender: TObject); var Stu: TStudent; begin Memo1.Lines.Clear; for Stu in StudentList do begin Memo1.Lines.Add(Stu.Name); end; end; procedure TForm1.FormCreate(Sender: TObject); begin //初始化学生列表 StudentList := TList<TStudent>.Create; StudentList.add(TStudent.Create('小强')); StudentList.add(TStudent.Create('萧蔷')); StudentList.add(TStudent.Create('小黑')); StudentList.add(TStudent.Create('小白')); StudentList.add(TStudent.Create('小黄')); end; end.
unit l3ProcessMessagesManager; {* Список окон, которым надо обрабатывать сообщения в длинных процессах. Используется в случаях, когда afw.ProcessMessages приводит к проблемам. } // Модуль: "w:\common\components\rtl\Garant\L3\l3ProcessMessagesManager.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3ProcessMessagesManager" MUID: (5475D1E30232) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3SimpleObject , l3LongintList , Windows ; type Tl3ProcessMessagesManager = class(Tl3SimpleObject) {* Список окон, которым надо обрабатывать сообщения в длинных процессах. Используется в случаях, когда afw.ProcessMessages приводит к проблемам. } private f_Handles: Tl3LongintList; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure Subscribe(aHandle: THandle); procedure Unsubscribe(aHandle: THandle); procedure ProcessMessages(wMsgFilterMin: LongWord; wMsgFilterMax: LongWord; wRemoveMsg: LongWord); class function Instance: Tl3ProcessMessagesManager; {* Метод получения экземпляра синглетона Tl3ProcessMessagesManager } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//Tl3ProcessMessagesManager implementation uses l3ImplUses {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , SysUtils , l3Base //#UC START# *5475D1E30232impl_uses* //#UC END# *5475D1E30232impl_uses* ; var g_Tl3ProcessMessagesManager: Tl3ProcessMessagesManager = nil; {* Экземпляр синглетона Tl3ProcessMessagesManager } procedure Tl3ProcessMessagesManagerFree; {* Метод освобождения экземпляра синглетона Tl3ProcessMessagesManager } begin l3Free(g_Tl3ProcessMessagesManager); end;//Tl3ProcessMessagesManagerFree procedure Tl3ProcessMessagesManager.Subscribe(aHandle: THandle); //#UC START# *5475D2910227_5475D1E30232_var* //#UC END# *5475D2910227_5475D1E30232_var* begin //#UC START# *5475D2910227_5475D1E30232_impl* if not Assigned(f_Handles) then f_Handles := Tl3LongintList.Create; f_Handles.Add(Integer(aHandle)); //#UC END# *5475D2910227_5475D1E30232_impl* end;//Tl3ProcessMessagesManager.Subscribe procedure Tl3ProcessMessagesManager.Unsubscribe(aHandle: THandle); //#UC START# *5475D2C003A9_5475D1E30232_var* //#UC END# *5475D2C003A9_5475D1E30232_var* begin //#UC START# *5475D2C003A9_5475D1E30232_impl* if Assigned(f_Handles) then f_Handles.Remove(Integer(aHandle)); //#UC END# *5475D2C003A9_5475D1E30232_impl* end;//Tl3ProcessMessagesManager.Unsubscribe procedure Tl3ProcessMessagesManager.ProcessMessages(wMsgFilterMin: LongWord; wMsgFilterMax: LongWord; wRemoveMsg: LongWord); //#UC START# *5475D2D4032E_5475D1E30232_var* {$IfDef l3HackedVCL} var l_Msg: TMsg; I: Integer; {$EndIf l3HackedVCL} //#UC END# *5475D2D4032E_5475D1E30232_var* begin //#UC START# *5475D2D4032E_5475D1E30232_impl* {$IfDef l3HackedVCL} if Assigned(f_Handles) then for I := 0 to f_Handles.Count - 1 do while PeekMessage(l_Msg, THandle(f_Handles[I]), wMsgFilterMin, wMsgFilterMax, wRemoveMsg) do begin {TranslateMessage(l_Msg); DispatchMessage(l_Msg);} Forms.Application.DoProcessMessage(l_Msg); end; {$EndIf l3HackedVCL} //#UC END# *5475D2D4032E_5475D1E30232_impl* end;//Tl3ProcessMessagesManager.ProcessMessages class function Tl3ProcessMessagesManager.Instance: Tl3ProcessMessagesManager; {* Метод получения экземпляра синглетона Tl3ProcessMessagesManager } begin if (g_Tl3ProcessMessagesManager = nil) then begin l3System.AddExitProc(Tl3ProcessMessagesManagerFree); g_Tl3ProcessMessagesManager := Create; end; Result := g_Tl3ProcessMessagesManager; end;//Tl3ProcessMessagesManager.Instance class function Tl3ProcessMessagesManager.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tl3ProcessMessagesManager <> nil; end;//Tl3ProcessMessagesManager.Exists procedure Tl3ProcessMessagesManager.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5475D1E30232_var* //#UC END# *479731C50290_5475D1E30232_var* begin //#UC START# *479731C50290_5475D1E30232_impl* l3Free(f_Handles); inherited; //#UC END# *479731C50290_5475D1E30232_impl* end;//Tl3ProcessMessagesManager.Cleanup end.
unit zsMainWindow; interface uses Windows, Messages, Graphics, zsAttach, zsProcess; function FindZSMainWindow(AZsDealSession: PZsDealSession): Boolean; procedure CheckZSMainWindow(AMainWindow: PZSMainWindow); procedure CheckZSOrderWindow(AMainWindow: PZSMainWindow); procedure CheckZSMoneyWindow(AMainWindow: PZSMainWindow); procedure CheckDealPanelSize(AMainWindow: PZSMainWindow); procedure ClickMenuOrderMenuItem(AMainWindow: PZSMainWindow); implementation uses SysUtils, UtilsWindows, zsDialogUtils, zsDealBuy, zsDealSale, CommCtrl; { CommCtrl, SysTreeView32 TreeNodeCount := return (uint)SendMessage(hwnd, TVM_GETCOUNT, 0, 0); function CommCtrl.TreeView_GetRoot(hwnd: HWND): HTreeItem; Root := TreeView_GetNextItem(hwnd, 0, TVGN_ROOT); function CommCtrl.TreeView_GetNextItem(hwnd: HWND; hitem: HTreeItem; code: Integer): HTreeItem; inline; } procedure ClickMenuOrderMenuItem(AMainWindow: PZSMainWindow); var tmpWnd: HWND; begin tmpWnd := AMainWindow.TopMenu.WndOrderButton; if IsWindow(tmpWnd) then begin if nil <> AMainWindow.HostWindowPtr then begin ForceBringFrontWindow(AMainWindow.HostWindowPtr.WindowHandle); SleepWait(20); ForceBringFrontWindow(AMainWindow.HostWindowPtr.WindowHandle); SleepWait(20); end; ForceBringFrontWindow(tmpWnd); UtilsWindows.ClickButtonWnd(tmpWnd); end; end; function FindZSMainWindow(AZsDealSession: PZsDealSession): Boolean; begin if nil <> AZsDealSession.MainWindow.HostWindowPtr then begin if not IsWindow(AZsDealSession.MainWindow.HostWindowPtr.WindowHandle) then begin AZsDealSession.MainWindow.HostWindowPtr := nil; end; end; if nil = AZsDealSession.MainWindow.HostWindowPtr then begin AZsDealSession.ProcessAttach.FindSession.WndClassKey := 'TdxW_MainFrame_Class'; AZsDealSession.ProcessAttach.FindSession.WndCaptionKey := '招商证券智远理财服务平台'; AZsDealSession.ProcessAttach.FindSession.WndCaptionExcludeKey := ''; AZsDealSession.ProcessAttach.FindSession.CheckFunc := nil; AZsDealSession.ProcessAttach.FindSession.NeedWinCount := 1; AZsDealSession.ProcessAttach.FindSession.FindCount := 0; FillChar(AZsDealSession.ProcessAttach.FindSession.FindWindow, SizeOf(AZsDealSession.ProcessAttach.FindSession.FindWindow), 0); Windows.EnumWindows(@EnumFindDesktopWindowProc, Integer(AZsDealSession)); end; Result := (AZsDealSession.ProcessAttach.FindSession.FindCount > 0) or (nil <> AZsDealSession.MainWindow.HostWindowPtr); if Result then begin if (0 < AZsDealSession.ProcessAttach.FindSession.FindCount) then begin AZsDealSession.MainWindow.HostWindowPtr := AZsDealSession.ProcessAttach.FindSession.FindWindow[0]; end; end; end; function FindZSDealPanel(AMainWindow: PZSMainWindow): Boolean; begin //通达信网上交易 Result := false; end; type PTraverse_MainWindow = ^TTraverse_MainWindow; TTraverse_MainWindow = record MainWindow: PZSMainWindow; end; procedure ParseMoneyText(AMainWindow: PZSMainWindow; AText: string); var tmpPos: integer; tmpHead: string; tmpValue: string; tmpData: string; begin tmpData := Trim(AText); tmpPos := Pos(':', tmpData); while 0 < tmpPos do begin tmpHead := Trim(Copy(tmpData, 1, tmpPos - 1)); tmpValue := ''; tmpData := Copy(tmpData, tmpPos + 1, maxint); tmpPos := Pos(#32, tmpData); if 0 < tmpPos then begin tmpValue := Copy(tmpData, 1, tmpPos - 1); tmpData := Copy(tmpData, tmpPos + 1, maxint); end else begin tmpValue := tmpData; end; if '' <> tmpValue then begin if SameText('余额', tmpHead) then begin AMainWindow.MoneyData.Balance := StrToFloatDef(tmpValue, 0); end; if SameText('可用', tmpHead) then begin AMainWindow.MoneyData.Available := StrToFloatDef(tmpValue, 0); end; if SameText('可取', tmpHead) then begin AMainWindow.MoneyData.Extractable := StrToFloatDef(tmpValue, 0); end; if SameText('参考市值', tmpHead) then begin AMainWindow.MoneyData.ValueRef := StrToFloatDef(tmpValue, 0); end; if SameText('资产', tmpHead) then begin AMainWindow.MoneyData.Asset := StrToFloatDef(tmpValue, 0); end; if SameText('盈亏', tmpHead) then begin AMainWindow.MoneyData.ProfitAndLoss := StrToFloatDef(tmpValue, 0); end; end; tmpPos := Pos(':', tmpData); end; end; procedure TraverseCheckMainChildWindowA(AWnd: HWND; ATraverseWindow: PTraverse_MainWindow); var tmpWndChild: HWND; tmpStr: string; tmpCtrlId: integer; tmpIsHandled: Boolean; begin if not IsWindowVisible(AWnd) then exit; if not IsWindowEnabled(AWnd) then exit; tmpStr := GetWndClassName(AWnd); tmpIsHandled := False; tmpCtrlId := Windows.GetDlgCtrlID(AWnd); if 0 = tmpCtrlId then begin if 0 = ATraverseWindow.MainWindow.WndDealPanel then begin tmpStr := GetWndTextName(AWnd); if 0 < Pos('通达信网上交易', tmpStr) then begin ATraverseWindow.MainWindow.WndDealPanel := AWnd; end; end; end; if SameText('SysTreeView32', tmpStr) then begin if $E900 = tmpCtrlId then begin tmpIsHandled := true; ATraverseWindow.MainWindow.WndFunctionTree := AWnd; end; end; if not tmpIsHandled then begin if SameText('AfxWnd42', tmpStr) then begin if $BC5 = tmpCtrlId then begin tmpIsHandled := true; ATraverseWindow.MainWindow.TopMenu.WndOrderButton := AWnd; end; end; end; if not tmpIsHandled then begin if SameText('Edit', tmpStr) then begin tmpIsHandled := true; if $2EE5 = tmpCtrlId then begin ATraverseWindow.MainWindow.CurrentDealWindow.WndStockCodeEdit := AWnd; end; if $2EE6 = tmpCtrlId then begin ATraverseWindow.MainWindow.CurrentDealWindow.WndPriceEdit := AWnd; end; if $2EE7 = tmpCtrlId then begin ATraverseWindow.MainWindow.CurrentDealWindow.WndNumEdit := AWnd; end; end; end; if not tmpIsHandled then begin if SameText('Button', tmpStr) then begin tmpIsHandled := true; if $7DA = tmpCtrlId then ATraverseWindow.MainWindow.CurrentDealWindow.WndOrderButton := AWnd; end; end; if not tmpIsHandled then begin if $628 = tmpCtrlId then begin tmpIsHandled := true; tmpStr := GetWndTextName(AWnd); if '' <> tmpStr then begin ParseMoneyText(ATraverseWindow.MainWindow, tmpStr); end; end; end; if not tmpIsHandled then begin if ($1FCB = tmpCtrlId) then begin tmpIsHandled := true; tmpStr := GetWndTextName(AWnd); ATraverseWindow.MainWindow.BuyWindowPtr := nil; if '' <> tmpStr then begin if Pos('买入', tmpStr) > 0 then begin ATraverseWindow.MainWindow.BuyWindowPtr := @ATraverseWindow.MainWindow.CurrentDealWindow; ATraverseWindow.MainWindow.SaleWindowPtr := nil; end; end; end; if ($1FD7 = tmpCtrlId) then begin tmpIsHandled := true; tmpStr := GetWndTextName(AWnd); ATraverseWindow.MainWindow.SaleWindowPtr := nil; if '' <> tmpStr then begin if Pos('卖出', tmpStr) > 0 then begin ATraverseWindow.MainWindow.SaleWindowPtr := @ATraverseWindow.MainWindow.CurrentDealWindow; ATraverseWindow.MainWindow.BuyWindowPtr := nil; end; end; end; end; if not tmpIsHandled then begin if ($E81E = tmpCtrlId) then begin if SameText('AfxControlBar42', tmpStr) then begin ATraverseWindow.MainWindow.WndDealPanelRoot := AWnd; CheckDealPanelSize(ATraverseWindow.MainWindow); end; end; end; //===================================================== if not tmpIsHandled then begin tmpWndChild := Windows.GetWindow(AWnd, GW_CHILD); while 0 <> tmpWndChild do begin TraverseCheckMainChildWindowA(tmpWndChild, ATraverseWindow); tmpWndChild := Windows.GetWindow(tmpWndChild, GW_HWNDNEXT); end; end; end; procedure CheckDealPanelSize(AMainWindow: PZSMainWindow); var tmpWinRect: TRect; tmpClientRect: TRect; i: Integer; dy: integer; tmpDy1: integer; tmpDyOffset: integer; tmpMoveDownOffset: integer; tmpCounter: integer; tmpIsHandled: Boolean; begin if not IsWindow(AMainWindow.WndDealPanelRoot) then exit; if not IsWindowVisible(AMainWindow.WndDealPanelRoot) then exit; Windows.GetClientRect(AMainWindow.WndDealPanelRoot, tmpClientRect); if tmpClientRect.Bottom = tmpClientRect.Top then exit; if 4 > (tmpClientRect.Bottom - tmpClientRect.Top) then exit; tmpCounter := 0; tmpIsHandled := false; while (tmpCounter < 2) and (not tmpIsHandled) do begin if tmpIsHandled then Break; tmpDyOffset := 3; while (0 <= tmpDyOffset) and (not tmpIsHandled) do begin Windows.GetClientRect(AMainWindow.WndDealPanelRoot, tmpClientRect); if 350 > (tmpClientRect.Bottom - tmpClientRect.Top) then begin ForceBringFrontWindow(AMainWindow.HostWindowPtr.WindowHandle); SleepWait(20); ForceBringFrontWindow(AMainWindow.HostWindowPtr.WindowHandle); SleepWait(20); // 242 Windows.GetWindowRect(AMainWindow.WndDealPanelRoot, tmpWinRect); tmpDy1 := 400 - (tmpWinRect.Bottom - tmpWinRect.Top); for tmpMoveDownOffset := 5 to 7 do begin Windows.SetCursorPos(tmpWinRect.Left + tmpWinRect.Right div 2, tmpWinRect.Top - tmpDyOffset); for i := 1 to tmpMoveDownOffset do begin Windows.mouse_event(MOUSEEVENTF_MOVE, // MOUSEEVENTF_ABSOLUTE or 0, 1, 0, 0); end; dy := tmpDy1; SleepWait(20); Windows.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); SleepWait(20); while dy > 0 do begin Windows.mouse_event(MOUSEEVENTF_MOVE, // MOUSEEVENTF_ABSOLUTE or 0, DWORD(-10), 0, 0); SleepWait(20); dy := dy - 10; end; Windows.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); SleepWait(20); Windows.GetClientRect(AMainWindow.WndDealPanelRoot, tmpClientRect); if 350 < (tmpClientRect.Bottom - tmpClientRect.Top) then begin tmpIsHandled := True; Break; end; end; end else begin tmpCounter := 5; end; tmpDyOffset := tmpDyOffset - 1; end; tmpCounter := tmpCounter + 1; end; end; procedure CheckZSMainWindow(AMainWindow: PZSMainWindow); var tmpTraverse_Window: TTraverse_MainWindow; begin if nil = AMainWindow.HostWindowPtr then exit; if IsWindow(AMainWindow.WndFunctionTree) then exit; FillChar(tmpTraverse_Window, SizeOf(tmpTraverse_Window), 0); tmpTraverse_Window.MainWindow := AMainWindow; if not IsWindow(AMainWindow.WndDealPanel) then AMainWindow.WndDealPanel := 0; if not IsWindow(AMainWindow.WndDealPanelRoot) then AMainWindow.WndDealPanelRoot := 0; TraverseCheckMainChildWindowA(AMainWindow.HostWindowPtr.WindowHandle, @tmpTraverse_Window); end; procedure CheckZSMoneyWindow(AMainWindow: PZSMainWindow); var tmpTraverse_Window: TTraverse_MainWindow; begin if nil = AMainWindow.HostWindowPtr then exit; FillChar(tmpTraverse_Window, SizeOf(tmpTraverse_Window), 0); tmpTraverse_Window.MainWindow := AMainWindow; if not IsWindow(AMainWindow.WndDealPanel) then AMainWindow.WndDealPanel := 0; if not IsWindow(AMainWindow.WndDealPanelRoot) then AMainWindow.WndDealPanelRoot := 0; TraverseCheckMainChildWindowA(AMainWindow.HostWindowPtr.WindowHandle, @tmpTraverse_Window); end; procedure CheckZSOrderWindow(AMainWindow: PZSMainWindow); var tmpTraverse_Window: TTraverse_MainWindow; begin if nil = AMainWindow.HostWindowPtr then exit; FillChar(tmpTraverse_Window, SizeOf(tmpTraverse_Window), 0); tmpTraverse_Window.MainWindow := AMainWindow; if not IsWindow(AMainWindow.WndDealPanel) then AMainWindow.WndDealPanel := 0; if not IsWindow(AMainWindow.WndDealPanelRoot) then AMainWindow.WndDealPanelRoot := 0; if 0 = AMainWindow.WndDealPanel then begin TraverseCheckMainChildWindowA(AMainWindow.HostWindowPtr.WindowHandle, @tmpTraverse_Window); end else begin TraverseCheckMainChildWindowA(AMainWindow.WndDealPanel, @tmpTraverse_Window); end; end; end.
unit uPduProtocol; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Registry; function GetCommNames(): string; function ExchangeCode(AStr:string): string; function Encode7bit(AStr: string): string; function Decode7bit(AStr: string): string; function EncodeUCS2(AStr: string): string; function DecodeUCS2(AStr: string): string; function Unicode2Ansi(AStr: string): string; function Ansi2Unicode(AStr: string): string; function PhoneNumber2PDU(AStr: string): string; function PDU2PhoneNumber(AStr: string): string; function Date2PDU(ADate: TDateTime): string; function PDU2Date(ADate: string): TDateTime; function PDU2DateStr(ADate: string): string; implementation function GetCommNames(): string; var reg: TRegistry; lst,lst2: TStrings; i: integer; begin lst:=TStringList.Create; lst2:=TStringList.Create; reg:=TRegistry.Create; try reg.RootKey :=HKEY_LOCAL_MACHINE; reg.OpenKey('HARDWARE\DEVICEMAP\SERIALCOMM',true); reg.GetValueNames(lst); for i := 0 to lst.Count -1 do lst2.Add(reg.ReadString(lst[i])); Result := lst2.CommaText; finally reg.CloseKey; reg.Free; lst.Free; lst2.Free; end; end; function Encode7bit(AStr: string): string; var i,j,len: Integer; cur: Integer; s: string; begin Result := ''; len := Length(AStr); //j 用于移位计数 i := 1; j := 0; while i <= len do begin if i < len then begin //数据变换 cur := (Ord(AStr[i]) shr j) or ((Ord(AStr[i+1]) shl (7-j)) and $ff); end else begin cur := (Ord(AStr[i]) shr j) and $7f; end; FmtStr(s, '%2.2X', [cur]); Result := Result+s; inc(i); //移位计数达到7位的特别处理 j := (j+1) mod 7; if j = 0 then inc(i); end; end; function Decode7bit(AStr: string): string; var nSrcLength:Integer; nSrc:Integer; // 源字符串的计数值 nByte:Integer; // 当前正在处理的组内字节的序号,范围是0-6 nLeft:Byte; // 上一字节残余的数据 tmpChar:Byte; pDst:string; begin // 计数值初始化 nSrc := 1; nSrcLength:=Length(AStr); // 组内字节序号和残余数据初始化 nByte := 0; nLeft := 0; pdst := ''; // 将源数据每7个字节分为一组,解压缩成8个字节 // 循环该处理过程,直至源数据被处理完 // 如果分组不到7字节,也能正确处理 while (nSrc < nSrcLength) do begin tmpChar := byte(StrToInt('$' + AStr[nsrc] + AStr[nsrc + 1])); // 将源字节右边部分与残余数据相加,去掉最高位,得到一个目标解码字节 pDst := pDst + Char(((tmpchar shl nByte) or nLeft) and $7F); // 将该字节剩下的左边部分,作为残余数据保存起来 nLeft := tmpChar shr (7 - nByte); // 修改字节计数值 Inc(nByte); // 到了一组的最后一个字节 if (nByte = 7) then begin // 额外得到一个目标解码字节 pdst := pDst + Char(nLeft); // 组内字节序号和残余数据初始化 nByte := 0; nLeft := 0; end; //end if // 修改源串的指针和计数值 nSrc:= nSrc + 2; end; // 返回目标串长度 Result:= pdst; end; function EncodeUCS2(AStr: string): string; var ws: WideString; i,len: Integer; cur: Integer; s: string; begin Result:=''; ws := AStr; len:= Length(ws); i:=1; while i <= len do begin cur:= ord(ws[i]); FmtStr(s, '%4.4X', [cur]); //BCD转换 Result:= Result+s; inc(i); end; end; function DecodeUCS2(AStr: string): string; var i:Integer; S:String; D:WideChar; ResultW: WideString; begin for i:=1 to Round(Length(AStr)/4) do begin S:= Copy(AStr, (i - 1) * 4 + 1, 4); D:= WideChar(StrToInt('$' + S)); ResultW:= ResultW + D; end; Result:= ResultW; end; function Ansi2Unicode(AStr: string): string; var s: string; i: Integer; j,k: string[2]; a: array[1..1000] of Char; begin s := ''; StringToWideChar(AStr, @(a[1]), 500); i := 1; while ((a[i] <> #0) or (a[i + 1] <> #0)) do begin j := IntToHex(Integer(a[i]), 2); k := IntToHex(Integer(a[i + 1]), 2); s := s + k + j; i := i + 2; end; Result := s; end; function Unicode2Ansi(AStr: string): string; var s:string; i:integer; j, k:string[2]; function ReadHex(AStr: string):integer; begin Result := StrToInt('$' + AStr) end; begin i := 1; s := ''; while i < Length(AStr) do begin j := Copy(AStr, i + 2, 2); k := Copy(AStr, i, 2); i := i + 4; s := s + Char(readhex(j)) + Char(ReadHex(k)); end; if s <> '' then s := WideCharToString(PWideChar(s + #0#0#0#0)) else s := ''; Result := s; end; function PhoneNumber2PDU(AStr: string): string; begin AStr:= StringReplace(AStr, '+', '', [rfReplaceAll]); // if Copy(AStr, 1 , 2) <> '86' then // AStr := '86' + AStr; if ((length(AStr) mod 2) = 1) then begin AStr:= AStr + 'F'; end; Result:= ExchangeCode(AStr); end; function PDU2PhoneNumber(AStr: string): string; begin Result:= ExchangeCode(AStr); Result:= StringReplace(Result, 'F', '', [rfReplaceAll]); end; function ExchangeCode(AStr: string): string; var I: Integer; begin Result:= ''; for i:=1 to (Length(AStr) Div 2) do begin Result:= Result+AStr[I*2]+AStr[I*2-1]; end; end; function Date2PDU(ADate: TDateTime): string; var str: String; begin DateTimeToString(str,'YYMMDDHHMMSS', ADate); Result := ExchangeCode(str); end; function PDU2Date(ADate: string): TDateTime; var tem:String; begin tem := PDU2DateStr(ADate); Result:= StrToDateTimeDef(tem, 0); end; function PDU2DateStr(ADate: string): string; var str:String; begin str := ExchangeCode(ADate);//倒叙,结果为081129105833 Result := copy(str,1,2)+'-'+ //格式化,结果为08-11-29 10:58:33 copy(str,3,2)+'-'+ copy(str,5,2)+' '+ copy(str,7,2)+':'+ copy(str,9,2)+':'+ copy(str,11,2); end; end.
{-------------------------------------------------- Progressive Path Tracing --------------------------------------------------- This unit implements the Mersenne Twister pseudorandom number generator, in a class (to make it thread-safe). This PRNG is very fast and has excellent pseudorandom statistical properties, which make it very suitable for use in Monte-Carlo simulations such as path tracing. -------------------------------------------------------------------------------------------------------------------------------} unit PRNG; interface uses Windows, Utils; { Period parameters } const MT19937M=397; MT19937MATRIX_A =$9908b0df; MT19937UPPER_MASK=$80000000; MT19937LOWER_MASK=$7fffffff; TEMPERING_MASK_B=$9d2c5680; TEMPERING_MASK_C=$efc60000; MT19937N=624; Type tMT19937StateArray = array [0..MT19937N-1] of longint; type TPRNG = class private mt : tMT19937StateArray; mti: integer; // mti=MT19937N+1 means mt[] is not initialized procedure sgenrand_MT19937(seed: longint); // Initialization by seed procedure lsgenrand_MT19937(const seed_array: tMT19937StateArray); // Initialization by array of seeds function genrand_MT19937: longint; // random longint (full range); public constructor Create(SeedModifier: Longword); reintroduce; function random: Double; overload; end; PPRNG = ^TPRNG; implementation { Initializes the PRNG with a given seed. } procedure TPRNG.sgenrand_MT19937(seed: longint); var i: integer; begin for i := 0 to MT19937N-1 do begin mt[i] := seed and $ffff0000; seed := 69069 * seed + 1; mt[i] := mt[i] or ((seed and $ffff0000) shr 16); seed := 69069 * seed + 1; end; mti := MT19937N; end; { Seeds the PRNG. } procedure TPRNG.lsgenrand_MT19937(const seed_array: tMT19937StateArray); VAR i: integer; begin for i := 0 to MT19937N-1 do mt[i] := seed_array[i]; mti := MT19937N; end; { Generates a new state for the PRNG. } function TPRNG.genrand_MT19937: longint; const mag01 : array [0..1] of longint =(0, MT19937MATRIX_A); var y: longint; kk: integer; begin if mti >= MT19937N { generate MT19937N longints at one time } then begin if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called, sgenrand_MT19937(4357); // default initial seed is used for kk:=0 to MT19937N-MT19937M-1 do begin y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK); mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001]; end; for kk:= MT19937N-MT19937M to MT19937N-2 do begin y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK); mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001]; end; y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK); mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001]; mti := 0; end; y := mt[mti]; inc(mti); y := y xor (y shr 11); y := y xor (y shl 7) and TEMPERING_MASK_B; y := y xor (y shl 15) and TEMPERING_MASK_C; y := y xor (y shr 18); Result := y; end; { Creates the PRNG. The SeedModifier is used to create different states for each thread. } constructor TPRNG.Create(SeedModifier: Longword); begin inherited Create; mti := MT19937N + 1; sgenrand_MT19937(GetWorkerSeed(SeedModifier)); end; // assembler magic function TPRNG.random: Double; const Minus32: double = -32.0; asm CALL genrand_MT19937 PUSH 0 PUSH EAX FLD Minus32 FILD qword ptr [ESP] ADD ESP,8 FSCALE FSTP ST(1) end; end.
unit nsbQueryUtils; { Начал: Инишев Дмитрий, Морозов Михаил } { Модуль: lgQueryUtils - } { Начат: 21.01.2005 16:51 } { $Id: nsbQueryUtils.pas,v 1.2 2016/08/04 12:07:51 lulin Exp $ } // $Log: nsbQueryUtils.pas,v $ // Revision 1.2 2016/08/04 12:07:51 lulin // - перегенерация. // // Revision 1.1 2015/03/05 18:05:24 kostitsin // {requestlink: 588808889 } // // Revision 1.4 2013/09/16 07:09:42 kostitsin // [$239370589] // // Revision 1.3 2010/12/22 18:26:03 lulin // {RequestLink:242845936}. // // Revision 1.2 2010/11/22 13:39:14 lulin // [$242845500]. // // Revision 1.1 2010/07/05 08:05:20 lulin // {RequestLink:207389954}. // - переносим на модель форму "SaveLoad". // // Revision 1.8 2009/09/03 18:49:16 lulin // - реструктуризируем поиски и удаляем ненужное. // // Revision 1.7 2008/03/12 07:51:36 oman // - new: Заготовки для поиска лекарственного препарата (ПЛП) // // Revision 1.6 2008/01/10 07:23:52 oman // Переход на новый адаптер // // Revision 1.5.4.1 2007/11/21 15:07:44 oman // Перепиливаем на новый адаптер // // Revision 1.5 2007/05/23 10:40:24 oman // - new: Новый тип запросов "Базовый поиск" (cq25374) // // Revision 1.4 2006/04/07 08:25:26 mmorozov // - приведение к общему знаменателю Поиска с правовой поддержкой, Запроса на консультацию, Консультации; // // Revision 1.3 2006/04/03 15:55:25 dinishev // Новая КЗ // // Revision 1.2 2006/03/10 13:38:26 dinishev // Подключение новой КЗ // // Revision 1.1 2005/07/29 12:52:17 mmorozov // - перенесен из другого каталога; // // Revision 1.1 2005/07/29 11:22:31 mmorozov // - файл перенесен из другого места; // // Revision 1.2 2005/03/04 15:05:14 demon // - new behavior: Открывается карточка "Обзор законодательства" (работает, пока возвращает список) // // Revision 1.1 2005/02/24 16:43:40 mmorozov // new: модуль бизнес уровня для работы с Query; // // Revision 1.1 2005/02/24 14:54:53 dinishev // new: модуль для работы с запросами; // {.$I lgDefine.inc } interface uses SearchUnit, nsQueryInterfaces ; function AdapterQueryToBusinessQuery(aQueryType : TQueryType) : TlgQueryType; {* - для преобразования адаптерного типа в тип бизнес уровня. } function BusinessQueryToAdapterQuery(aQueryType : TlgQueryType) : TQueryType; {* - для преобразования адаптерного типа в тип бизнес уровня. } implementation function AdapterQueryToBusinessQuery(aQueryType : TQueryType) : TlgQueryType; {* - для преобразования адаптерного типа в тип бизнес уровня. } begin Result := lg_qtNone; case aQueryType of QT_KEYWORD: Result := lg_qtKeyWord; QT_ATTRIBUTE: Result := lg_qtAttribute; QT_PUBLISHED_SOURCE: Result := lg_qtPublishedSource; QT_REVIEW: Result := lg_qtLegislationReview; QT_MAIL_LIST: Result := lg_qtPostingOrder; QT_CONSULT: begin Result := lg_qtNone; Assert(false); end;//QT_CONSULT QT_HANDYCRAFT_CONSULT: Result := lg_qtSendConsultation; QT_BASE_SEARCH: Result := lg_qtBaseSearch; QT_PHARM_SEARCH: Result := lg_qtInpharmSearch; else Assert(false); end; end; function BusinessQueryToAdapterQuery(aQueryType : TlgQueryType) : TQueryType; {* - для преобразования адаптерного типа в тип бизнес уровня. } begin Result := QT_ATTRIBUTE; // для неизвестных типов считаем, что запрос по атрибутам case aQueryType of lg_qtKeyWord: Result := QT_KEYWORD; lg_qtAttribute: Result := QT_ATTRIBUTE; lg_qtPublishedSource: Result := QT_PUBLISHED_SOURCE; lg_qtPostingOrder: Result := QT_MAIL_LIST; lg_qtLegislationReview: Result := QT_REVIEW; lg_qtSendConsultation: Result := QT_HANDYCRAFT_CONSULT; lg_qtBaseSearch: Result := QT_BASE_SEARCH; lg_qtInpharmSearch: Result := QT_PHARM_SEARCH; else Assert(false); end; end; end.
unit cLevel; interface uses contnrs, cenemy, sysutils, bytelist, cspecobj, OffsetList, cPatternTableSettings, ROMObj; type TPPUSettings = record Offset : Integer; Size : Integer; PPUOffset : Integer; end; TLevel = class private _TSAOffset : Integer; _AttributeOffset : Integer; _RoomOrder : Integer; _RoomPointers : Integer; _LevelBGOffset : Integer; _PaletteOffset : Integer; _RoomAmount : Integer; _NumberOfTiles : Integer; _Name : String; _EnemyPointerOffset : Integer; _StartTSA : Integer; _ScrollOffset : Integer; _ScrollStartOffset : Integer; _WilyPPU : Boolean; _SpecObjOffset : Integer; procedure SetScrollStart(pData : Byte); // function GetRoomOrderStart : Byte; // procedure SetRoomOrderStart(pData : Byte); function GetScrollStart : Byte; procedure SetPalette(index1,index2 : Integer;pByte : Byte); function GetPalette(index1,index2 : Integer): byte; procedure SetCycleColours(index : Integer;pByte : Byte); function GetCycleColours(index : Integer): byte; public Properties : T1BytePropertyList; Enemies : TEnemyList; PPUSettings : Array of TPPUSettings; ScrollData : TByteList; SpecObj : TSpecObjList; PatternTableSettings : TPatternTableSettingsList; destructor Destroy;override; procedure WorkOutLevelLength; property TSAOffset : Integer read _TSAOffset write _TSAOffset; property AttributeOffset : Integer read _AttributeOffset write _AttributeOffset; property RoomOrderOffset : Integer read _RoomOrder write _RoomOrder; property RoomPointersOffset : Integer read _RoomPointers write _RoomPointers; property LevelBGOffset : Integer read _LevelBGOffset write _LevelBGOffset; property PaletteOffset : Integer read _PaletteOffset write _PaletteOffset; property RoomAmount : Integer read _RoomAmount write _RoomAmount; property NumberOfTiles : Integer read _NumberOfTiles write _NumberOfTiles; property Name : String read _Name write _Name; property EnemyPointerOffset : Integer read _EnemyPointerOffset write _EnemyPointerOffset; property StartTSAAt : Integer read _StartTSA write _StartTSA; property ScrollOffset : Integer read _ScrollOffset write _ScrollOffset; // property RoomOrderStartOffset : Integer read _RoomOrderStartOffset write _RoomOrderStartOffset; // property RoomOrderStart : Byte read GetRoomOrderStart write SetRoomOrderStart; property ScrollStart : byte read GetScrollStart write SetScrollStart; property ScrollStartOffset : Integer read _ScrollStartOffset write _ScrollStartOffset; property WilyPPU : Boolean read _WilyPPU write _WilyPPU; property SpecObjOffset : Integer read _SpecObjOffset write _SpecObjOffset; property PaletteAfter[index1,index2 : Integer] : byte read GetPalette write SetPalette; property CycleColours[index : Integer] : byte read GetCycleColours write SetCycleColours; end; { This is a class that will be used to store the levels. This is a descendant of the TObjectList class. The reason that I am not using a TObjectList, is that for every access, you have to explicitly cast your objects to their correct type.} TLevelList = class(TObjectList) protected _CurrentLevel : Integer; function GetCurrentLevel: Integer; procedure SetCurrentLevel(const Value: Integer); function GetLevelItem(Index: Integer) : TLevel; procedure SetLevelItem(Index: Integer; const Value: TLevel); public function Add(AObject: TLevel) : Integer; property Items[Index: Integer] : TLevel read GetLevelItem write SetLevelItem;default; function Last : TLevel; // property CurrentLevel : Integer read GetCurrentLevel write SetCurrentLevel; end; implementation { TLevelList } uses urom; function TLevelList.Add(AObject: TLevel): Integer; begin Result := inherited Add(AObject); end; function TLevelList.GetCurrentLevel: Integer; begin result := self._CurrentLevel; end; function TLevelList.GetLevelItem(Index: Integer): TLevel; begin Result := TLevel(inherited Items[Index]); end; procedure TLevelList.SetCurrentLevel(const Value: Integer); begin self._CurrentLevel := Value; end; procedure TLevelList.SetLevelItem(Index: Integer; const Value: TLevel); begin inherited Items[Index] := Value; end; function TLevelList.Last : TLevel; begin result := TLevel(inherited Last); end; { TLevel } destructor TLevel.Destroy; begin FreeAndNil(SpecObj); FreeAndNil(self.Enemies); FreeAndNil(ScrollData); FreeAndNil(properties); FreeAndNil(patterntablesettings); inherited; end; procedure TLevel.SetPalette(index1,index2 : Integer;pByte : Byte); begin ROM[Properties['AfterDoorsPalette'].Offset + (index1 * 4) + index2] := pByte; end; function TLevel.GetPalette(index1,index2 : Integer): byte; begin result := ROM[Properties['AfterDoorsPalette'].Offset + (index1 * 4) + index2]; end; procedure TLevel.WorkOutLevelLength; var pos : Integer; begin pos := self._ScrollOffset + ROM[self._ScrollStartOffset]; _RoomAmount := 0; while (ROM[pos] <> $00) do begin _RoomAmount := _RoomAmount + ((ROM[pos] and $1F) + 1); inc(pos); end; end; procedure TLevel.SetScrollStart(pData : Byte); begin ROM[self._ScrollStartOffset] := pData; end; {function TLevel.GetRoomOrderStart : Byte; begin result := ROM[self.RoomOrderStartOffset]; end; procedure TLevel.SetRoomOrderStart(pData : Byte); begin ROM[RoomOrderStartOffset] := pData; end;} function TLevel.GetScrollStart : Byte; begin result := ROM[self.ScrollStartOffset]; end; procedure TLevel.SetCycleColours(index : Integer;pByte : Byte); begin ROM[Properties['ColourCycles'].Offset + index] := pByte; end; function TLevel.GetCycleColours(index : Integer): byte; begin result := ROM[Properties['ColourCycles'].Offset + index]; end; end.
unit BuyAdsTask; interface uses Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, MathUtils, BasicAccounts; type TMetaBuyAdsTask = class(TMetaTask) private // >> public // >> end; TBuyAdsTask = class(TAtomicTask) public function Execute : TTaskResult; override; private // >> public procedure LoadFromBackup(Reader : IBackupReader); override; procedure StoreToBackup (Writer : IBackupWriter); override; end; procedure RegisterBackup; implementation // TBuyAdsTask function TBuyAdsTask.Execute : TTaskResult; var Tycoon : TTycoon; Account : TAccount; begin Tycoon := TTycoon(Context.getContext(tcIdx_Tycoon)); if Tycoon <> nil then Account := Tycoon.Accounts.AccountArray[accIdx_ResearchCenter_Supplies] else Account := nil; if Account <> nil then begin if Account.Value < 0 then result := trFinished else result := trContinue; end else result := trFinished end; procedure TBuyAdsTask.LoadFromBackup(Reader : IBackupReader); begin inherited; end; procedure TBuyAdsTask.StoreToBackup (Writer : IBackupWriter); begin inherited; end; procedure RegisterBackup; begin RegisterClass(TBuyAdsTask); end; end.
unit Main; { $Id: Main.pas,v 1.1 2005/09/26 14:23:36 step Exp $ } // $Log: Main.pas,v $ // Revision 1.1 2005/09/26 14:23:36 step // занесено в cvs // interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, HT_Const, HT_Dll, Mask, ToolEdit, ComCtrls, DbInfo; type TFormMain = class(TForm) pTop: TPanel; bDoVerify: TButton; mLog: TMemo; IniFileDialog: TOpenDialog; labIniFile: TLabel; edIniFile: TEdit; bSelectIniFile: TButton; lbFamilyNames: TListBox; labDBList: TLabel; labGarantFolder: TLabel; labMainFolder: TLabel; bDoRepair: TButton; procedure bDoVerifyClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure AddToMemo(aStr: string); procedure bSelectIniFileClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private f_DbInfo: TDbInfo; procedure ReadArchiIniFile(aArchiIniFile: string); public end; var FormMain: TFormMain; implementation {$R *.dfm} uses l3Base, l3FileUtils, //DbReformer, DbVerifier; procedure TFormMain.AddToMemo(aStr: string); begin if aStr <> '' then mLog.Lines.Add(aStr); Application.ProcessMessages; end; procedure TFormMain.bDoVerifyClick(Sender: TObject); var l_SavedCursor: TCursor; l_DoRepair: Boolean; begin f_DbInfo.CheckFolderVersions; l_DoRepair := Sender = bDoRepair; mLog.Clear; l_SavedCursor := Screen.Cursor; Screen.Cursor := crHourGlass; bDoVerify.Enabled := False; bDoRepair.Enabled := False; try with TDbVerifier.Create(f_DbInfo, lbFamilyNames.Items[lbFamilyNames.ItemIndex], AddToMemo) do try Execute(l_DoRepair); finally Free; end; finally bDoVerify.Enabled := True; bDoRepair.Enabled := True; Screen.Cursor := l_SavedCursor; end; end; procedure TFormMain.FormCreate(Sender: TObject); var l_Path: string; begin IniFileDialog.InitialDir := Application.ExeName; l_Path := ConcatDirName(ExtractDirName(Application.ExeName), 'archi.ini'); if FileExists(l_Path) then begin edIniFile.Text := l_Path; ReadArchiIniFile(edIniFile.Text); end; end; procedure TFormMain.bSelectIniFileClick(Sender: TObject); begin if IniFileDialog.Execute then begin edIniFile.Text := IniFileDialog.FileName; ReadArchiIniFile(edIniFile.Text); end; end; procedure TFormMain.ReadArchiIniFile(aArchiIniFile: string); begin edIniFile.Text := aArchiIniFile; if Assigned(f_DbInfo) then FreeAndNil(f_DbInfo); f_DbInfo := TDbInfo.Create(aArchiIniFile); // заполнение сведений о БД f_DbInfo.GetFamilyNames(lbFamilyNames.Items); if lbFamilyNames.Items.Count > 0 then lbFamilyNames.ItemIndex := 0; labGarantFolder.Caption := 'Папка Garant: ' + f_DbInfo.FamilyFolder; labMainFolder.Caption := 'Папка Main : ' + f_DbInfo.MainFolder; // вкл-выкл контролов bDoVerify.Enabled := True; bDoRepair.Enabled := True; end; procedure TFormMain.FormDestroy(Sender: TObject); begin l3Free(f_DbInfo); end; end.
unit atControlStatusConverter; // Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atControlStatusConverter.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatControlStatusConverter" MUID: (504F47A401F7) interface uses l3IntfUses , atStringToBitMaskConverterBase ; type TatControlStatusConverter = class(TatStringToBitMaskConverterBase) protected procedure InitConvertMap; override; public class function Instance: TatControlStatusConverter; {* Метод получения экземпляра синглетона TatControlStatusConverter } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TatControlStatusConverter implementation uses l3ImplUses , UnderControlUnit , SysUtils , l3Base //#UC START# *504F47A401F7impl_uses* //#UC END# *504F47A401F7impl_uses* ; var g_TatControlStatusConverter: TatControlStatusConverter = nil; {* Экземпляр синглетона TatControlStatusConverter } procedure TatControlStatusConverterFree; {* Метод освобождения экземпляра синглетона TatControlStatusConverter } begin l3Free(g_TatControlStatusConverter); end;//TatControlStatusConverterFree procedure TatControlStatusConverter.InitConvertMap; //#UC START# *503E3A040395_504F47A401F7_var* const CONVERT_MAP : array [0..6] of atStringToBitMaskConverterBase.Synonyms = ( (First : 'Документ удален' ; Second : CS_DELETED), (First : 'Документ вступил в действие' ; Second : CS_ACTIVE), (First : 'Документ изменен' ; Second : CS_CHANGED), (First : 'Документ утратил силу' ; Second : CS_ABOLISHED), (First : 'Документ зарегистрирован в Минюсте РФ' ; Second : CS_REGISTERED), (First : 'Документу отказано в регистрации в Минюсте РФ' ; Second : CS_NOT_REGISTERED), (First : 'Документ не изменился' ; Second : CS_NONE) ); //#UC END# *503E3A040395_504F47A401F7_var* begin //#UC START# *503E3A040395_504F47A401F7_impl* InitConvertMap(CONVERT_MAP); //#UC END# *503E3A040395_504F47A401F7_impl* end;//TatControlStatusConverter.InitConvertMap class function TatControlStatusConverter.Instance: TatControlStatusConverter; {* Метод получения экземпляра синглетона TatControlStatusConverter } begin if (g_TatControlStatusConverter = nil) then begin l3System.AddExitProc(TatControlStatusConverterFree); g_TatControlStatusConverter := Create; end; Result := g_TatControlStatusConverter; end;//TatControlStatusConverter.Instance class function TatControlStatusConverter.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TatControlStatusConverter <> nil; end;//TatControlStatusConverter.Exists end.
unit a2bMain; // реализация бизнес-объекта главной формы { $Id: a2bMain.pas,v 1.18 2016/08/11 10:41:53 lukyanets Exp $ } // $Log: a2bMain.pas,v $ // Revision 1.18 2016/08/11 10:41:53 lukyanets // Полчищаем dt_user // // Revision 1.17 2016/07/12 13:26:26 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.16 2016/07/11 12:59:53 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.15 2016/07/08 12:49:31 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.14 2016/06/23 13:10:47 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.13 2016/06/17 06:20:10 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.12 2016/06/16 05:38:36 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.11 2016/05/18 06:02:39 lukyanets // Выключаем удаленную отладку // // Revision 1.10 2016/05/16 12:54:13 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.9 2016/04/20 11:57:00 lukyanets // Пересаживаем UserManager на новые рельсы // Committed on the Free edition of March Hare Software CVSNT Server. // Upgrade to CVS Suite for more features and support: // http://march-hare.com/cvsnt/ // // Revision 1.8 2015/09/01 12:31:12 lukyanets // Заготовки к Postgress // // Revision 1.7 2015/05/29 12:54:36 fireton // - "служебный" 255 регион: исключаем из интерфейса и экспорта пользователей // // Revision 1.6 2015/04/07 07:35:52 lukyanets // Изолируем HT // // Revision 1.5 2015/03/31 14:08:40 lukyanets // Начинаем изолировать GlobalHTServer // // Revision 1.4 2014/09/09 05:28:35 lukyanets // Не собиралось. Переименовали CurUserID в UserID // // Revision 1.3 2012/02/27 10:26:45 fireton // - не собиралось // // Revision 1.2 2010/10/27 10:40:06 fireton // - статистика импорта пользователей // // Revision 1.1 2010/10/26 08:54:19 fireton // - переносим часть операций на главную форму // interface uses l3ProtoObject, l3IniFile, a2Interfaces; type Ta2bMain = class(Tl3ProtoObject, Ia2MainForm) private f_ConfiguredThroughServer: Boolean; procedure ChangeSupervisorPassword(aNewPassword: string); procedure ExportUsers(const aFileName: string; const aRegion: Integer); procedure ImportUsers(const aFileName: string; const aRegion: Integer; out theAddedCount, theChangedCount: Integer); function pm_GetIsConfiguredThroughServer: Boolean; function pm_GetIsSupervisor: Boolean; function SortUsersProc(I,J: Longint): LongInt; public constructor Create; end; implementation uses SysUtils, l3Base, l3Types, l3String, l3DatLst, l3Stream, l3Parser, l3LongintList, daDataProvider, daUtils, daTypes, daInterfaces, DT_Types, l3LongintListPrim; resourcestring seGeneralCSVError = 'Ошибка в файле CSV (строка %d)'; seIDError = 'Ошибка в ID (строка %d)'; constructor Ta2bMain.Create; begin inherited; StationConfig.Section:='ServerConfig'; f_ConfiguredThroughServer := StationConfig.ReadParamStrDef('ServerConfigINI', '') <> ''; end; procedure Ta2bMain.ChangeSupervisorPassword(aNewPassword: string); begin GlobalDataProvider.UserManager.AdminChangePassWord(usSupervisor, aNewPassword); end; procedure Ta2bMain.ExportUsers(const aFileName: string; const aRegion: Integer); var lActive: string; lFlag: Byte; I,J: Integer; lID: TdaUserID; lName,l_Login: String; lGroups: string; lGList: Tl3StringDataList; F: TextFile; lOldCompareProc: Tl3OnCompareItems; l_Region : Integer; begin AssignFile(F, aFileName); Rewrite(F); try lOldCompareProc := GlobalDataProvider.UserManager.AllUsers.OnCompareItems; GlobalDataProvider.UserManager.AllUsers.OnCompareItems := SortUsersProc; GlobalDataProvider.UserManager.AllUsers.Sort; try for I := 0 to Pred(GlobalDataProvider.UserManager.AllUsers.Count) do begin lID := TdaUserID(GlobalDataProvider.UserManager.AllUsers.DataInt[I]); l_Region := lID shr 24; if ((aRegion = regAllRegions) and (l_Region < 255)) or (l_Region = aRegion) then // исключаем "служебный" 255 регион begin GlobalDataProvider.UserManager.GetUserInfo(lID, lName, l_Login, lFlag); lGList := Tl3StringDataList.Create; try GlobalDataProvider.UserManager.GetUserGroupsList(lID, lGList); lGroups := ''; for J := 0 to Pred(lGList.Count) do if lGList.Select[J] then begin if lGroups <> '' then lGroups := lGroups+','; lGroups := lGroups+lGlist.Strings[J]; end; finally FreeAndNil(lGList); end; {try..finally} if lGroups <> '' then lGroups := ';'+lGroups; if (lFlag and $01) > 0 then // active flag lActive := '1' else lActive := '0'; if (lFlag and $02) > 0 then // "admin" flag lActive := lActive + ';1' else lActive := lActive + ';0'; Writeln(F,lID,';',l_Login,';*;',lName,';',lActive,lGroups); end; end; finally GlobalDataProvider.UserManager.AllUsers.OnCompareItems := lOldCompareProc; end; {try..finally} finally CloseFile(F); end; {try..finally} end; procedure Ta2bMain.ImportUsers(const aFileName: string; const aRegion: Integer; out theAddedCount, theChangedCount: Integer); var lOldFlag: Byte; lOldLogin: String; lOldUserName: String; lExactUserID: Integer; l_Idx: Integer; lGrStr: Tl3String; lIsActive, lIsAdmin: Byte; l_Flags : Byte; EM: TdaUserEditMask; l_UserID: TdaUserID; LineNum: Integer; FieldNum: Integer; lStream: Tl3FileStream; lParser, lGrParser: Tl3Parser; l_Login, l_Password, lName: ShortString; lGroups: string; l_Region: TdaRegionID; l_IsNewUser: Boolean; l_IsLocalUser: Boolean; l_TmpStr: string; l_Edited: Boolean; l_UGList: Tl3LongintList; l_GroupID: TdaUserGroupID; begin lStream := Tl3FileStream.Create(aFileName, l3_fmRead); try lParser := Tl3Parser.Make(lStream, [], [' '..#255]-[';'], l3_DefaultParserWhiteSpace-[#10,#13]); try FieldNum := 0; l_Login := ''; l_Password := ''; lName := ''; lGroups := ''; LineNum := 1; lIsActive := 0; lIsAdmin := 0; lExactUserID := -1; l_UGList := Tl3LongintList.Make; theAddedCount := 0; theChangedCount := 0; try repeat lParser.NextTokenSp; case lParser.TokenType of l3_ttSymbol: case FieldNum of 0: begin l_TmpStr := Trim(lParser.TokenString); try lExactUserID := StrToInt(l_TmpStr); except raise EAdminError.CreateFmt(seIDError, [LineNum]); end; end; 1: l_Login := Trim(lParser.TokenString); 2: l_Password := Trim(lParser.TokenString); 3: lName := Trim(lParser.TokenString); 4: try lIsActive := StrToInt(lParser.TokenString); except raise EAdminError.CreateFmt(seGeneralCSVError, [LineNum]); end; 5: try lIsAdmin := StrToInt(lParser.TokenString); except raise EAdminError.CreateFmt(seGeneralCSVError, [LineNum]); end; 6: lGroups := lParser.TokenString; end; l3_ttSingleChar: if lParser.TokenChar = ';' then Inc(FieldNum); l3_ttEOL, l3_ttEOF: begin if FieldNum > 2 then begin if lExactUserID > 0 then l_UserID := lExactUserID else l_UserID := 0; // новый пользователь l_Region := l_UserID shr 24; l_IsLocalUser := (l_UserID = 0) or (l_Region = GlobalDataProvider.RegionID); l_IsNewUser := not GlobalDataProvider.UserManager.IsUserExists(l_UserID); if (l_UserID = 0) or (aRegion = regAllRegions) or (aRegion = l_Region) then begin if not l_IsNewUser then begin try GlobalDataProvider.UserManager.GetUserInfo(l_UserID, lOldUserName, lOldLogin, lOldFlag); except l_TmpStr := Format('Невозможно получить данные пользователя (строка %d)', [LineNum]); l3System.Stack2Log(l_TmpStr); raise EAdminError.Create(l_TmpStr); end; EM.LoginName := l_IsLocalUser and (AnsiUpperCase(l_Login) <> AnsiUpperCase(lOldLogin)); EM.Name := (FieldNum > 3) and (lName <> lOldUserName); l_Flags := lOldFlag; if FieldNum > 4 then l_Flags := (l_Flags and not $01) or lIsActive; if FieldNum > 5 then l_Flags := (l_Flags and not $02) or (lIsAdmin shl 1); EM.ActivFlag := lOldFlag <> l_Flags; l_Edited := False; if EM.LoginName or EM.Name or EM.ActivFlag then begin try GlobalDataProvider.UserManager.EditUser(l_UserID, lName, l_Login, l_Flags, EM); l_Edited := True; except l_TmpStr := Format('Невозможно отредактировать пользователя (строка %d)', [LineNum]); l3System.Stack2Log(l_TmpStr); raise EAdminError.Create(l_TmpStr); end; end; if l_IsLocalUser and (l_Password <> '*') then begin GlobalDataProvider.UserManager.AdminChangePassWord(l_UserID, l_Password); l_Edited := True; end; GlobalDataProvider.UserManager.GetUserGroupsList(l_UserID, l_UGList); GlobalDataProvider.UserManager.RemoveUserFromAllGroups(l_UserID); end else//if not l_IsNewUser begin // создаем пользователя с нужным ID try if l_IsLocalUser then begin l_Flags := lIsActive or lIsAdmin; if l_Password = '*' then l_Password := ''; end else begin l_Flags := lIsAdmin; // "не нашим" пользователям (из других регионов) по умолчанию вырубаем активность l_Login := ''; // и логина при импорте им тоже не полагается l_Password := ''; end; GlobalDataProvider.UserManager.AddUserID(l_UserID, lName, l_Login, l_Password, l_Flags); except l_TmpStr := Format('Невозможно создать пользователя c ID %d (строка %d)', [l_UserID, LineNum]); l3System.Stack2Log(l_TmpStr); raise EAdminError.Create(l_TmpStr); end; end;//if not l_IsNewUser if (lGroups <> '') and not (l_IsNewUser and not l_IsLocalUser) then begin lGrStr := Tl3String.Make(l3PCharLen(lGroups)); try lGrParser := Tl3Parser.Make(lGrStr, [], [#32..#255] - [','], []); try with lGrParser do repeat NextTokenSp; if TokenType = l3_ttSymbol then begin l_TmpStr := Trim(TokenString); if l_TmpStr <> '' then begin l_Idx := 0; if GlobalDataProvider.UserManager.AllGroups.FindStr(PAnsiChar(l_TmpStr), l_Idx) then begin l_GroupID := GlobalDataProvider.UserManager.AllGroups.DataInt[l_Idx]; GlobalDataProvider.UserManager.SetUserGroup(l_UserID, l_GroupID, True); if (not l_IsNewUser) and (not l_Edited) then begin l_Idx := l_UGList.IndexOf(l_GroupID); if l_Idx = -1 then l_Edited := True else l_UGList.Delete(l_Idx); end; end else begin Str2Log('Импорт пользователей из CSV: несуществующая группа - '+l_TmpStr); end; end; end; until TokenType = l3_ttEOF; if (not l_IsNewUser) and (not l_Edited) and (l_UGList.Count > 0) then l_Edited := True; finally FreeAndNil(lGrParser); end; finally FreeAndNil(lGrStr); end; end; if l_IsNewUser then Inc(theAddedCount) else if l_Edited then Inc(theChangedCount); end;// if (l_UserID = 0) or (aRegion = regAllRegions) or (aRegion = l_Region) then end else if FieldNum > 1 then // пустые строки просто пропускаем raise EAdminError.CreateFmt('Ошибка в файле CSV (строка %d)', [LineNum]); FieldNum := 0; l_Login := ''; l_Password := ''; lName := ''; lGroups := ''; lIsActive := 0; lIsAdmin := 0; lExactUserID := -1; Inc(LineNum); //Application.MainForm.Update; end; end; until lParser.TokenType = l3_ttEOF; finally FreeAndNil(l_UGList); end; finally FreeAndNil(lParser); end; finally FreeAndNil(lStream); end; end; function Ta2bMain.pm_GetIsConfiguredThroughServer: Boolean; begin Result := f_ConfiguredThroughServer; end; function Ta2bMain.pm_GetIsSupervisor: Boolean; begin Result := GlobalDataProvider.UserID = usSupervisor; end; function Ta2bMain.SortUsersProc(I,J: Longint): LongInt; begin with GlobalDataProvider.UserManager.AllUsers do begin if TdaUserID(DataInt[I]) > TdaUserID(DataInt[J]) then Result := 1 else if TdaUserID(DataInt[I]) < TdaUserID(DataInt[J]) then Result := -1 else Result := 0; end; {with..} end; end.
unit RoomMod; {$mode objfpc}{$H+} interface Type TRoomD=Object length,width:real; {поля и ширина комнаты} function Square:real; virtual; {метод определения площади} constructor Init(l,w:real); {конструктор} end; Type TVRoomD=object(TRoomD) height:real; {дополнительное поле класса} function Square:real; virtual; {виртуальный полиморфный метод} constructor Init(l,w,h:real); {конструктор} end; implementation Function TRoomD.Square:real; {тело метода определения площади} begin Square:=length*width; end; Constructor TRoomD.Init(l,w:real); {тело конструктора} begin length:=l; width:=w; end; constructor TVRoomD.Init(l,w,h:real); begin inherited Init(l,w); {инициализирует поля базового класса} height:=h; {инициализируем собственное поле класса} end; Function TVRoomD.Square:real; begin Square:=inherited Square+2*height*(length+width); end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, SvcMgr, Variants, xClasses, xLog, DB, DBClient, ssClientDataSet, MConnect, SConnect, ssSocketConnection, ExtCtrls; type TsvcBackup = class(TService) tmrMain: TTimer; SConn: TssSocketConnection; cdsDB: TssClientDataSet; Log: TxLog; qMain: TxQueue; procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceContinue(Sender: TService; var Continued: Boolean); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure tmrMainTimer(Sender: TObject); procedure ServiceCreate(Sender: TObject); procedure ServiceShutdown(Sender: TService); procedure qMainAction(AAction: TxQueueAction); private InProcess: Boolean; public function GetServiceController: TServiceController; override; { Public declarations } end; var svcBackup: TsvcBackup; //============================================================================= //============================================================================= //============================================================================= //============================================================================= implementation uses Registry, ssRegUtils, ok_svc_const; {$R *.DFM} //============================================================================= function IntToStrEx(const AValue, ADigits: Integer): string; var S: string; i, l: Integer; begin S := IntToStr(AValue); L := Length(S); for i := 1 to ADigits - l do S := '0' + S; Result := S; end; //============================================================================= procedure ServiceController(CtrlCode: DWord); stdcall; begin svcBackup.Controller(CtrlCode); end; //============================================================================= function TsvcBackup.GetServiceController: TServiceController; begin Result := ServiceController; end; //============================================================================= procedure TsvcBackup.ServiceStart(Sender: TService; var Started: Boolean); begin Log.Add('Backup Service started'); tmrMain.Enabled := True; Started := True; end; //============================================================================= procedure TsvcBackup.ServiceStop(Sender: TService; var Stopped: Boolean); begin Log.Add('Backup Service stopped'); tmrMain.Enabled := False; Stopped := True; end; //============================================================================= procedure TsvcBackup.ServiceContinue(Sender: TService; var Continued: Boolean); begin Log.Add('Backup Service continued'); tmrMain.Enabled := True; Continued := True; end; //============================================================================= procedure TsvcBackup.ServicePause(Sender: TService; var Paused: Boolean); begin Log.Add('Backup Service paused'); tmrMain.Enabled := False; Paused := True; end; //============================================================================= procedure TsvcBackup.tmrMainTimer(Sender: TObject); var h, min, sec, msec, d, m, y, h2, min2, sec2: Word; FDBKey: string; intTmp, i, DBID, intInterval: Integer; strDir, strType: string; dtTime, dtLastBackup: TDateTime; lstKeys: TStringList; begin if (Status = csRunning) and not InProcess then begin InProcess := True; DecodeTime(Time, h, min, sec, msec); DecodeDate(Date, y, m, d); with TRegistry.Create do try lstKeys := TStringList.Create; RootKey := HKEY_LOCAL_MACHINE; if not OpenKey(BackupSvcRegKey, False) then Exit; GetKeyNames(lstKeys); CloseKey; for i := 0 to lstKeys.Count - 1 do begin FDBKey := lstKeys.Strings[i]; if OpenKey(BackupSvcRegKey + '\' + FDBKey, False) then begin try try intTmp := ReadInteger('IntervalValue'); if intTmp <= 0 then Continue; strDir := ReadString('BackupDir'); strType := ReadString('IntervalType'); dtTime := ReadDateTime('BackupTime'); dtLastBackup := ReadDateTime('LastBackupTime'); DecodeTime(dtTime, h2, min2, sec2, msec); intInterval := 1; case strType[1] of 'D': intInterval := intTmp; 'W': intInterval := intTmp * 7; 'M': intInterval := intTmp * 30; end; {$IFDEF DEBUG} Log.Add(DateTimeToStr(Now)); Log.Add(DateTimeToStr(dtLastBackup)); Log.Add(FloatToStr(Now - dtLastBackup)); {$ENDIF} if (Now - dtLastBackup) > intInterval then begin DBID := StrToInt(Copy(FDBKey, 3, Length(FDBKey) - 2)); if (h = h2) and (min = min2)// and (sec = sec2) then begin qMain.Add(0, DBID, strDir); end; end; finally CloseKey; end; except on e: exception do begin Log.Add(e.message); end; end; end; end; finally Free; lstKeys.Free; end; InProcess := False; end; end; //============================================================================= procedure TsvcBackup.ServiceCreate(Sender: TObject); begin Log.FileName := ExtractFilePath(ParamStr(0)) + 'svcbackup.log'; end; //============================================================================= procedure TsvcBackup.ServiceShutdown(Sender: TService); begin Log.Add('Backup Service shutdowned'); end; //============================================================================= procedure TsvcBackup.qMainAction(AAction: TxQueueAction); var h, min, sec, msec, d, m, y: Word; DBID, Res: Integer; BackupFile: string; begin try SConn.Connected := True; except InProcess := False; Log.Add('Error: could not connect to OK_Server'); Exit; end; cdsDB.Open; if cdsDB.Locate('dbid', AAction.Param, []) then begin Log.Add('Start backuping batabase <' + cdsDB.FieldByName('desc').AsString + '>'); DBID := AAction.Param; DecodeTime(Time, h, min, sec, msec); DecodeDate(Date, y, m, d); try BackupFile := VarToStr(AAction.AddInfo) + '\' + cdsDB.FieldByName('desc').AsString + IntToStrEx(d, 2) + IntToStrEx(m, 2) + IntToStr(y) + '_' + IntToStrEx(h, 2) + IntToStrEx(min, 2) + '.fbk'; //Log.Add(BackupFile); Res := SConn.AppServer.db_Backup(BackupFile, DBID); if Res = 0 then begin Log.Add('Database <' + cdsDB.FieldByName('desc').AsString + '> backup complete'); WriteToRegDate(BackupSvcRegKey + '\DB' + IntToStr(DBID), 'LastBackupTime', Now, HKEY_LOCAL_MACHINE); end else Log.Add('Error: Database <' + cdsDB.FieldByName('desc').AsString + '> backup failed') except on E:Exception do begin Log.Add('Error: ' + E.Message); SConn.Connected := False; end; end; end; cdsDB.Close; SConn.Connected := False; 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 ClpX9IntegerConverter; interface uses ClpIECInterface, ClpIECFieldElement, ClpCryptoLibTypes, ClpBigInteger; type TX9IntegerConverter = class sealed(TObject) public class function GetByteLength(const fe: IECFieldElement): Int32; overload; static; inline; class function GetByteLength(const c: IECCurve): Int32; overload; static; inline; class function IntegerToBytes(const s: TBigInteger; qLength: Int32) : TCryptoLibByteArray; static; end; implementation { TX9IntegerConverter } class function TX9IntegerConverter.GetByteLength (const fe: IECFieldElement): Int32; begin result := (fe.FieldSize + 7) div 8; end; class function TX9IntegerConverter.GetByteLength(const c: IECCurve): Int32; begin result := (c.FieldSize + 7) div 8; end; class function TX9IntegerConverter.IntegerToBytes(const s: TBigInteger; qLength: Int32): TCryptoLibByteArray; var bytes, tmp: TCryptoLibByteArray; begin bytes := s.ToByteArrayUnsigned(); if (qLength < System.Length(bytes)) then begin System.SetLength(tmp, qLength); System.Move(bytes[System.Length(bytes) - System.Length(tmp)], tmp[0], System.Length(tmp) * System.SizeOf(Byte)); result := tmp; Exit; end; if (qLength > System.Length(bytes)) then begin System.SetLength(tmp, qLength); System.Move(bytes[0], tmp[System.Length(tmp) - System.Length(bytes)], System.Length(bytes) * System.SizeOf(Byte)); result := tmp; Exit; end; result := bytes; end; end.
unit dac; interface uses {$ifdef windows}windows,{$else}main_engine,{$ENDIF}sound_engine; type dac_chip=class(snd_chip_class) constructor Create(amp:single=1;internal:boolean=false); destructor free; public procedure update; procedure reset; procedure data8_w(data:byte); procedure signed_data8_w(data:byte); procedure data16_w(data:word); procedure signed_data16_w(data:word); function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); function internal_update:integer; private output:integer; amp:single; end; var dac_0,dac_1,dac_2,dac_3:dac_chip; implementation constructor dac_chip.Create(amp:single=1;internal:boolean=false); begin self.amp:=amp; if not(internal) then self.tsample_num:=init_channel; self.reset; end; destructor dac_chip.free; begin end; function dac_chip.save_snapshot(data:pbyte):word; var ptemp:pbyte; begin ptemp:=data; copymemory(ptemp,@self.output,sizeof(integer));inc(ptemp,sizeof(integer)); copymemory(ptemp,@self.amp,sizeof(single)); save_snapshot:=8; end; procedure dac_chip.load_snapshot(data:pbyte); var ptemp:pbyte; begin ptemp:=data; copymemory(@self.output,ptemp,sizeof(integer));inc(ptemp,sizeof(integer)); copymemory(@self.amp,ptemp,sizeof(single)); end; function dac_chip.internal_update:integer; begin internal_update:=trunc(self.output*self.amp); end; procedure dac_chip.update; var res:smallint; begin if (self.output*self.amp)>32767 then res:=32767 else if (self.output*self.amp)<=-32767 then res:=-32767 else res:=trunc(self.output*self.amp); tsample[self.tsample_num,sound_status.posicion_sonido]:=res; if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=res; end; procedure dac_chip.data8_w(data:byte); begin self.output:=data shl 7; end; procedure dac_chip.signed_data8_w(data:byte); begin self.output:=(data-$80) shl 7; end; procedure dac_chip.data16_w(data:word); begin self.output:=data shr 1; end; procedure dac_chip.signed_data16_w(data:word); begin self.output:=data-$8000; end; procedure dac_chip.reset; begin self.output:=0; end; end.
{ Clever Internet Suite Copyright (C) 2017 Clever Components All Rights Reserved www.CleverComponents.com } unit clCryptEncoder; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clUtils, clConfig, clCryptDataHeader; type TclCryptDataType = (dtNone, dtPemFormat, dtRsaPrivateKey, dtRsaPublicKey, dtPublicKeyInfo, dtCertificate, dtCertificateRequest, dtNewCertificateRequest, dtSsh2Format, dtSsh2EncryptedPrivateKey, dtSsh2PrivateKey, dtSsh2PublicKey); TclCryptEncoder = class(TComponent) private FConfig: TclConfig; FHeader: TclCryptDataHeader; FDataType: TclCryptDataType; FDataTypeName: string; FCharsPerLine: Integer; FPassPhrase: string; procedure SetDataType(const Value: TclCryptDataType); procedure SetDataTypeName(const Value: string); procedure SetHeader(const Value: TclCryptDataHeader); function GetEncodingFormat: TclCryptEncodingFormat; function GetDefaultCharsPerLine(AEncodingFormat: TclCryptEncodingFormat): Integer; function ExtractEncodingFormat(ASource: string): TclCryptEncodingFormat; function ExtractDataType(const ASource: string; AEncodingFormat: TclCryptEncodingFormat): TclCryptDataType; function ExtractDataTypeName(const ASource: string; ADataType: TclCryptDataType): string; procedure ParseDataType(const ASource: string); function GetHeaderBegin: string; function GetHeaderEnd: string; function DecryptData(const ASource: TclByteArray): TclByteArray; function EncryptData(const ASource: TclByteArray): TclByteArray; protected function CreateConfig: TclConfig; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function EncodeToBytes(const ASource: TclByteArray; ADataType: TclCryptDataType): TclByteArray; overload; class function DecodeBytes(const ASource: TclByteArray): TclByteArray; class function EncodeToString(const ASource: TclByteArray; ADataType: TclCryptDataType): string; class function DecodeString(const ASource: string): TclByteArray; procedure Clear; procedure EncodeToFile(const ASource: TclByteArray; const ADestinationFile: string); function DecodeFile(const ASourceFile: string): TclByteArray; procedure Encode(const ASource: TclByteArray; ADestination: TStream); overload; function Decode(ASource: TStream): TclByteArray; overload; function EncodeToBytes(const ASource: TclByteArray): TclByteArray; overload; function Decode(const ASource: TclByteArray): TclByteArray; overload; function Encode(const ASource: TclByteArray): string; overload; function Decode(const ASource: string): TclByteArray; overload; property EncodingFormat: TclCryptEncodingFormat read GetEncodingFormat; property Config: TclConfig read FConfig; published property CharsPerLine: Integer read FCharsPerLine write FCharsPerLine default 64; property DataType: TclCryptDataType read FDataType write SetDataType default dtNone; property DataTypeName: string read FDataTypeName write SetDataTypeName; property Header: TclCryptDataHeader read FHeader write SetHeader; property PassPhrase: string read FPassPhrase write FPassPhrase; end; TclCryptEncoderConfig = class(TclConfig) public constructor Create; end; implementation uses clTranslator, clEncoder, clHeaderFieldList, clCryptUtils, clCryptHash, clCryptCipher, clCryptPemEncryptor; const DefaultCharsPerLine = 64; CRLF = #13#10; BEGINLexem = 'BEGIN '; ENDLexem = 'END '; PemHeaderPrefix = '-----'; PemHeaderPostfix = '-----'; Ssh2HeaderPrefix = '---- '; Ssh2HeaderPostfix = ' ----'; HeaderPrefix: array[TclCryptEncodingFormat] of string = ('', PemHeaderPrefix, Ssh2HeaderPrefix); HeaderPostfix: array[TclCryptEncodingFormat] of string = ('', PemHeaderPostfix, Ssh2HeaderPostfix); DataHeader: array[TclCryptDataType] of string = ('', '', 'RSA PRIVATE KEY', 'RSA PUBLIC KEY', 'PUBLIC KEY', 'CERTIFICATE', 'CERTIFICATE REQUEST', 'NEW CERTIFICATE REQUEST', '', 'SSH2 ENCRYPTED PRIVATE KEY', 'SSH2 PRIVATE KEY', 'SSH2 PUBLIC KEY'); DataEncoding: array[TclCryptDataType] of TclCryptEncodingFormat = (efNone, efPem, efPem, efPem, efPem, efPem, efPem, efPem, efSsh2, efSsh2, efSsh2, efSsh2); { TclCryptEncoder } class function TclCryptEncoder.DecodeBytes(const ASource: TclByteArray): TclByteArray; var encoder: TclCryptEncoder; begin encoder := TclCryptEncoder.Create(nil); try Result := encoder.Decode(ASource); finally encoder.Free(); end; end; class function TclCryptEncoder.DecodeString(const ASource: string): TclByteArray; var encoder: TclCryptEncoder; begin encoder := TclCryptEncoder.Create(nil); try Result := encoder.Decode(ASource); finally encoder.Free(); end; end; class function TclCryptEncoder.EncodeToBytes(const ASource: TclByteArray; ADataType: TclCryptDataType): TclByteArray; var encoder: TclCryptEncoder; begin encoder := TclCryptEncoder.Create(nil); try encoder.DataType := ADataType; Result := encoder.EncodeToBytes(ASource); finally encoder.Free(); end; end; class function TclCryptEncoder.EncodeToString(const ASource: TclByteArray; ADataType: TclCryptDataType): string; var encoder: TclCryptEncoder; begin encoder := TclCryptEncoder.Create(nil); try encoder.DataType := ADataType; Result := encoder.Encode(ASource); finally encoder.Free(); end; end; function TclCryptEncoder.ExtractEncodingFormat(ASource: string): TclCryptEncodingFormat; begin if (System.Pos(PemHeaderPrefix + BEGINLexem, ASource) > 0) then begin Result := efPem; end else if (System.Pos(Ssh2HeaderPrefix + BEGINLexem, ASource) > 0) then begin Result := efSsh2; end else begin Result := efNone; end; end; function TclCryptEncoder.ExtractDataType(const ASource: string; AEncodingFormat: TclCryptEncodingFormat): TclCryptDataType; var i: TclCryptDataType; ind: Integer; prefix, postfix: string; begin prefix := HeaderPrefix[AEncodingFormat]; postfix := HeaderPostfix[AEncodingFormat]; for i := Low(TclCryptDataType) to High(TclCryptDataType) do begin ind := System.Pos(prefix + BEGINLexem + DataHeader[i] + postfix, ASource); if (ind > 0) and (System.Pos(prefix + ENDLexem + DataHeader[i] + postfix, ASource) > ind) then begin Result := i; Exit; end; end; if (AEncodingFormat = efPem) then begin Result := dtPemFormat; end else if (AEncodingFormat = efSsh2) then begin Result := dtSsh2Format; end else begin Result := dtNone; end; end; function TclCryptEncoder.ExtractDataTypeName(const ASource: string; ADataType: TclCryptDataType): string; var indPrefix, indPostfix, prefixLen: Integer; name, prefix, postfix: string; begin Result := ''; prefix := HeaderPrefix[DataEncoding[ADataType]]; postfix := HeaderPostfix[DataEncoding[ADataType]]; indPrefix := TextPos(prefix + BEGINLexem, ASource); if (indPrefix > 0) then begin prefixLen := Length(prefix + BEGINLexem); indPostfix := TextPos(postfix, ASource, indPrefix + prefixLen); if (indPrefix < indPostfix) then begin name := System.Copy(ASource, indPrefix + prefixLen, indPostfix - indPrefix - prefixLen); if (System.Pos(prefix + ENDLexem + name + postfix, ASource) > 0) then begin Result := name; end; end; end; end; procedure TclCryptEncoder.ParseDataType(const ASource: string); var encodingFormat: TclCryptEncodingFormat; begin Clear(); encodingFormat := ExtractEncodingFormat(ASource); if (encodingFormat <> efNone) then begin FDataType := ExtractDataType(ASource, encodingFormat); end; FDataTypeName := DataHeader[FDataType]; if ((FDataType <> dtNone) and (FDataTypeName = '')) then begin FDataTypeName := ExtractDataTypeName(ASource, FDataType); end; if (FDataTypeName = '') then begin FDataType := dtNone; end; FCharsPerLine := GetDefaultCharsPerLine(encodingFormat); end; function TclCryptEncoder.GetDefaultCharsPerLine(AEncodingFormat: TclCryptEncodingFormat): Integer; begin if (AEncodingFormat = efPem) then begin Result := 64; end else if (AEncodingFormat = efSsh2) then begin Result := 72; end else begin Result := DefaultCharsPerLine; end; end; function TclCryptEncoder.GetEncodingFormat: TclCryptEncodingFormat; begin Result := DataEncoding[DataType]; end; function TclCryptEncoder.GetHeaderBegin: string; begin Result := HeaderPrefix[EncodingFormat] + BEGINLexem + DataTypeName + HeaderPostfix[EncodingFormat]; end; function TclCryptEncoder.GetHeaderEnd: string; begin Result := HeaderPrefix[EncodingFormat] + ENDLexem + DataTypeName + HeaderPostfix[EncodingFormat]; end; procedure TclCryptEncoder.Clear; begin FDataType := dtNone; FDataTypeName := ''; FHeader.Clear(); FCharsPerLine := GetDefaultCharsPerLine(EncodingFormat); end; constructor TclCryptEncoder.Create(AOwner: TComponent); begin inherited Create(AOwner); FConfig := CreateConfig(); FHeader := TclCryptDataHeader.Create(); Clear(); FCharsPerLine := DefaultCharsPerLine; end; function TclCryptEncoder.CreateConfig: TclConfig; begin Result := TclCryptEncoderConfig.Create(); end; function TclCryptEncoder.DecodeFile(const ASourceFile: string): TclByteArray; var src: TStream; begin {$IFNDEF DELPHI2005}Result := nil;{$ENDIF} src := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); try Result := Decode(src); finally src.Free(); end; end; function TclCryptEncoder.Decode(ASource: TStream): TclByteArray; var buf: TclByteArray; len: Integer; begin len := ASource.Size - ASource.Position; SetLength(buf, len); ASource.Read(buf[0], len); Result := Decode(buf); end; function TclCryptEncoder.Decode(const ASource: TclByteArray): TclByteArray; var s: string; begin s := TclTranslator.GetString(ASource); ParseDataType(s); if (DataType = dtNone) then begin Result := ASource; end else begin Result := Decode(s); end; end; function TclCryptEncoder.DecryptData(const ASource: TclByteArray): TclByteArray; var encryptor: TclRsaKeyPemEncryptor; begin Result := ASource; if (PassPhrase <> '') and (DataType = dtRsaPrivateKey) then begin encryptor := TclRsaKeyPemEncryptor.Create(FConfig); try Result := encryptor.Decrypt(Header, ASource, PassPhrase); finally encryptor.Free(); end; end else if (PassPhrase <> '') and (DataType = dtSsh2EncryptedPrivateKey) then begin RaiseCryptError('The SSH key decryption is not implemented', -1); end; end; function TclCryptEncoder.Decode(const ASource: string): TclByteArray; var ind: Integer; data, sigBegin, sigEnd: string; begin ParseDataType(ASource); if (DataType = dtNone) then begin Result := TclTranslator.GetBytes(ASource); Exit; end; sigBegin := GetHeaderBegin(); sigEnd := GetHeaderEnd(); data := ASource; ind := TextPos(sigBegin, data, 1); System.Delete(data, 1, ind - 1 + Length(sigBegin)); ind := TextPos(sigEnd, data, 1); Delete(data, ind, Length(data)); data := Header.Parse(data, EncodingFormat); Result := TclEncoder.DecodeBytes(data, cmBase64); Result := DecryptData(Result); end; destructor TclCryptEncoder.Destroy; begin FHeader.Free(); FConfig.Free(); inherited Destroy(); end; procedure TclCryptEncoder.EncodeToFile(const ASource: TclByteArray; const ADestinationFile: string); var dst: TStream; begin dst := TFileStream.Create(ADestinationFile, fmCreate); try Encode(ASource, dst); finally dst.Free(); end; end; procedure TclCryptEncoder.Encode(const ASource: TclByteArray; ADestination: TStream); var buf: TclByteArray; begin buf := EncodeToBytes(ASource); if (buf <> nil) and (Length(buf) > 0) then begin ADestination.Write(buf[0], Length(buf)); end; end; function TclCryptEncoder.EncodeToBytes(const ASource: TclByteArray): TclByteArray; begin Result := TclTranslator.GetBytes(Encode(ASource), ''); end; function TclCryptEncoder.EncryptData(const ASource: TclByteArray): TclByteArray; begin Result := ASource; if (PassPhrase <> '') and (DataType = dtRsaPrivateKey) then begin RaiseCryptError('The key encryption is not implemented', -1); end else if (PassPhrase <> '') and (DataType = dtSsh2EncryptedPrivateKey) then begin RaiseCryptError('The key encryption is not implemented', -1); end; end; function TclCryptEncoder.Encode(const ASource: TclByteArray): string; var encoder: TclEncoder; data: TclByteArray; begin {$IFNDEF DELPHI2005}data := nil;{$ENDIF} if (DataType = dtNone) then begin Result := TclTranslator.GetString(ASource, ''); end else begin data := EncryptData(ASource); encoder := TclEncoder.Create(nil); try encoder.CharsPerLine := CharsPerLine; encoder.EncodeMethod := cmBase64; Result := Header.Build(EncodingFormat, CharsPerLine); Result := Result + encoder.EncodeBytes(data); if (RTextPos(CRLF, Result) <> Length(Result) - 1) then begin Result := Result + CRLF; end; Result := GetHeaderBegin() + CRLF + Result + GetHeaderEnd() + CRLF; finally encoder.Free(); end; end; end; procedure TclCryptEncoder.SetDataType(const Value: TclCryptDataType); begin FDataType := Value; if not (csLoading in ComponentState) then begin FDataTypeName := DataHeader[FDataType]; FCharsPerLine := GetDefaultCharsPerLine(EncodingFormat); end; end; procedure TclCryptEncoder.SetDataTypeName(const Value: string); begin FDataTypeName := Value; if not (csLoading in ComponentState) then begin FDataType := dtNone; FCharsPerLine := GetDefaultCharsPerLine(EncodingFormat); end; end; procedure TclCryptEncoder.SetHeader(const Value: TclCryptDataHeader); begin FHeader.Assign(Value); end; { TclCryptEncoderConfig } constructor TclCryptEncoderConfig.Create; begin inherited Create(); SetType('md5', TclMd5); SetType('3des-cbc', TclTripleDesCbc); end; end.
unit viewer_ipro; {$mode delphi} interface uses Classes, SysUtils, // fpreadgif, fpimage, fpwritebmp, // LCL Graphics, Forms, Controls, LCLProc, // browserviewer, IPHtml, Ipfilebroker, IpMsg; type { TMyIpHtmlDataProvider } TMyIpHtmlDataProvider = class(TIpHtmlDataProvider) protected function DoGetStream(const URL: string): TStream; override; end; { TiProViewer } TiProViewer = class(TBrowserViewer) private IpHtmlPanel1: TIpHtmlPanel; DataProvider1: TMyIpHtmlDataProvider; function DataProvider1CanHandle(Sender: TObject; const URL: string ): Boolean; procedure DataProvider1CheckURL(Sender: TObject; const URL: string; var Available: Boolean; var ContentType: string); procedure DataProvider1GetHtml(Sender: TObject; const URL: string; const PostData: TIpFormDataEntity; var Stream: TStream); procedure DataProvider1GetImage(Sender: TIpHtmlNode; const URL: string; var Picture: TPicture); procedure DataProvider1Leave(Sender: TIpHtml); procedure DataProvider1ReportReference(Sender: TObject; const URL: string); procedure ShowHTML(Src: string); 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 function TMyIpHtmlDataProvider.DoGetStream(const URL: string): TStream; var ms: TMemoryStream; begin Result:=nil; DebugLn('TMyIpHtmlDataProvider.DoGetStream '+URL); if URL='fpdoc.css' then begin //debugln(['TMyIpHtmlDataProvider.DoGetStream ',FileExists(URL)]); ms:=TMemoryStream.Create; try ms.LoadFromFile(URL); ms.Position:=0; except ms.Free; end; Result:=ms; end; end; function TiProViewer.DataProvider1CanHandle(Sender: TObject; const URL: string ): Boolean; begin DebugLn('TformBrowser.DataProvider1CanHandle ',URL); Result:=True; end; procedure TiProViewer.DataProvider1CheckURL(Sender: TObject; const URL: string; var Available: Boolean; var ContentType: string); begin DebugLn('TformBrowser.DataProvider1CheckURL ',URL); Available:=True; ContentType:='text/html'; end; procedure TiProViewer.DataProvider1GetHtml(Sender: TObject; const URL: string; const PostData: TIpFormDataEntity; var Stream: TStream); var lStream: TMemoryStream; begin DebugLn('TformBrowser.DataProvider1GetHtml ',URL); { MyPageLoader.LoadBinaryResource(URL, lStream); Stream := lStream; lStream.Position := 0;} Stream := nil; LoadFromURL(URL); end; procedure TiProViewer.DataProvider1GetImage(Sender: TIpHtmlNode; const URL: string; var Picture: TPicture); var lStream: TMemoryStream = nil; lConvertedStream: TMemoryStream = nil; lStr: String; // image: TFPCustomImage; reader: TFPCustomImageReader; writer: TFPCustomImageWriter; lAbsURL: String; begin DebugLn('TformBrowser.DataProvider1GetImage URL=', URL); // Corrections of the URL if (URL[1] = '/') and (URL[2] = '/') then lAbsURL := 'http:' + URL; DebugLn('TformBrowser.DataProvider1GetImage Corrected URL=', lAbsURL); lStr := ExtractFileExt(lAbsURL); if (lStr = '.jpeg') or (lStr = '.jpg') then begin try MyPageLoader.LoadBinaryResource(lAbsURL, lStream); lStream.Position := 0; Picture := TPicture.Create; Picture.Jpeg.LoadFromStream(lStream); finally lStream.Free end; end else if (lStr = '.gif') then begin DebugLn('TformBrowser.DataProvider1GetImage Processing GIF'); try MyPageLoader.LoadBinaryResource(lAbsURL, lStream); lStream.Position := 0; Picture := TPicture.Create; Image := TFPMemoryImage.Create(10, 10); Reader := TFPReaderGIF.Create; Image.LoadFromStream(lStream, Reader); Writer := TFPWriterBMP.Create; lConvertedStream := TMemoryStream.Create; Image.SaveToStream(lConvertedStream, Writer); lConvertedStream.Position:=0; Picture.Bitmap.LoadFromStream(lConvertedStream); finally lStream.Free; image.Free; reader.Free; writer.Free; lConvertedStream.Free; end; end else begin DebugLn('TformBrowser.DataProvider1GetImage Unsupported format: ', lStr); Picture := nil; Exit; end; // and (lStr <> '.bmp') and (lStr <> '.png') end; procedure TiProViewer.DataProvider1Leave(Sender: TIpHtml); begin end; procedure TiProViewer.DataProvider1ReportReference(Sender: TObject; const URL: string ); begin //debugln(['TForm1.DataProvider1ReportReference ',URL]); end; procedure TiProViewer.ShowHTML(Src: string); var ss: TStringStream; NewHTML: TIpHtml; begin ss := TStringStream.Create(Src); try NewHTML := TIpHtml.Create; // Beware: Will be freed automatically by IpHtmlPanel1 //debugln(['TForm1.ShowHTML BEFORE SETHTML']); IpHtmlPanel1.SetHtml(NewHTML); //debugln(['TForm1.ShowHTML BEFORE LOADFROMSTREAM']); NewHTML.LoadFromStream(ss); //if Anchor <> '' then IpHtmlPanel1.MakeAnchorVisible(Anchor); finally ss.Free; end; end; procedure TiProViewer.CreateViewer(AParent, AOwner: TWinControl); begin ViewerName := 'Turbo Power iPro HTML viewer written in Pascal'; DataProvider1:=TMyIpHtmlDataProvider.Create(AOwner); //DataProvider1.Name:='DataProvider1'; DataProvider1.OnCanHandle:=DataProvider1CanHandle; DataProvider1.OnGetHtml:=DataProvider1GetHtml; DataProvider1.OnGetImage:=DataProvider1GetImage; DataProvider1.OnLeave:=DataProvider1Leave; DataProvider1.OnCheckURL:=DataProvider1CheckURL; DataProvider1.OnReportReference:=DataProvider1ReportReference; IpHtmlPanel1:=TIpHtmlPanel.Create(AOwner); //IpHtmlPanel1.Name:='IpHtmlPanel1'; IpHtmlPanel1.Parent:=AParent; IpHtmlPanel1.Align:=alClient; IpHtmlPanel1.DefaultFontSize:=10; IpHtmlPanel1.DataProvider:=DataProvider1; end; procedure TiProViewer.LoadFromFile(AFilename: string); begin end; function TiProViewer.GetDocumentTitle: string; begin Result:=''; end; procedure TiProViewer.SetShowImages(AValue: Boolean); begin end; procedure TiProViewer.HandlePageLoaderTerminated(Sender: TObject); begin inherited HandlePageLoaderTerminated(Sender); ShowHTML(MyPageLoader.Contents); end; procedure TiProViewer.Reload; begin end; initialization SetBrowserViewerClass(TiProViewer); end.
{ dbdateedit unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit dbdateedit; {$I rx.inc} interface uses Classes, SysUtils, LResources, LMessages, LCLType, Controls, Graphics, DB, DbCtrls, EditBtn, tooledit; type { TRxDBDateEdit } TRxDBDateEdit = class(TRxDateEdit) private FDataLink:TFieldDataLink; FDefaultToday: Boolean; procedure DoCheckEnable; function GetDataField: string; function GetDataSource: TDataSource; function GetReadOnly: Boolean; procedure SetDataField(const AValue: string); procedure SetDataSource(const AValue: TDataSource); procedure SetReadOnly(const AValue: Boolean); protected procedure ActiveChange(Sender:TObject); procedure DataChange(Sender:TObject); procedure EditingChange(Sender: TObject); procedure UpdateData(Sender:TObject); procedure CMExit(var Message:TLMessage); message CM_EXIT; procedure LMCut(var Message: TLMessage); message LM_CUT; procedure LMPaste(var Message: TLMessage); message LM_PASTE; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure ButtonClick; override; procedure EditChange; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure EditingDone; override; Procedure RunDialog; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property DefaultToday: Boolean read FDefaultToday write FDefaultToday default False; end; { TRxDBCalcEdit } TRxDBCalcEdit = class(TCalcEdit) private FDataLink: TFieldDataLink; procedure DoCheckEnable; function GetDataField: string; function GetDataSource: TDataSource; function GetReadOnly: Boolean; procedure SetDataField(const AValue: string); procedure SetDataSource(const AValue: TDataSource); procedure SetReadOnly(const AValue: Boolean); protected procedure ActiveChange(Sender:TObject); procedure DataChange(Sender:TObject); procedure EditingChange(Sender: TObject); procedure UpdateData(Sender:TObject); procedure CMExit(var Message:TLMessage); message CM_EXIT; procedure LMCut(var Message: TLMessage); message LM_CUT; procedure LMPaste(var Message: TLMessage); message LM_PASTE; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure EditChange; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure EditingDone; override; Procedure RunDialog; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; end; implementation uses DateUtil; { TRxDBDateEdit } procedure TRxDBDateEdit.DoCheckEnable; begin Enabled:=FDataLink.Active and (FDataLink.Field<>nil) and (not FDataLink.Field.ReadOnly); end; function TRxDBDateEdit.GetDataField: string; begin Result:=FDataLink.FieldName; end; function TRxDBDateEdit.GetDataSource: TDataSource; begin Result:=FDataLink.DataSource; end; function TRxDBDateEdit.GetReadOnly: Boolean; begin Result:=FDataLink.ReadOnly; end; procedure TRxDBDateEdit.SetDataField(const AValue: string); begin try FDataLink.FieldName:=AValue; finally DoCheckEnable; end; end; procedure TRxDBDateEdit.SetDataSource(const AValue: TDataSource); begin FDataLink.DataSource:=AValue; DoCheckEnable; end; procedure TRxDBDateEdit.SetReadOnly(const AValue: Boolean); begin inherited ReadOnly:=AValue; FDataLink.ReadOnly:=AValue; end; procedure TRxDBDateEdit.CMExit(var Message: TLMessage); begin try FDataLink.UpdateRecord; except SetFocus; SelectAll; raise; end; inherited; end; procedure TRxDBDateEdit.LMCut(var Message: TLMessage); begin FDataLink.Edit; inherited; end; procedure TRxDBDateEdit.LMPaste(var Message: TLMessage); begin FDataLink.Edit; inherited; end; procedure TRxDBDateEdit.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if Key=VK_ESCAPE then begin //cancel out of editing by reset on esc FDataLink.Reset; SelectAll; Key := VK_UNKNOWN; end else if (Key<>VK_UNKNOWN) then begin //make sure we call edit to ensure the datset is in edit, //this is for where the datasource is in autoedit, so we aren't //read only even though the dataset isn't realy in edit FDataLink.Edit; end; end; procedure TRxDBDateEdit.EditChange; begin if Assigned(FDataLink) then FDataLink.Modified; inherited EditChange; end; procedure TRxDBDateEdit.Notification(AComponent: TComponent; Operation: TOperation ); begin inherited Notification(AComponent, Operation); // if the datasource is being removed then we need to make sure // we are updated or we can get AV/Seg's *cough* as I foolishly // discovered firsthand.... if (Operation=opRemove) then begin if (FDataLink<>nil) and (AComponent=DataSource) then DataSource:=nil; end; end; procedure TRxDBDateEdit.EditingDone; begin inherited EditingDone; if FDataLink.CanModify then FDataLink.UpdateRecord; end; procedure TRxDBDateEdit.RunDialog; begin if FDataLink.CanModify then FDataLink.UpdateRecord; end; procedure TRxDBDateEdit.ButtonClick; begin inherited ButtonClick; RunDialog; end; procedure TRxDBDateEdit.ActiveChange(Sender: TObject); begin DoCheckEnable; end; procedure TRxDBDateEdit.DataChange(Sender: TObject); begin if Assigned(FDataLink.Field) and (FDataLink.Field is TDateTimeField) then begin if FDataLink.Field.IsNull then Text:='' else Date:=FDataLink.Field.AsDateTime end else Text:=''; end; procedure TRxDBDateEdit.EditingChange(Sender: TObject); begin inherited ReadOnly := not FDataLink.Editing; if FDataLink.Editing and DefaultToday and (FDataLink.Field <> nil) and (FDataLink.Field.AsDateTime = NullDate) then FDataLink.Field.AsDateTime := SysUtils.Now; end; procedure TRxDBDateEdit.UpdateData(Sender: TObject); var D: TDateTime; begin if Assigned(FDataLink.Field) then begin D := Self.Date; if (D <> NullDate) then FDataLink.Field.AsDateTime := D + Frac(FDataLink.Field.AsDateTime) else FDataLink.Field.Clear; end; end; constructor TRxDBDateEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink:=TFieldDataLink.Create; FDataLink.Control:=Self; FDataLink.OnActiveChange:=@ActiveChange; FDataLink.OnDataChange:=@DataChange; FDataLink.OnUpdateData:=@UpdateData; Text:=''; //UpdateMask; end; destructor TRxDBDateEdit.Destroy; begin FreeAndNil(FDataLink); inherited Destroy; end; { TRxDBCalcEdit } procedure TRxDBCalcEdit.DoCheckEnable; begin Enabled:=FDataLink.Active and (FDataLink.Field<>nil) and (not FDataLink.Field.ReadOnly); end; function TRxDBCalcEdit.GetDataField: string; begin Result:=FDataLink.FieldName; end; function TRxDBCalcEdit.GetDataSource: TDataSource; begin Result:=FDataLink.DataSource; end; function TRxDBCalcEdit.GetReadOnly: Boolean; begin Result:=FDataLink.ReadOnly; end; procedure TRxDBCalcEdit.SetDataField(const AValue: string); begin try FDataLink.FieldName:=AValue; finally DoCheckEnable; end; end; procedure TRxDBCalcEdit.SetDataSource(const AValue: TDataSource); begin FDataLink.DataSource:=AValue; DoCheckEnable; end; procedure TRxDBCalcEdit.SetReadOnly(const AValue: Boolean); begin FDataLink.ReadOnly:=AValue; end; procedure TRxDBCalcEdit.ActiveChange(Sender: TObject); begin DoCheckEnable; end; procedure TRxDBCalcEdit.DataChange(Sender: TObject); begin if Assigned(FDataLink.Field) and (FDataLink.Field is TNumericField) then begin if FDataLink.Field.IsNull then Text:='' else Self.AsFloat:=FDataLink.Field.AsFloat; end else Text:=''; end; procedure TRxDBCalcEdit.EditingChange(Sender: TObject); begin inherited ReadOnly := not FDataLink.Editing; { if FDataLink.Editing and DefaultToday and (FDataLink.Field <> nil) and (FDataLink.Field.AsDateTime = NullDate) then FDataLink.Field.AsDateTime := SysUtils.Now;} end; procedure TRxDBCalcEdit.UpdateData(Sender: TObject); begin if Assigned(FDataLink.Field) then begin if Self.Text<>'' then FDataLink.Field.AsFloat := Self.AsFloat else FDataLink.Field.Clear; end; end; procedure TRxDBCalcEdit.CMExit(var Message: TLMessage); begin try FDataLink.UpdateRecord; except SetFocus; SelectAll; raise; end; inherited; end; procedure TRxDBCalcEdit.LMCut(var Message: TLMessage); begin FDataLink.Edit; inherited; end; procedure TRxDBCalcEdit.LMPaste(var Message: TLMessage); begin FDataLink.Edit; inherited; end; procedure TRxDBCalcEdit.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if Key=VK_ESCAPE then begin //cancel out of editing by reset on esc FDataLink.Reset; SelectAll; Key := VK_UNKNOWN; end else if (Key<>VK_UNKNOWN) then begin //make sure we call edit to ensure the datset is in edit, //this is for where the datasource is in autoedit, so we aren't //read only even though the dataset isn't realy in edit FDataLink.Edit; end; end; procedure TRxDBCalcEdit.EditChange; begin FDataLink.Modified; inherited EditChange; end; procedure TRxDBCalcEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); // if the datasource is being removed then we need to make sure // we are updated or we can get AV/Seg's *cough* as I foolishly // discovered firsthand.... if (Operation=opRemove) then begin if (FDataLink<>nil) and (AComponent=DataSource) then DataSource:=nil; end; end; procedure TRxDBCalcEdit.EditingDone; begin inherited EditingDone; if FDataLink.CanModify then FDataLink.UpdateRecord; end; procedure TRxDBCalcEdit.RunDialog; begin inherited RunDialog; if FDataLink.CanModify then FDataLink.UpdateRecord; end; constructor TRxDBCalcEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink:=TFieldDataLink.Create; FDataLink.Control:=Self; FDataLink.OnActiveChange:=@ActiveChange; FDataLink.OnDataChange:=@DataChange; FDataLink.OnUpdateData:=@UpdateData; end; destructor TRxDBCalcEdit.Destroy; begin FreeAndNil(FDataLink); inherited Destroy; end; end.
{======================================================================================================================= RkDBAddress_Common Unit RK Components - Support Source Unit This unit defines common types used by the various TRkAddress*** compound components. Copyright © 1995-2003 by Ray Konopka. All Rights Reserved. =======================================================================================================================} //{$I RkComps.inc} unit RkDBAddress_Common; interface type TRkLabelPosition = ( lpOnLeft, lpOnTop ); TRkEditField = ( efFirstName, efLastName, efAddress1, efAddress2, efCity, efState, efZIP ); TRkEditChangeEvent = procedure( Field: TRkEditField; Text: string ) of object; TRkDataField = string; // Required for property editor override implementation end.
program ejercicio5; { suma los números entre a y b, y retorna el resultado en c } procedure sumar(a, b, c : integer) // No recibe result como parámetro var suma :integer; begin for i := a to b do // La variable i no está declarada suma := suma + i; c := c + suma; end; var result :integer; begin result := 0; readln(a); // La variable no está declarada readln(b); // La variable no está declarada sumar(a, b, 0); write(‘La suma total es ‘, result); // Result nunca se utilizó, sigue valiendo 0 { averigua si el resultado final estuvo entre 10 y 30} ok := (result >= 10) or (result <= 30); // Para cualquier valor de a y b estó da siempre true if (not ok) then write (‘La suma no quedó entre 10 y 30’); end.
unit caTabledQuery; // Модуль: "w:\common\components\rtl\Garant\ComboAccess\caTabledQuery.pas" // Стереотип: "SimpleClass" // Элемент модели: "TcaTabledQuery" MUID: (56C6DB730289) {$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc} interface {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3IntfUses , daTabledQuery , daInterfaces ; type TcaTabledQuery = class(TdaTabledQuery) private f_PGQuery: IdaTabledQuery; f_HTQuery: IdaTabledQuery; protected procedure PrepareTable; override; procedure UnPrepareTable; override; procedure Cleanup; override; {* Функция очистки полей объекта. } function MakeResultSet(Unidirectional: Boolean): IdaResultSet; override; function DoMakeParam(const aParamDesc: IdaParamDescription): IdaParam; override; public constructor Create(const aFactory: IdaTableQueryFactory; const aDataConverter: IdaDataConverter; const aFromClause: IdaFromClause; const aHTQuery: IdaTabledQuery; const aPGQuery: IdaTabledQuery); reintroduce; class function Make(const aFactory: IdaTableQueryFactory; const aDataConverter: IdaDataConverter; const aFromClause: IdaFromClause; const aHTQuery: IdaTabledQuery; const aPGQuery: IdaTabledQuery): IdaTabledQuery; reintroduce; end;//TcaTabledQuery {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) implementation {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3ImplUses , daFromTable , caResultSet , caParam //#UC START# *56C6DB730289impl_uses* //#UC END# *56C6DB730289impl_uses* ; constructor TcaTabledQuery.Create(const aFactory: IdaTableQueryFactory; const aDataConverter: IdaDataConverter; const aFromClause: IdaFromClause; const aHTQuery: IdaTabledQuery; const aPGQuery: IdaTabledQuery); //#UC START# *56C6DC070160_56C6DB730289_var* //#UC END# *56C6DC070160_56C6DB730289_var* begin //#UC START# *56C6DC070160_56C6DB730289_impl* inherited Create(aFactory, aDataConverter, aFromClause); f_HTQuery := aHTQuery; f_PGQuery := aPGQuery; //#UC END# *56C6DC070160_56C6DB730289_impl* end;//TcaTabledQuery.Create class function TcaTabledQuery.Make(const aFactory: IdaTableQueryFactory; const aDataConverter: IdaDataConverter; const aFromClause: IdaFromClause; const aHTQuery: IdaTabledQuery; const aPGQuery: IdaTabledQuery): IdaTabledQuery; var l_Inst : TcaTabledQuery; begin l_Inst := Create(aFactory, aDataConverter, aFromClause, aHTQuery, aPGQuery); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TcaTabledQuery.Make procedure TcaTabledQuery.PrepareTable; //#UC START# *566A892A0191_56C6DB730289_var* //#UC END# *566A892A0191_56C6DB730289_var* begin //#UC START# *566A892A0191_56C6DB730289_impl* f_HTQuery.Prepare; f_PGQuery.Prepare; //#UC END# *566A892A0191_56C6DB730289_impl* end;//TcaTabledQuery.PrepareTable procedure TcaTabledQuery.UnPrepareTable; //#UC START# *566A893B03C7_56C6DB730289_var* //#UC END# *566A893B03C7_56C6DB730289_var* begin //#UC START# *566A893B03C7_56C6DB730289_impl* f_HTQuery.UnPrepare; f_PGQuery.UnPrepare; //#UC END# *566A893B03C7_56C6DB730289_impl* end;//TcaTabledQuery.UnPrepareTable procedure TcaTabledQuery.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_56C6DB730289_var* //#UC END# *479731C50290_56C6DB730289_var* begin //#UC START# *479731C50290_56C6DB730289_impl* f_HTQuery := nil; f_PGQuery := nil; inherited; //#UC END# *479731C50290_56C6DB730289_impl* end;//TcaTabledQuery.Cleanup function TcaTabledQuery.MakeResultSet(Unidirectional: Boolean): IdaResultSet; //#UC START# *56010A7801F2_56C6DB730289_var* //#UC END# *56010A7801F2_56C6DB730289_var* begin //#UC START# *56010A7801F2_56C6DB730289_impl* Result := TcaResultSet.Make(SelectFields, f_HTQuery.OpenResultSet(Unidirectional), f_PGQuery.OpenResultSet(Unidirectional)); //#UC END# *56010A7801F2_56C6DB730289_impl* end;//TcaTabledQuery.MakeResultSet function TcaTabledQuery.DoMakeParam(const aParamDesc: IdaParamDescription): IdaParam; //#UC START# *56E120F00095_56C6DB730289_var* //#UC END# *56E120F00095_56C6DB730289_var* begin //#UC START# *56E120F00095_56C6DB730289_impl* Result := TcaParam.Make((f_HTQuery as IdaComboAccessQueryHelper).AddParam(aParamDesc), (f_PGQuery as IdaComboAccessQueryHelper).AddParam(aParamDesc)); //#UC END# *56E120F00095_56C6DB730289_impl* end;//TcaTabledQuery.DoMakeParam {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) end.
{************************************************************************************************************************** * Classe/Objeto : TAbrangenciaExpressas * Finalidade : pesquisa, alteração, exclusão e inclusão de dados na tabela sistema_abrangencia_expressas * Nível : Model * Autor : Celso Mutti * Data : 12/05/2021 * Versão : 1 * Histórico : 12/05/2021 - Criação - Celso Mutti (1) **************************************************************************************************************************} unit Model.AbrangenciaExpressas; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, System.DateUtils, System.Variants; type TAbrangenciaExpressas = class private FLogradouro : string; FZona : string; FBairro : string; FCliente : integer; FPrazo : string; FCEP : string; FID : integer; FTipo : integer; FAcao : TAcao; FQuery : TFDQuery; FConexao : TConexao; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public constructor Create; property ID : integer read FID write FID; // id do registro chave primaria property CEP : string read FCEP write FCEP; // CEP completo do logradouro property Prazo : string read FPrazo write FPrazo; // Tipo de prazo de entrega ("D + 1 ou D + 0") property Zona : string read FZona write FZona; // Sigla da Zona (I)terminicipal ou (U)rbana property Tipo : integer read FTipo write FTipo; // Código do tipo (0 - não faz, 1 - Leve, 2 - Pesado, 3 - Misto) property Logradouro : string read FLogradouro write FLogradouro; // Descrição do logradouro property Bairro : string read FBairro write FBairro; // Descrição do bairro property Cliente : integer read FCliente write FCliente; // Código do cliente da empresa (0 para todos) property Acao : TAcao read FAcao write FAcao; // Acao de gravação no banco de dados property Query : TFDQuery read FQuery write FQuery; // Query resultado de pesquisa function Search(aParam : array of variant) : boolean; // realiza pesquisa em banco de dados function Save() : Boolean; // salva, exclue dados no banco de dados function GetField(sField : String; sKey : String; sKeyValue : String) : String; // localiza e retorna o valor de um campo de uma tabela procedure SetupSelf(fdQuery : TFDQuery); // atribui os valores dos campos de uma query às propriedades da classe procedure ClearSelf(); // limpa as propriedades da dos campos da tabela da classe end; const // nome da tabela no banco de dados TABLENAME = 'sistema_abrangencia_expressas'; // script de inclusão na tabela SQLINSERT = 'insert into ' + TABLENAME + ' (id_registro, num_cep, des_prazo, dom_zona, cod_tipo, des_logradouro, ' + 'des_bairro, cod_cliente) ' + 'value ' + '(:id_registro, :num_cep, :des_prazo, :dom_zona, :cod_tipo, :des_logradouro, :des_bairro, :cod_cliente)'; // script de alteração de dados na tabela SQLUPDATE = 'update ' + TABLENAME + ' set num_cep = :num_cep, des_prazo = :des_prazo, dom_zona = :dom_zona, ' + 'cod_tipo = :cod_tipo, des_logradouro = :des_logradouro, des_bairro = :des_bairro, cod_cliente = :cod_cliente ' + 'where id_registro = :idregistro'; // script de exclusão da tabela SQLDELETE = 'delete from ' + TABLENAME + ' where id_registro = :idregistro'; // script de pesquisa na tabela SQLSELECT = 'select id_registro, num_cep, des_prazo, dom_zona, cod_tipo, des_logradouro, des_bairro, cod_cliente ' + 'from ' + TABLENAME; implementation { TAbrangenciaExpressas } procedure TAbrangenciaExpressas.ClearSelf; begin FLogradouro := ''; FZona := ''; FBairro := ''; FCliente := 0; FPrazo := ''; FCEP := ''; FID := 0; FTipo := 0; end; constructor TAbrangenciaExpressas.Create; begin FConexao := TConexao.Create; end; function TAbrangenciaExpressas.Delete: Boolean; var FQueryDelete : TFDQuery; begin try Result := False; FQueryDelete := FConexao.ReturnQuery; FQueryDelete.ExecSQL(SQLDELETE, [FID]); if FQueryDelete.RowsAffected = 0 then Exit; Result := True; finally FQueryDelete.Active := False; FQueryDelete.Connection.Connected := False; FQueryDelete.Free end; end; function TAbrangenciaExpressas.GetField(sField, sKey, sKeyValue: String): String; var FQueryField : TFDQuery; begin try Result := ''; FQueryField := FConexao.ReturnQuery; FQueryField.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FQueryField.Open(); if FQueryField.IsEmpty then Exit; Result := FQueryField.FieldByName(sField).AsString; finally FQueryField.Active := False; FQueryField.Connection.Connected := False; FQueryField.Free; end; end; function TAbrangenciaExpressas.Insert: Boolean; var FQueryInsert : TFDQuery; begin try Result := False; FQueryInsert := FConexao.ReturnQuery; FQueryInsert.ExecSQL(SQLINSERT, [FID, FCEP, FPrazo, FZona, FTipo, FLogradouro, FBairro, FCliente]); if FQueryInsert.RowsAffected = 0 then Exit; Result := True; finally FQueryInsert.Active := False; FQueryInsert.Connection.Connected := False; FQueryInsert.Free; end; end; function TAbrangenciaExpressas.Save: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Insert(); Common.ENum.tacAlterar: Result := Update(); Common.ENum.tacExcluir: Result := Delete(); end; end; function TAbrangenciaExpressas.Search(aParam: array of variant): boolean; begin Result := False; if Length(aParam) < 2 then Exit; FQuery := FConexao.ReturnQuery; FQuery.SQL.Add(SQLSELECT); if aParam[0] = 'ID' then begin FQuery.SQL.Add('where id_registro = :id_registro'); FQuery.ParamByName('id_registro').AsInteger := aParam[1]; end else if aParam[0] = 'CEP' then begin FQuery.SQL.Add('where num_cep = :num_cep'); FQuery.ParamByName('num_cep').AsString := aParam[1]; end else if aParam[0] = 'CEPCLIENTE' then begin FQuery.SQL.Add('where num_cep = :num_cep and cod_cliente = :cod_cliente'); FQuery.ParamByName('num_cep').AsString := aParam[1]; FQuery.ParamByName('cod_cliente').AsInteger := aParam[2]; end else if aParam[0] = 'BAIRRO' then begin FQuery.SQL.Add('where des_bairro = :des_bairro'); FQuery.ParamByName('des_bairro').AsString := aParam[1]; end else if aParam[0] = 'FILTRO' then begin if VarToStr(aParam[1]) <> '' then FQuery.SQL.Add('where ' + VarToStr(aParam[1])); end else if aParam[0] = 'APOIO' then begin FQuery.SQL.Clear; FQuery.SQL.Add('select ' + VarToStr(aParam[1]) + ' from ' + TABLENAME + ' where ' + VarToStr(aParam[2])); end; FQuery.Open(); if FQuery.IsEmpty then begin FQuery.Active := False; FQuery.Connection.Connected := False; Exit; end; Result := True; end; procedure TAbrangenciaExpressas.SetupSelf(fdQuery: TFDQuery); begin FLogradouro := fdQuery.FieldByName('des_logradouro').AsString; FZona := fdQuery.FieldByName('dom_zona').AsString; FBairro := fdQuery.FieldByName('des_bairro').AsString; FCliente := fdQuery.FieldByName('cod_cliente').AsInteger; FPrazo := fdQuery.FieldByName('des_prazo').AsString; FCEP := fdQuery.FieldByName('num_cep').AsString; FID := fdQuery.FieldByName('id_registro').AsInteger; FTipo := fdQuery.FieldByName('cod_tipo').AsInteger; end; function TAbrangenciaExpressas.Update: Boolean; var FQueryUpdate : TFDQuery; begin try Result := False; FQueryUpdate := FConexao.ReturnQuery; FQueryUpdate.ExecSQL(SQLUPDATE, [FCEP,FPrazo, FZona, FTipo, FLogradouro, FBairro, FCliente, FID]); if FQueryUpdate.RowsAffected = 0 then Exit; Result := True; finally FQueryUpdate.Active := False; FQueryUpdate.Connection.Connected := False; FQueryUpdate.Free; end; end; end.
unit NotificationService; interface uses JunoApi4Delphi.Interfaces, EventType, Webhook, System.Generics.Collections, System.JSON, RESTRequest4D, System.SysUtils, REST.Types, REST.Json; type TNotificationService = class(TInterfacedObject, iNotificationService) private FParent : iJunoApi4DelphiConig; FAuth : iAuthorizationService; public constructor Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService); destructor Destroy; override; class function New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iNotificationService; function ListaEventTypes : TObjectList<TEventTypes>; function ListaWebhooks : TObjectList<TWebhook>; function CreateWebhook : String; end; implementation CONST NOTIFICATIONS_ENDPOINT = '/notifications'; EVENT_TYPES_ENDPOINT = NOTIFICATIONS_ENDPOINT + '/event-types'; WEBHOOKS_ENDPOINT = NOTIFICATIONS_ENDPOINT + '/webhooks'; WEBHOOKS_TEMPLATED_ENDPOINT = WEBHOOKS_ENDPOINT + '/{id}'; { TNotificationService } constructor TNotificationService.Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService); begin FParent := Parent; FAuth := AuthService; end; function TNotificationService.CreateWebhook: String; begin end; destructor TNotificationService.Destroy; begin inherited; end; function TNotificationService.ListaEventTypes: TObjectList<TEventTypes>; var JsonObj : TJSONObject; jv: TJSONValue; ja : TJSONArray; Event : TEventTypes; I: Integer; begin JsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes( TRequest.New .BaseURL(FParent.ResourceEndpoint + EVENT_TYPES_ENDPOINT) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .Get.Content), 0) as TJSONObject; jv := JsonObj.Get('_embedded').JsonValue; JsonObj := jv as TJSONObject; jv := JsonObj.Get('eventTypes').JsonValue; ja := jv as TJSONArray; Result := TObjectList<TEventTypes>.Create; for I := 0 to ja.Size -1 do begin Result.Add(TEventTypes.Create); JsonObj := (ja.Get(i) as TJSONObject); Result[I].Id := JsonObj.GetValue('id').ToString; Result[I].&Label := JsonObj.GetValue('label').ToString; Result[I].Name := JsonObj.GetValue('name').ToString; Result[I].Status := JsonObj.GetValue('status').ToString; end; end; function TNotificationService.ListaWebhooks: TObjectList<TWebhook>; begin end; class function TNotificationService.New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iNotificationService; begin Result := Self.Create(Parent, AuthService); end; end.
program allSearchingAlgorithms; (*Binary Search | Linear Search*) const size = 20; type arr = array[1..size] of integer; var list : arr; found : boolean; data, pos : integer; procedure insertionSort(var a : arr); var i : integer; position : integer; num : integer; begin for i := 2 to size do begin num := a[i]; position := i; while (position > 1) and (a[position-1] > num) do begin a[position] := a[position-1]; position := position - 1; end; a[position] := num; end; end; procedure generateValues(var a : arr); var i : integer; begin for i := 1 to size do a[i] := random(1000) + 1; insertionSort(a); for i := 1 to size do writeln('a[', i, '] = ', a[i]); end; procedure binarySearch(a : arr; data : integer; var x : boolean; var n : integer); var first, mid, last : integer; begin first := 1; n := -1; last := size; writeln('first':6, 'mid':6, 'last':6); while (not x) and not(last < first) do begin mid := (first + last) div 2; writeln(first:6,mid:6,last:6); readln; if a[mid] > data then last := mid-1 //minus 1 to avoid infinite loops else if a[mid] < data then first := mid+1 else begin x := true; n := mid; end; end; end; function binarySearchV2(a : arr; data : integer; first, last : integer): boolean; var mid : integer; begin mid := (first + last) div 2; if (last >= first) then if a[mid] = data then binarySearchV2 := true else if a[mid] > data then binarySearchV2 := binarySearchV2(a, data, first, mid - 1) else binarySearchV2 := binarySearchV2(a, data, mid + 1, last) else binarySearchV2 := false; end; function binarySearchV3(a : arr; data : integer; first, last : integer): boolean; begin if (last >= first) then if a[(first + last) div 2] = data then binarySearchV3 := true else if a[(first + last) div 2] > data then binarySearchV3 := binarySearchV3(a, data, first, (first + last) div 2 - 1) else binarySearchV3 := binarySearchV3(a, data, (first + last) div 2 + 1, last) else binarySearchV3 := false; end; begin randomize; generateValues(list); repeat found := false; readln(data); binarySearch(list, data, found, pos); writeln(found, ' at ', pos); //writeln(binarySearchV2(list, data, 1, size)); until false; end.
unit XueQiuInfoAppWindow2; interface uses Windows, Messages, BaseFloatWindow, BaseApp, win.thread; type PRT_FloatWindow = ^TRT_FloatWindow; TRT_FloatWindow = record BaseFloatWindow: TRT_BaseFloatWindow; DrawBuyStockCode: AnsiString; BuyStockCode: AnsiString; BuyPrice: AnsiString; SaleStockCode: AnsiString; SalePrice: AnsiString; LastBuyStockCode: AnsiString; LastSaleStockCode: AnsiString; IsFirstGot: Byte; IsTwinkle: Byte; IsTwinkleShow: Boolean; TwinkleThread: TSysWinThread; end; procedure WMAppStart(); function CreateFloatWindow(App: TBaseApp): Boolean; overload; procedure CreateRefreshDataThread(ABaseFloatWindow: PRT_BaseFloatWindow); procedure ShowFloatWindow; overload; implementation uses IniFiles, Sysutils, uiwin_memdc, define_DealItem, UtilsLog, zsHelperMessage, UIBaseWndProc, Classes, JsonTestData, superobject2_define, superobject2_parse, Define_Price, def_basemessage, NetHttpClient, NetHttpClientProc, NetClientIocpProc, HttpProtocol, XueQiuInfoApp; procedure TestClient(); var tmpHttpClient: PNetHttpClient; tmpRet: AnsiString; tmpHeader: AnsiString; tmpCookie: AnsiString; tmpUrl: AnsiString; tmpHttpInfo: THttpUrlInfo; begin tmpHttpClient := GlobalApp.NetMgr.CheckOutHttpClient; if nil <> tmpHttpClient then begin //tmpUrl := 'http://market.finance.sina.com.cn/downxls.php?date=2015-12-03&symbol=sh600000'; //tmpUrl := 'http://xueqiu.com/P/ZH010389'; tmpUrl := 'http://xueqiu.com/cubes/rebalancing/history.json?cube_symbol=ZH010389&count=5&page=1'; //tmpUrl := 'http://127.0.0.1/'; //tmpUrl := 'http://www.163.com'; FillChar(tmpHttpInfo, SizeOf(tmpHttpInfo), 0); if HttpProtocol.HttpUrlInfoParse(tmpUrl, @tmpHttpInfo) then begin tmpCookie := 'Cookie:s=2bxb1yl5un' + '; ' + 'Hm_lvt_1db88642e346389874251b5a1eded6e3=1450080574; ' + '__utma=1.976138422.1450081342.1450081342.1450081342.1; ' + '__utmz=1.1450081342.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ' + 'xq_a_token=726b01d9f1825d1c7cd7c561bd110c037fffeade; ' + 'xq_r_token=6a975187c5c6d7c58b0f99b376864ebec47b46d3'; tmpHeader := HttpClientGenRequestHeader(@tmpHttpInfo, tmpCookie, '', false); tmpRet := NetHttpClientProc.HttpGet(GlobalApp.NetMgr, tmpHttpClient, tmpUrl, tmpHeader, false); end; //tmpRet := NetClientIocpProc.HttpGet(GlobalApp.NetMgr, tmpHttpClient, tmpUrl); end; end; procedure LoadFloatWindowConfig(AFloatWindow: PRT_FloatWindow); var tmpRect: TRect; tmpIni: TIniFile; begin tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try AFloatWindow.LastBuyStockCode := tmpIni.ReadString('stock', 'buy', ''); AFloatWindow.LastSaleStockCode := tmpIni.ReadString('stock', 'sale', ''); AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Left := tmpIni.ReadInteger('win', 'left', 0); AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Top := tmpIni.ReadInteger('win', 'top', 0); Windows.SystemParametersInfo(SPI_GETWORKAREA, 0, @tmpRect, 0); if AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Top > tmpRect.Bottom - 100 then AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Top := tmpRect.Bottom - 100; if AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Left > tmpRect.Right - 100 then AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Left := tmpRect.Right - 100; tmpIni.WriteInteger('win', 'left', AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Left); tmpIni.WriteInteger('win', 'top', AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Top); finally tmpIni.Free; end; end; procedure SaveFloatWindowConfig(AFloatWindow: PRT_FloatWindow); var tmpIni: TIniFile; begin tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try tmpIni.WriteString('stock', 'buy', AFloatWindow.BuyStockCode); tmpIni.WriteString('stock', 'buyprice', AFloatWindow.BuyPrice); tmpIni.WriteString('stock', 'sale', AFloatWindow.SaleStockCode); tmpIni.WriteString('stock', 'saleprice', AFloatWindow.SalePrice); tmpIni.WriteInteger('win', 'left', AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Left); tmpIni.WriteInteger('win', 'top', AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Top); finally tmpIni.Free; end; end; function ThreadProc_Twinkle(AParam: PRT_FloatWindow): HResult; stdcall; var i: integer; begin Result := 0; while 1 = AParam.IsTwinkle do begin for i := 0 to 25 do begin if 0 = AParam.BaseFloatWindow.BaseApp.IsActiveStatus then Break; Sleep(20); end; if 0 = AParam.BaseFloatWindow.BaseApp.IsActiveStatus then Break; AParam.IsTwinkleShow := not AParam.IsTwinkleShow; PostMessage(AParam.BaseFloatWindow.BaseWindow.UIWndHandle, CM_INVALIDATE, 1, 0); end; ExitThread(Result); end; procedure Paint_FloatWindow(ADC: HDC; ABaseFloatWindow: PRT_BaseFloatWindow); var i: integer; tmpX, tmpY: Integer; tmpSize: TSize; tmpHeight: integer; tmpNameWidth: Integer; tmpBuyText: AnsiString; tmpSaleText: AnsiString; tmpOldFont: HFONT; tmpFloatWindow: PRT_FloatWindow; begin tmpNameWidth := 0; tmpBuyText := ''; tmpSaleText := ''; //FillRect(ADC, ABaseFloatWindow.BaseWindow.ClientRect, GetStockObject(BLACK_BRUSH)); tmpFloatWindow := PRT_FloatWindow(ABaseFloatWindow); if nil <> tmpFloatWindow then begin if '' <> tmpFloatWindow.BuyStockCode then tmpBuyText := 'B' + tmpFloatWindow.BuyStockCode + ':' + tmpFloatWindow.BuyPrice; if '' <> tmpFloatWindow.SaleStockCode then tmpSaleText := 'S' + tmpFloatWindow.SaleStockCode + ':' + tmpFloatWindow.SalePrice; if not SameText(tmpFloatWindow.DrawBuyStockCode, tmpFloatWindow.BuyStockCode) then begin if '' <> tmpFloatWindow.DrawBuyStockCode then begin if 0 = tmpFloatWindow.IsTwinkle then begin tmpFloatWindow.IsTwinkle := 1; end; if 1 = tmpFloatWindow.IsTwinkle then begin tmpFloatWindow.IsTwinkleShow := true; if 0 = tmpFloatWindow.TwinkleThread.ThreadHandle then begin tmpFloatWindow.TwinkleThread.ThreadHandle := Windows.CreateThread(nil, 0, @ThreadProc_Twinkle, ABaseFloatWindow, Create_Suspended, ABaseFloatWindow.DataThread.ThreadID); Windows.ResumeThread(tmpFloatWindow.TwinkleThread.ThreadHandle); end; end; end; tmpFloatWindow.DrawBuyStockCode := tmpFloatWindow.BuyStockCode; end; if 1 <> tmpFloatWindow.IsTwinkle then begin tmpFloatWindow.IsTwinkleShow := false; end; if tmpFloatWindow.IsTwinkleShow then begin FrameRect(ADC, ABaseFloatWindow.BaseWindow.ClientRect, GetStockObject(BLACK_BRUSH)); BringWindowToTop(ABaseFloatWindow.BaseWindow.UIWndHandle); end; tmpY := 4; tmpX := 4; tmpOldFont := SelectObject(ADC, ABaseFloatWindow.Font); try SetBkMode(ADC, Transparent); SetTextColor(ADC, $FF000000); tmpHeight := 0; if '' <> tmpBuyText then begin if 0 = tmpHeight then begin Windows.GetTextExtentPoint32A(ADC, PAnsiChar(@tmpBuyText[1]), Length(tmpBuyText), tmpSize); tmpHeight := tmpSize.cy; tmpNameWidth := tmpSize.cx; end; Windows.TextOutA(ADC, tmpX, tmpY, @tmpBuyText[1], Length(tmpBuyText)); tmpY := tmpY + tmpHeight + 4; end; if '' <> tmpSaleText then begin Windows.TextOutA(ADC, tmpX, tmpY, @tmpSaleText[1], Length(tmpSaleText)); end; finally SelectObject(ADC, tmpOldFont); end; end; end; procedure NotifyXueQiuBuyMessage(AParam: PRT_FloatWindow); var tmpWnd: HWND; tmpLParam: string; begin tmpWnd := FindWindow('WndZSHelper', ''); if IsWindow(tmpWnd) then begin SDLog('XueQiuInfoAppWindow.pas', 'buy:' + AParam.BuyStockCode + '/' + AParam.BuyPrice); SDLog('XueQiuInfoAppWindow.pas', 'sale:' + AParam.SaleStockCode + '/' + AParam.SalePrice); PostMessage(tmpWnd, WM_StockBuy_XueQiu, getStockCodePack(AParam.BuyStockCode), getRTPricePackValue(AParam.BuyPrice)); PostMessage(tmpWnd, WM_StockSale_XueQiu, getStockCodePack(AParam.SaleStockCode), getRTPricePackValue(AParam.SalePrice)); end; end; function FloatWindowWndProcA(ABaseFloatWindow: PRT_BaseFloatWindow; AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := 0; case AMsg of WM_Paint: begin WMPaint_FloatWindowWndProcA(ABaseFloatWindow, AWnd); end; WM_LBUTTONDBLCLK: begin SaveLayout(ABaseFloatWindow); ABaseFloatWindow.BaseApp.IsActiveStatus := 0; // sleep wait thread exit Sleep(500); PostQuitMessage(0); end; WM_MOVE: begin Result := DefWindowProcA(AWnd, AMsg, wParam, lParam); end; WM_LBUTTONDOWN: begin if 1 = PRT_FloatWindow(ABaseFloatWindow).IsTwinkle then begin PRT_FloatWindow(ABaseFloatWindow).IsTwinkle := 2; PRT_FloatWindow(ABaseFloatWindow).IsTwinkleShow := false; end; SendMessage(AWnd, WM_SysCommand, SC_Move or HTCaption, 0); end; WM_NCHITTEST: begin Result := HTCLIENT;//CAPTION; end; CM_INVALIDATE: begin Windows.BringWindowToTop(AWnd); Paint_FloatWindow_Layered(ABaseFloatWindow); //Windows.InvalidateRect(AWnd, nil, true); end; else Result := UIBaseWndProc.UIWndProcA(@ABaseFloatWindow.BaseWindow, AWnd, AMsg, wParam, lParam); end; end; function ParseXueQiuData(const AParam: PRT_FloatWindow; const AXueqiuData:string): Boolean; var tmpSO: PJsonObject; begin tmpSO := JsonParseStringW(PWideChar(WideString(AXueqiuData)), False); if nil = tmpSO then exit; if joObject <> tmpSO.DataType then begin end; end; function ParseXueQiuData2(const AParam: PRT_FloatWindow; const AXueqiuData:string): Boolean; begin end; function GetXueQiuCookie(AHttpClient: PNetHttpClient): string; var tmpUrl: AnsiString; tmpHttpInfo: THttpUrlInfo; tmpHeader: AnsiString; tmpRet: string; tmpPos: integer; i: integer; tmpCookieItem: string; tmpCookieKey: string; tmpIsUseCookieKey: Boolean; begin Result := ''; tmpUrl := 'http://xueqiu.com/P/ZH010389'; if not HttpProtocol.HttpUrlInfoParse(tmpUrl, @tmpHttpInfo) then exit; tmpHeader := 'GET' + #32 + tmpHttpInfo.PathName + #32 + 'HTTP/' + '1.1' + #13#10; tmpHeader := tmpHeader + 'Accept:text/html, application/xhtml+xml, */*' + #13#10; tmpHeader := tmpHeader + 'Accept-Language:zh-CN' + #13#10; tmpHeader := tmpHeader + 'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko' + #13#10; tmpHeader := tmpHeader + 'Accept-Encoding:gzip, deflate' + #13#10; tmpHeader := tmpHeader + 'Host:xueqiu.com' + #13#10; tmpHeader := tmpHeader + 'Connection:Keep-Alive' + #13#10; tmpHeader := tmpHeader + #13#10; tmpRet := NetHttpClientProc.HttpGet(GlobalApp.NetMgr, AHttpClient, tmpUrl, tmpHeader, true); if '' <> tmpRet then begin tmpPos := Pos('Set-Cookie', tmpRet); while 0 < tmpPos do begin tmpRet := Copy(tmpRet, tmpPos + Length('Set-Cookie') + 1, maxint); tmpCookieItem := ''; for i := 1 to Length(tmpRet) do begin if (';' = tmpRet[i]) or (#13 = tmpRet[i]) or (#10 = tmpRet[i])then begin tmpCookieItem := Copy(tmpRet, 1, i - 1); Break; end; end; if '' <> tmpCookieItem then begin tmpPos := Pos('=', tmpCookieItem); if 0 < tmpPos then begin tmpCookieKey := Trim(Copy(tmpCookieItem, 1, tmpPos - 1)); tmpIsUseCookieKey := false; if SameText('s', tmpCookieKey) then tmpIsUseCookieKey := true; if SameText('xq_a_token', tmpCookieKey) then tmpIsUseCookieKey := true; if SameText('xq_r_token', tmpCookieKey) then tmpIsUseCookieKey := true; if tmpIsUseCookieKey then begin if '' <> Result then begin Result := Result + ';'; end else begin Result := 'Cookie:'; end; Result := Result + tmpCookieItem; end; end; end; tmpPos := Pos('Set-Cookie', tmpRet); end; end; end; function ThreadProc_RefreshData(AParam: PRT_FloatWindow): HResult; stdcall; var i: integer; tmpPos: integer; tmpHttpClient: PNetHttpClient; tmpUrl: AnsiString; tmpHttpInfo: THttpUrlInfo; tmpHeader: AnsiString; tmpPost: AnsiString; tmpCookie: AnsiString; tmpRet: string; tmpStr: string; tmpIni: TIniFile; begin Result := 0; //(*// tmpHttpClient := GlobalApp.NetMgr.CheckOutHttpClient; tmpCookie := '';//GetXueQiuCookie(tmpHttpClient); tmpUrl := ''; //*) (*// xueqiu login md5(password) areacode=86& password=467E2CDD0CD8B6AAE0446A4CD60DDC97& remember_me=on& telephone=13917781774 Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0 P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT" X-Whom: hzali-ngx-228-73 P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT" X-Whom: hzali-ngx-228-73 {}16 05:05:41 GMT; httpOnly X-RT: 8 Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0 Content-Encoding: gzip P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT" X-Whom: hzali-ngx-228-73 P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT" X-Whom: hzali-ngx-228-73 //*) if '' = tmpCookie then begin tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try tmpCookie := '';//Trim(tmpIni.ReadString('XQ', 'cookie', '')); if '' = tmpCookie then begin tmpCookie := 'Cookie:' + 's=2tto120zt0; ' + 'xq_a_token=5cd91d6495cb27f5bbf5e60e3be4b041329f42b2; ' + 'xq_r_token=00333e2391d332225466a980ddc7b5fb83f0bf8e; ' + 'xqat=5cd91d6495cb27f5bbf5e60e3be4b041329f42b2; ' + 'xq_is_login=1; ' + 'u=1834645252; ' + 'xq_token_expire=Tue%20Feb%2002%202016%2010%3A14%3A08%20GMT%2B0800%20(CST); ' + 'Hm_lvt_1db88642e346389874251b5a1eded6e3=1452219252; ' + 'Hm_lpvt_1db88642e346389874251b5a1eded6e3=1452219252; ' + '__utma=1.1671392041.1452219252.1452219252.1452219252.1; ' + '__utmb=1.1.10.1452219252; ' + '__utmz=1.1452219252.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ' + '__utmt=1; ' + '_sid=5DF0ETDcbmZeNaT8payG4padtveXX1; ' + '__utmc=1; ' + 'bid=fd46228ed88baf1babe077973b522d02_ij51uimj'; end; tmpUrl := Trim(tmpIni.ReadString('XQ', 'url', 'http://xueqiu.com/cubes/rebalancing/history.json?cube_symbol=ZH010389&count=20&page=1')); tmpIni.WriteString('XQ', 'url', tmpUrl); finally tmpIni.Free; end; end; if '' = tmpUrl then exit; //tmpUrl := 'http://xueqiu.com/user/login'; if not HttpProtocol.HttpUrlInfoParse(tmpUrl, @tmpHttpInfo) then exit; //tmpCookie := //'s=c0314lsw8q' + '; ' + //'xq_a_token=51ae43fe10914e301fb74017584c7bee426ed0e6' + '; ' + //'xq_r_token=5630ffe651fb9190c98bb2f9bddcd2284e76463b'; tmpHeader := HttpClientGenRequestHeader(@tmpHttpInfo, tmpCookie, 'POST', true); while True do begin Sleep(20); if nil = AParam.BaseFloatWindow.BaseApp then Break; if 0 <> AParam.BaseFloatWindow.BaseApp.IsActiveStatus then begin if 0 = AParam.IsFirstGot then begin end else begin //if not IsValidStockDealTime then // Continue; end; //tmpUrl := 'http://127.0.0.1/'; //tmpUrl := 'http://www.163.com'; //tmpPost := 'areacode=86&password=467E2CDD0CD8B6AAE0446A4CD60DDC97&remember_me=on&telephone=13917781774'; //tmpRet := NetHttpClientProc.HttpPost(GlobalApp.NetMgr, tmpHttpClient, tmpUrl, tmpHeader, tmpPost, false); tmpRet := JsonTestData.JsonData; //NetHttpClientProc.HttpGet(GlobalApp.NetMgr, tmpHttpClient, tmpUrl, tmpHeader, false); tmpPos := Pos('{', tmpRet); if 0 < tmpPos then begin tmpRet := Copy(tmpRet, tmpPos, MaxInt); for i := Length(tmpRet) downto 1 do begin if '}' = tmpRet[i] then begin tmpRet := Trim(Copy(tmpRet, 1, i + 1)); Break; end; end; end; if 1 = AParam.IsTwinkle then begin // 一旦获取过新的 买卖记录 不必再刷了 Break; end; if not ParseXueQiuData(AParam, tmpRet) then begin tmpCookie := GetXueQiuCookie(tmpHttpClient); tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try if '' <> tmpCookie then begin tmpIni.WriteString('XQ', 'cookie', Trim(tmpCookie)); end; finally tmpIni.Free; end; tmpHeader := HttpClientGenRequestHeader(@tmpHttpInfo, tmpCookie, 'POST', true); Continue; end else begin with Classes.TStringList.Create do try Text := tmpRet; SaveToFile('e:\xueqiu.txt'); finally Free; end; if 0 = AParam.IsFirstGot then begin AParam.IsFirstGot := 1; end; end; if not SameText(AParam.DrawBuyStockCode, AParam.BuyStockCode) then begin PostMessage(AParam.BaseFloatWindow.BaseWindow.UIWndHandle, CM_INVALIDATE, 0, 0); end; end else begin Break; end; for i := 1 to 300 do begin Sleep(20); if nil = AParam.BaseFloatWindow.BaseApp then Break; if 0 = AParam.BaseFloatWindow.BaseApp.IsActiveStatus then Break; end; end; ExitThread(Result); end; procedure CreateRefreshDataThread(ABaseFloatWindow: PRT_BaseFloatWindow); begin ABaseFloatWindow.DataThread.ThreadHandle := Windows.CreateThread(nil, 0, @ThreadProc_RefreshData, ABaseFloatWindow, Create_Suspended, ABaseFloatWindow.DataThread.ThreadID); Windows.ResumeThread(ABaseFloatWindow.DataThread.ThreadHandle); end; function CreateFloatWindow(App: TBaseApp; AFloatWindow: PRT_FloatWindow; AWndProc: TFNWndProc): Boolean; overload; var tmpRegWndClass: TWndClassA; tmpCheckWndClass: TWndClassA; tmpIsRegistered: Boolean; i: integer; tmpDC: HDC; tmpText: AnsiString; tmpSize: TSize; tmpRowCount: integer; tmpLogFontA: TLogFontA; tmpOldFont: HFONT; begin FillChar(tmpRegWndClass, SizeOf(tmpRegWndClass), 0); FillChar(tmpCheckWndClass, SizeOf(tmpCheckWndClass), 0); if not IsWindow(AFloatWindow.BaseFloatWindow.BaseWindow.UIWndHandle) then begin FillChar(AFloatWindow^, SizeOf(TRT_FloatWindow), 0); end; AFloatWindow.BaseFloatWindow.BaseApp := App; AFloatWindow.BaseFloatWindow.OnPaint := Paint_FloatWindow; FillChar(tmpLogFontA, SizeOf(tmpLogFontA), 0); tmpLogFontA.lfHeight := 12; tmpLogFontA.lfHeight := 10; tmpLogFontA.lfWidth := 0; tmpLogFontA.lfFaceName := 'MS Sans Serif'; tmpLogFontA.lfCharSet := DEFAULT_CHARSET; tmpLogFontA.lfPitchAndFamily := FIXED_PITCH; AFloatWindow.BaseFloatWindow.Font := Windows.CreateFontIndirectA(tmpLogFontA); LoadFloatWindowConfig(AFloatWindow); tmpRegWndClass.style := CS_VREDRAW or CS_HREDRAW or CS_DBLCLKS; tmpRegWndClass.hInstance := HInstance; //tmpRegWndClass.hbrBackground := GetStockObject(GRAY_BRUSH); tmpRegWndClass.hbrBackground := GetStockObject(WHITE_BRUSH); tmpRegWndClass.hCursor := LoadCursorA(0, IDC_ARROW); tmpRegWndClass.lpfnWndProc := AWndProc; tmpRegWndClass.lpszClassName := 'StockFloater1'; tmpIsRegistered := Windows.GetClassInfoA(HInstance, tmpRegWndClass.lpszClassName, tmpCheckWndClass); if tmpIsRegistered then begin if tmpCheckWndClass.lpfnWndProc <> AWndProc then begin Windows.UnregisterClass(tmpRegWndClass.lpszClassName, HInstance); tmpIsRegistered := false; end; end; if not tmpIsRegistered then begin Windows.RegisterClassA(tmpRegWndClass); end; AFloatWindow.BaseFloatWindow.BaseWindow.Style := WS_POPUP; AFloatWindow.BaseFloatWindow.BaseWindow.ExStyle := WS_EX_TOOLWINDOW or WS_EX_LAYERED or WS_EX_TOPMOST; tmpDC := GetDC(0); try tmpOldFont := SelectObject(tmpDC, AFloatWindow.BaseFloatWindow.Font); try tmpText := 'B600000:100.00'; Windows.GetTextExtentPoint32A(tmpDC, PAnsiChar(@tmpText[1]), Length(tmpText), tmpSize); finally SelectObject(tmpDC, tmpOldFont); end; finally ReleaseDC(0, tmpDC); end; if 0 < tmpSize.cx then begin AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Right := tmpSize.cx + 8; end else begin AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Right := 80; end; if 0 < tmpSize.cy then begin tmpRowCount := 2; AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Bottom := tmpRowCount * (tmpSize.cy + 4) + 4; end; if 10 > AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Bottom then begin AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Bottom := 10; end; UpdateMemDC(@AFloatWindow.BaseFloatWindow.MemDC, AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Right, AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Bottom); AFloatWindow.BaseFloatWindow.BaseWindow.UIWndHandle := Windows.CreateWindowExA( AFloatWindow.BaseFloatWindow.BaseWindow.ExStyle, tmpRegWndClass.lpszClassName, '', AFloatWindow.BaseFloatWindow.BaseWindow.Style {+ 0}, AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Left, AFloatWindow.BaseFloatWindow.BaseWindow.WindowRect.Top, AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Right, AFloatWindow.BaseFloatWindow.BaseWindow.ClientRect.Bottom, 0, 0, HInstance, nil); Result := IsWindow(AFloatWindow.BaseFloatWindow.BaseWindow.UIWndHandle); end; procedure ShowFloatWindow(ABaseFloatWindow: PRT_BaseFloatWindow); overload; begin ShowWindow(ABaseFloatWindow.BaseWindow.UIWndHandle, SW_SHOW); UpdateWindow(ABaseFloatWindow.BaseWindow.UIWndHandle); Paint_FloatWindow_Layered(ABaseFloatWindow); CreateRefreshDataThread(ABaseFloatWindow); end; var Global_FloatWindow_1: TRT_FloatWindow; function FloatWndProcA_1(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin Result := FloatWindowWndProcA(@Global_FloatWindow_1, AWnd, AMsg, wParam, lParam); end; function CreateFloatWindow(App: TBaseApp): Boolean; overload; begin Result := CreateFloatWindow(App, @Global_FloatWindow_1, @FloatWndProcA_1); end; procedure ShowFloatWindow; begin ShowFloatWindow(@Global_FloatWindow_1); end; procedure WMAppStart(); begin if CreateFloatWindow(GlobalBaseApp) then begin ShowFloatWindow; end; end; end.
unit UnaInstancia; { Taken from Delphi 2 Developers Guide by Pacheco and Teixeira With heavy Modifications. Usage: In the Project source change to the following if InitInstance then begin Application.Initialize; Application.CreateForm(TFrmSelProject, FrmSelProject); Application.Run; end; That's all folks ( I hope ;() } interface uses Forms, Windows, Dialogs, SysUtils; const MI_NO_ERROR = 0; MI_FAIL_SUBCLASS = 1; MI_FAIL_CREATE_MUTEX = 2; { Query this function to determine if error occurred in startup. } { Value will be one or more of the MI_* error flags. } function GetMIError: Integer; Function InitInstance : Boolean; implementation const UniqueAppStr : PChar = ''; {Change for every Application} var MessageId: Integer; WProc: TFNWndProc = Nil; MutHandle: THandle = 0; MIError: Integer = 0; function GetMIError: Integer; begin Result := MIError; end; function NewWndProc(Handle: HWND; Msg: Integer; wParam, lParam: Longint): Longint; StdCall; begin { If this is the registered message... } if Msg = MessageID then begin { if main form is minimized, normalize it } { set focus to application } if IsIconic(Application.Handle) then begin Application.MainForm.WindowState := wsNormal; ShowWindow(Application.Mainform.Handle, sw_restore); end; SetForegroundWindow(Application.MainForm.Handle); end { Otherwise, pass message on to old window proc } else Result := CallWindowProc(WProc, Handle, Msg, wParam, lParam); end; procedure SubClassApplication; begin { We subclass Application window procedure so that } { Application.OnMessage remains available for user. } WProc := TFNWndProc(SetWindowLong(Application.Handle, GWL_WNDPROC, Longint(@NewWndProc))); { Set appropriate error flag if error condition occurred } if WProc = Nil then MIError := MIError or MI_FAIL_SUBCLASS; end; procedure DoFirstInstance; begin SubClassApplication; MutHandle := CreateMutex(Nil, False, UniqueAppStr); if MutHandle = 0 then MIError := MIError or MI_FAIL_CREATE_MUTEX; end; procedure BroadcastFocusMessage; { This is called when there is already an instance running. } var BSMRecipients: DWORD; begin { Don't flash main form } Application.ShowMainForm := False; { Post message and inform other instance to focus itself } BSMRecipients := BSM_APPLICATIONS; BroadCastSystemMessage(BSF_IGNORECURRENTTASK or BSF_POSTMESSAGE, @BSMRecipients, MessageID, 0, 0); end; Function InitInstance : Boolean; begin MutHandle := OpenMutex(MUTEX_ALL_ACCESS, False, UniqueAppStr); if MutHandle = 0 then begin { Mutex object has not yet been created, meaning that no previous } { instance has been created. } // ShowMessage( UniqueAppStr + ' ' + IntToStr( MutHandle )); ShowWindow(Application.Handle, SW_ShowNormal); Application.ShowMainForm:=True; DoFirstInstance; result := True; end else begin BroadcastFocusMessage; result := False; end; end; initialization begin UniqueAppStr := PChar( Application.Exename ); MessageID := RegisterWindowMessage(UniqueAppStr); ShowWindow(Application.Handle, SW_Hide); Application.ShowMainForm:=FALSE; end; finalization begin if WProc <> Nil then { Restore old window procedure } SetWindowLong(Application.Handle, GWL_WNDPROC, LongInt(WProc)); end; end.
unit uProgressForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TProgressForm = class(TForm) lblProgressText: TLabel; pb1: TProgressBar; btn1: TButton; procedure btn1Click(Sender: TObject); private FAbortFlag: Boolean; { Private declarations } public { Public declarations } end; function ShowProgress(AMessageText: String; APosition: Integer; ATotal: Integer; AShowAbortButton : Boolean = True): Boolean; procedure HideProgress; var ProgressForm: TProgressForm; implementation {$R *.dfm} function ShowProgress(AMessageText: String; APosition: Integer; ATotal: Integer; AShowAbortButton : Boolean = True): Boolean; begin if ProgressForm = nil then begin ProgressForm := TProgressForm.Create(Application); end; ProgressForm.lblProgressText.Caption := AMessageText; ProgressForm.pb1.Max := ATotal; ProgressForm.pb1.Position := APosition; ProgressForm.Show; ProgressForm.btn1.Visible := AShowAbortButton; Application.ProcessMessages; Result := not ProgressForm.FAbortFlag; end; procedure HideProgress; begin if ProgressForm <> nil then begin ProgressForm.Free; ProgressForm := nil; end; Application.ProcessMessages; end; procedure TProgressForm.btn1Click(Sender: TObject); begin FAbortFlag := True; end; end.
{$MODE OBJFPC} {$M 30000000} {$DEFINE RELEASE} {$R-,Q-,S-,I-} {$OPTIMIZATION LEVEL2} {$INLINE ON} program Traffic; const InputFile = 'TRAFFIC.INP'; OutputFile = 'TRAFFIC.OUT'; maxN = Round(1E5); maxM = Round(2E5); type TEdge = record x, y: Integer; link: Integer; end; TMarkArr = array[1..maxN] of Boolean; var n, m, savem: Integer; e: array[1..maxM + maxN] of TEdge; head: array[1..maxN] of Integer; num, low, stack, lab: array[1..maxN] of Integer; top: Integer; noI, noO: TMarkArr; fi, fo: TextFile; procedure Enter; var i: Integer; begin ReadLn(fi, n, m); for i := 1 to m do with e[i] do ReadLn(fi, x, y); savem := m; end; procedure BuildIncidentLists; var i: Integer; begin FillDWord(head[1], n, 0); for i := 1 to m do with e[i] do begin link := head[x]; head[x] := i; end; end; procedure Push(u: Integer); inline; begin Inc(top); stack[top] := u; end; function Pop: Integer; inline; begin Result := stack[top]; Dec(top); end; procedure Minimize(var target: Integer; value: Integer); inline; begin if target > value then target := value; end; procedure FindSCCs; var count: Integer; i: Integer; procedure Visit(u: Integer); var i: Integer; begin Inc(count); num[u] := count; low[u] := maxN + 1; Push(u); i := head[u]; while i <> 0 do with e[i] do begin if num[y] = 0 then begin Visit(y); Minimize(low[u], low[y]); end else if num[y] > 0 then Minimize(low[u], num[y]); i := link; end; if low[u] >= num[u] then repeat i := Pop; lab[i] := u; num[i] := -1; until i = u; end; begin FillDWord(num[1], n, 0); top := 0; count := 0; for i := 1 to n do if num[i] = 0 then Visit(i); end; procedure FindNoIO; var i: Integer; begin for i := 1 to n do begin noI[i] := lab[i] = i; noO[i] := lab[i] = i; end; for i := 1 to m do with e[i] do if lab[x] <> lab[y] then begin noO[lab[x]] := False; noI[lab[y]] := False; end; end; procedure InverseDirections; var i: Integer; btemp: Boolean; itemp: Integer; begin for i := 1 to m do with e[i] do begin itemp := x; x := y; y := itemp; end; BuildIncidentLists; for i := 1 to n do begin btemp := noI[i]; noI[i] := noO[i]; noO[i] := btemp; end; end; procedure AddEdge(u, v: Integer); begin Inc(m); with e[m] do begin x := u; y := v; link := head[x]; head[x] := m; end; noI[v] := False; noO[u] := False; end; procedure AddMoreEdges; var p, q, black, white, oldtop: Integer; procedure Visit(u: Integer); var i: Integer; begin if noO[u] then Push(u); num[u] := 1; i := head[u]; while i <> 0 do with e[i] do begin if num[y] = 0 then Visit(y); i := link; end; end; begin FillDWord(num[1], n, 0); top := 0; black := 0; for q := 1 to n do if noI[q] then begin oldtop := top; Visit(q); if black = 0 then black := q else if oldtop <> top then begin p := Pop; AddEdge(p, black); black := q; end; end; InverseDirections; FillDWord(num[1], n, 0); top := 0; white := 0; for q := 1 to n do if noI[q] then begin oldtop := top; Visit(q); if white = 0 then white := q else if oldtop <> top then begin p := Pop; AddEdge(p, white); white := q; end; end; if not noO[black] then black := stack[top]; //white: NoIn den duoc moi dinh khac //black: NoOut moi dinh khac den duoc AddEdge(black, white); q := 0; for p := 1 to n do if noI[p] then begin Inc(q); while (q <= n) and not noO[q] do Inc(q); if q <= n then AddEdge(q, p); end; for q := 1 to n do begin if noI[q] then AddEdge(black, q); if noO[q] then AddEdge(q, white); end; end; procedure Solve; var SCount, TCount, ACount: Integer; i: Integer; begin BuildIncidentLists; FindSCCs; FindNoIO; SCount := 0; TCount := 0; ACount := 0; for i := 1 to n do begin if noI[i] then Inc(SCount); if noO[i] then Inc(TCount); if noI[i] and noO[i] then Inc(ACount); end; if (SCount = 1) and (TCount = 1) and (ACount = 1) then Exit; AddMoreEdges; end; procedure PrintResult; var i: Integer; begin WriteLn(fo, m - savem); for i := savem + 1 to m do with e[i] do WriteLn(fo, y, ' ', x); end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try Enter; Solve; PrintResult; finally CloseFile(fi); CloseFile(fo); end; end.
unit Exceptions.EFieldNameMustBeUniqueException; interface uses System.SysUtils; type EFieldNameMustBeUniqueException = class(Exception) const FIELD_NAME_MUST_BE_UNIQUE_MESSAGE = 'Field Name must be unique'; end; implementation end.
namespace Sugar; interface uses Sugar.IO; type TargetPlatform = public enum(Net, Java, macOS, OSX = macOS, iOS, tvOS, watchOS, Android, WinRT, WindowsPhone); CompilerMode = public enum(Echoes, Toffee, Cooper, Island); CompilerSubMode = public enum(NetFull, NetCore, WinRT, WindowsPhone, macOS, iOS, tvOS, watchOS, PlainJava, Android, Windows, Linux); OperatingSystem = public enum(Unknown, Windows, Linux, macOS, iOS, tvOS, watchOS, Android, WindowsPhone, Xbox); Environment = public static class private class method GetNewLine: Sugar.String; class method GetUserName: Sugar.String; class method GetOS: OperatingSystem; class method GetOSName: Sugar.String; class method GetOSVersion: Sugar.String; class method GetTargetPlatform: Sugar.TargetPlatform; class method GetTargetPlatformName: Sugar.String; class method GetCompilerSubMode: CompilerSubMode; {$IF ECHOES} [System.Runtime.InteropServices.DllImport("libc")] class method uname(buf: IntPtr): Integer; external; class method unameWrapper: String; class var unameResult: String; {$ENDIF} public property NewLine: String read GetNewLine; property UserName: String read GetUserName; property OS: OperatingSystem read GetOS; property OSName: String read GetOSName; property OSVersion: String read GetOSVersion; property TargetPlatform: TargetPlatform read GetTargetPlatform; property TargetPlatformName: String read GetTargetPlatformName; property CompilerMode: CompilerMode read {$IF ECHOES}CompilerMode.Echoes{$ELSEIF TOFFEE}CompilerMode.Toffee{$ELSEIF COOPER}CompilerMode.Cooper{$ELSEIF ISLAND}CompilerMode.Island{$ENDIF}; property CompilerSubMode: CompilerSubMode read GetCompilerSubMode; property ApplicationContext: {$IF ANDROID}android.content.Context{$ELSE}Object{$ENDIF} read write; method GetEnvironmentVariable(Name: String): String; method CurrentDirectory: String; end; implementation class method Environment.GetEnvironmentVariable(Name: String): String; begin {$IF COOPER} exit System.getenv(Name); {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} raise new SugarNotSupportedException("GetEnvironmentVariable not supported on this platfrom"); {$ELSEIF ECHOES} exit System.Environment.GetEnvironmentVariable(Name); {$ELSEIF TOFFEE} exit Foundation.NSProcessInfo.processInfo:environment:objectForKey(Name); {$ENDIF} end; class method Environment.GetNewLine: String; begin {$IF COOPER} exit System.getProperty("line.separator"); {$ELSEIF ECHOES} exit System.Environment.NewLine; {$ELSEIF TOFFEE} exit Sugar.String(#10); {$ENDIF} end; class method Environment.GetUserName: String; begin {$IF ANDROID} SugarAppContextMissingException.RaiseIfMissing; var Manager := android.accounts.AccountManager.get(ApplicationContext); var Accounts := Manager.Accounts; if Accounts.length = 0 then exit ""; exit Accounts[0].name; {$ELSEIF COOPER} exit System.getProperty("user.name"); {$ELSEIF WINDOWS_PHONE} exit Windows.Networking.Proximity.PeerFinder.DisplayName; {$ELSEIF NETFX_CORE} exit Windows.System.UserProfile.UserInformation.GetDisplayNameAsync.Await; {$ELSEIF ECHOES} exit System.Environment.UserName; {$ELSEIF OSX} exit Foundation.NSUserName; {$ELSEIF IOS} exit UIKit.UIDevice.currentDevice.name; {$ELSEIF WATCHOS} exit "Apple Watch"; {$ELSEIF tvOS} exit "Apple TV"; {$ENDIF} end; class method Environment.GetOS: OperatingSystem; begin {$IF ANDROID} exit OperatingSystem.Android {$ELSEIF COOPER} var lOSName := Sugar.String(System.getProperty("os.name")):ToLowerInvariant; if lOSName.Contains("windows") then exit OperatingSystem.Windows else if lOSName.Contains("linux") then exit OperatingSystem.Linux else if lOSName.Contains("mac") then exit OperatingSystem.macOS else exit OperatingSystem.Unknown; {$ELSEIF WINDOWS_PHONE} exit OperatingSystem.WindowsPhone; {$ELSEIF NETFX_CORE} exit OperatingSystem.Windows {$ELSEIF ECHOES} case System.Environment.OSVersion.Platform of PlatformID.WinCE, PlatformID.Win32NT, PlatformID.Win32S, PlatformID.Win32Windows: exit OperatingSystem.Windows; PlatformID.Xbox: exit OperatingSystem.Xbox; else begin case unameWrapper() of "Linux": exit OperatingSystem.Linux; "Darwin": exit OperatingSystem.macOS; else exit OperatingSystem.Unknown; end; end; end; {$ELSEIF TOFFEE} {$IF OSX} exit OperatingSystem.macOS; {$ELSEIF IOS} exit OperatingSystem.iOS; {$ELSEIF WATCHOS} exit OperatingSystem.watchOS; {$ELSEIF TVOS} exit OperatingSystem.tvOS; {$ENDIF} {$ELSEIF ISLAND} {$IF WINDOWS} exit OperatingSystem.Windows; {$ELSEIF IOS} exit OperatingSystem.Linux; {$ENDIF} {$ENDIF} end; {$IF ECHOES} class method Environment.unameWrapper: String; begin if not assigned(unameResult) then begin var lBuffer := IntPtr.Zero; try lBuffer := System.Runtime.InteropServices.Marshal.AllocHGlobal(8192); if uname(lBuffer) = 0 then unameResult := System.Runtime.InteropServices.Marshal.PtrToStringAnsi(lBuffer); except finally if lBuffer ≠ IntPtr.Zero then System.Runtime.InteropServices.Marshal.FreeHGlobal(lBuffer); end; end; result := unameResult; end; {$ENDIF} class method Environment.GetOSName: String; begin {$IF COOPER} exit System.getProperty("os.name"); {$ELSEIF WINDOWS_PHONE} exit System.Environment.OSVersion.Platform.ToString(); {$ELSEIF NETFX_CORE} exit "Microsoft Windows NT 6.2"; {$ELSEIF ECHOES} exit System.Environment.OSVersion.Platform.ToString(); {$ELSEIF TOFFEE} {$IF OSX} exit "macOS"; {$ELSEIF IOS} exit "iOS"; {$ELSEIF WATCHOS} exit "watchOS"; {$ELSEIF TVOS} exit "tvOS"; {$ENDIF} {$ELSEIF ISLAND} {$IF WINDOWS} exit "Windows"; {$ELSEIF IOS} exit "Linux"; {$ENDIF} {$ENDIF} end; class method Environment.GetOSVersion: String; begin {$IF COOPER} System.getProperty("os.version"); {$ELSEIF WINDOWS_PHONE} exit System.Environment.OSVersion.Version.ToString; {$ELSEIF NETFX_CORE} exit "6.2"; {$ELSEIF ECHOES} exit System.Environment.OSVersion.Version.ToString; {$ELSEIF TOFFEE} exit NSProcessInfo.processInfo.operatingSystemVersionString; {$ENDIF} end; class method Environment.GetTargetPlatform: TargetPlatform; begin exit{$IF ANDROID} TargetPlatform.Android {$ELSEIF COOPER} TargetPlatform.Java {$ELSEIF WINDOWS_PHONE} TargetPlatform.WindowsPhone {$ELSEIF NETFX_CORE} TargetPlatform.WinRT {$ELSEIF ECHOES} TargetPlatform.Net {$ELSEIF OSX} TargetPlatform.OSX {$ELSEIF IOS} TargetPlatform.iOS {$ELSEIF WATCHOS} TargetPlatform.watchOS {$ELSEIF TVOS} TargetPlatform.tvOS {$ENDIF}; end; class method Environment.GetTargetPlatformName: String; begin exit{$IF ANDROID} "Android" {$ELSEIF COOPER} "Java" {$ELSEIF WINDOWS_PHONE} "Windows Phone Runtime" {$ELSEIF NETFX_CORE} "Windows Runtime" {$ELSEIF ECHOES} ".NET" {$ELSEIF OSX} "Cocoa" {$ELSEIF IOS or WATCHIOS or TVOS} "Cocoa Touch" {$ENDIF}; end; class method Environment.GetCompilerSubMode: CompilerSubMode; begin {$IF COOPER} {$IF ANDROID} exit CompilerSubMode.Android {$ELSE} exit CompilerSubMode.PlainJava; {$ENDIF} {$ELSEIF ECHOES} {$IF WINDOWS_PHONE} exit CompilerSubMode.WindowsPhone; {$ELSEIF NETFX_CORE} exit CompilerSubMode.WinRT; {$ELSE} exit CompilerSubMode.NetFull; {$ENDIF} {$ELSEIF TOFFEE} {$IF OSX} exit CompilerSubMode.macOS; {$ELSEIF IOS} exit CompilerSubMode.iOS; {$ELSEIF WATCHOS} exit CompilerSubMode.watchOS; {$ELSEIF TVOS} exit CompilerSubMode.tvOS; {$ENDIF} {$ELSEIF ISLAND} {$IF WINDOWS} exit CompilerSubMode.Windows; {$ELSEIF LINUX} exit CompilerSubMode.Linux; {$ELSE} {$ERROR Unsupported CompilerSubMode} {$ENDIF} {$ELSE} {$ERROR Unsupported CompilerMode} {$ENDIF} end; class method Environment.CurrentDirectory(): String; begin {$IF COOPER} exit System.getProperty("user.dir"); {$ELSEIF NETFX_CORE} exit Windows.Storage.ApplicationData.Current.LocalFolder.Path; {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} exit System.Environment.CurrentDirectory; {$ELSEIF ECHOES} exit System.Environment.CurrentDirectory; {$ELSEIF TOFFEE} exit Foundation.NSFileManager.defaultManager().currentDirectoryPath; {$ENDIF} end; end.
{ rxconst unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxconst; interface {$I RX.INC} uses LMessages, Controls; const RX_VERSION = $0002004B; { 2.75 } const { Command message for Speedbar editor } CM_SPEEDBARCHANGED = CM_BASE + 80; { Command message for TRxSpeedButton } CM_RXBUTTONPRESSED = CM_BASE + 81; { Command messages for TRxWindowHook } CM_RECREATEWINDOW = CM_BASE + 82; CM_DESTROYHOOK = CM_BASE + 83; { Notify message for TRxTrayIcon } CM_TRAYICON = CM_BASE + 84; const crHand = TCursor(14000); crDragHand = TCursor(14001); //const //{ TBitmap.GetTransparentColor from GRAPHICS.PAS uses this value } // PaletteMask = $02000000; resourcestring sBrowse = 'Browse'; sDefaultFilter = 'All files (*.*)|*.*'; sDateDlgTitle = 'Select a Date'; sNextYear = 'Next Year|'; sNextMonth = 'Next Month|'; sPrevYear = 'Previous Year|'; sPrevMonth = 'Previous Month|'; sNotImplemented = 'Function not yet implemented'; sFileNotExec = 'File specified is not an executable file, dynamic-link library, or icon file'; sLoadLibError = 'Could not load ''%s'' library'; sDetails = 'Details'; sWindowsIcoFiles = 'Windows Ico files (*.ico)|*.ico|All files (*.*)|*.*'; sToCurDate = 'Set current date'; //TDualListDialog SDualListSrcCaption = 'Source'; SDualListDestCaption = 'Destination'; SDualListCaption = 'Dual list dialog'; //TToolPanelSetupForm sToolPanelSetup = 'Tool panel setup'; sVisibleButtons = 'Visible buttons'; sOptions = 'Options'; sAvaliableButtons = 'Avaliable buttons'; sShowCaption = 'Show caption'; sToolBarStyle = 'Tool bar style'; sToolBarStyle1 = 'Standart'; sToolBarStyle2 = 'Windows XP'; sToolBarStyle3 = 'Native'; sFlatButtons = 'Flat buttons'; sTransparent = 'Transparent'; sShowHint = 'Show hint'; sButtonAlign = 'Button align'; sButtonAlign1 = 'None'; sButtonAlign2 = 'Left'; sButtonAlign3 = 'Rignt'; sGTKWidgetSet = 'GTK widget set'; sGTK2WidgetSet = 'GTK 2 widget set'; sWin32_64WidgetSet = 'Win32/Win64 widget set'; sWinCEWidgetSet = 'WinCE widget set'; sCarbonWidgetSet = 'Carbon widget set'; sQTWidgetSet = 'QT widget set'; sFpGUIWidgetSet = 'FpGUI widget set'; sOtherGUIWidgetSet = 'Other gui'; sAppVersion = 'Version : '; sLCLVersion = 'LCL Version: '; sFpcVersion = 'FPC version : '; sTargetCPU = 'Target CPU : '; sTargetOS = 'Target OS : '; sBuildDate = 'Build date : '; sAbout = 'About'; sGeneral = 'General'; sLicense = 'License'; SOutOfRange = 'Out of range %d %d %d %d'; { TRxHistoryNavigator } sHistoryDesc = 'History - "%s"'; { RxCloseFormValidator } sCloseValidError = 'Error. Expected vailes...'; sReqValue = 'Error. Expected value for filed %s.'; sExptControlNotFound = 'Control not found in validate %s.'; { RxMDI } sCloseWindows = 'Close window'; sCloseAllExceptThis = 'Close all except this'; sCloseAllWindows = 'Close all windows'; implementation end.
unit db_dealclass; interface uses BaseDataSet, define_dealclass, QuickList_DealClass; type TDBDealClassDictionary = class(TBaseDataSetAccess) protected fDealClassList: TDealClassList; function GetRecordCount: Integer; override; function GetRecordItem(AIndex: integer): Pointer; override; function GetItem(AIndex: integer): PRT_DefClass; overload; function GetItem(ACode: string): PRT_DefClass; overload; public constructor Create(ADBType: integer); reintroduce; destructor Destroy; override; class function DataTypeDefine: integer; override; procedure Sort; override; procedure Clear; override; function AddDealClass(ADataSrc: integer; AId: integer; AName: AnsiString): PRT_DefClass; function CheckOutDealClass(ADataSrc: integer; AId: integer; AName: AnsiString): PRT_DefClass; function DealClassByIndex(AIndex: integer): PRT_DefClass; property Items[AIndex: integer]: PRT_DefClass read GetItem; property Item[ACode: string]: PRT_DefClass read GetItem; end; implementation uses define_datasrc, QuickSortList, define_dealstore_file; constructor TDBDealClassDictionary.Create(ADBType: integer); begin inherited Create(ADBType, 0); fDealClassList := TDealClassList.Create; fDealClassList.Duplicates := QuickSortList.lstDupAccept; end; destructor TDBDealClassDictionary.Destroy; begin Clear; fDealClassList.Free; inherited; end; class function TDBDealClassDictionary.DataTypeDefine: integer; begin Result := DataType_Class; end; function TDBDealClassDictionary.GetRecordItem(AIndex: integer): Pointer; begin Result := Pointer(fDealClassList.DealClass[AIndex]); end; function TDBDealClassDictionary.GetItem(AIndex: integer): PRT_DefClass; begin Result := GetRecordItem(AIndex); end; function TDBDealClassDictionary.GetItem(ACode: string): PRT_DefClass; begin Result := nil; end; function TDBDealClassDictionary.GetRecordCount: integer; begin Result := fDealClassList.Count; end; procedure TDBDealClassDictionary.Sort; begin fDealClassList.Sort; end; procedure TDBDealClassDictionary.Clear; var i: integer; tmpDealClass: PRT_DefClass; begin for i := fDealClassList.Count - 1 downto 0 do begin tmpDealClass := fDealClassList.DealClass[i]; FreeMem(tmpDealClass); end; fDealClassList.Clear; end; function TDBDealClassDictionary.AddDealClass(ADataSrc: integer; AId: integer; AName: AnsiString): PRT_DefClass; begin Result := CheckOutDefClass(nil); if nil <> Result then begin Result.DataSrc := ADataSrc; Result.Id := AId; Result.Name := AName; fDealClassList.AddDealClass(AId, Result); end; end; function TDBDealClassDictionary.DealClassByIndex(AIndex: integer): PRT_DefClass; begin Result := GetRecordItem(AIndex); end; function TDBDealClassDictionary.CheckOutDealClass(ADataSrc: integer; AId: integer; AName: AnsiString): PRT_DefClass; begin Result := nil; //FindDealClassByCode(AMarketCode + AStockCode); if nil = Result then begin Result := AddDealClass(ADataSrc, AId, AName); end; end; end.
unit MarkAddressAsDetectedAsDepartedUnit; interface uses SysUtils, BaseExampleUnit; type TMarkAddressAsDetectedAsDeparted = class(TBaseExample) public procedure Execute(RouteId: String; RouteDestinationId: integer; IsDeparted: boolean); end; implementation procedure TMarkAddressAsDetectedAsDeparted.Execute(RouteId: String; RouteDestinationId: integer; IsDeparted: boolean); var ErrorString: String; begin Route4MeManager.Address.MarkAsDetectedAsDeparted( RouteId, RouteDestinationId, IsDeparted, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then WriteLn('MarkAddressAsDetectedAsDeparted executed successfully') else WriteLn(Format('MarkAddressAsDetectedAsDeparted error: "%s"', [ErrorString])); end; end.
unit adMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, l3StringList, l3Types, adEngine, OvcBase, afwControlPrim, afwBaseControl, afwControl, afwInputControl, vtLister, StdCtrls, l3Interfaces, ComCtrls; type TMainForm = class(TForm) btnAdd: TButton; btnDelete: TButton; lstItems: TvtLister; btnDistribute: TButton; btnRestore: TButton; ProgressBar: TProgressBar; lblDisp: TLabel; procedure FormDestroy(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnDistributeClick(Sender: TObject); procedure btnRestoreClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lstItemsActionElement(Sender: TObject; Index: Integer); procedure lstItemsCountChanged(Sender: TObject; NewCount: Integer); procedure lstItemsGetItemColor(Sender: TObject; Index: Integer; var FG, BG: TColor); procedure lstItemsGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); private f_CurProcMsg: AnsiString; { Private declarations } f_Manager: TadManager; procedure AddNewItem; procedure DispMsg(const aMsg: AnsiString; aIsError: Boolean = False); procedure DoDistribute; procedure DoProgress(aState: Byte; aValue: Long; const aMsg: AnsiString = ''); procedure DoRestore; function EditItem(anItem: TadItem): Boolean; procedure EnableUI(Value: Boolean); function GetArchiveFolder: AnsiString; function GetDataFilename: AnsiString; function GetNewArchiveFilename: AnsiString; procedure SendNotificationEmail(const aDate: TDateTime); function ShowErrorsBox(const aTitle, aText: AnsiString; const aErrList: Tl3StringList; aYesNo: Boolean): Integer; procedure UpdateButtons; public procedure UpdateLister; { Public declarations } end; var MainForm: TMainForm; implementation uses l3Base, l3String, l3FileUtils, l3IniFile, l3Filer, l3ShellUtils, adItemEdit, adErrorBox, adArchiveList, DateUtils; {$R *.dfm} procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(f_Manager); end; procedure TMainForm.AddNewItem; var l_Item: TadItem; begin l_Item := TadItem.Create; try if EditItem(l_Item) then begin f_Manager.AddItem(l_Item); UpdateLister; end; finally FreeAndNil(l_Item); end; end; procedure TMainForm.btnAddClick(Sender: TObject); begin AddNewItem; end; procedure TMainForm.btnDeleteClick(Sender: TObject); var l_Idx: Integer; begin l_Idx := lstItems.Current; if MessageDlg(Format('Вы действительно ходите удалить "%s"?', [l3Str(lstItems.Strings[l_Idx])]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin f_Manager.DeleteItem(l_Idx); UpdateLister; end; end; procedure TMainForm.btnDistributeClick(Sender: TObject); begin DoDistribute; end; procedure TMainForm.btnRestoreClick(Sender: TObject); begin DoRestore; end; procedure TMainForm.DispMsg(const aMsg: AnsiString; aIsError: Boolean = False); begin lblDisp.Caption := aMsg; if aIsError then lblDisp.Font.Color := clRed else lblDisp.Font.Color := clWindowText; end; procedure TMainForm.DoDistribute; var l_ArchiveFN: AnsiString; l_ErrList: Tl3StringList; begin f_Manager.RefreshValidity; if not f_Manager.IsValid then begin DispMsg('Сборка невалидна!', True); Exit; end; l_ErrList := Tl3StringList.MakeSorted; try if f_Manager.CheckDistribution(l_ErrList) then begin EnableUI(False); try if ForceDirectories(GetArchiveFolder) then begin l_ArchiveFN := GetNewArchiveFilename; f_Manager.Archive(l_ArchiveFN, DoProgress); f_Manager.Distribute(DoProgress); SendNotificationEmail(Now); DispMsg('Новая версия успешно подложена!'); end else DispMsg('Папка с архивами недоступна!', True); finally EnableUI(True); end; end else ShowErrorsBox('Заняты файлы', 'Невозможно выполнить задание. Следующие целевые файлы заняты:', l_ErrList, False); finally FreeAndNil(l_ErrList); end; end; procedure TMainForm.DoProgress(aState: Byte; aValue: Long; const aMsg: AnsiString = ''); begin case aState of piStart: begin ProgressBar.Max := aValue; ProgressBar.Position := 0; f_CurProcMsg := aMsg; DispMsg(aMsg); end; piCurrent: begin ProgressBar.Position := aValue; DispMsg(aMsg); end; piEnd: begin ProgressBar.Position := ProgressBar.Max; DispMsg(f_CurProcMsg); end; end; Application.ProcessMessages; end; procedure TMainForm.DoRestore; begin end; function TMainForm.EditItem(anItem: TadItem): Boolean; var l_EditForm: TadItemEditDlg; begin l_EditForm := TadItemEditDlg.Create(Self); try l_EditForm.Item := anItem; Result := l_EditForm.Execute; finally FreeAndNil(l_EditForm); end; end; procedure TMainForm.EnableUI(Value: Boolean); begin btnAdd.Enabled := Value; btnDelete.Enabled := Value; btnDistribute.Enabled := Value; btnRestore.Enabled := Value; end; procedure TMainForm.FormCreate(Sender: TObject); begin f_Manager := TadManager.Create(GetDataFilename); f_Manager.Load; UpdateLister; end; function TMainForm.GetArchiveFolder: AnsiString; begin Result := ConcatDirName(ExtractFilePath(Application.ExeName), 'ARCHIVES'); end; function TMainForm.GetDataFilename: AnsiString; begin Result := ChangeFileExt(Application.ExeName, '.dat'); end; function TMainForm.GetNewArchiveFilename: AnsiString; var D, M, Y, H, MN, S, MS: Word; l_FN: AnsiString; begin DecodeDateTime(Now, Y, M, D, H, MN, S, MS); l_FN := Format('archive-%.4d-%.2d-%.2d-%.2d-%.2d.zip', [Y, M, D, H, MN]); Result := ConcatDirName(GetArchiveFolder, l_FN); end; procedure TMainForm.lstItemsActionElement(Sender: TObject; Index: Integer); var l_Item: TadItem; begin l_Item := f_Manager.Items[Index]; if EditItem(l_Item) then begin lstItems.InvalidateItem(Index); f_Manager.Save; end; end; procedure TMainForm.lstItemsCountChanged(Sender: TObject; NewCount: Integer); begin UpdateButtons; end; procedure TMainForm.lstItemsGetItemColor(Sender: TObject; Index: Integer; var FG, BG: TColor); begin if f_Manager.Items[Index].IsValid then FG := clWindowText else FG := clRed; end; procedure TMainForm.lstItemsGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); begin ItemString := l3CStr(f_Manager.Items[Index].Name); end; procedure TMainForm.SendNotificationEmail(const aDate: TDateTime); var l_Ini: Tl3IniFile; l_ToAddress: AnsiString; l_Filer : Tl3DOSFiler; l_Str: AnsiString; begin l_Ini := Tl3IniFile.Create; try l_Ini.Section := 'Email'; l_ToAddress := l_Ini.ReadParamStrDef('SendTo', ''); if l_ToAddress <> '' then begin if FileExists('blat.exe') then begin l_Filer := Tl3DOSFiler.Make('mailopt.txt', l3_fmWrite); try l_Filer.Open; l_Filer.WriteLn('-server smtp.garant.ru'); l_Filer.WriteLn('-f archi@garant.ru'); l_Filer.WriteLn('-charset windows-1251'); l_Filer.WriteLn(Format('-to "%s"', [l_ToAddress])); DateTimeToString(l_Str, 'dd/mm/yyyy', aDate); l_Filer.WriteLn(Format('-subject "Подложена версия Архивариуса от %s"', [l_Str])); l_Filer.WriteLn('-bodyF "mailbody.txt"'); l_Filer.Close; finally FreeAndNil(l_Filer); end; l_Filer := Tl3DOSFiler.Make('mailbody.txt', l3_fmWrite); try l_Filer.Open; l_Filer.WriteLn('Уважаемые коллеги!'); l_Filer.WriteLn(''); l_Filer.WriteLn(Format('Обратите внимание, что на сервер была подложена версия Архивариуса от %s', [l_Str])); l_Filer.WriteLn(''); l_Filer.WriteLn('Всегда ваши,'); l_Filer.WriteLn('группа "Архивариус"'); l_Filer.WriteLn(''); l_Filer.WriteLn('--------------------------------------'); l_Filer.WriteLn('Это письмо создано автоматически, вам не нужно отвечать на него.'); l_Filer.Close; finally FreeAndNil(l_Filer); end; FileExecuteWait('blat.exe', '- -of "mailopt.txt"', '', esMinimized); end else l3System.Msg2Log('Не найден blat.exe, письмо не отправлено!'); end; finally FreeAndNil(l_Ini); end; end; function TMainForm.ShowErrorsBox(const aTitle, aText: AnsiString; const aErrList: Tl3StringList; aYesNo: Boolean): Integer; var l_Dlg: TErrorBox; begin l_Dlg := TErrorBox.Create(aTitle, aText, aErrList); try l_Dlg.IsYesNo := aYesNo; Result := l_Dlg.ShowModal; finally FreeAndNil(l_Dlg); end; end; procedure TMainForm.UpdateButtons; begin btnDelete.Enabled := lstItems.Total > 0; end; procedure TMainForm.UpdateLister; begin lstItems.Total := f_Manager.ItemCount; lstItems.Invalidate; end; end.
unit uTransferAntarCabang; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,uModel, uAppUtils, System.Generics.Collections, uTAGRequests; type TTransferAntarCabangKirim = class; TTransferAntarCabangTerima = class; TTransferAntarCabangTerimaItem = class(TAppObjectItem) private FBarang: TBarang; FBarangSatuangItemID: string; FHarga: Double; FKeterangan: string; FKonversi: Double; FQtyKirim: Double; FQtyTerima: Double; FTransferAntarCabangTerima: TTransferAntarCabangTerima; FUOM: TUOM; public destructor Destroy; override; function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; property BarangSatuangItemID: string read FBarangSatuangItemID write FBarangSatuangItemID; published property Barang: TBarang read FBarang write FBarang; property Harga: Double read FHarga write FHarga; property Keterangan: string read FKeterangan write FKeterangan; property Konversi: Double read FKonversi write FKonversi; property QtyKirim: Double read FQtyKirim write FQtyKirim; property QtyTerima: Double read FQtyTerima write FQtyTerima; property TransferAntarCabangTerima: TTransferAntarCabangTerima read FTransferAntarCabangTerima write FTransferAntarCabangTerima; property UOM: TUOM read FUOM write FUOM; end; TTransferAntarCabangKirimItem = class(TAppObjectItem) private FBarang: TBarang; FBarangSatuangItemID: string; FHarga: Double; FKeterangan: string; FKonversi: Double; FQtyKirim: Double; FQtyRequest: Double; FTransferAntarCabangKirim: TTransferAntarCabangKirim; FUOM: TUOM; public destructor Destroy; override; function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; property BarangSatuangItemID: string read FBarangSatuangItemID write FBarangSatuangItemID; published property Barang: TBarang read FBarang write FBarang; property Harga: Double read FHarga write FHarga; property Keterangan: string read FKeterangan write FKeterangan; property Konversi: Double read FKonversi write FKonversi; property QtyKirim: Double read FQtyKirim write FQtyKirim; property QtyRequest: Double read FQtyRequest write FQtyRequest; property TransferAntarCabangKirim: TTransferAntarCabangKirim read FTransferAntarCabangKirim write FTransferAntarCabangKirim; property UOM: TUOM read FUOM write FUOM; end; TTransferAntarCabangKirim = class(TAppObject) private FTransferAntarCabangKirimItems: TObjectList<TTransferAntarCabangKirimItem>; FCabang: TCabang; FGudangAsal: TGudang; FGudangTujuan: TGudang; FKeterangan: string; FNoBukti: string; FPetugas: string; FStatus: string; FTAGRequest: TTAGRequest; FTglBukti: TDatetime; FToCabang: TCabang; function GetTransferAntarCabangKirimItems: TObjectList<TTransferAntarCabangKirimItem>; public constructor Create; published property TransferAntarCabangKirimItems: TObjectList<TTransferAntarCabangKirimItem> read GetTransferAntarCabangKirimItems write FTransferAntarCabangKirimItems; property Cabang: TCabang read FCabang write FCabang; property GudangAsal: TGudang read FGudangAsal write FGudangAsal; property GudangTujuan: TGudang read FGudangTujuan write FGudangTujuan; property Keterangan: string read FKeterangan write FKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property Petugas: string read FPetugas write FPetugas; property Status: string read FStatus write FStatus; property TAGRequest: TTAGRequest read FTAGRequest write FTAGRequest; property TglBukti: TDatetime read FTglBukti write FTglBukti; property ToCabang: TCabang read FToCabang write FToCabang; end; TTransferAntarCabangTerima = class(TAppObject) private FTransferAntarCabangTerimaItems: TObjectList<TTransferAntarCabangTerimaItem>; FCabang: TCabang; FGudangAsal: TGudang; FGudang: TGudang; FKeterangan: string; FNoBukti: string; FPetugas: string; FTransferAntarCabangKirim: TTransferAntarCabangKirim; FTglBukti: TDatetime; FFromCabang: TCabang; function GetTransferAntarCabangTerimaItems: TObjectList<TTransferAntarCabangTerimaItem>; procedure SetTransferAntarCabangKirim(const Value: TTransferAntarCabangKirim); public constructor Create; published property TransferAntarCabangTerimaItems: TObjectList<TTransferAntarCabangTerimaItem> read GetTransferAntarCabangTerimaItems write FTransferAntarCabangTerimaItems; property Cabang: TCabang read FCabang write FCabang; property GudangAsal: TGudang read FGudangAsal write FGudangAsal; property Gudang: TGudang read FGudang write FGudang; property Keterangan: string read FKeterangan write FKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property Petugas: string read FPetugas write FPetugas; property TransferAntarCabangKirim: TTransferAntarCabangKirim read FTransferAntarCabangKirim write SetTransferAntarCabangKirim; property TglBukti: TDatetime read FTglBukti write FTglBukti; property FromCabang: TCabang read FFromCabang write FFromCabang; end; implementation constructor TTransferAntarCabangKirim.Create; begin inherited; Status := 'KIRIM'; end; { ********************************** TTransferAntarCabangKirim *********************************** } function TTransferAntarCabangKirim.GetTransferAntarCabangKirimItems: TObjectList<TTransferAntarCabangKirimItem>; begin if FTransferAntarCabangKirimItems = nil then FTransferAntarCabangKirimItems := TObjectList<TTransferAntarCabangKirimItem>.Create(False); Result := FTransferAntarCabangKirimItems; end; constructor TTransferAntarCabangTerima.Create; begin inherited; end; { ********************************** TTransferAntarCabangTerima ********************************** } function TTransferAntarCabangTerima.GetTransferAntarCabangTerimaItems: TObjectList<TTransferAntarCabangTerimaItem>; begin if FTransferAntarCabangTerimaItems = nil then FTransferAntarCabangTerimaItems := TObjectList<TTransferAntarCabangTerimaItem>.Create(); Result := FTransferAntarCabangTerimaItems; end; procedure TTransferAntarCabangTerima.SetTransferAntarCabangKirim(const Value: TTransferAntarCabangKirim); begin if FTransferAntarCabangKirim <> Value then begin FreeAndNil(FTransferAntarCabangKirim); FTransferAntarCabangKirim := Value; end; end; destructor TTransferAntarCabangKirimItem.Destroy; begin inherited; FreeAndNil(FBarang); FreeAndNil(FUOM); end; function TTransferAntarCabangKirimItem.GetHeaderField: string; begin Result := 'TransferAntarCabangKirim'; end; procedure TTransferAntarCabangKirimItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.TransferAntarCabangKirim := TTransferAntarCabangKirim(AHeaderProperty); end; destructor TTransferAntarCabangTerimaItem.Destroy; begin inherited; FreeAndNil(FBarang); FreeAndNil(FUOM); end; function TTransferAntarCabangTerimaItem.GetHeaderField: string; begin Result := 'TransferAntarCabangTerima'; end; procedure TTransferAntarCabangTerimaItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.TransferAntarCabangTerima := TTransferAntarCabangTerima(AHeaderProperty); end; end.
unit GetTerritoryUnit; interface uses SysUtils, BaseExampleUnit; type TGetTerritory = class(TBaseExample) public procedure Execute(TerritoryId: String); end; implementation uses TerritoryUnit; procedure TGetTerritory.Execute(TerritoryId: String); var ErrorString: String; Territory: TTerritory; GetEnclosedAddresses: boolean; begin GetEnclosedAddresses := False; Territory := Route4MeManager.Territory.Get( TerritoryId, GetEnclosedAddresses, ErrorString); try WriteLn(''); if (Territory <> nil) then begin WriteLn('GetTerritory executed successfully'); WriteLn(Format('Territory ID: %s', [Territory.Id.Value])); end else WriteLn(Format('GetTerritory error: %s', [ErrorString])); finally FreeAndNil(Territory); end; end; end.
{******************************************************************* * General Turbo Circuit file structure: * * Offset Length Description * * 0 len Identification string: STR_TCFILE_IDENTIFIER * len var Sequence of records * * Description of a tipical record: * * 0 1 Record ID * 1 1 Record version * 2 2 Data size (sz) * 4 sz * *******************************************************************} unit tcfileformat; {$mode objfpc}{$H+} interface uses Classes, SysUtils, constants; {******************************************************************* * Turbo Circuit file format constants *******************************************************************} var STR_TCFILE_IDENTIFIER: string = 'Turbo Circuit File ID string'; const INT_TCFILE_IDENTIFIER_SIZE = 28; TCRECORD_BOF = $01; TCRECORD_GUI_DATA = $02; TCRECORD_DOC_DATA = $03; TCRECORD_COMPONENT = $04; TCRECORD_WIRE = $05; TCRECORD_TEXT = $06; TCRECORD_POLYLINE = $81; TCRECORD_EOF = $0F; { BOF record constants } TCRECORD_BOF_SIZE = $00; TCRECORD_BOF_VER = $00; { GUI_DATA record constants } TCRECORD_GUI_DATA_SIZE = $00; TCRECORD_GUI_DATA_VER = $00; { SCHEMATICS_DOC_DATA record constants } TCRECORD_DOC_DATA_SIZE = $00; TCRECORD_DOC_DATA_VER = $00; { COMPONENT record constants } TCRECORD_COMPONENT_SIZE = SizeOf(TCComponent); TCRECORD_COMPONENT_VER = $00; { WIRE record constants } TCRECORD_WIRE_SIZE = SizeOf(TCWire); TCRECORD_WIRE_VER = $00; { TEXT record constants } TCRECORD_TEXT_SIZE = SizeOf(TCText); TCRECORD_TEXT_VER = $00; { POLYLINE record constants } TCRECORD_POLYLINE_SIZE = SizeOf(TCPolyline); TCRECORD_POLYLINE_VER = $00; { EOF record constants } TCRECORD_EOF_SIZE = $00; TCRECORD_EOF_VER = $00; implementation end.
unit CRILoggerImpl; interface uses pi, pi_int, orbtypes; type TCRILoggerImpl = class(TClientRequestInterceptor) private FCDRCodec: ICodec; FSlotId: TSlotId; function Level(ri: IClientRequestInfo): Integer; procedure DisplayClientRequestInfo(ri: IClientRequestInfo; level: short); protected procedure _destroy; override; function _get_name: AnsiString; override; procedure send_request(const ri: IClientRequestInfo); override; procedure send_poll(const ri: IClientRequestInfo); override; procedure receive_reply(const ri: IClientRequestInfo); override; procedure receive_exception(const ri: IClientRequestInfo); override; procedure receive_other(const ri: IClientRequestInfo); override; public constructor Create(const info: IORBInitInfo; const slotId: TSlotId); end; implementation uses LoggerPolicy_int, LoggerPolicy, orb_int, Callstack_int, pi_impl, RILogger, code_int, any, std_seq, tcode, static, exceptions, SysUtils; { TCRILoggerImpl } constructor TCRILoggerImpl.Create(const info: IORBInitInfo; const slotId: TSlotId); var factory: ICodecFactory; how: pi_int.TEncoding; begin FSlotId := slotId; // // Get the codec factory // factory := info.codec_factory; Assert(factory <> nil); // // Create codec // how.major_version := 1; how.minor_version := 0; how.format := ENCODING_CDR_ENCAPS; try FCDRCodec := factory.create_codec(how); except on E: TUnknownEncoding do Assert(false); end; Assert(FCDRCodec <> nil); // // Get the dynamic any factory // (*DynamicAny::DynAnyFactory_var dynAnyFactory; try { CORBA::Object_var obj = info -> resolve_initial_references("DynAnyFactory"); dynAnyFactory = DynamicAny::DynAnyFactory::_narrow(obj); } catch(const PortableInterceptor::ORBInitInfo::InvalidName&) { assert(false); } assert(!CORBA::is_nil(dynAnyFactory)); // // Create the CORBA_OUT object for displaying the CORBA::Any // out_ = new CORBA_OUT(dynAnyFactory, cout); out_ -> down();*) end; procedure TCRILoggerImpl.DisplayClientRequestInfo(ri: IClientRequestInfo; level: short); var exception: IAny; i: Integer; profile: TTaggedProfile; repoId: TRepositoryId; begin DisplayRequestInfo(ri, level, FSlotId); if level > 2 then begin // // Display effective profile // profile := ri.effective_profile; Skip(); Write('effective profile = '); if (profile.tag = TAG_INTERNET_IOP) then Write('TAG_INTERNET_IOP') else if (profile.tag = TAG_MULTIPLE_COMPONENTS) then Write('TAG_MULTIPLE_COMPONENTS') else Write('UNKNOWN_TAG'); Write(': '); for i := 0 to Length(profile.profile_data) do Write(GetOctet(profile.profile_data[i])); WriteLn; end; // // Display received exception // try exception := ri.received_exception; Skip(); WriteLn('received exception = '); Down(); TCORBAOut.DisplayAny(exception); Up(); except on E: BAD_INV_ORDER do ; // Operation not supported in this context end; // // Display received exception id // try repoId := ri.received_exception_id; Skip(); WriteLn('received exception id = ', repoId); except on E: BAD_INV_ORDER do ; // Operation not supported in this context end; end; function TCRILoggerImpl.Level(ri: IClientRequestInfo): Integer; var p: IPolicy; loggerPolicy: ILoggerPolicy; begin Result := 0; try // // Get the logger policy // p := ri.get_request_policy(LOGGER_POLICY_ID); loggerPolicy := TLoggerPolicy._narrow(p); if loggerPolicy <> nil then Result := loggerPolicy.level; except on E: INV_POLICY do ; end; { try/except } end; procedure TCRILoggerImpl.receive_exception(const ri: IClientRequestInfo); var l: short; begin l := Level(ri); if (l > 0) then begin WriteLn('receive exception:'); DisplayClientRequestInfo(ri, l); WriteLn; end; end; procedure TCRILoggerImpl.receive_other(const ri: IClientRequestInfo); var l: short; begin l := Level(ri); if (l > 0) then begin WriteLn('receive other:'); DisplayClientRequestInfo(ri, l); WriteLn; end; end; procedure TCRILoggerImpl.receive_reply(const ri: IClientRequestInfo); var l: short; begin l := Level(ri); if (l > 0) then begin WriteLn('receive reply:'); DisplayClientRequestInfo(ri, l); WriteLn; end; end; procedure TCRILoggerImpl.send_poll(const ri: IClientRequestInfo); var l: short; begin l := Level(ri); if (l > 0) then begin WriteLn('send poll:'); DisplayClientRequestInfo(ri, l); WriteLn; end; end; procedure TCRILoggerImpl.send_request(const ri: IClientRequestInfo); var l: short; a: IAny; tc: ITypeCode; data: OctetSeq; sc: ServiceContext; begin data := nil; l := Level(ri); if (l > 0) then begin // // Try to get the CallStack from slot // try a := ri.get_slot(FSlotId); tc := a.get_type(); if (tc.kind() <> tk_null) and (tc.kind() <> tk_void) then begin // // Encode CallStack // data := FCDRCodec.encode_value(a); // // Add encoded CallStack to service context // sc.context_id := REQUEST_CONTEXT_ID; SetLength(sc.context_data, Length(data)); Move(Pointer(sc.context_data)^, Pointer(data)^, Length(data)); ri.add_request_service_context(sc, false); end; except on E: TInvalidSlot do ; // Ignore failure in this demo on E: TInvalidTypeForEncoding do ; // Ignore failure in this demo end; WriteLn('send request:'); DisplayClientRequestInfo(ri, l); WriteLn; end; end; procedure TCRILoggerImpl._destroy; begin end; function TCRILoggerImpl._get_name: AnsiString; begin Result := 'CRILogger'; end; end.
unit fAdvancedEnemyManagement; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, gr32, cenemy, Menus, StrUtils, cMegaROM, cConfiguration; type TfrmAdvancedEnemyInfo = class(TForm) grpCheckPointInfo: TGroupBox; lblCheckpoint1Screen: TLabel; lblCheckPoint2Screen: TLabel; cmdOK: TButton; lstEnemies: TListBox; cmdDelete: TButton; cmdSetEnemyCheckpoint1: TButton; cmdSetEnemyCheckpoint2: TButton; cmdSort: TButton; cmdMoveUp: TButton; cmdMoveDown: TButton; cmdSortByX: TButton; procedure FormShow(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure lstEnemiesDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure cmdDeleteClick(Sender: TObject); procedure cmdSetEnemyCheckpoint1Click(Sender: TObject); procedure cmdSetEnemyCheckpoint2Click(Sender: TObject); procedure cmdSortClick(Sender: TObject); procedure cmdMoveUpClick(Sender: TObject); procedure cmdMoveDownClick(Sender: TObject); procedure cmdSortByXClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; procedure LoadEnemies(); { Private declarations } public property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmAdvancedEnemyInfo: TfrmAdvancedEnemyInfo; implementation {$R *.dfm} procedure TfrmAdvancedEnemyInfo.LoadEnemies(); var Space : String; i,x : Integer; begin with lstEnemies.Items do begin BeginUpdate; Clear; for i := 0 to _ROMData.CurrLevel.Enemies.Count -1 do begin // Calculate the space. Space := ''; if length(_ROMData.EnemyDescriptions[_ROMData.CurrLevel.Enemies[i].ID]) < 43 then begin for x := length(_ROMData.EnemyDescriptions[_ROMData.CurrLevel.Enemies[i].ID]) to 43 do Space := Space + ' '; end else Space := ' '; Add(AnsiMidStr(_ROMData.EnemyDescriptions[_ROMData.CurrLevel.Enemies[i].ID],0,43) + Space + '$' + IntToHex(_ROMData.CurrLevel.Enemies[i].ScreenID,2) + ' ' + IntToHex(_ROMData.CurrLevel.Enemies[i].X,2) + ' ' + IntToHex(_ROMData.CurrLevel.Enemies[i].Y,2) + ' ' + IntToHex(_ROMData.CurrLevel.Enemies[i].CheckPointStatus,2) ); end; EndUpdate; end; end; procedure TfrmAdvancedEnemyInfo.FormShow(Sender: TObject); begin lblCheckPoint1Screen.Caption := 'Checkpoint 1 Screen: $' + IntToHex(_ROMData.CurrLevel.Properties['ScreenStartCheck2'].Value,2); lblCheckPoint2Screen.Caption := 'Checkpoint 2 Screen: $' + IntToHex(_ROMData.CurrLevel.Properties['ScreenStartCheck3'].Value,2); LoadEnemies(); end; procedure TfrmAdvancedEnemyInfo.cmdOKClick(Sender: TObject); begin _ROMData.SaveEnemyData; end; procedure TfrmAdvancedEnemyInfo.lstEnemiesDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var TempRect : TRect; begin // First, fill the current area with the colour of the window. lstEnemies.Canvas.Brush.Color := clWindow; lstEnemies.Canvas.FillRect(Rect); if _ROMData.CurrLevel.Enemies[Index].CheckPointStatus = 3 then begin TempRect := Rect; TempRect.Right := TempRect.Right div 2; lstEnemies.Canvas.Brush.Color := clGreen; lstEnemies.Canvas.FillRect(TempRect); TempRect.Right := Rect.Right; TempRect.Left := TempRect.Right div 2; lstEnemies.Canvas.Brush.Color := clYellow; lstEnemies.Canvas.FillRect(TempRect); lstEnemies.Canvas.Brush.Color := clGreen; end else if _ROMData.CurrLevel.Enemies[Index].CheckPointStatus = 1 then begin lstEnemies.Canvas.Brush.Color := clGreen; lstEnemies.Canvas.FillRect(Rect); end else if _ROMData.CurrLevel.Enemies[Index].CheckPointStatus = 2 then begin lstEnemies.Canvas.Brush.Color := clYellow; lstEnemies.Canvas.FillRect(Rect); end else begin lstEnemies.Canvas.Brush.Color := clWindow; lstEnemies.Canvas.FillRect(Rect); end; lstEnemies.Canvas.Font.Color := clBlack; lstEnemies.Canvas.TextOut(Rect.Left + 1,Rect.Top + 1,lstEnemies.Items[index]); end; procedure TfrmAdvancedEnemyInfo.cmdDeleteClick(Sender: TObject); var Selected : Integer; begin if lstEnemies.ItemIndex > -1 then begin Selected := lstEnemies.ItemIndex; _ROMData.DeleteEnemy(Selected); LoadEnemies(); lstEnemies.ItemIndex := Selected; end; end; procedure TfrmAdvancedEnemyInfo.cmdSetEnemyCheckpoint1Click( Sender: TObject); begin if lstEnemies.ItemIndex > -1 then begin lstEnemies.Refresh; end; end; procedure TfrmAdvancedEnemyInfo.cmdSetEnemyCheckpoint2Click( Sender: TObject); begin if lstEnemies.ItemIndex > -1 then begin lstEnemies.Refresh; end; end; procedure TfrmAdvancedEnemyInfo.cmdSortClick(Sender: TObject); begin _ROMData.SortEnemyData(_ROMData.CurrentLevel); LoadEnemies(); end; procedure TfrmAdvancedEnemyInfo.cmdMoveUpClick(Sender: TObject); begin if lstEnemies.ItemIndex > 0 then begin _ROMData.CurrLevel.Enemies.Exchange(lstEnemies.ItemIndex,lstEnemies.ItemIndex -1); LoadEnemies(); end; end; procedure TfrmAdvancedEnemyInfo.cmdMoveDownClick(Sender: TObject); begin if (lstEnemies.ItemIndex < lstEnemies.Items.Count -1) and (lstEnemies.ItemIndex > -1) then begin _ROMData.CurrLevel.Enemies.Exchange(lstEnemies.ItemIndex,lstEnemies.ItemIndex +1); LoadEnemies(); end; end; procedure TfrmAdvancedEnemyInfo.cmdSortByXClick(Sender: TObject); begin _ROMData.SortEnemyDataByX(_ROMData.CurrentLevel); LoadEnemies(); 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 ClpBerGenerator; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpStreams, ClpStreamHelper, ClpIProxiedInterface, ClpAsn1Tags, ClpAsn1Generator, ClpBerOutputStream, ClpIBerGenerator; type TBerGenerator = class abstract(TAsn1Generator, IBerGenerator) strict private var F_tagged, F_isExplicit: Boolean; F_tagNo: Int32; procedure WriteHdr(tag: Int32); strict protected constructor Create(outStream: TStream); overload; constructor Create(outStream: TStream; tagNo: Int32; isExplicit: Boolean); overload; procedure WriteBerHeader(tag: Int32); procedure WriteBerBody(contentStream: TStream); procedure WriteBerEnd(); public procedure AddObject(const obj: IAsn1Encodable); override; function GetRawOutputStream(): TStream; override; procedure Close(); override; end; implementation { TBerGenerator } constructor TBerGenerator.Create(outStream: TStream); begin Inherited Create(outStream); end; procedure TBerGenerator.AddObject(const obj: IAsn1Encodable); var temp: TBerOutputStream; begin temp := TBerOutputStream.Create(&Out); try temp.WriteObject(obj); finally temp.Free; end; end; procedure TBerGenerator.Close; begin WriteBerEnd(); end; constructor TBerGenerator.Create(outStream: TStream; tagNo: Int32; isExplicit: Boolean); begin Inherited Create(outStream); F_tagged := true; F_isExplicit := isExplicit; F_tagNo := tagNo; end; function TBerGenerator.GetRawOutputStream: TStream; begin result := &Out; end; procedure TBerGenerator.WriteBerBody(contentStream: TStream); begin TStreams.PipeAll(contentStream, &Out); end; procedure TBerGenerator.WriteBerEnd; begin &Out.WriteByte($00); &Out.WriteByte($00); if (F_tagged and F_isExplicit) then // write extra end for tag header begin &Out.WriteByte($00); &Out.WriteByte($00); end; end; procedure TBerGenerator.WriteBerHeader(tag: Int32); var tagNum: Int32; begin if (F_tagged) then begin tagNum := F_tagNo or TAsn1Tags.Tagged; if (F_isExplicit) then begin WriteHdr(tagNum or TAsn1Tags.Constructed); WriteHdr(tag); end else begin if ((tag and TAsn1Tags.Constructed) <> 0) then begin WriteHdr(tagNum or TAsn1Tags.Constructed); end else begin WriteHdr(tagNum); end; end end else begin WriteHdr(tag); end; end; procedure TBerGenerator.WriteHdr(tag: Int32); begin &Out.WriteByte(Byte(tag)); &Out.WriteByte($80); end; end.
unit nsHistoryTree; {* Содержит поля и методы общие для деревьев содержащих последние открытые документы и запросы } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Common\nsHistoryTree.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsHistoryTree" MUID: (490AE2C7034B) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses , nsBaseMainMenuTree ; type TnsHistoryTree = class(TnsBaseMainMenuTree) {* Содержит поля и методы общие для деревьев содержащих последние открытые документы и запросы } private f_MaxCount: Integer; {* Определяет максимальное количество элементов в дереве. Ноль означает неограниченное количество элементов } public constructor Create(aMaxCount: Integer); reintroduce; public property MaxCount: Integer read f_MaxCount; {* Определяет максимальное количество элементов в дереве. Ноль означает неограниченное количество элементов } end;//TnsHistoryTree {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses //#UC START# *490AE2C7034Bimpl_uses* //#UC END# *490AE2C7034Bimpl_uses* ; constructor TnsHistoryTree.Create(aMaxCount: Integer); //#UC START# *490AE2F50049_490AE2C7034B_var* //#UC END# *490AE2F50049_490AE2C7034B_var* begin //#UC START# *490AE2F50049_490AE2C7034B_impl* inherited Create; f_MaxCount := aMaxCount; //#UC END# *490AE2F50049_490AE2C7034B_impl* end;//TnsHistoryTree.Create {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
program hw3q3c; type TAGTYPE = (i, r, b); IRB = record case kind: TAGTYPE of i: (IFIELD: integer); r: (RFIELD: real); b: (BFIELD: Boolean); end; var Vtype : char ; Vval : string ; Vint : integer ; Vreal : real ; V : IRB ; sCode : integer ; procedure NEG(var test : IRB) ; (*This program forgets to check the kind of the variant record and operates on the variant record as if all the fields are present and meaningful at the same time. As a result, some of the results of this program may sometimes be correct, but they will never be trustworthy.*) var principal : integer ; rate, interest : real ; changeRate : Boolean ; begin (*set the integer, real, and Boolean variables*) changeRate := test.BFIELD ; principal := test.IFIELD ; rate := test.RFIELD ; writeln ; writeln('Change effective interest rate: ', changeRate) ; (*Perform an operation using the numbers, based on the Boolean value, and print the results. *) if changeRate = true then rate := 0.5 * rate ; interest := principal * rate ; writeln('Principal is ', principal) ; writeln('Rate is ', rate) ; writeln('Interest is ', interest) ; end;(*proc NEG*) begin (*program*) (*identification*) writeln('Mark Sattolo, 428500, CSI3125, DGD-2, Homework#3') ; writeln ; (*request input*) writeln('Please enter a value preceded by its type (i, r, or b).') ; writeln('For example: r 3.14129 ') ; writeln ; (*get input*) readln(Vtype, Vval) ; (*According to Prof.Szpackowicz in class on Nov.9, we can assume that all input will be perfect and do not have to do any error-checking for this.*) (*if a boolean*) if Vtype = 'b' then begin (*set the kind field of V*) V.kind := b ; (*check for the most probable variations of 'true'*) if ((Vval = ' true') or (Vval = ' True') or (Vval = ' TRUE')) then V.BFIELD := true (*else can assume the input must be some variation of 'false'*) else V.BFIELD := false ; end ; (*if an integer*) if Vtype = 'i' then begin (*set the kind field of V*) V.kind := i ; (*convert the string to an integer value - we can assume Vval will represent an integer*) Val(Vval, Vint, sCode) ; (*set the integer field of V*) V.IFIELD := Vint ; end ; (*if a real*) if Vtype = 'r' then begin (*set the kind field of V*) V.kind := r ; (*convert the string to a real value - we can assume Vval will represent a real*) Val(Vval, Vreal, sCode) ; (*set the real field of V*) V.RFIELD := Vreal ; end ; (*negate the value in V by calling the NEG procedure*) NEG(V) ; end.(*program*)
unit kwMain; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwMain.pas" // Начат: 10.05.2011 13:49 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwMain // // Поддержка основного кода скрипта. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces, kwCompiledWord, l3Interfaces, l3ParserInterfaces, l3BaseStream, tfwValueStack, l3PrimString ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type IDlgInitListner = interface(IUnknown) ['{07616FB4-3E14-45AB-BD51-86D8D3D17ACE}'] procedure Init(const aCode: TObject; aContext: Pointer); end;//IDlgInitListner {$Include ..\ScriptEngine\tfwCompilingWord.imp.pas} _tfwScriptEngine_Parent_ = _tfwCompilingWord_; {$Include ..\ScriptEngine\tfwScriptEngine.imp.pas} TkwMain = class(_tfwScriptEngine_, IDlgInitListner) {* Поддержка основного кода скрипта. } private // private fields f_Compiled : TkwCompiledWord; {* Компилированный код} protected // realized methods function EndBracket(const aContext: TtfwContext): AnsiString; override; procedure Init(const aCode: TObject; aContext: Pointer); protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure BeforeCompile(const aPrevContext: TtfwContext; var theNewContext: TtfwContext); override; procedure AfterCompile(var aPrevContext: TtfwContext; var theNewContext: TtfwContext; aCompiled: TkwCompiledWord); override; function CompiledWordClass: RkwCompiledWord; override; function AcceptsEOF: Boolean; override; class function ReallyNeedRegister: Boolean; override; public // overridden public methods procedure Script(aStream: Tl3Stream; const aCaller: ItfwScriptCaller); override; public // public methods procedure RunCompiled(const aContext: TtfwContext); end;//TkwMain {$IfEnd} //not NoScripts {$If not defined(NoScripts)} var g_ScriptEngine : TkwMain; {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses SysUtils, l3Base, kwSystemIncluded, l3Stream, l3Types, kwCompiledMain, seThreadSupport, kwEtalonNeedsComputerName, kwEtalonNeedsXE, kwEtalonNeedsOSName, kwEtalonNeeds64, l3Parser, kwInteger, kwString, TypInfo, kwIntegerFactory, kwStringFactory, l3String, l3Chars, tfwAutoregisteredDiction, tfwScriptEngine, l3StringList, tfwParser, l3Filer, tfwStoredValuesStack ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwMain; {$Include ..\ScriptEngine\tfwCompilingWord.imp.pas} {$Include ..\ScriptEngine\tfwScriptEngine.imp.pas} // start class TkwMain procedure TkwMain.RunCompiled(const aContext: TtfwContext); //#UC START# *4DC90A79006D_4DC90A1E03C2_var* //#UC END# *4DC90A79006D_4DC90A1E03C2_var* begin //#UC START# *4DC90A79006D_4DC90A1E03C2_impl* kwEtalonNeedsComputerName.g_EtalonNeedsComputerName := false; kwEtalonNeedsOSName.g_EtalonNeedsOSName := false; kwEtalonNeedsXE.g_EtalonNeedsXE := false; kwEtalonNeeds64.g_EtalonNeeds64 := false; RunnerAssert(f_Compiled <> nil, 'Код пустой', aContext); try f_Compiled.DoIt(aContext); finally if TseWorkThreadList.WasInit then TseWorkThreadList.Instance.WaitForAllThreads; end; //#UC END# *4DC90A79006D_4DC90A1E03C2_impl* end;//TkwMain.RunCompiled function TkwMain.EndBracket(const aContext: TtfwContext): AnsiString; //#UC START# *4DB6C99F026E_4DC90A1E03C2_var* //#UC END# *4DB6C99F026E_4DC90A1E03C2_var* begin //#UC START# *4DB6C99F026E_4DC90A1E03C2_impl* Result := ''; //#UC END# *4DB6C99F026E_4DC90A1E03C2_impl* end;//TkwMain.EndBracket procedure TkwMain.Init(const aCode: TObject; aContext: Pointer); //#UC START# *4E4B9AE20283_4DC90A1E03C2_var* var l_Ctx : TtfwContext; //#UC END# *4E4B9AE20283_4DC90A1E03C2_var* begin //#UC START# *4E4B9AE20283_4DC90A1E03C2_impl* l_Ctx.rEngine := Self; l_Ctx.rCaller := ItfwScriptCaller(aContext); l_Ctx.rParser := nil;//l_P; l_Ctx.rCompiling := false; l_Ctx.rCompiler := nil; l_Ctx.rException := nil; l_Ctx.rUsed := nil;//l_Used; l_Ctx.rModifiers := []; l_Ctx.rScriptFileName := ''; (aCode as TtfwWord).DoIt(l_Ctx); //#UC END# *4E4B9AE20283_4DC90A1E03C2_impl* end;//TkwMain.Init procedure TkwMain.Cleanup; //#UC START# *479731C50290_4DC90A1E03C2_var* //#UC END# *479731C50290_4DC90A1E03C2_var* begin //#UC START# *479731C50290_4DC90A1E03C2_impl* FreeAndNil(f_Compiled); inherited; //#UC END# *479731C50290_4DC90A1E03C2_impl* end;//TkwMain.Cleanup procedure TkwMain.BeforeCompile(const aPrevContext: TtfwContext; var theNewContext: TtfwContext); //#UC START# *4DB6CDDA038B_4DC90A1E03C2_var* var l_S : IStream; l_SI : TkwSystemIncluded; l_SystemFilename : AnsiString; l_NS : Tl3NamedTextStream; //#UC END# *4DB6CDDA038B_4DC90A1E03C2_var* begin //#UC START# *4DB6CDDA038B_4DC90A1E03C2_impl* inherited; l_SystemFilename := aPrevContext.rCaller.ResolveIncludedFilePath('System.script'); if FileExists(l_SystemFilename) then begin l_NS := Tl3NamedTextStream.Create(l_SystemFilename, l3_fmRead); try l_SI := TkwSystemIncluded.Create(l_NS); try l_SI.DoIt(aPrevContext); finally FreeAndNil(l_SI); end;//try..finally finally FreeAndNil(l_NS); end;//try..finally end//FileExists(l_SystemFilename) else // - кто первый (под ногами приложения), тот и папа begin l_S := aPrevContext.rCaller.SystemDictionary; if (l_S <> nil) then begin l_SI := TkwSystemIncluded.Create(l_S); try l_SI.DoIt(aPrevContext); finally FreeAndNil(l_SI); end;//try..finally end;//l_S <> nil end;//FileExists(l_SystemFilename) {$IfDef Nemesis} {$IfDef InsiderTest} l_SystemFilename := aPrevContext.rCaller.ResolveIncludedFilePath('HLTCLike.script'); if FileExists(l_SystemFilename) then begin aPrevContext.rUsed.Add(l_SystemFilename); l_NS := Tl3NamedTextStream.Create(l_SystemFilename, l3_fmRead); try l_SI := TkwSystemIncluded.Create(l_NS); try l_SI.DoIt(aPrevContext); finally FreeAndNil(l_SI); end;//try..finally finally FreeAndNil(l_NS); end;//try..finally end;//FileExists(l_SystemFilename); {$EndIf InsiderTest} {$EndIf Nemesis} //#UC END# *4DB6CDDA038B_4DC90A1E03C2_impl* end;//TkwMain.BeforeCompile procedure TkwMain.AfterCompile(var aPrevContext: TtfwContext; var theNewContext: TtfwContext; aCompiled: TkwCompiledWord); //#UC START# *4DB6CE2302C9_4DC90A1E03C2_var* //#UC END# *4DB6CE2302C9_4DC90A1E03C2_var* begin //#UC START# *4DB6CE2302C9_4DC90A1E03C2_impl* aCompiled.SetRefTo(f_Compiled); inherited; //#UC END# *4DB6CE2302C9_4DC90A1E03C2_impl* end;//TkwMain.AfterCompile function TkwMain.CompiledWordClass: RkwCompiledWord; //#UC START# *4DBAEE0D028D_4DC90A1E03C2_var* //#UC END# *4DBAEE0D028D_4DC90A1E03C2_var* begin //#UC START# *4DBAEE0D028D_4DC90A1E03C2_impl* Result := TkwCompiledMain; //#UC END# *4DBAEE0D028D_4DC90A1E03C2_impl* end;//TkwMain.CompiledWordClass function TkwMain.AcceptsEOF: Boolean; //#UC START# *4DC2DEE70178_4DC90A1E03C2_var* //#UC END# *4DC2DEE70178_4DC90A1E03C2_var* begin //#UC START# *4DC2DEE70178_4DC90A1E03C2_impl* Result := true; //#UC END# *4DC2DEE70178_4DC90A1E03C2_impl* end;//TkwMain.AcceptsEOF class function TkwMain.ReallyNeedRegister: Boolean; //#UC START# *4DC2E05B03DD_4DC90A1E03C2_var* //#UC END# *4DC2E05B03DD_4DC90A1E03C2_var* begin //#UC START# *4DC2E05B03DD_4DC90A1E03C2_impl* Result := false; //#UC END# *4DC2E05B03DD_4DC90A1E03C2_impl* end;//TkwMain.ReallyNeedRegister procedure TkwMain.Script(aStream: Tl3Stream; const aCaller: ItfwScriptCaller); //#UC START# *4F733B9C0064_4DC90A1E03C2_var* var l_PrevScriptEngine : TkwMain; //#UC END# *4F733B9C0064_4DC90A1E03C2_var* begin //#UC START# *4F733B9C0064_4DC90A1E03C2_impl* l_PrevScriptEngine := g_ScriptEngine; try g_ScriptEngine := Self; inherited Script(aStream, aCaller); finally g_ScriptEngine := l_PrevScriptEngine; end;//try..finally //#UC END# *4F733B9C0064_4DC90A1E03C2_impl* end;//TkwMain.Script {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwCompilingWord.imp.pas} {$IfEnd} //not NoScripts 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.6 10/26/2004 9:36:30 PM JPMugaas Updated ref. Rev 1.5 4/19/2004 5:05:30 PM JPMugaas Class rework Kudzu wanted. Rev 1.4 2004.02.03 5:45:22 PM czhower Name changes Rev 1.3 11/26/2003 6:22:24 PM JPMugaas IdFTPList can now support file creation time for MLSD servers which support that feature. I also added support for a Unique identifier for an item so facilitate some mirroring software if the server supports unique ID with EPLF and MLSD. Rev 1.2 10/19/2003 2:27:14 PM DSiders Added localization comments. Rev 1.1 4/7/2003 04:03:48 PM JPMugaas User can now descover what output a parser may give. Rev 1.0 2/19/2003 04:18:16 AM JPMugaas More things restructured for the new list framework. } unit IdFTPListParseEPLF; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdAEPLFFTPListItem = class(TIdFTPListItem) protected //Unique ID for an item to prevent yourself from downloading something twice FUniqueID : String; public property ModifiedDateGMT; //Valid only with EPLF and MLST property UniqueID : string read FUniqueID write FUniqueID; end; TIdFTPLPEPLF = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseEPLF"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPEPLF } class function TIdFTPLPEPLF.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var s: String; begin Result := (AListing.Count > 0); if Result then begin s := AListing[0]; Result := (Length(s) > 2) and (s[1] = '+') and (IndyPos(#9, s) > 0); end; end; class function TIdFTPLPEPLF.GetIdent: String; begin Result := 'EPLF'; {do not localize} end; class function TIdFTPLPEPLF.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdAEPLFFTPListItem.Create(AOwner); end; class function TIdFTPLPEPLF.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LFacts : TStrings; i : Integer; LI : TIdAEPLFFTPListItem; LBuf: String; begin LI := AItem as TIdAEPLFFTPListItem; LFacts := TStringList.Create; try LI.FileName := ParseFacts(Copy(LI.Data, 2, MaxInt), LFacts, ',', #9); for i := 0 to LFacts.Count-1 do begin LBuf := LFacts[i]; if LBuf = '/' then begin {do not localize} LI.ItemType := ditDirectory; end; if Length(LBuf) > 0 then begin case LBuf[1] of 's': {do not localize} begin AItem.Size := IndyStrToInt64(Copy(LBuf, 2, MaxInt), 0); end; 'm': {do not localize} begin LBuf := Copy(LBuf, 2, MaxInt); LI.ModifiedDate := EPLFDateToLocalDateTime(LBuf); LI.ModifiedDateGMT := EPLFDateToGMTDateTime(LBuf); end; 'i': {do not localize} begin LI.UniqueID := Copy(LBuf, 2, MaxInt); end; end; end; end; finally FreeAndNil(LFacts); end; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPEPLF); finalization UnRegisterFTPListParser(TIdFTPLPEPLF); end.
unit ntvUtils; {** * 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 Belal Alhamed <belalhamed at gmail dot com> * @author Zaher Dirkey *} {$mode objfpc}{$H+} interface uses Dialogs, Classes, Messages, Controls, ExtCtrls, SysUtils, Math, Contnrs, Graphics, LCLType, Forms, LCLIntf; procedure ExcludeClipRect(Canvas: TCanvas; Rect: TRect); function WidthOf(R: TRect): Integer; function HeightOf(R: TRect): Integer; implementation uses Types; procedure ExcludeClipRect(Canvas: TCanvas; Rect: TRect); begin LCLIntf.ExcludeClipRect(Canvas.Handle, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); end; function WidthOf(R: TRect): Integer; begin Result := R.Right - R.Left; end; function HeightOf(R: TRect): Integer; begin Result := R.Bottom - R.Top; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElList; interface uses SysUtils, {$IFNDEF VCL_5_USED} ElVCLUtils, // FreeAndNil {$ENDIF} Classes, ElContBase, ElTools; const AlignMem = $500; // Align at 1280 items type TElListSortCompare = function(Item1, Item2: TxListItem; Cargo: TxListItem): Integer; TElListSortCompareEx = function(Item1, Item2: TxListItem; Cargo: TxListItem): Integer of object; TElListDeleteEvent = procedure (Sender: TObject; Item: TxListItem) of object; PElPointerList = ^TElPointerList; TElPointerList = array[0..MaxListSize - 1] of TxListItem; {: } TElList = class (TPersistent) protected FAutoClearObjects: Boolean; FCapacity: Integer; FCount: Integer; FList: PElPointerList; FOnDelete: TElListDeleteEvent; class procedure Error(const Msg: string; Data: Integer); function Get(Index: Integer): TxListItem; virtual; procedure Grow; virtual; procedure Put(Index: Integer; const Item: TxListItem); virtual; procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); procedure IntDelete(Index: Integer); procedure TriggerDeleteEvent(const Item: TxListItem); virtual; public constructor Create; destructor Destroy; override; procedure CheckRange(Index: Integer); function FastGet(Index: Integer): TxListItem; function Add(const Item: TxListItem): Integer; procedure Assign(Source : TPersistent); override; procedure Clear; virtual; procedure Delete(Index: Integer); virtual; procedure DeleteRange(StartIndex, EndIndex: Integer); virtual; procedure Exchange(Index1, Index2: Integer); function Expand: TElList; function First: TxListItem; function IndexOf(const Item: TxListItem): Integer; function IndexOfBack(StartIndex: integer; const Item: TxListItem): Integer; function IndexOfFrom(StartIndex: integer; const Item: TxListItem): Integer; procedure Insert(Index: Integer; const Item: TxListItem); function Last: TxListItem; procedure Move(CurIndex, NewIndex: Integer); procedure MoveRange(CurStart, CurEnd, NewStart: integer); procedure Pack; function Remove(const Item: TxListItem): Integer; procedure Sort(Compare: TElListSortCompare; const Cargo: TxListItem); procedure SortC(Compare: TElListSortCompareEx; const Cargo: TxListItem); property AutoClearObjects: Boolean read FAutoClearObjects write FAutoClearObjects; property Capacity: Integer read FCapacity write SetCapacity; property Count: Integer read FCount write SetCount; property Items[Index: Integer]: TxListItem read Get write Put; default; {.$ifndef BUILDER_USED} property List: PElPointerList read FList; {.$endif} property OnDelete: TElListDeleteEvent read FOnDelete write FOnDelete; end; implementation type {: } EElListError = class (Exception) end; //T & R {$ifdef D_3_UP} resourcestring {$else} const {$endif} rs_ListIndexOutOfBounds = 'List index [%d] out of bounds...'; procedure RaiseOutOfBoundsError(Ind: integer); begin raise EelListError.CreateFmt(rs_ListIndexOutOfBounds, [Ind]); end; procedure QuickSortC(SortList: PElPointerList; L, R: Integer; SCompare: TelListSortCompareEx; const Cargo: TxListItem); var I, J : Integer; P, T : TxListItem; begin repeat I := L; J := R; //vAd: old: P := SortList^[(L + R) shr 1]; // remove all ^ P := SortList[(L + R) shr 1]; repeat while SCompare(SortList[I], P, Cargo) < 0 do Inc(I); while SCompare(SortList[J], P, Cargo) > 0 do Dec(J); if I <= J then begin if I <> J then begin T := SortList[I]; SortList[I] := SortList[J]; SortList[J] := T; end; Inc(I); Dec(J); end; until I > J; if L < J then QuickSortC(SortList, L, J, SCompare, Cargo); L := I; until I >= R; end; procedure QuickSort(SortList: PElPointerList; L, R: Integer; SCompare: TelListSortCompare; const Cargo: TxListItem); var I, J : Integer; P, T : TxListItem; begin repeat I := L; J := R; P := SortList[(L + R) shr 1]; repeat // rI := SCompare(SortList^[I], P, Cargo); while SCompare(SortList[I], P, Cargo) < 0 do Inc(I); // rJ := SCompare(SortList^[J], P, Cargo); while SCompare(SortList[J], P, Cargo) > 0 do Dec(J); if I <= J then begin if I <> J then begin T := SortList[I]; SortList[I] := SortList[J]; SortList[J] := T; end; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(SortList, L, J, SCompare, Cargo); L := I; until I >= R; end; {: } {: } { *********************************** TElList ************************************ } constructor TElList.Create; begin inherited; FList := nil; FCount := 0; FCapacity := 0; FAutoClearObjects := FALSE; FOnDelete := nil; end; destructor TElList.Destroy; begin Clear; inherited; end; function TElList.Add(const Item: TxListItem): Integer; begin if FCount = FCapacity then begin Inc(FCapacity, Min(Count * 2 + 1, AlignMem)); ReAllocMem(FList, FCapacity * SizeOf(TxListItem)); end; FList[FCount] := Item; Result := FCount; Inc(FCount); end; procedure TElList.Assign(Source : TPersistent); begin if Source is TElList then begin Clear; SetCapacity(TElList(Source).Capacity); SetCount(TElList(Source).Count); if FCount > 0 then System.Move(TElList(Source).FList^[0], FList^[0], FCount * sizeof(TxListItem)); end else inherited; end; procedure TElList.Clear; var I: Integer; P: TxListItem; begin for I := 0 to Count - 1 do TriggerDeleteEvent(FList[I]); if AutoClearObjects then for I := 0 to FCount - 1 do begin p := Get(i); try if (P <> nil) and (TObject(P) is TObject) then TObject(P).Free; except end; end; // Don't call two routines for this. Just assign FCount := 0; FCapacity := 0; ReallocMem(FList, 0); end; procedure TElList.IntDelete(Index: Integer); begin CheckRange(Index); Dec(FCount); if Index < FCount then System.Move(FList[Index + 1], FList[Index], (FCount - Index) * SizeOf(TxListItem)); end; procedure TElList.DeleteRange(StartIndex, EndIndex: Integer); var i : integer; begin CheckRange(StartIndex); CheckRange(EndIndex); if (EndIndex < StartIndex) then RaiseOutOfBoundsError(EndIndex); for i := StartIndex to EndIndex do TriggerDeleteEvent(FList[I]); if (FCount > EndIndex + 1) then System.Move(FList[EndIndex + 1], FList[StartIndex], (FCount - (EndIndex - StartIndex + 1)) * SizeOf(TxListItem)); Dec(FCount, EndIndex - StartIndex + 1); if FCount < FCapacity shr 1 then begin FCapacity := FCapacity shr 1; ReAllocMem(FList, FCapacity * SizeOf(TxListItem)); end; end; procedure TElList.Delete(Index: Integer); begin CheckRange(Index); if Assigned(FList[Index]) then begin TriggerDeleteEvent(FList[Index]); if AutoClearObjects then FreeAndNil(TObject(FList[Index])); end; Dec(FCount); if FCount > Index then System.Move(FList[Index + 1], FList[Index], (FCount - Index) * SizeOf(TxListItem)); if FCount < FCapacity shr 1 Then begin FCapacity := FCapacity shr 1; ReAllocMem(FList, FCapacity * SizeOf(TxListItem)); end; end; class procedure TElList.Error(const Msg: string; Data: Integer); function ReturnAddr: TxListItem; asm MOV EAX,[EBP+4] end; begin raise EElListError.CreateFmt(Msg, [Data])at ReturnAddr; end; procedure TElList.CheckRange(Index: Integer); begin if (Index < 0) or (Index >= FCount) then RaiseOutOfBoundsError(Index); end; procedure TElList.Exchange(Index1, Index2: Integer); var Item: TxListItem; begin CheckRange(Index1); CheckRange(Index2); Item := FList[Index1]; FList[Index1] := FList[Index2]; FList[Index2] := Item; end; function TElList.Expand: TElList; begin if FCount = FCapacity then begin Inc(FCapacity, Min(Count * 2 + 1, AlignMem)); ReallocMem(FList, FCapacity * SizeOf(TxListItem)); end; Result := Self; end; function TElList.First: TxListItem; begin CheckRange(0); Result := FList[0]; end; function TElList.FastGet(Index: Integer): TxListItem; begin CheckRange(Index); Result := FList[Index]; end; function TElList.Get(Index: Integer): TxListItem; begin CheckRange(Index); Result := FList[Index]; end; procedure TElList.Grow; begin Inc(FCapacity, Min(Count * 2 + 1, AlignMem)); ReAllocMem(FList, FCapacity * SizeOf(TxListItem)); end; function TElList.IndexOf(const Item: TxListItem): Integer; begin Result := 0; // TODO: rewrite in assembler while (Result < FCount) and (FList[Result] <> Item) do Inc(Result); if Result = FCount then Result := -1; end; function TElList.IndexOfBack(StartIndex: integer; const Item: TxListItem): Integer; begin CheckRange(StartIndex); Result := StartIndex; while (Result >= 0) and (FList[Result] <> Item) do dec(Result); end; function TElList.IndexOfFrom(StartIndex: integer; const Item: TxListItem): Integer; begin CheckRange(StartIndex); Result := StartIndex; while (Result < FCount) and (FList[Result] <> Item) do Inc(Result); if Result = FCount then Result := -1; end; procedure TElList.Insert(Index: Integer; const Item: TxListItem); begin if (Index < 0) or (Index > FCount) then RaiseOutOfBoundsError(Index); if FCount = FCapacity then Begin Inc(FCapacity, Min(Count * 2 + 1, AlignMem)); ReAllocMem(FList, FCapacity * SizeOf(TxListItem)); End; // if Index < FCount then == Useless. See first line. System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TxListItem)); FList[Index] := Item; Inc(FCount); end; function TElList.Last: TxListItem; begin if FCount = 0 then Result := nil else Result := FList[FCount-1]; end; procedure TElList.Move(CurIndex, NewIndex: Integer); var Item: TxListItem; begin if CurIndex <> NewIndex then begin CheckRange(CurIndex); CheckRange(NewIndex); Item := FList[CurIndex]; if NewIndex<CurIndex then // Shift Left System.Move(FList[NewIndex], FList[NewIndex+1], (CurIndex-NewIndex) * SizeOf(TxListItem)) else // Shift Right System.Move(FList[CurIndex+1], FList[CurIndex], (NewIndex-CurIndex) * SizeOf(TxListItem)); FList[NewIndex] := Item; end; end; procedure TElList.MoveRange(CurStart, CurEnd, NewStart: integer); var bs: Integer; P: PChar; begin if CurStart <> NewStart then begin CheckRange(CurStart); CheckRange(CurEnd); CheckRange(NewStart); if ((NewStart >= CurStart) and (NewStart <= CurEnd)) then // vAd: shift without overhead diapasone RaiseOutOfBoundsError(NewStart); if CurStart > NewStart then begin bs := CurEnd - CurStart + 1; GetMem(P, bs * SizeOf(TxListItem)); System.Move(FList^[CurStart], P^, BS * SizeOf(TxListItem)); System.Move(FList^[NewStart], FList^[NewStart + BS], (CurStart - NewStart) * SizeOf(TxListItem)); System.Move(P^, FList^[NewStart], BS * SizeOf(TxListItem)); FreeMem(P); end else begin bs := CurEnd - CurStart + 1; GetMem(P, BS * SizeOf(TxListItem)); System.Move(FList^[CurStart], P^, BS * SizeOf(TxListItem)); System.Move(FList^[CurEnd + 1], FList^[CurStart], (NewStart - CurEnd) * SizeOf(TxListItem)); NewStart := CurStart - 1 + NewStart - CurEnd; System.Move(P^, FList^[NewStart], BS * SizeOf(TxListItem)); FreeMem(P); end; end; end; procedure TElList.Pack; var I: Integer; begin for I := FCount - 1 downto 0 do if Items[I] = nil then Delete(I); end; procedure TElList.Put(Index: Integer; const Item: TxListItem); begin CheckRange(Index); if Assigned(FList[Index]) then begin TriggerDeleteEvent(FList[Index]); if AutoClearObjects then FreeAndNil(TObject(FList[Index])); end; FList[Index] := Item; end; function TElList.Remove(const Item: TxListItem): Integer; begin Result := IndexOf(Item); // changed by chmv. if Result <> -1 then if Result >= 0 then begin TriggerDeleteEvent(FList[Result]); Dec(FCount); // if Index < FCount then == Useless. See above. System.Move(FList^[Result + 1], FList^[Result], (FCount - Result) * SizeOf(TxListItem)); if FCount < FCapacity shr 1 then begin FCapacity := FCapacity shr 1; ReAllocMem(FList, FCapacity * SizeOf(TxListItem)); end; end; end; procedure TElList.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then RaiseOutOfBoundsError(NewCapacity); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(TxListItem)); FCapacity := NewCapacity; end; end; procedure TElList.SetCount(NewCount: Integer); begin if (NewCount < 0) or (NewCount > MaxListSize) then RaiseOutOfBoundsError(NewCount); if NewCount > FCapacity then SetCapacity(NewCount); if NewCount > FCount then FillChar(FList^[FCount], (NewCount - FCount) * SizeOf(TxListItem), 0); FCount := NewCount; end; procedure TElList.Sort(Compare: TElListSortCompare; const Cargo: TxListItem); begin if (FList <> nil) and (Count > 0) then QuickSort(FList, 0, Count - 1, Compare, Cargo); end; procedure TElList.SortC(Compare: TElListSortCompareEx; const Cargo: TxListItem); begin if (FList <> nil) and (Count > 0) then QuickSortC(FList, 0, Count - 1, Compare, Cargo); end; procedure TElList.TriggerDeleteEvent(const Item: TxListItem); { Triggers the OnDelete event. This is a virtual method (descendants of this component can override it). } begin if (Assigned(FOnDelete)) then FOnDelete(Self, Item); end; end.
program TESTRND ( OUTPUT ) ; (********) (*$A+ *) (********) var R : REAL ; I : INTEGER ; local procedure DUMP ( PVON : VOIDPTR ; PBIS : VOIDPTR ) ; (*********************************************************) (* Speicherbereich von PVON bis PBIS hexadezimal *) (* ausgeben *) (*********************************************************) var P1 : VOIDPTR ; P2 : VOIDPTR ; MOD1 : INTEGER ; MOD2 : INTEGER ; procedure DUMPCHAR ( CH : CHAR ) ; begin (* DUMPCHAR *) if CH in [ 'a' .. 'i' , 'j' .. 'r' , 's' .. 'z' , 'A' .. 'I' , 'J' .. 'R' , 'S' .. 'Z' , '0' .. '9' , ' ' , ',' , '.' , '-' , ';' , ':' , '_' , '!' , '"' , 'õ' , '$' , '%' , '&' , '/' , '(' , ')' , '=' , '?' , '+' , '*' , '#' , '*' ] then WRITE ( CH ) else WRITE ( '.' ) end (* DUMPCHAR *) ; procedure DUMPZEILE ( ADR : VOIDPTR ; P1 : VOIDPTR ; P2 : VOIDPTR ) ; var CH : -> CHAR ; I : INTEGER ; const HEXTAB : array [ 0 .. 15 ] of CHAR = '0123456789abcdef' ; begin (* DUMPZEILE *) WRITE ( ADR , ': ' ) ; CH := ADR ; if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 ) then WRITE ( '........ ' ) else begin for I := 1 to 4 do begin WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD ( CH -> ) MOD 16 ] ) ; CH := PTRADD ( CH , 1 ) ; end (* for *) ; WRITE ( ' ' ) ; end (* else *) ; ADR := PTRADD ( ADR , 4 ) ; CH := ADR ; if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 ) then WRITE ( '........ ' ) else begin for I := 1 to 4 do begin WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD ( CH -> ) MOD 16 ] ) ; CH := PTRADD ( CH , 1 ) ; end (* for *) ; WRITE ( ' ' ) ; end (* else *) ; ADR := PTRADD ( ADR , 4 ) ; CH := ADR ; if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 ) then WRITE ( '........ ' ) else begin for I := 1 to 4 do begin WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD ( CH -> ) MOD 16 ] ) ; CH := PTRADD ( CH , 1 ) ; end (* for *) ; WRITE ( ' ' ) ; end (* else *) ; ADR := PTRADD ( ADR , 4 ) ; CH := ADR ; if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 ) then WRITE ( '........ ' ) else begin for I := 1 to 4 do begin WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD ( CH -> ) MOD 16 ] ) ; CH := PTRADD ( CH , 1 ) ; end (* for *) ; WRITE ( ' ' ) ; end (* else *) ; ADR := PTRADD ( ADR , - 12 ) ; CH := ADR ; WRITE ( ' *' ) ; for I := 1 to 16 do begin DUMPCHAR ( CH -> ) ; CH := PTRADD ( CH , 1 ) end (* for *) ; WRITELN ( '*' ) ; end (* DUMPZEILE *) ; begin (* DUMP *) WRITELN ( 'Dump Speicherbereich von ' , PVON , ' bis ' , PBIS ) ; P1 := PTRADD ( PVON , - 16 ) ; MOD1 := PTR2INT ( P1 ) MOD 16 ; P1 := PTRADD ( P1 , 16 - MOD1 ) ; P2 := PTRADD ( PBIS , 15 ) ; MOD2 := PTR2INT ( P2 ) MOD 16 ; P2 := PTRADD ( P2 , - MOD2 ) ; while PTRDIFF ( P1 , P2 ) < 0 do begin DUMPZEILE ( P1 , PVON , PBIS ) ; P1 := PTRADD ( P1 , 16 ) ; end (* while *) ; end (* DUMP *) ; begin (* HAUPTPROGRAMM *) /******************/ /* positiver wert */ /******************/ R := 12.5 ; DUMP ( ADDR ( R ) , PTRADD ( ADDR ( R ) , 7 ) ) ; R := R * 4724731.123456 ; R := R / 4724731.123456 ; DUMP ( ADDR ( R ) , PTRADD ( ADDR ( R ) , 7 ) ) ; WRITELN ( 'r vor round = ' , R : 15 : 7 ) ; I := ROUND ( R ) ; WRITELN ( 'i nach round = ' , I : 13 ) ; I := TRUNC ( R ) ; WRITELN ( 'i nach trunc = ' , I : 13 ) ; R := FLOOR ( R ) ; WRITELN ( 'r nach floor = ' , R : 15 : 7 ) ; R := 12.357 ; WRITELN ( 'r vor roundx = ' , R : 15 : 7 ) ; R := ROUNDX ( R , - 2 ) ; WRITELN ( 'r nach roundx = ' , R : 15 : 7 ) ; /******************/ /* negativer wert */ /******************/ R := - 12.5 ; DUMP ( ADDR ( R ) , PTRADD ( ADDR ( R ) , 7 ) ) ; R := R * 4724731.123456 ; R := R / 4724731.123456 ; DUMP ( ADDR ( R ) , PTRADD ( ADDR ( R ) , 7 ) ) ; WRITELN ( 'r vor round = ' , R : 15 : 7 ) ; I := ROUND ( R ) ; WRITELN ( 'i nach round = ' , I : 13 ) ; I := TRUNC ( R ) ; WRITELN ( 'i nach trunc = ' , I : 13 ) ; R := FLOOR ( R ) ; WRITELN ( 'r nach floor = ' , R : 15 : 7 ) ; R := - 12.357 ; WRITELN ( 'r vor roundx = ' , R : 15 : 7 ) ; R := ROUNDX ( R , - 2 ) ; WRITELN ( 'r nach roundx = ' , R : 15 : 7 ) ; end (* HAUPTPROGRAMM *) .
{ Inno Setup Preprocessor Copyright (C) 2001-2002 Alex Yackimoff $Id: IsppStacks.pas,v 1.1 2004/02/26 22:24:19 mlaan Exp $ } unit IsppStacks; interface uses Classes; type { Borrowed from Delphi 5 Contnrs unit } { TOrdered class } TOrderedList = class(TObject) private FList: TList; protected procedure PushItem(AItem: Pointer); virtual; abstract; function PopItem: Pointer; virtual; function PeekItem: Pointer; virtual; property List: TList read FList; public constructor Create; destructor Destroy; override; function Count: Integer; function AtLeast(ACount: Integer): Boolean; procedure Push(AItem: Pointer); function Pop: Pointer; function Peek: Pointer; end; { TStack class } TStack = class(TOrderedList) protected procedure PushItem(AItem: Pointer); override; end; implementation uses IsppConsts; { TOrderedList } function TOrderedList.AtLeast(ACount: integer): boolean; begin Result := List.Count >= ACount; end; function TOrderedList.Peek: Pointer; begin Result := PeekItem; end; function TOrderedList.Pop: Pointer; begin Result := PopItem; end; procedure TOrderedList.Push(AItem: Pointer); begin PushItem(AItem); end; function TOrderedList.Count: Integer; begin Result := List.Count; end; constructor TOrderedList.Create; begin inherited Create; FList := TList.Create; end; destructor TOrderedList.Destroy; begin List.Free; inherited Destroy; end; function TOrderedList.PeekItem: Pointer; begin Result := List[List.Count-1]; end; function TOrderedList.PopItem: Pointer; begin Result := PeekItem; List.Delete(List.Count-1); end; { TStack } procedure TStack.PushItem(AItem: Pointer); begin List.Add(AItem); end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StMerge.pas 4.04 *} {*********************************************************} {* SysTools: "Mail Merge" functionality *} {*********************************************************} {$include StDefine.inc} unit StMerge; interface uses Windows, SysUtils, Classes; const StDefaultTagStart = '<'; StDefaultTagEnd = '>'; StDefaultEscapeChar = '\'; type TStGotMergeTagEvent = procedure (Sender : TObject; Tag : AnsiString; var Value : AnsiString; var Discard : Boolean) of object; TStMergeProgressEvent = procedure (Sender : TObject; Index : Integer; var Abort : Boolean); TStTextMerge = class private FBadTag: AnsiString; FDefaultTags: TStrings; FEscapeChar: AnsiChar; FMergedText : TStrings; FMergeTags: TStrings; FTagEnd: AnsiString; FTagStart: AnsiString; FTemplate : TStrings; FOnMergeStart: TNotifyEvent; FOnMergeDone: TNotifyEvent; FOnLineStart: TStMergeProgressEvent; FOnLineDone: TStMergeProgressEvent; FOnGotMergeTag: TStGotMergeTagEvent; FOnGotUnknownTag: TStGotMergeTagEvent; protected {private} procedure DoGotUnknownTag(Tag: AnsiString; var Value: AnsiString; var Discard: Boolean); procedure DoGotMergeTag(Tag : AnsiString; var Value : AnsiString; var Discard : Boolean); procedure SetEscapeChar(const Value: AnsiChar); procedure SetTagEnd(const Value: AnsiString); procedure SetTagStart(const Value: AnsiString); public constructor Create; destructor Destroy; override; { Access and Update Methods } procedure Merge; { Persistence and streaming methods } {template } procedure LoadTemplateFromFile(const AFile : TFileName); procedure LoadTemplateFromStream(AStream : TStream); procedure SaveTemplateToFile(const AFile : TFileName); procedure SaveTemplateToStream(AStream : TStream); { merge result text } procedure SaveMergeToFile(const AFile : TFileName); procedure SaveMergeToStream(AStream : TStream); { properties } property BadTag : AnsiString read FBadTag write FBadTag; property DefaultTags : TStrings read FDefaultTags; property EscapeChar : AnsiChar read FEscapeChar write SetEscapeChar; property MergedText : TStrings read FMergedText; property MergeTags : TStrings read FMergeTags; property TagEnd : AnsiString read FTagEnd write SetTagEnd; property TagStart : AnsiString read FTagStart write SetTagStart; property Template : TStrings read FTemplate; { events } property OnGotMergeTag : TStGotMergeTagEvent read FOnGotMergeTag write FOnGotMergeTag; property OnGotUnknownTag : TStGotMergeTagEvent read FOnGotUnknownTag write FOnGotUnknownTag; property OnLineDone : TStMergeProgressEvent read FOnLineDone write FOnLineDone; property OnLineStart : TStMergeProgressEvent read FOnLineStart write FOnLineStart; property OnMergeDone : TNotifyEvent read FOnMergeDone write FOnMergeDone; property OnMergeStart : TNotifyEvent read FOnMergeStart write FOnMergeStart; end; implementation uses AnsiStrings; { TStTextMerge } constructor TStTextMerge.Create; begin inherited Create; FDefaultTags := TStringList.Create; FMergeTags := TStringList.Create; FMergedText := TStringList.Create; FTemplate := TStringList.Create; FTagEnd := StDefaultTagEnd; FTagStart := StDefaultTagStart; FEscapeChar := StDefaultEscapeChar; FBadTag := ''; end; destructor TStTextMerge.Destroy; begin FDefaultTags.Free; FMergeTags.Free; FMergedText.Free; FTemplate.Free; inherited Destroy; end; procedure TStTextMerge.DoGotMergeTag(Tag : AnsiString; var Value : AnsiString; var Discard : Boolean); begin if Assigned(FOnGotMergeTag) then FOnGotMergeTag(self, Tag, Value, Discard); end; procedure TStTextMerge.DoGotUnknownTag(Tag : AnsiString; var Value : AnsiString; var Discard : Boolean); begin if Assigned(FOnGotUnknownTag) then FOnGotUnknownTag(self, Tag, Value, Discard) else Value := FBadTag; end; procedure TStTextMerge.LoadTemplateFromFile(const AFile: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFile, fmOpenRead or fmShareDenyNone); try LoadTemplateFromStream(FS); finally FS.Free; end; end; procedure TStTextMerge.LoadTemplateFromStream(AStream: TStream); begin FTemplate.Clear; FTemplate.LoadFromStream(AStream); end; procedure TStTextMerge.Merge; { merge template with current DataTags } const TagIDChars = ['A'..'Z', 'a'..'z', '0'..'9', '_']; function MatchDelim(Delim : AnsiString; var PC : PAnsiChar) : Boolean; { see if current sequence matches specified Tag delimiter } var Match : PAnsiChar; Len : Integer; begin { compare text starting at PC with Tag delimiter } Len := Length(Delim); GetMem(Match, Len + 1); FillChar(Match^, Len + 1, #0); AnsiStrings.StrLCopy(Match, PC, Len); Result := AnsiStrings.StrPas(Match) = Delim; if Result then Inc(PC, Len); {advance past Tag delimiter } FreeMem(Match, Len + 1); end; function GetTag(const Tag: AnsiString; var Discard : Boolean) : AnsiString; var IdxMerge, IdxDef : Integer; TagID : string; begin { extract TagID from delimiters } TagID := Copy(string(Tag), Length(TagStart) + 1, Length(Tag)); TagID := Copy(TagID, 1, Length(TagID) - Length(TagEnd)); { see if it matches Tag in MergeTags or DefaultTags } IdxMerge := FMergeTags.IndexOfName(TagID); IdxDef := FDefaultTags.IndexOfName(TagID); { fire events as needed } if (IdxMerge < 0) and (IdxDef < 0) then begin { no match } DoGotUnknownTag(AnsiString(TagID), Result, Discard) end else begin { found match } if (IdxMerge > -1) then begin { match in MergeTags } Result := AnsiString(FMergeTags.Values[TagID]); DoGotMergeTag(AnsiString(TagID), Result, Discard); end else { not in MergTags, use Default } if (IdxDef > -1) then begin Result := AnsiString(FDefaultTags.Values[TagID]); DoGotMergeTag(AnsiString(TagID), Result, Discard); end; end; end; procedure ReplaceTags(Idx : Integer); type TagSearchStates = (fsCollectingText, fsCollectingTagID); var i, Len : Integer; P, Cur : PAnsiChar; Buff, NewBuff, TagBuff, DataBuff, TextBuff : AnsiString; State : TagSearchStates; FS, FE, Prev : AnsiChar; {Escaped,} Discard : Boolean; begin { copy current template line } Buff := AnsiString(FTemplate[Idx]); Len := Length(Buff); { output line starts empty } NewBuff := ''; TagBuff := ''; TextBuff := ''; { starts of delimiter strings } FS := FTagStart[1]; FE := FTagEnd[1]; Prev := ' '; { point at start of current line } P := PAnsiChar(Buff); Cur := P; { start looking for Tags } State := fsCollectingText; for i := 1 to Len do begin case State of { accumulating non-Tag text } fsCollectingText: begin { matching the start of a Tag? } if (Cur^ = FS) and (Prev <> EscapeChar) and MatchDelim(FTagStart, Cur) then begin { dump what we've got } NewBuff := NewBuff + TextBuff; TextBuff := ''; { start accumulating a TagID } TagBuff := TagStart; State := fsCollectingTagID; end else if (Cur^ = FS) and (Prev = EscapeChar) and MatchDelim(FTagStart, Cur) then begin { overwrite escape character } TextBuff[Length(TextBuff)] := Cur^; { go to next character } Prev := Cur^; Inc(Cur); end else { accumulate text } begin TextBuff := TextBuff + Cur^; { go to next character } Prev := Cur^; Inc(Cur); end; end; { accumulating a possible Tag } fsCollectingTagID: begin { matching the end of a Tag? } if (Cur^ = FE) and (Prev <> EscapeChar) and MatchDelim(FTagEnd, Cur) then begin { insert Tag value in place of TagID } TagBuff := TagBuff + TagEnd; DataBuff := GetTag(TagBuff, Discard); if not Discard then NewBuff := NewBuff + DataBuff; { switch back to accumulating non-Tag text } State := fsCollectingText; end else { accumulate TagID } if (Cur^ in TagIDChars) then begin TagBuff := TagBuff + Cur^; { go to next character } Prev := Cur^; Inc(Cur); end else { doesn't look like a TagID; pass it back to text collection logic } begin { turn the "failed Tag" into regular accumulated text } TextBuff := TagBuff + Cur^; TagBuff := ''; { go to next character } Prev := Cur^; Inc(Cur); { switch back to accumulating non-Tag text } State := fsCollectingText; end; end; end; {case State} end; {for} { append anything remaining } if State = fsCollectingText then NewBuff := NewBuff + TextBuff else NewBuff := NewBuff + TagBuff; { update merge text with current line } FMergedText.Add(string(NewBuff)); end; var i : Integer; Abort : Boolean; begin { notify start of merge } if Assigned(FOnMergeStart) then FOnMergeStart(self); FMergedText.Clear; Abort := False; { iterate Template } for i := 0 to Pred(FTemplate.Count) do begin if Assigned(FOnLineStart) then FOnLineStart(self, i, Abort); if Abort then Break; ReplaceTags(i); if Assigned(FOnLineDone) then FOnLineDone(self, i, Abort); if Abort then Break; end; {for} { notify end of merge } if Assigned(FOnMergeDone) then FOnMergeDone(self); end; procedure TStTextMerge.SaveMergeToFile(const AFile: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFile, fmCreate); try SaveMergeToStream(FS); finally FS.Free; end; end; procedure TStTextMerge.SaveMergeToStream(AStream: TStream); begin FMergedText.SaveToStream(AStream); end; procedure TStTextMerge.SaveTemplateToFile(const AFile: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFile, fmCreate); try SaveTemplateToStream(FS); finally FS.Free; end; end; procedure TStTextMerge.SaveTemplateToStream(AStream: TStream); begin FTemplate.SaveToStream(AStream); end; procedure TStTextMerge.SetEscapeChar(const Value: AnsiChar); begin FEscapeChar := Value; end; procedure TStTextMerge.SetTagEnd(const Value: AnsiString); begin FTagEnd := Value; end; procedure TStTextMerge.SetTagStart(const Value: AnsiString); begin FTagStart := Value; end; end.
unit udmDBBackupAndRecovery; interface uses SysUtils, Classes,Forms; type TdmDBBackupAndRecovery = class(TDataModule) private { Private declarations } Function InsertIntoTB_DEVICE_Value(aFieldName,aData:string):Boolean; Function InsertIntoTB_DOORSETTINGINFO_Value(aFieldName,aData:string):Boolean; Function InsertIntoTB_READERSETTING_Value(aFieldName,aData:string):Boolean; Function InsertIntoTB_ZONESETTING_Value(aFieldName,aData:string):Boolean; Function InsertIntoTB_CARDPERMIT_Value(aFieldName,aData:string):Boolean; public { Public declarations } procedure DeviceTabletoFile(aFilename:string); procedure DeviceRcvTabletoFile(aFilename:string); procedure CardPermitTabletoFile(aFilename:string); Function FileToInsertDeviceTable(afilename:string):integer; end; var dmDBBackupAndRecovery: TdmDBBackupAndRecovery; implementation uses udmDataBase, uCommon; {$R *.dfm} { TdmDBBackupAndRecovery } procedure TdmDBBackupAndRecovery.CardPermitTabletoFile(aFilename: string); var st :string; slTempList: Tstringlist; i : integer; stFieldName : string; stFieldData : string; stData : string; begin Try slTempList := TStringList.Create; slTempList.Clear; slTempList.Add('Ver,1'); slTempList.Add('Table,TB_CARDPERMIT'); with dmDataBase.TB_CARDPERMIT do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.SaveToFile(aFilename); Finally slTempList.Free; End; end; procedure TdmDBBackupAndRecovery.DeviceRcvTabletoFile(aFilename: string); var st :string; slTempList: Tstringlist; i : integer; stFieldName : string; stFieldData : string; stData : string; begin Try slTempList := TStringList.Create; slTempList.Clear; slTempList.Add('Ver,1'); slTempList.Add('Table,TB_DEVICERCV'); with dmDataBase.TB_DEVICERCV do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_DOORSettingInfoRCV'); with dmDataBase.TB_DOORSettingInfoRCV do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_READERSETTINGRCV'); with dmDataBase.TB_READERSETTINGRCV do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_ZONESETTINGRCV'); with dmDataBase.TB_ZONESETTINGRCV do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.SaveToFile(aFilename); Finally slTempList.Free; End; end; procedure TdmDBBackupAndRecovery.DeviceTabletoFile(aFilename: string); var st :string; slTempList: Tstringlist; i : integer; stFieldName : string; stFieldData : string; stData : string; begin Try slTempList := TStringList.Create; slTempList.Clear; slTempList.Add('Ver,1'); slTempList.Add('Table,TB_DEVICE'); with dmDataBase.TB_DEVICE do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_DOORSettingInfo'); with dmDataBase.TB_DOORSettingInfo do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_READERSETTING'); with dmDataBase.TB_READERSETTING do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_ZONESETTING'); with dmDataBase.TB_ZONESETTING do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.Add('Table,TB_CARDPERMIT'); with dmDataBase.TB_CARDPERMIT do begin stData := 'Field'; for i:= 0 to FieldCount - 1 do begin stFieldName := Fields.Fields[i].FieldName; if stData <> '' then stData := stData + ','; stData := stData + stFieldName; end; slTempList.Add(stData); First; While Not Eof do begin stData := 'Data'; for i:= 0 to FieldCount - 1 do begin stFieldData := Fields.Fields[i].AsString; if stData <> '' then stData := stData + ','; stData := stData + stFieldData; end; slTempList.Add(stData); Next; end; end; slTempList.SaveToFile(aFilename); Finally slTempList.Free; End; end; Function TdmDBBackupAndRecovery.FileToInsertDeviceTable( afilename: string):integer; var slFileList : TStringList; slTempList : TStringList; i : integer; stTableName : string; stFieldName : string; begin result := -1; Try slFileList := TStringList.Create; slTempList := TStringList.Create; slFileList.LoadFromFile(aFileName); slTempList.Delimiter := ','; slTempList.DelimitedText := slFileList.Strings[0]; if UpperCase(slTempList.Strings[0]) <> 'VER' then Exit; slFileList.Delete(0); for i := 0 to slFileList.Count - 1 do begin if G_bApplicationTerminate then Exit; slTempList.Delimiter := ','; slTempList.DelimitedText := slFileList.Strings[i]; if UpperCase(slTempList.Strings[0]) = 'TABLE' then begin stTableName := slTempList.Strings[1]; end else if UpperCase(slTempList.Strings[0]) = 'FIELD' then begin stFieldName := slFileList.Strings[i]; end else if UpperCase(slTempList.Strings[0]) = 'DATA' then begin if UpperCase(stTableName) = 'TB_DEVICE' then begin InsertIntoTB_DEVICE_Value(stFieldName,slFileList.Strings[i]); end else if UpperCase(stTableName) = 'TB_DOORSETTINGINFO' then begin InsertIntoTB_DOORSETTINGINFO_Value(stFieldName,slFileList.Strings[i]); end else if UpperCase(stTableName) = 'TB_READERSETTING' then begin InsertIntoTB_READERSETTING_Value(stFieldName,slFileList.Strings[i]); end else if UpperCase(stTableName) = 'TB_ZONESETTING' then begin InsertIntoTB_ZONESETTING_Value(stFieldName,slFileList.Strings[i]); end else if UpperCase(stTableName) = 'TB_CARDPERMIT' then begin InsertIntoTB_CARDPERMIT_Value(stFieldName,slFileList.Strings[i]); end; end; Application.ProcessMessages; end; Finally slFileList.Free; slTempList.Free; End; result := 1; end; function TdmDBBackupAndRecovery.InsertIntoTB_CARDPERMIT_Value(aFieldName, aData: string): Boolean; var slFieldNameList : TStringList; slDataList : TStringList; i : integer; nKeyIndex1 : integer; nKeyIndex2 : integer; nKeyIndex3 : integer; stKey1 : string; stKey2 : string; stKey3 : string; stData : string; begin result := False; Try aFieldName := stringReplace(aFieldName,' ',SOH,[rfReplaceAll]); aData := stringReplace(aData,' ',SOH,[rfReplaceAll]); slFieldNameList := TStringList.Create; slDataList := TStringList.Create; slFieldNameList.Delimiter := ','; slFieldNameList.DelimitedText := aFieldName; slDataList.Delimiter := ','; slDataList.DelimitedText := aData; if slFieldNameList.Count > slDataList.Count then Exit; nKeyIndex1 := slFieldNameList.IndexOf('ECUID'); nKeyIndex2 := slFieldNameList.IndexOf('CARDNO'); if (nKeyIndex1 < 0) or (nKeyIndex2 < 0) then begin Exit; end; stKey1 := slDataList.Strings[nKeyIndex1]; stKey2 := slDataList.Strings[nKeyIndex2]; stKey1 := stringReplace(stKey1,SOH,' ',[rfReplaceAll]); stKey2 := stringReplace(stKey2,SOH,' ',[rfReplaceAll]); dmDataBase.InsertIntoTB_CARDPERMIT(stKey1,stKey2,'','','','','','','','','','','','','','','','','','', '', '','',''); for i := 1 to slFieldNameList.Count - 1 do begin if G_bApplicationTerminate then Exit; if (i <> nKeyIndex1) and (i <> nKeyIndex2) then begin stData := slDataList.Strings[i]; stData := stringReplace(stData,SOH,' ',[rfReplaceAll]); dmDataBase.UpdateTB_CARDPERMIT_FieldName(stKey1,stKey2,slFieldNameList.Strings[i],stData); end; end; result := True; Finally slFieldNameList.Free; slDataList.Free; End; end; function TdmDBBackupAndRecovery.InsertIntoTB_DEVICE_Value(aFieldName, aData: string): Boolean; var slFieldNameList : TStringList; slDataList : TStringList; i : integer; nKeyIndex : integer; stKey : string; stData : string; begin result := False; Try aFieldName := stringReplace(aFieldName,' ',SOH,[rfReplaceAll]); aData := stringReplace(aData,' ',SOH,[rfReplaceAll]); slFieldNameList := TStringList.Create; slDataList := TStringList.Create; slFieldNameList.Delimiter := ','; slFieldNameList.DelimitedText := aFieldName; slDataList.Delimiter := ','; slDataList.DelimitedText := aData; if slFieldNameList.Count > slDataList.Count then Exit; nKeyIndex := slFieldNameList.IndexOf('ECU_ID'); if nKeyIndex < 0 then begin Exit; end; stKey := slDataList.Strings[nKeyIndex]; stKey := stringReplace(stKey,SOH,' ',[rfReplaceAll]); for i := 1 to slFieldNameList.Count - 1 do begin if G_bApplicationTerminate then Exit; if i <> nKeyIndex then begin stData := slDataList.Strings[i]; stData := stringReplace(stData,SOH,' ',[rfReplaceAll]); dmDataBase.UpdateTB_DEVICE_FieldName(stKey,slFieldNameList.Strings[i],stData); dmDataBase.UpdateTB_DEVICERCV_FieldName(stKey,slFieldNameList.Strings[i],'U'); end; end; result := True; Finally slFieldNameList.Free; slDataList.Free; End; end; function TdmDBBackupAndRecovery.InsertIntoTB_DOORSETTINGINFO_Value( aFieldName, aData: string): Boolean; var slFieldNameList : TStringList; slDataList : TStringList; i : integer; nKeyIndex1 : integer; nKeyIndex2 : integer; nKeyIndex3 : integer; stKey1 : string; stKey2 : string; stKey3 : string; stData : string; begin result := False; Try aFieldName := stringReplace(aFieldName,' ',SOH,[rfReplaceAll]); aData := stringReplace(aData,' ',SOH,[rfReplaceAll]); slFieldNameList := TStringList.Create; slDataList := TStringList.Create; slFieldNameList.Delimiter := ','; slFieldNameList.DelimitedText := aFieldName; slDataList.Delimiter := ','; slDataList.DelimitedText := aData; if slFieldNameList.Count > slDataList.Count then Exit; nKeyIndex1 := slFieldNameList.IndexOf('ECU_ID'); nKeyIndex2 := slFieldNameList.IndexOf('ECU_EXTEND'); nKeyIndex3 := slFieldNameList.IndexOf('DOORNO'); if (nKeyIndex1 < 0) or (nKeyIndex2 < 0) or (nKeyIndex3 < 0) then begin Exit; end; stKey1 := slDataList.Strings[nKeyIndex1]; stKey2 := slDataList.Strings[nKeyIndex2]; stKey3 := slDataList.Strings[nKeyIndex3]; stKey1 := stringReplace(stKey1,SOH,' ',[rfReplaceAll]); stKey2 := stringReplace(stKey2,SOH,' ',[rfReplaceAll]); stKey3 := stringReplace(stKey3,SOH,' ',[rfReplaceAll]); for i := 1 to slFieldNameList.Count - 1 do begin if G_bApplicationTerminate then Exit; if (i <> nKeyIndex1) and (i <> nKeyIndex2) and (i <> nKeyIndex3) then begin stData := slDataList.Strings[i]; stData := stringReplace(stData,SOH,' ',[rfReplaceAll]); dmDataBase.UpdateTB_DOORSETTING_FieldName(stKey1,stKey3,slFieldNameList.Strings[i],stData); dmDataBase.UpdateTB_DOORSETTINGRCV_FieldName(stKey1,stKey3,slFieldNameList.Strings[i],'U'); end; end; result := True; Finally slFieldNameList.Free; slDataList.Free; End; end; function TdmDBBackupAndRecovery.InsertIntoTB_READERSETTING_Value( aFieldName, aData: string): Boolean; var slFieldNameList : TStringList; slDataList : TStringList; i : integer; nKeyIndex1 : integer; nKeyIndex2 : integer; nKeyIndex3 : integer; stKey1 : string; stKey2 : string; stKey3 : string; stData : string; begin result := False; Try aFieldName := stringReplace(aFieldName,' ',SOH,[rfReplaceAll]); aData := stringReplace(aData,' ',SOH,[rfReplaceAll]); slFieldNameList := TStringList.Create; slDataList := TStringList.Create; slFieldNameList.Delimiter := ','; slFieldNameList.DelimitedText := aFieldName; slDataList.Delimiter := ','; slDataList.DelimitedText := aData; if slFieldNameList.Count > slDataList.Count then Exit; nKeyIndex1 := slFieldNameList.IndexOf('ECU_ID'); nKeyIndex2 := slFieldNameList.IndexOf('ECU_EXTEND'); nKeyIndex3 := slFieldNameList.IndexOf('READERNO'); if (nKeyIndex1 < 0) or (nKeyIndex2 < 0) or (nKeyIndex3 < 0) then begin Exit; end; stKey1 := slDataList.Strings[nKeyIndex1]; stKey2 := slDataList.Strings[nKeyIndex2]; stKey3 := slDataList.Strings[nKeyIndex3]; stKey1 := stringReplace(stKey1,SOH,' ',[rfReplaceAll]); stKey2 := stringReplace(stKey2,SOH,' ',[rfReplaceAll]); stKey3 := stringReplace(stKey3,SOH,' ',[rfReplaceAll]); for i := 1 to slFieldNameList.Count - 1 do begin if G_bApplicationTerminate then Exit; if (i <> nKeyIndex1) and (i <> nKeyIndex2) and (i <> nKeyIndex3) then begin stData := slDataList.Strings[i]; stData := stringReplace(stData,SOH,' ',[rfReplaceAll]); dmDataBase.UpdateTB_READERSETTING_FieldName(stKey1,stKey2,stKey3,slFieldNameList.Strings[i],stData); dmDataBase.UpdateTB_READERSETTINGRCV_FieldName(stKey1,stKey2,stKey3,slFieldNameList.Strings[i],'U'); end; end; result := True; Finally slFieldNameList.Free; slDataList.Free; End; end; function TdmDBBackupAndRecovery.InsertIntoTB_ZONESETTING_Value(aFieldName, aData: string): Boolean; var slFieldNameList : TStringList; slDataList : TStringList; i : integer; nKeyIndex1 : integer; nKeyIndex2 : integer; nKeyIndex3 : integer; stKey1 : string; stKey2 : string; stKey3 : string; stData : string; begin result := False; Try aFieldName := stringReplace(aFieldName,' ',SOH,[rfReplaceAll]); aData := stringReplace(aData,' ',SOH,[rfReplaceAll]); slFieldNameList := TStringList.Create; slDataList := TStringList.Create; slFieldNameList.Delimiter := ','; slFieldNameList.DelimitedText := aFieldName; slDataList.Delimiter := ','; slDataList.DelimitedText := aData; if slFieldNameList.Count > slDataList.Count then Exit; nKeyIndex1 := slFieldNameList.IndexOf('ECU_ID'); nKeyIndex2 := slFieldNameList.IndexOf('ECU_EXTEND'); nKeyIndex3 := slFieldNameList.IndexOf('ZONENO'); if (nKeyIndex1 < 0) or (nKeyIndex2 < 0) or (nKeyIndex3 < 0) then begin Exit; end; stKey1 := slDataList.Strings[nKeyIndex1]; stKey2 := slDataList.Strings[nKeyIndex2]; stKey3 := slDataList.Strings[nKeyIndex3]; stKey1 := stringReplace(stKey1,SOH,' ',[rfReplaceAll]); stKey2 := stringReplace(stKey2,SOH,' ',[rfReplaceAll]); stKey3 := stringReplace(stKey3,SOH,' ',[rfReplaceAll]); for i := 1 to slFieldNameList.Count - 1 do begin if G_bApplicationTerminate then Exit; if (i <> nKeyIndex1) and (i <> nKeyIndex2) and (i <> nKeyIndex3) then begin stData := slDataList.Strings[i]; stData := stringReplace(stData,SOH,' ',[rfReplaceAll]); dmDataBase.UpdateTB_ZONESETTING_FieldName(stKey1,stKey2,stKey3,slFieldNameList.Strings[i],stData); dmDataBase.UpdateTB_ZONESETTINGRCV_FieldName(stKey1,stKey2,stKey3,slFieldNameList.Strings[i],'U'); end; end; result := True; Finally slFieldNameList.Free; slDataList.Free; End; end; end.
unit atOperationEnv; // Модуль: "w:\quality\test\garant6x\AdapterTest\OperationsFramework\atOperationEnv.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatOperationEnv" MUID: (5396EA3E0230) interface uses l3IntfUses , Classes ; const ENV_CURRENT_FILE_PATH: AnsiString = '%CURRENT_FILE_PATH%'; ENV_CURRENT_FILE_DIR: AnsiString = '%CURRENT_FILE_DIR%'; ENV_CURRENT_FILE_NAME: AnsiString = '%CURRENT_FILE_NAME%'; ENV_F1_USER_NAME: AnsiString = '%F1_USER_NAME%'; type TatOperationEnv = class(TObject) private f_VarList: TStringList; protected function pm_GetEnvVar(const aName: AnsiString): AnsiString; procedure pm_SetEnvVar(const aName: AnsiString; const aValue: AnsiString); public function ExpandString(const aString: AnsiString): AnsiString; virtual; constructor Create; reintroduce; class function Instance: TatOperationEnv; {* Метод получения экземпляра синглетона TatOperationEnv } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } destructor Destroy; override; public property EnvVar[const aName: AnsiString]: AnsiString read pm_GetEnvVar write pm_SetEnvVar; end;//TatOperationEnv implementation uses l3ImplUses , StrUtils , SysUtils , l3Base //#UC START# *5396EA3E0230impl_uses* //#UC END# *5396EA3E0230impl_uses* ; var g_TatOperationEnv: TatOperationEnv = nil; {* Экземпляр синглетона TatOperationEnv } procedure TatOperationEnvFree; {* Метод освобождения экземпляра синглетона TatOperationEnv } begin l3Free(g_TatOperationEnv); end;//TatOperationEnvFree function TatOperationEnv.pm_GetEnvVar(const aName: AnsiString): AnsiString; //#UC START# *5396EBFF012A_5396EA3E0230get_var* //#UC END# *5396EBFF012A_5396EA3E0230get_var* begin //#UC START# *5396EBFF012A_5396EA3E0230get_impl* Result := f_VarList.Values[aName]; //#UC END# *5396EBFF012A_5396EA3E0230get_impl* end;//TatOperationEnv.pm_GetEnvVar procedure TatOperationEnv.pm_SetEnvVar(const aName: AnsiString; const aValue: AnsiString); //#UC START# *5396EBFF012A_5396EA3E0230set_var* var l_Value : String; //#UC END# *5396EBFF012A_5396EA3E0230set_var* begin //#UC START# *5396EBFF012A_5396EA3E0230set_impl* l_Value := aValue; if aName = ENV_CURRENT_FILE_PATH then l_Value := ExpandFileName(l_Value); f_VarList.Values[aName] := l_Value; //#UC END# *5396EBFF012A_5396EA3E0230set_impl* end;//TatOperationEnv.pm_SetEnvVar function TatOperationEnv.ExpandString(const aString: AnsiString): AnsiString; //#UC START# *5396EC3D006D_5396EA3E0230_var* var i : Integer; l_Name, l_CFP : String; //#UC END# *5396EC3D006D_5396EA3E0230_var* begin //#UC START# *5396EC3D006D_5396EA3E0230_impl* Result := aString; for i := 0 to f_VarList.Count-1 do begin l_Name := f_VarList.Names[i]; if l_Name <> '' then Result := AnsiReplaceText(Result, l_Name, EnvVar[l_Name]); end; // отрабатываем вычисляемые переменные l_CFP := EnvVar[ENV_CURRENT_FILE_PATH]; if l_CFP <> '' then begin if AnsiContainsText(Result, ENV_CURRENT_FILE_DIR) then Result := AnsiReplaceText(Result, ENV_CURRENT_FILE_DIR, ExtractFilePath(l_CFP)); if AnsiContainsText(Result, ENV_CURRENT_FILE_NAME) then Result := AnsiReplaceText(Result, ENV_CURRENT_FILE_NAME, ExtractFileName(l_CFP)); end; //#UC END# *5396EC3D006D_5396EA3E0230_impl* end;//TatOperationEnv.ExpandString constructor TatOperationEnv.Create; //#UC START# *5396F0310309_5396EA3E0230_var* //#UC END# *5396F0310309_5396EA3E0230_var* begin //#UC START# *5396F0310309_5396EA3E0230_impl* inherited; // f_VarList := TStringList.Create; f_VarList.NameValueSeparator := '='; f_VarList.CaseSensitive := False; f_VarList.Duplicates := dupIgnore; //#UC END# *5396F0310309_5396EA3E0230_impl* end;//TatOperationEnv.Create class function TatOperationEnv.Instance: TatOperationEnv; {* Метод получения экземпляра синглетона TatOperationEnv } begin if (g_TatOperationEnv = nil) then begin l3System.AddExitProc(TatOperationEnvFree); g_TatOperationEnv := Create; end; Result := g_TatOperationEnv; end;//TatOperationEnv.Instance class function TatOperationEnv.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TatOperationEnv <> nil; end;//TatOperationEnv.Exists destructor TatOperationEnv.Destroy; //#UC START# *48077504027E_5396EA3E0230_var* //#UC END# *48077504027E_5396EA3E0230_var* begin //#UC START# *48077504027E_5396EA3E0230_impl* FreeAndNil(f_VarList); // inherited; //#UC END# *48077504027E_5396EA3E0230_impl* end;//TatOperationEnv.Destroy end.
unit OutputSearch; interface uses Classes, SysUtils, FluidLinks, CacheCommon; type TOutputLink = class; // Temporal object to store an output TOutputSearchResult = class; // List of the resulting best outputs TOuputSearch = class; // Performs a query to find the best group of outputs TOutputLink = class(TFluidLink) public constructor Create(const Name : string); private fK : integer; fP : single; fT : single; public function Cost(aX, aY : word) : single; public property K : integer read fK; property P : single read fP; property T : single read fT; end; TOutputSearchResult = class(TFluidSearchResult) protected function CreateFluidLink(Name : string) : TFluidLink; override; function CompareFluidLinks(Item1, Item2 : TObject) : integer; override; private function GetFluidLink(index : integer) : TOutputLink; function GetCost(index : integer) : single; public property Links[index : integer] : TOutputLink read GetFluidLink; default; property Costs[index : integer] : single read GetCost; end; TOuputSearch = class public constructor Create(const aPath : string; Town, Company : string; aCount : integer; aX, aY, aSortMode : word; aRole : TFacilityRoleSet); destructor Destroy; override; private fResult : TOutputSearchResult; public property Result : TOutputSearchResult read fResult; end; implementation uses CacheObjects, CompStringsParser, SpecialChars, MathUtils;//, AutoLog; // TOutputLink constructor TOutputLink.Create(const Name : string); var p : integer; begin inherited Create(Name); try if fRole = rolNeutral then p := 1 else p := 2; fX := StrToInt(GetNextStringUpTo(Name, p, BackslashChar)); inc(p); fY := StrToInt(GetNextStringUpTo(Name, p, BackslashChar)); inc(p); fK := StrToInt(GetNextStringUpTo(Name, p, BackslashChar)); inc(p); fP := StrToInt(GetNextStringUpTo(Name, p, BackslashChar))/SmallFloatShift; inc(p); fT := StrToInt(GetNextStringUpTo(Name, p, BackslashChar))/SmallFloatShift; inc(p); fTown := GetNextStringUpTo(Name, p, BackslashChar); inc(p); fCompany := GetNextStringUpTo(Name, p, BackslashChar); inc(p); fFacility := GetNextStringUpTo(Name, p, BackslashChar); inc(p); fCircuits := GetNextStringUpTo(Name, p, #0); except end; end; function TOutputLink.Cost(aX, aY : word) : single; begin result := fP + fT * Distance(aX, aY); end; // TOutputSearchResult function TOutputSearchResult.CreateFluidLink(Name : string) : TFluidLink; begin result := TOutputLink.Create(Name); end; function TOutputSearchResult.GetFluidLink(index : integer) : TOutputLink; begin result := TOutputLink(fList[index]); end; function TOutputSearchResult.GetCost(index : integer) : single; begin result := Links[index].Cost(fX, fY); end; function TOutputSearchResult.CompareFluidLinks(Item1, Item2 : TObject) : integer; var O1 : TOutputLink absolute Item1; O2 : TOutputLink absolute Item2; dif : single; d : integer; begin d := MathUtils.Dist(O1.fX, O1.fY, O2.fX, O2.fY); if d <> 0 then begin case fMode of smDist : result := O1.Distance(fX, fY) - O2.Distance(fX, fY); smPrice : begin dif := O1.Cost(fX, fY) - O2.Cost(fX, fY); if dif = 0 then if O1.fK > O2.fK then result := 1 else result := -1 else if dif > 0 then result := 1 else result := -1; end; smQuality : begin dif := O1.fK - O2.fK; if dif = 0 then if O1.Cost(fX, fY) > O2.Cost(fX, fY) then result := 1 else result := -1 else if dif > 0 then result := -1 else result := 1; end; else result := -1; end; end else result := 0; end; // TOuputSearch constructor TOuputSearch.Create(const aPath : string; Town, Company : string; aCount : integer; aX, aY, aSortMode : word; aRole : TFacilityRoleSet); var FolderItr : TFolderIterator; begin inherited Create; fResult := TOutputSearchResult.Create(aCount, aX, aY, aSortMode, aRole); if Town = '' then Town := '*'; if Company = '' then Company := '*'; //AutoLog.Log('output', DateTimeToStr(Now) + ': begin find cycle.. '); FolderItr := TFolderIterator.Create(GetCacheRootPath + aPath, '*' + BackslashChar + '*' + BackslashChar + '*' + BackslashChar + '*' + BackslashChar + Town + BackslashChar + Company + BackslashChar + '*', onArchives); try if not FolderItr.Empty then repeat fResult.Add(FolderItr.Current); until not FolderItr.Next; finally //AutoLog.Log('output', DateTimeToStr(Now) + ': end cycle.. '); FolderItr.Free; end; end; destructor TOuputSearch.Destroy; begin fResult.Free; inherited; end; end.
unit Eagle.Alfred.MigrateCommand; interface uses Eagle.ConsoleIO, Eagle.Alfred.Command; type TMigrateCommand = class(TInterfacedObject, ICommand) private FConsoleIO: IConsoleIO; public constructor Create(const AppPath: string; ConsoleIO: IConsoleIO); procedure Execute; procedure Help; end; implementation { TMigrateCommand } constructor TMigrateCommand.Create(const AppPath: string; ConsoleIO: IConsoleIO); begin FConsoleIO := ConsoleIO; end; procedure TMigrateCommand.Execute; begin Help; end; procedure TMigrateCommand.Help; begin FConsoleIO.WriteInfo('Cria arquivos de migração de versão do banco de dados'); FConsoleIO.WriteInfo(''); FConsoleIO.WriteInfo('Para executar alguma ação de migração use:'); FConsoleIO.WriteInfo('MIGRATE [opção] [versão] [nome_da_migração]'); FConsoleIO.WriteInfo(''); FConsoleIO.WriteInfo('Opções:'); FConsoleIO.WriteInfo(''); FConsoleIO.WriteInfo('CREATE Cria uma nova migrate'); FConsoleIO.WriteInfo('EXECUTE Executa as migrates'); FConsoleIO.WriteInfo('DELETE Apaga a migrate informada'); FConsoleIO.WriteInfo(''); end; end.
(******************************************************************) (* SFX for DelZip v1.9 *) (* Copyright 2002-2004, 2008 *) (* *) (* written by Markus Stephany *) (* modified by Russell Peters, Roger Aelbrecht This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License (licence.txt) for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA contact: problems AT delphizip DOT org updates: http://www.delphizip.org modified 30-Jan-2008 ---------------------------------------------------------------------------*) unit ZMSFXDefs19; { this unit contains most definitions, constants and types used by the sfx binary of delzip. } interface uses Messages, Windows; //{$I DELVER.INC} {$I ..\ZipVers19.inc} { Dialog Control-IDs } const // buttons !! don't change the order of the first two buttons (SFXDialogs.pas, FileExistsDialogProc) ID_BTN_YES = 1; // yes/ok-buttons ID_BTN_NO = 2; // no/cancel-buttons ID_BTN_ABOUT = 103; // about-button ID_BTN_BROWSE = 104; // browse for extraction path ID_BTN_SHOWFILES = 105; // enlarge dialog to show files list box // edit box ID_EDITBOX = 201; // path/password edit // check boxes ID_CB_NOASK = 301; // file already exist : don't ask again checkbox ID_CB_RUN = 302; // after extraction, run/install... // files list view ID_LV_FILES = 401; // file list view // lines/edges (gui enhancements) ID_EDGE_BOTTOM = 502; // lower // other STATICs ID_ST_EXTRACTTO = 601; // "extract to" ID_ST_OVWGROUP = 602; // "existing files:..." ID_ST_FILES = 501; // "Files:" // radio buttons !! don't change the order! ID_RB_OVERWRITE = 701; // overwrite existing files ID_RB_SKIP = 702; // do not overwrite existing files ID_RB_CONFIRM = 703; // ask before overwriting // progress bar ID_PRG_EXTRACT = 801; // extraction progress // language combo ID_LANG_COMBO = 901; ID_LANG_SELECT = 903; const // max password length MAX_PASSWORD = 80; const // request value for Dialogs for setting strings SFX_DLG_MAIN = 1;//$400; SFX_DLG_FILE = 2;//$800; SFX_DLG_PWRD = 3;//$C00; SFX_DLG_LANG = 4; // SFX_DLG_MASK = $C00; type // crc table type TCRC32Table = array[0..256] of Cardinal; const // window size--must be a power OF two, and at least 32k WSIZE = 32768; RAND_HEAD_LEN = 12; CRC_MASK = HIGH(Cardinal); // CRC_MASK = {$IFNDEF DELPHI3UP}Cardinal(-1){$ELSE}$FFFFFFFF{$ENDIF}; SFXSpanTypeNone = 0; SFXSpanTypeSpanned = 1; SFXSpanTypeMultiVol = 2; SFXSpanTypeUnknown = -1; const { DEFLATE stuff } // Tables for deflate from PKZIP's appnote.txt. // Copy lengths FOR literal codes 257..285 cplens: array[0..30] of word = (3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0); // Copy offsets FOR distance codes 0..29 cpdist: array[0..29] of word = (1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577); // Extra bits FOR literal codes 257..285 cplext: array[0..30] of byte = (0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99); { 99==invalid } // Extra bits FOR distance codes cpdext: array[0..29] of byte = (0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13); // AND'ing with mask[n] masks the lower n bits maskr: array[0..16] of word = ($0000, $0001, $0003, $0007, $000F, $001F, $003F, $007F, $00FF, $01FF, $03FF, $07FF, $0FFF, $1FFF, $3FFF, $7FFF, $FFFF); lbits = 9; dbits = 6; N_MAX = 288; type PT = ^Thuft; Thuft = packed record e, b: shortint; n: word; Next: PT; end; BufPtr = ^BufType; BufType = array[0..WSIZE] of byte; const { SHBrowseForFolder definitions and functions } BFFM_INITIALIZED = 1; {$IFDEF UNICODE} BFFM_SETSELECTION = WM_USER + 103; {$ELSE} BFFM_SETSELECTION = WM_USER + 102; {$ENDIF} BFFM_SELCHANGED = 2; BIF_RETURNONLYFSDIRS = 1; BIF_NEWDIALOGSTYLE = $40; BIF_EDITBOX = $10; BIF_USENEWUI = (BIF_NEWDIALOGSTYLE or BIF_EDITBOX); type // browsecallback TFNBFFCallBack = function(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): integer; stdcall; // TSHItemID -- Item ID TSHItemID = packed record { mkid } cb: word; { Size of the ID (including cb itself) } abID: array[0..0] of byte; { The item ID (variable length) } end; // TItemIDList -- List if item IDs (combined with 0-terminator) pItemIDList = ^TItemIDList; TItemIDList = packed record { idl } mkid: TSHItemID; end; TBrowseInfo = packed record hwndOwner: HWND; pidlRoot: pItemIDList; // pszDisplayName: pAnsiChar; { Return display name of item selected. } // lpszTitle: pAnsiChar; { text to go in the banner over the tree. } pszDisplayName: pChar; { Return display name of item selected. } lpszTitle: pChar; { text to go in the banner over the tree. } ulFlags: UINT; { Flags that control the return stuff } lpfn: TFNBFFCallBack; lParam: LPARAM; { extra info that's passed back in callbacks } iImage: integer; { output var: where to return the Image index. } end; // {$IFDEF DELPHI3UP} // Lucjan Lukasik { IMalloc interface } IMalloc = interface(IUnknown) ['{00000002-0000-0000-C000-000000000046}'] function Alloc(cb: longint): Pointer; stdcall; function Realloc(pv: Pointer; cb: longint): Pointer; stdcall; procedure Free(pv: Pointer); stdcall; function GetSize(pv: Pointer): longint; stdcall; function DidAlloc(pv: Pointer): integer; stdcall; procedure HeapMinimize; stdcall; end; // {$ENDIF} PSHFileInfo = ^TSHFileInfo; TSHFileInfo = record hIcon: HICON; iIcon: Integer; dwAttributes: Cardinal; szDisplayName: array [0..MAX_PATH-1] of Char; szTypeName: array [0..79] of Char; end; const SHGFI_SYSICONINDEX = $000004000; SHGFI_SELECTED = $000010000; SHGFI_SMALLICON = $000000001; SHGFI_SHELLICONSIZE = $000000004; SHGFI_USEFILEATTRIBUTES = $000000010; //{$ENDIF} const // progressbar defs PBM_SETRANGE = WM_USER + 1; PBM_SETPOS = WM_USER + 2; { strings } Chr_DirSep = '\'; {! do not localize dialog resource names below !} { dialog resource names } Str_Dlg_Main = 'MAINDIALOG'; // main dialog res Str_Dlg_Password = 'PASSWD'; // password input box Str_Dlg_FileExists = 'FILEEXIST'; // overwrite file confirmation dialog Str_Dlg_Language = 'LANGS'; // languages dialog res {! do not localize dialog resource names above !} // stuff different between delphi versions type //{$IFDEF DELPHI4UP} // may be incorrect (DELPHI3UP?) //{$IFDEF VERD4up} TWriteFileWritten = Cardinal; //{$ELSE} // TWriteFileWritten = Integer; //{$ENDIF} // stuff not defined in delphi 2 //{$I missing_types.inc} // list view definitions const LVFI_STRING = $0002; LVCFMT_LEFT = $0000; LVCFMT_RIGHT = $0001; LVCFMT_CENTER = $0002; LVCFMT_JUSTIFYMASK = $0003; LVCF_FMT = $0001; LVCF_WIDTH = $0002; LVCF_TEXT = $0004; LVCF_SUBITEM = $0008; LVCF_IMAGE = $0010; LVCF_ORDER = $0020; LVSIL_SMALL = 1; LVS_EX_FULLROWSELECT = $00000020; LVN_FIRST = 0-100; LVN_ITEMCHANGING = LVN_FIRST-0; LVN_ITEMCHANGED = LVN_FIRST-1; LVM_FIRST = $1000; LVM_SETIMAGELIST = LVM_FIRST + 3; LVM_GETITEMCOUNT = LVM_FIRST + 4; LVM_GETITEMA = LVM_FIRST + 5; LVM_GETITEMW = LVM_FIRST + 75; LVM_SETITEMA = LVM_FIRST + 6; LVM_SETITEMW = LVM_FIRST + 76; LVM_INSERTITEMA = LVM_FIRST + 7; LVM_INSERTITEMW = LVM_FIRST + 77; LVM_FINDITEMA = LVM_FIRST + 13; LVM_FINDITEMW = LVM_FIRST + 83; LVM_ENSUREVISIBLE = LVM_FIRST + 19; LVM_SETCOLUMNA = LVM_FIRST + 26; LVM_SETCOLUMNW = LVM_FIRST + 96; LVM_INSERTCOLUMNA = LVM_FIRST + 27; LVM_INSERTCOLUMNW = LVM_FIRST + 97; LVM_SETITEMSTATE = LVM_FIRST + 43; LVM_GETITEMSTATE = LVM_FIRST + 44; LVM_GETITEMTEXTA = LVM_FIRST + 45; LVM_GETITEMTEXTW = LVM_FIRST + 115; LVM_GETSELECTEDCOUNT = LVM_FIRST + 50; LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54; {$IFDEF UNICODE} LVM_GETITEM = LVM_GETITEMW; LVM_SETITEM = LVM_SETITEMW; LVM_INSERTITEM = LVM_INSERTITEMW; LVM_FINDITEM = LVM_FINDITEMW; LVM_SETCOLUMN = LVM_SETCOLUMNW; LVM_INSERTCOLUMN = LVM_INSERTCOLUMNW; LVM_GETITEMTEXT = LVM_GETITEMTEXTW; {$ELSE} LVM_GETITEM = LVM_GETITEMA; LVM_SETITEM = LVM_SETITEMA; LVM_INSERTITEM = LVM_INSERTITEMA; LVM_FINDITEM = LVM_FINDITEMA; LVM_SETCOLUMN = LVM_SETCOLUMNA; LVM_INSERTCOLUMN = LVM_INSERTCOLUMNA; LVM_GETITEMTEXT = LVM_GETITEMTEXTA; {$ENDIF} CCM_FIRST = $2000; { Common control shared messages } CCM_SETUNICODEFORMAT = CCM_FIRST + 5; CCM_GETUNICODEFORMAT = CCM_FIRST + 6; type PLVColumn = ^TLVColumn; TLVCOLUMN = packed record mask: Cardinal; fmt: Integer; cx: Integer; pszText: PChar; cchTextMax: Integer; iSubItem: Integer; iImage: Integer; iOrder: Integer; end; PLVFindInfo = ^TLVFindInfo; TLVFindInfo = packed record flags: UINT; psz: PChar; lParam: LPARAM; pt: TPoint; vkDirection: UINT; end; const LVIF_TEXT = $0001; LVIF_IMAGE = $0002; LVIF_PARAM = $0004; LVIF_STATE = $0008; LVIS_SELECTED = $0002; ICC_LISTVIEW_CLASSES = $00000001; // listview, header ICC_TREEVIEW_CLASSES = $00000002; // treeview, tooltips ICC_BAR_CLASSES = $00000004; // toolbar, statusbar, trackbar, tooltips ICC_TAB_CLASSES = $00000008; // tab, tooltips ICC_UPDOWN_CLASS = $00000010; // updown ICC_PROGRESS_CLASS = $00000020; // progress ICC_HOTKEY_CLASS = $00000040; // hotkey ICC_ANIMATE_CLASS = $00000080; // animate ICC_WIN95_CLASSES = $000000FF; ICC_DATE_CLASSES = $00000100; // month picker, date picker, time picker, updown ICC_USEREX_CLASSES = $00000200; // comboex ICC_COOL_CLASSES = $00000400; // rebar (coolbar) control ICC_STANDARD_CLASSES = $00004000; type PLVItem = ^TLVItem; TLVITEM = packed record mask: Cardinal; iItem: Integer; iSubItem: Integer; state: Cardinal; stateMask: Cardinal; pszText: PChar; cchTextMax: Integer; iImage: Integer; lParam: LPARAM; iIndent: Integer; // iGroupId: Integer; // cColumns: Integer;{ tile view columns } // puColumns: PUINT; end; PNMListView = ^TNMListView; TNMListView = packed record hdr: TNMHDR; iItem: Integer; iSubItem: Integer; uNewState: UINT; uOldState: UINT; uChanged: UINT; ptAction: TPoint; lParam: LPARAM; end; PCCInitCommonControlsEx = ^TCCInitCommonControlsEx; TCCInitCommonControlsEx = packed record dwSize: DWORD; dwICC: DWORD; end; { api definitions } // initialize common controls (progress bar) //procedure InitCommonControls; stdcall; external 'comctl32.dll' Name 'InitCommonControls'; function InitCommonControlsEx(const IntCtrls : PCCINITCOMMONCONTROLSEX): LongBool; stdcall; external 'comctl32.dll' Name 'InitCommonControlsEx'; {$IFDEF UNICODE} // needed by ShBrowseForFolder function SHBrowseForFolder(var lpbi: TBrowseInfo): pItemIDList; stdcall; external 'shell32.dll' Name 'SHBrowseForFolderW'; function SHGetPathFromIDList(pidl: pItemIDList; pszPath: PChar): BOOL; stdcall; external 'shell32.dll' Name 'SHGetPathFromIDListW'; {$ELSE} function SHBrowseForFolder(var lpbi: TBrowseInfo): pItemIDList; stdcall; external 'shell32.dll' Name 'SHBrowseForFolderA'; function SHGetPathFromIDList(pidl: pItemIDList; pszPath: PAnsiChar): BOOL; stdcall; external 'shell32.dll' Name 'SHGetPathFromIDListA'; {$ENDIF} //{$IFDEF DELPHI3UP} function SHGetMalloc(var ppMalloc: IMalloc): HResult; stdcall; external 'shell32.dll' Name 'SHGetMalloc'; // Lucjan Lukasik //{$ENDIF} {$IFDEF UNICODE} function SHGetFileInfo(pszPath: PChar; dwFileAttributes: DWORD; var psfi: TSHFileInfo; cbFileInfo, uFlags: Cardinal): DWORD; stdcall; external 'shell32.dll' name 'SHGetFileInfoW'; {$ELSE} function SHGetFileInfo(pszPath: PAnsiChar; dwFileAttributes: DWORD; var psfi: TSHFileInfo; cbFileInfo, uFlags: Cardinal): DWORD; stdcall; external 'shell32.dll' name 'SHGetFileInfoA'; {$ENDIF} function ShellExecute(hWnd: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: integer): HINST; stdcall; external 'shell32.dll' Name 'ShellExecuteA'; implementation end.
unit UninstSharedFileForm; { Inno Setup Copyright (C) 1997-2004 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. "Remove Shared File" form $jrsoftware: issrc/Projects/UninstSharedFileForm.pas,v 1.5 2007/12/04 04:34:30 jr Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SetupForm, StdCtrls, NewStaticText, BidiCtrls; type TUninstSharedFileForm = class(TSetupForm) BodyLabel: TNewStaticText; FilenameLabel: TNewStaticText; FilenameEdit: TEdit; LocationLabel: TNewStaticText; LocationEdit: TEdit; YesButton: TNewButton; YesToAllButton: TNewButton; NoButton: TNewButton; NoToAllButton: TNewButton; private { Private declarations } protected procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } constructor Create(AOwner: TComponent); override; end; function ExecuteRemoveSharedFileDlg(const Filename: String; var AAll: Boolean): Boolean; implementation uses PathFunc, Struct, Msgs, MsgIDs, Main; {$R *.DFM} const { These aren't defined on Delphi 2 } mrAll = mrNo + 1; mrNoToAll = mrAll + 1; mrYesToAll = mrNoToAll + 1; function ExecuteRemoveSharedFileDlg(const Filename: String; var AAll: Boolean): Boolean; var Form: TUninstSharedFileForm; Res: Integer; begin Form := TUninstSharedFileForm.Create(nil); try Form.FilenameEdit.Text := PathExtractName(Filename); Form.LocationEdit.Text := PathExtractDir(Filename); Res := Form.ShowModal; finally Form.Free; end; Result := (Res = mrYes) or (Res = mrYesToAll); AAll := (Res = mrYesToAll) or (Res = mrNoToAll); end; { TSelectLanguageForm } constructor TUninstSharedFileForm.Create(AOwner: TComponent); begin inherited; InitializeFont; Center; Caption := SetupMessages[msgConfirmDeleteSharedFileTitle]; BodyLabel.Caption := SetupMessages[msgConfirmDeleteSharedFile2]; FilenameLabel.Caption := SetupMessages[msgSharedFileNameLabel]; LocationLabel.Caption := SetupMessages[msgSharedFileLocationLabel]; YesButton.Caption := SetupMessages[msgButtonYes]; YesToAllButton.Caption := SetupMessages[msgButtonYesToAll]; NoButton.Caption := SetupMessages[msgButtonNo]; NoToAllButton.Caption := SetupMessages[msgButtonNoToAll]; end; procedure TUninstSharedFileForm.CreateParams(var Params: TCreateParams); begin inherited; Params.WindowClass.style := Params.WindowClass.style or CS_NOCLOSE; end; end.
{ lzRichEdit Copyright (C) 2010 Elson Junio elsonjunio@yahoo.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This library 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 General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Gtk2WSRichBox; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, LCLType, LCLProc, Clipbrd, StdCtrls, WSRichBox, gtk2, glib2, gdk2, pango, Gtk2Proc, Gtk2Def, gdk2pixbuf, Gtk2Globals, Gtk2WSControls, RichBox, Gtk2RTFTool; const BulletCode=$2022; type TWSFontAttributes=record Charset: TFontCharset; Color: TColor; Name: TFontName; Pitch: TFontPitch; fProtected: Boolean; Size: Integer; Style: TFontStyles; end; TWSParaAttributes=record Alignment: TAlignment; FirstIndent: Integer; LeftIndent: Integer; RightIndent: Integer; Numbering: TNumberingStyle; Tab: Integer; TabCount: Integer; end; { TGtk2WSCustomRichBox } TGtk2WSCustomRichBox = class(TWSCustomRichBox) class function CreateHandle(const AWinControl: TWinControl; const AParams: TCreateParams): TLCLIntfHandle; override; //Funções de Fonte class function Font_GetColor(const AWinControl: TWinControl): TColor; override; class function Font_GetName(const AWinControl: TWinControl): TFontName; override; class function Font_GetSize(const AWinControl: TWinControl): integer; override; class function Font_GetStyle(const AWinControl: TWinControl): TFontStyles; override; // //Funções de Paragrafos class function Para_GetAlignment(const AWinControl: TWinControl): TAlignment; override; class function Para_GetFirstIndent(const AWinControl: TWinControl): Longint; override; class function Para_GetLeftIndent(const AWinControl: TWinControl): Longint; override; class function Para_GetRightIndent(const AWinControl: TWinControl): Longint; override; class function Para_GetNumbering(const AWinControl: TWinControl): TNumberingStyle; override; // //Procedimentos de Fonte class procedure Font_SetColor(const AWinControl: TWinControl; Value: TColor); override; class procedure Font_SetName(const AWinControl: TWinControl; Value: TFontName); override; class procedure Font_SetSize(const AWinControl: TWinControl; Value: integer); override; class procedure Font_SetStyle(const AWinControl: TWinControl; Value: TFontStyles); override; // //Procedimentos de Paragrafos class procedure Para_SetAlignment(const AWinControl: TWinControl; Value: TAlignment); override; class procedure Para_SetFirstIndent(const AWinControl: TWinControl; Value: Longint); override; class procedure Para_SetLeftIndent(const AWinControl: TWinControl; Value: Longint); override; class procedure Para_SetRightIndent(const AWinControl: TWinControl; Value: Longint); override; class procedure Para_SetNumbering(const AWinControl: TWinControl; Value: TNumberingStyle); override; class procedure Paste(const ACustomEdit: TCustomEdit); override; // class procedure SaveToStream(const AWinControl: TWinControl; var Stream: TStream); override; class procedure LoadFromStream(const AWinControl: TWinControl; const Stream: TStream); override; // class function GetTextBuf (const AWinControl: TWinControl):String; override; class function GetTextSel (const AWinControl: TWinControl):String; override; end; {Exceptional} function WGGetBuffer(const AWinControl: TWinControl; var Buffer: PGtkTextBuffer): boolean; function WGGetRealTextBuf(const AWinControl: TWinControl; var S:String): Boolean; function WGGetFontAttributes(const AWinControl: TWinControl; Position:Integer; var FontAttributes: TWSFontAttributes): boolean; function WGGetParaAttributes(const AWinControl: TWinControl; Position:Integer; var ParaAttributes: TWSParaAttributes): boolean; function WGGetPos_FirstCharacter_Line(const AWinControl: TWinControl; Position: integer): integer; function WGGetPos_LastCharacter_Line(const AWinControl: TWinControl; Position: integer): integer; function WGGetNumbering(const AWinControl: TWinControl; Position: integer):TNumberingStyle; procedure WGSetFormat(const iSelStart, iSelLength: integer; Buffer: PGtkTextBuffer; Tag: Pointer); Procedure WGDelete(const AWinControl: TWinControl; iSelStart, iSelLength: integer); procedure WGInsertPos(const AWinControl: TWinControl; Position:Integer; const S:String); procedure WGInsertImage(const AWinControl: TWinControl; Position: integer; Image: TPicture; ResizeWidth, ResizeHeight: integer); {...} implementation function WGGetBuffer(const AWinControl: TWinControl; var Buffer: PGtkTextBuffer ): boolean; var AWidget: PGtkWidget; begin Result := False; //-- AWidget := PGtkWidget(AWinControl.Handle); AWidget := GetWidgetInfo(AWidget, False)^.CoreWidget; if not (Assigned(AWidget)) then Exit; //-- Buffer := gtk_text_view_get_buffer(PGtkTextView(AWidget)); if not (Assigned(Buffer)) then Exit; //-- Result := True; end; function WGGetRealTextBuf(const AWinControl: TWinControl; var S: String ): Boolean; var iterStart, iterEnd: TGtkTextIter; Buffer: PGtkTextBuffer=nil; begin Result:= False; if not (WGGetBuffer(AWinControl, Buffer)) then Exit; gtk_text_buffer_get_start_iter(Buffer, @iterStart); gtk_text_buffer_get_end_iter(Buffer, @iterEnd); S := gtk_text_buffer_get_slice(Buffer, @iterStart, @iterEnd, gboolean(False)); Result:= True; end; function WGGetFontAttributes(const AWinControl: TWinControl; Position: Integer; var FontAttributes: TWSFontAttributes): boolean; var Buffer: PGtkTextBuffer = nil; Attributes: PGtkTextAttributes; iPosition: TGtkTextIter; begin Result:= False; //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- Attributes := gtk_text_attributes_new; if not Assigned(Attributes) then Exit; //-- gtk_text_buffer_get_iter_at_offset(buffer, @iPosition, Position); //-- if (gtk_text_iter_get_attributes(@iPosition, Attributes)) then begin FontAttributes.Name := pango_font_description_get_family(Attributes^.font); FontAttributes.Size := pango_font_description_get_size(Attributes^.font); if not (pango_font_description_get_size_is_absolute(Attributes^.font)) then FontAttributes.Size := Round(FontAttributes.Size / PANGO_SCALE); FontAttributes.Color := TGDKColorToTColor(Attributes^.appearance.fg_color); //-- FontAttributes.Style := []; //-- if (Strikethrough(Attributes^.appearance) > 0) then Include(FontAttributes.Style, fsStrikeOut); if (underline(Attributes^.appearance) > 0) then Include(FontAttributes.Style, fsUnderline); //-- if (pango_font_description_get_weight(Attributes^.font) = PANGO_WEIGHT_BOLD) then Include(FontAttributes.Style,fsBold); if (pango_font_description_get_style(Attributes^.font) = PANGO_STYLE_ITALIC) then Include(FontAttributes.Style,fsItalic); //-- Result:= True; end; gtk_text_attributes_unref(Attributes); end; function WGGetParaAttributes(const AWinControl: TWinControl; Position: Integer; var ParaAttributes: TWSParaAttributes): boolean; var Buffer: PGtkTextBuffer = nil; Attributes: PGtkTextAttributes; iPosition: TGtkTextIter; begin Result:= False; //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- Attributes := gtk_text_attributes_new; if not Assigned(Attributes) then Exit; //-- gtk_text_buffer_get_iter_at_offset(buffer, @iPosition, Position); //-- if (gtk_text_iter_get_attributes(@iPosition, Attributes)) then begin case Attributes^.justification of GTK_JUSTIFY_LEFT: ParaAttributes.Alignment := taLeftJustify; GTK_JUSTIFY_RIGHT: ParaAttributes.Alignment := taRightJustify; GTK_JUSTIFY_CENTER: ParaAttributes.Alignment := taCenter; end; //-- ParaAttributes.LeftIndent := Attributes^.left_margin div 37; ParaAttributes.RightIndent := Attributes^.right_margin div 37; ParaAttributes.FirstIndent := Attributes^.indent div 37; //-- Result:= True; end; gtk_text_attributes_unref(Attributes); end; function WGGetPos_FirstCharacter_Line(const AWinControl: TWinControl; Position: integer): integer; var S: string=''; CH: TUTF8Char; I, I2: integer; begin Result:= 0; if not(WGGetRealTextBuf(AWinControl, S)) then Exit; for I := Position downto 0 do begin CH := UTF8Copy(S, I, 1); if (UTF8CharacterToUnicode(@CH[1], I2) = $A) or (I = 0) then begin Result := I; Exit; end; end; Result := Position; end; function WGGetPos_LastCharacter_Line(const AWinControl: TWinControl; Position: integer): integer; var S: string=''; CH: TUTF8Char; I, I2: integer; Len: integer; begin Result:= 0; if not(WGGetRealTextBuf(AWinControl, S)) then Exit; Len := UTF8Length(S); for I := Position to Len do begin CH := UTF8Copy(S, I, 1); if (UTF8CharacterToUnicode(@CH[1], I2) = $A) or (I = Len) then begin Result := I; Exit; end; end; Result := Position; end; function WGGetNumbering(const AWinControl: TWinControl; Position: integer ): TNumberingStyle; var I: integer; CH: TUTF8Char; RText: String=''; begin Result:= nsNone; I := WGGetPos_FirstCharacter_Line(AWinControl, Position); if not(WGGetRealTextBuf(AWinControl, RText)) then Exit; CH:= UTF8Copy(RText, I + 1, 1); if (UTF8CharacterToUnicode(@CH[1], I) = BulletCode) then Result:= nsBullets; end; procedure WGSetFormat(const iSelStart, iSelLength: integer; Buffer: PGtkTextBuffer; Tag: Pointer); var iterStart, iterEnd: TGtkTextIter; begin gtk_text_buffer_get_iter_at_offset(buffer, @iterStart, iSelStart); gtk_text_buffer_get_iter_at_offset(buffer, @iterEnd, iSelStart + iSelLength); gtk_text_buffer_apply_tag(buffer, tag, @iterStart, @iterEnd); end; procedure WGDelete(const AWinControl: TWinControl; iSelStart, iSelLength: integer); var iterStart, iterEnd: TGtkTextIter; Buffer: PGtkTextBuffer; begin if not (WGGetBuffer(AWinControl, Buffer)) then Exit; gtk_text_buffer_get_iter_at_offset(buffer, @iterStart, iSelStart); gtk_text_buffer_get_iter_at_offset(buffer, @iterEnd, iSelStart + iSelLength); gtk_text_buffer_delete(buffer, @iterStart, @iterEnd); end; procedure WGInsertPos(const AWinControl: TWinControl; Position: Integer; const S: String); var iterStart: TGtkTextIter; Buffer: PGtkTextBuffer = nil; Ch: String; //N2:Boolean=False; begin if not (WGGetBuffer(AWinControl, Buffer)) then Exit; if (Position < 0) then Exit; //-- Ch := S; gtk_text_buffer_get_iter_at_offset(Buffer, @iterStart, Position); gtk_text_buffer_insert(Buffer, @iterStart, @Ch[1], Length(Ch)); end; procedure WGInsertImage(const AWinControl: TWinControl; Position: integer; Image: TPicture; ResizeWidth, ResizeHeight: integer); var Buffer: PGtkTextBuffer = nil; iPosition: TGtkTextIter; GDIObj: PGDIObject = nil; pixbuf: PGDKPixBuf = nil; scaled: PGDKPixBuf = nil; pixmap: PGdkDrawable = nil; bitmap: PGdkBitmap = nil; Width, Height: integer; begin if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- gtk_text_buffer_get_iter_at_offset(buffer, @iPosition, Position); //-- GDIObj := PGDIObject(Image.Bitmap.Handle); //-- case GDIObj^.GDIBitmapType of gbBitmap: begin bitmap := GDIObj^.GDIBitmapObject; gdk_drawable_get_size(bitmap, @Width, @Height); pixbuf := CreatePixbufFromDrawable(bitmap, nil, False, 0, 0, 0, 0, Width, Height); end; gbPixmap: begin pixmap := GDIObj^.GDIPixmapObject.Image; if pixmap <> nil then begin gdk_drawable_get_size(pixmap, @Width, @Height); bitmap := CreateGdkMaskBitmap(Image.Bitmap.Handle, 0); pixbuf := CreatePixbufFromImageAndMask(pixmap, 0, 0, Width, Height, nil, Bitmap); end; end; gbPixbuf: begin pixbuf := gdk_pixbuf_copy(GDIObj^.GDIPixbufObject); end; end; if (ResizeWidth > 1) and (ResizeHeight > 1) then begin scaled := gdk_pixbuf_scale_simple(pixbuf, ResizeWidth, ResizeHeight, GDK_INTERP_HYPER); g_object_unref(pixbuf); pixbuf := scaled; end; if (pixbuf <> nil) then gtk_text_buffer_insert_pixbuf(buffer, @iPosition, pixbuf); end; { TGtk2WSCustomRichBox } class function TGtk2WSCustomRichBox.CreateHandle( const AWinControl: TWinControl; const AParams: TCreateParams ): TLCLIntfHandle; var Widget, TempWidget: PGtkWidget; WidgetInfo: PWidgetInfo; begin Widget := gtk_scrolled_window_new(nil, nil); Result := TLCLIntfHandle(PtrUInt(Widget)); if Result = 0 then Exit; WidgetInfo := CreateWidgetInfo(Pointer(Result), AWinControl, AParams); TempWidget := gtk_text_view_new(); gtk_container_add(PGtkContainer(Widget), TempWidget); GTK_WIDGET_UNSET_FLAGS(PGtkScrolledWindow(Widget)^.hscrollbar, GTK_CAN_FOCUS); GTK_WIDGET_UNSET_FLAGS(PGtkScrolledWindow(Widget)^.vscrollbar, GTK_CAN_FOCUS); gtk_scrolled_window_set_policy(PGtkScrolledWindow(Widget), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(PGtkScrolledWindow(Widget), BorderStyleShadowMap[TCustomControl(AWinControl).BorderStyle]); SetMainWidget(Widget, TempWidget); GetWidgetInfo(Widget, True)^.CoreWidget := TempWidget; gtk_text_view_set_editable(PGtkTextView(TempWidget), True); if TCustomRichBox(AWinControl).WordWrap then gtk_text_view_set_wrap_mode(PGtkTextView(TempWidget), GTK_WRAP_WORD) else gtk_text_view_set_wrap_mode(PGtkTextView(TempWidget), GTK_WRAP_NONE); gtk_text_view_set_accepts_tab(PGtkTextView(TempWidget), TCustomRichBox(AWinControl).WantTabs); gtk_widget_show_all(Widget); Set_RC_Name(AWinControl, Widget); TGtk2WSWinControl.SetCallbacks(PGtkObject(Widget), TComponent(WidgetInfo^.LCLObject)); end; class function TGtk2WSCustomRichBox.Font_GetColor(const AWinControl: TWinControl ): TColor; var FontAttributes: TWSFontAttributes; begin if WGGetFontAttributes(AWinControl, TRichBox(AWinControl).SelStart, FontAttributes) then Result:= FontAttributes.Color else Result:= clBlack; end; class function TGtk2WSCustomRichBox.Font_GetName(const AWinControl: TWinControl ): TFontName; var FontAttributes: TWSFontAttributes; begin if WGGetFontAttributes(AWinControl, TRichBox(AWinControl).SelStart, FontAttributes) then Result:= FontAttributes.Name else Result:= ''; end; class function TGtk2WSCustomRichBox.Font_GetSize(const AWinControl: TWinControl ): integer; var FontAttributes: TWSFontAttributes; begin if WGGetFontAttributes(AWinControl, TRichBox(AWinControl).SelStart, FontAttributes) then Result:= FontAttributes.Size else Result:= 10; end; class function TGtk2WSCustomRichBox.Font_GetStyle(const AWinControl: TWinControl ): TFontStyles; var FontAttributes: TWSFontAttributes; begin if WGGetFontAttributes(AWinControl, TRichBox(AWinControl).SelStart, FontAttributes) then Result:= FontAttributes.Style else Result:= []; end; class function TGtk2WSCustomRichBox.Para_GetAlignment( const AWinControl: TWinControl): TAlignment; var ParaAttributes: TWSParaAttributes; begin if WGGetParaAttributes(AWinControl, TRichBox(AWinControl).SelStart, ParaAttributes) then Result:= ParaAttributes.Alignment else Result:= taLeftJustify; end; class function TGtk2WSCustomRichBox.Para_GetFirstIndent( const AWinControl: TWinControl): Longint; var ParaAttributes: TWSParaAttributes; begin if WGGetParaAttributes(AWinControl, TRichBox(AWinControl).SelStart, ParaAttributes) then Result:= ParaAttributes.FirstIndent else Result:= 0; end; class function TGtk2WSCustomRichBox.Para_GetLeftIndent( const AWinControl: TWinControl): Longint; var ParaAttributes: TWSParaAttributes; begin if WGGetParaAttributes(AWinControl, TRichBox(AWinControl).SelStart, ParaAttributes) then Result:= ParaAttributes.LeftIndent else Result:= 0; end; class function TGtk2WSCustomRichBox.Para_GetRightIndent( const AWinControl: TWinControl): Longint; var ParaAttributes: TWSParaAttributes; begin if WGGetParaAttributes(AWinControl, TRichBox(AWinControl).SelStart, ParaAttributes) then Result:= ParaAttributes.RightIndent else Result:= 0; end; class function TGtk2WSCustomRichBox.Para_GetNumbering( const AWinControl: TWinControl): TNumberingStyle; begin Result:= WGGetNumbering(AWinControl, WGGetPos_FirstCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart)); end; class procedure TGtk2WSCustomRichBox.Font_SetColor( const AWinControl: TWinControl; Value: TColor); var FontColor: TGDKColor; Buffer: PGtkTextBuffer = nil; Tag: Pointer = nil; begin FontColor := TColortoTGDKColor(Value); //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- Tag := gtk_text_buffer_create_tag(buffer, nil, 'foreground-gdk',[@FontColor, 'foreground-set', gboolean(gTRUE), nil]); //-- WGSetFormat(TRichBox(AWinControl).SelStart, TRichBox(AWinControl).SelLength, Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Font_SetName( const AWinControl: TWinControl; Value: TFontName); var FontFamily: string; Buffer: PGtkTextBuffer = nil; Tag: Pointer = nil; begin FontFamily := Value; //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- Tag := gtk_text_buffer_create_tag(buffer, nil, 'family', [@FontFamily[1], 'family-set', gTRUE, nil]); //-- WGSetFormat(TRichBox(AWinControl).SelStart, TRichBox(AWinControl).SelLength, Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Font_SetSize( const AWinControl: TWinControl; Value: integer); var Buffer: PGtkTextBuffer = nil; Tag: Pointer = nil; begin //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- Tag := gtk_text_buffer_create_tag(buffer, nil, 'size-points', [double(Value), nil]); //-- WGSetFormat(TRichBox(AWinControl).SelStart, TRichBox(AWinControl).SelLength, Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Font_SetStyle( const AWinControl: TWinControl; Value: TFontStyles); var Tag: Pointer = nil; Buffer: PGtkTextBuffer = nil; const PangoUnderline: array [boolean] of integer = (PANGO_UNDERLINE_NONE, PANGO_UNDERLINE_SINGLE); PangoBold: array [boolean] of integer = (PANGO_WEIGHT_NORMAL, PANGO_WEIGHT_BOLD); PangoItalic: array [boolean] of integer = (PANGO_STYLE_NORMAL, PANGO_STYLE_ITALIC); begin if not (WGGetBuffer(AWinControl, Buffer)) then Exit; Tag := gtk_text_buffer_create_tag(buffer, nil, 'underline', [PangoUnderline[fsUnderline in Value], 'underline-set', gboolean(gTRUE), 'weight', PangoBold[fsBold in Value], 'weight-set', gboolean(gTRUE), 'style', PangoItalic[fsItalic in Value], 'style-set', gboolean(gTRUE), 'strikethrough', gboolean(fsStrikeOut in Value), 'strikethrough-set', gboolean(gTRUE), nil]); WGSetFormat(TRichBox(AWinControl).SelStart, TRichBox(AWinControl).SelLength, Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Para_SetAlignment( const AWinControl: TWinControl; Value: TAlignment); const GTKJustification: array [TAlignment] of integer = (GTK_JUSTIFY_LEFT, GTK_JUSTIFY_RIGHT, GTK_JUSTIFY_CENTER); var Tag: Pointer = nil; Buffer: PGtkTextBuffer = nil; StartLine, EndLine:Integer; begin //-- StartLine:= WGGetPos_FirstCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); EndLine:= WGGetPos_LastCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); if (TRichBox(AWinControl).SelLength) > (EndLine - StartLine) then EndLine:= WGGetPos_LastCharacter_Line(AWinControl, (TRichBox(AWinControl).SelStart + TRichBox(AWinControl).SelLength)); //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; Tag := gtk_text_buffer_create_tag(buffer, nil, 'justification', [GTKJustification[Value], 'justification-set', gboolean(gTRUE), nil]); WGSetFormat(StartLine, (EndLine - StartLine), Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Para_SetFirstIndent( const AWinControl: TWinControl; Value: Longint); var Tag: Pointer = nil; Buffer: PGtkTextBuffer = nil; StartLine, EndLine:Integer; begin //-- StartLine:= WGGetPos_FirstCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); EndLine:= WGGetPos_LastCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); //-- if (TRichBox(AWinControl).SelLength) > (EndLine - StartLine) then EndLine:= WGGetPos_LastCharacter_Line(AWinControl, (TRichBox(AWinControl).SelStart + TRichBox(AWinControl).SelLength)); //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; Tag := gtk_text_buffer_create_tag(buffer, nil, 'indent', [Value * 37, 'indent-set', gboolean(gTRUE), nil]); WGSetFormat(StartLine, (EndLine - StartLine), Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Para_SetLeftIndent( const AWinControl: TWinControl; Value: Longint); var Tag: Pointer = nil; Buffer: PGtkTextBuffer = nil; StartLine, EndLine:Integer; begin //-- StartLine:= WGGetPos_FirstCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); EndLine:= WGGetPos_LastCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); //-- if (TRichBox(AWinControl).SelLength) > (EndLine - StartLine) then EndLine:= WGGetPos_LastCharacter_Line(AWinControl, (TRichBox(AWinControl).SelStart + TRichBox(AWinControl).SelLength)); //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; Tag := gtk_text_buffer_create_tag(buffer, nil, 'left_margin', [Value * 37, 'left_margin-set', gboolean(gTRUE), nil]); WGSetFormat(StartLine, (EndLine - StartLine), Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Para_SetRightIndent( const AWinControl: TWinControl; Value: Longint); var Tag: Pointer = nil; Buffer: PGtkTextBuffer = nil; StartLine, EndLine:Integer; begin //-- StartLine:= WGGetPos_FirstCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); EndLine:= WGGetPos_LastCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); //-- if (TRichBox(AWinControl).SelLength) > (EndLine - StartLine) then EndLine:= WGGetPos_LastCharacter_Line(AWinControl, (TRichBox(AWinControl).SelStart + TRichBox(AWinControl).SelLength)); //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; Tag := gtk_text_buffer_create_tag(buffer, nil, 'right_margin', [Value * 37, 'right_margin-set', gboolean(gTRUE), nil]); WGSetFormat(StartLine, (EndLine - StartLine), Buffer, Tag); end; class procedure TGtk2WSCustomRichBox.Para_SetNumbering( const AWinControl: TWinControl; Value: TNumberingStyle); var I: integer; iterStart, iterEnd: TGtkTextIter; Buffer: PGtkTextBuffer = nil; Ch: TUTF8Char; N2: TNumberingStyle = nsNone; begin I := WGGetPos_FirstCharacter_Line(AWinControl, TRichBox(AWinControl).SelStart); if not (WGGetBuffer(AWinControl, Buffer)) then Exit; N2:= Para_GetNumbering(AWinControl); if (Value = nsNone) and (N2 = nsBullets) then begin gtk_text_buffer_get_iter_at_offset(Buffer, @iterStart, I); gtk_text_buffer_get_iter_at_offset(Buffer, @iterEnd, I + 1); gtk_text_buffer_Delete(Buffer, @iterStart, @iterEnd); end; if (Value = nsBullets) and (N2 = nsNone) then begin Ch := UnicodeToUTF8(BulletCode); gtk_text_buffer_get_iter_at_offset(Buffer, @iterStart, I); gtk_text_buffer_insert(Buffer, @iterStart, @Ch[1], Length(Ch)); //-- end; end; class procedure TGtk2WSCustomRichBox.Paste(const ACustomEdit: TCustomEdit); var S:String; P:TPicture; begin if Clipboard.HasFormat(CF_TEXT) then begin if ACustomEdit.SelLength > 0 then WGDelete(ACustomEdit, ACustomEdit.SelStart, ACustomEdit.SelLength); S := Clipboard.AsText; WGInsertPos(ACustomEdit, ACustomEdit.SelStart ,S); end; if Clipboard.HasFormat(CF_Bitmap) or Clipboard.HasFormat(CF_Picture) then begin if ACustomEdit.SelLength > 0 then WGDelete(ACustomEdit, ACustomEdit.SelStart, ACustomEdit.SelLength); P:=TPicture.Create; if Clipboard.HasFormat(CF_Bitmap) then P.Bitmap.Assign(Clipboard) else P.Assign(Clipboard); WGInsertImage(ACustomEdit, ACustomEdit.SelStart, P, 0, 0); P.Free; end; end; class procedure TGtk2WSCustomRichBox.SaveToStream( const AWinControl: TWinControl; var Stream: TStream); var RTFSave: TRTFSave; begin RTFSave:= TRTFSave.Create(AWinControl); RTFSave.SaveToStream(Stream); RTFSave.Free; end; class procedure TGtk2WSCustomRichBox.LoadFromStream( const AWinControl: TWinControl; const Stream: TStream); var RTFRead:TRTFRead; begin RTFRead:=TRTFRead.Create(AWinControl); RTFRead.LoadFromStream(Stream); RTFRead.Free; end; class function TGtk2WSCustomRichBox.GetTextBuf(const AWinControl: TWinControl ): String; var iterStart, iterEnd: TGtkTextIter; Buffer: PGtkTextBuffer=nil; begin Result := ''; if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- gtk_text_buffer_get_start_iter(Buffer, @iterStart); gtk_text_buffer_get_end_iter(Buffer, @iterEnd); Result := gtk_text_buffer_get_slice(Buffer, @iterStart, @iterEnd, gboolean(False)); end; class function TGtk2WSCustomRichBox.GetTextSel(const AWinControl: TWinControl ): String; var SelStart, SelEnd:Integer; iterStart, iterEnd: TGtkTextIter; Buffer: PGtkTextBuffer = nil; begin SelStart:= TRichBox(AWinControl).SelStart; SelEnd:= TRichBox(AWinControl).SelStart + TRichBox(AWinControl).SelLength; //-- if not (WGGetBuffer(AWinControl, Buffer)) then Exit; //-- gtk_text_buffer_get_iter_at_offset(Buffer, @iterStart, SelStart); gtk_text_buffer_get_iter_at_offset(Buffer, @iterEnd, SelEnd); //-- Result := gtk_text_buffer_get_slice(Buffer, @iterStart, @iterEnd, gboolean(False)); end; end.
unit MFichas.Controller.Usuario.Operacoes.PedirSenha; interface uses MFichas.Controller.Usuario.Operacoes.Interfaces, MFichas.Controller.Types; type TControllerUsuarioOperacoesPedirSenha = class(TInterfacedObject, iControllerUsuarioOperacoes, iControllerUsuarioOperacoesPedirSenha) private FTitle : String; FTextConfirm: String; FTextCancel : String; FChamada : TTypeTipoUsuario; FOperacao : TTypePermissoesUsuario; constructor Create; public destructor Destroy; override; class function New: iControllerUsuarioOperacoes; function PedirSenha: iControllerUsuarioOperacoesPedirSenha; function SetTitle(ATitle: String) : iControllerUsuarioOperacoesPedirSenha; function SetTextConfirm(ATextConfirm: String) : iControllerUsuarioOperacoesPedirSenha; function SetTextCancel(ATextCancel: String) : iControllerUsuarioOperacoesPedirSenha; function SetChamada(AChamada: TTypeTipoUsuario): iControllerUsuarioOperacoesPedirSenha; function SetOperacao(AOperacao: TTypePermissoesUsuario): iControllerUsuarioOperacoesPedirSenha; function &End : iControllerUsuarioOperacoesPedirSenha; end; implementation uses MaykoFichas.View.Principal; { TControllerUsuarioOperacoesPedirSenha } function TControllerUsuarioOperacoesPedirSenha.&End: iControllerUsuarioOperacoesPedirSenha; begin Result := Self; Form3 .ExibirFormSenha( FTitle, FTextConfirm, FTextCancel, FChamada, FOperacao ); end; constructor TControllerUsuarioOperacoesPedirSenha.Create; begin end; destructor TControllerUsuarioOperacoesPedirSenha.Destroy; begin inherited; end; class function TControllerUsuarioOperacoesPedirSenha.New: iControllerUsuarioOperacoes; begin Result := Self.Create; end; function TControllerUsuarioOperacoesPedirSenha.PedirSenha: iControllerUsuarioOperacoesPedirSenha; begin Result := Self; end; function TControllerUsuarioOperacoesPedirSenha.SetChamada(AChamada: TTypeTipoUsuario): iControllerUsuarioOperacoesPedirSenha; begin Result := Self; FChamada := AChamada; end; function TControllerUsuarioOperacoesPedirSenha.SetOperacao( AOperacao: TTypePermissoesUsuario): iControllerUsuarioOperacoesPedirSenha; begin Result := Self; FOperacao := AOperacao; end; function TControllerUsuarioOperacoesPedirSenha.SetTextCancel(ATextCancel: String) : iControllerUsuarioOperacoesPedirSenha; begin Result := Self; FTextCancel := ATextCancel; end; function TControllerUsuarioOperacoesPedirSenha.SetTextConfirm(ATextConfirm: String): iControllerUsuarioOperacoesPedirSenha; begin Result := Self; FTextConfirm := ATextConfirm; end; function TControllerUsuarioOperacoesPedirSenha.SetTitle(ATitle: String) : iControllerUsuarioOperacoesPedirSenha; begin Result := Self; FTitle := ATitle; end; end.
unit UserTests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ChannelList, fpcunit, testutils, testregistry; type { TUserTests } TUserTests = class(TTestCase) private FSUT: TUser; published procedure RemoveOPVoiceChars; procedure MaintainOpVoicePrefixInChannel; end; implementation procedure TUserTests.RemoveOPVoiceChars; begin FSUT := TUser.Create('@op'); try CheckEquals('op', FSUT.NickName, '@ char must be removed from OP nicks'); finally FSUT.Free; end; FSUT := TUser.Create('+voice'); try CheckEquals('voice', FSUT.NickName, '+ char must be removed from voice nicks'); finally FSUT.Free; end; end; procedure TUserTests.MaintainOpVoicePrefixInChannel; begin FSUT := TUser.Create('@op'); try FSUT.NickName := 'nick'; CheckEquals('@nick', FSUT.NickNameInChannel); finally FSUT.Free; end; FSUT := TUser.Create('+voice'); try FSUT.NickName := 'myvoice'; CheckEquals('+myvoice', FSUT.NickNameInChannel); finally FSUT.Free; end; end; initialization RegisterTest(TUserTests); end.
unit ClientModule; interface uses System.SysUtils, System.Classes, ClientClassesUnit, IPPeerClient, Datasnap.DSClientRest, uModel, cxStyles, cxClasses, uSettingApp; type TClientDataModule = class(TDataModule) DSRestConnection: TDSRestConnection; cxStyleRepTrans: TcxStyleRepository; cxstylGridHeader: TcxStyle; cxstylGridOdd: TcxStyle; cxstylGridEven: TcxStyle; cxstylGridFooter: TcxStyle; procedure DataModuleCreate(Sender: TObject); private FCabang: tcabang; FInstanceOwner: Boolean; FServerUOMClient: TServerUOMClient; FServerSupplierClient: TServerSupplierClient; FServerBarangClient: TServerBarangClient; FServerGroupBarangClient: TServerGroupBarangClient; FServerPenerimaanBarangClient: TServerPenerimaanBarangClient; FServerCabangClient: TServerCabangClient; FServerLogAppObjectClient: TServerLogAppObjectClient; FServerUtilsClient: TServerUtilsClient; FServerReturSupplierClient: TServerReturSupplierClient; FServerGudangClient: TServerGudangClient; FServerLaporanClient: TServerLaporanClient; FServerCustomerInvoiceClient: TServerCustomerInvoiceClient; FServerPenjualanClient: TServerPenjualanClient; FServerAccountClient: TServerAccountClient; FServerRekBankClient: TServerRekBankClient; FServerPenerimaanKasClient: TServerPenerimaanKasClient; FDSDataCLient: TDSDataClient; FServerPengeluaranKasClient: TServerPengeluaranKasClient; FServerSettingAppClient: TServerSettingAppClient; FServerTAGRequestClient: TServerTAGRequestClient; FServerTransferAntarGudang: TServerTransferAntarGudangClient; FSettingApp: TSettingApp; FServerTransferAntarCabangKirimClient: TServerTransferAntarCabangKirimClient; FServerTransferAntarCabangTerimaClient: TServerTransferAntarCabangTerimaClient; FServerJurnalClient: TServerJurnalClient; FServerMenuClient: TServerMenuClient; FServerUserClient: TServerUserClient; FServerSettlementARAPClient: TServerSettlementARAPClient; FServerAPClient: TServerAPClient; FServerPenarikanDepositClient: TServerPenarikanDepositClient; function GetCabang: tcabang; function GetServerUOMClient: TServerUOMClient; function GetServerSupplierClient: TServerSupplierClient; function GetServerBarangClient: TServerBarangClient; function GetServerGroupBarangClient: TServerGroupBarangClient; function GetServerPenerimaanBarangClient: TServerPenerimaanBarangClient; function GetServerCabangClient: TServerCabangClient; function GetServerLogAppObjectClient: TServerLogAppObjectClient; function GetServerUtilsClient: TServerUtilsClient; function GetServerReturSupplierClient: TServerReturSupplierClient; function GetServerGudangClient: TServerGudangClient; function GetServerLaporanClient: TServerLaporanClient; function GetServerCustomerInvoiceClient: TServerCustomerInvoiceClient; function GetServerPenjualanClient: TServerPenjualanClient; function GetServerAccountClient: TServerAccountClient; function GetServerRekBankClient: TServerRekBankClient; function GetServerPenerimaanKasClient: TServerPenerimaanKasClient; function GetDSDataCLient: TDSDataClient; function GetServerPengeluaranKasClient: TServerPengeluaranKasClient; function GetServerSettingAppClient: TServerSettingAppClient; function GetServerTAGRequestClient: TServerTAGRequestClient; function GetServerTransferAntarGudang: TServerTransferAntarGudangClient; function GetSettingApp: TSettingApp; function GetServerTransferAntarCabangKirimClient: TServerTransferAntarCabangKirimClient; function GetServerTransferAntarCabangTerimaClient: TServerTransferAntarCabangTerimaClient; function GetServerJurnalClient: TServerJurnalClient; function GetServerMenuClient: TServerMenuClient; function GetServerUserClient: TServerUserClient; function GeTServerSettlementARAPClient: TServerSettlementARAPClient; function GetServerAPClient: TServerAPClient; function GetServerPenarikanDepositClient: TServerPenarikanDepositClient; { Private declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Cabang: tcabang read GetCabang write FCabang; property InstanceOwner: Boolean read FInstanceOwner write FInstanceOwner; property ServerAccountClient: TServerAccountClient read GetServerAccountClient write FServerAccountClient; property ServerRekBankClient: TServerRekBankClient read GetServerRekBankClient write FServerRekBankClient; property ServerUOMClient: TServerUOMClient read GetServerUOMClient write FServerUOMClient; property ServerSupplierClient: TServerSupplierClient read GetServerSupplierClient write FServerSupplierClient; property ServerBarangClient: TServerBarangClient read GetServerBarangClient write FServerBarangClient; property ServerGroupBarangClient: TServerGroupBarangClient read GetServerGroupBarangClient write FServerGroupBarangClient; property ServerPenerimaanBarangClient: TServerPenerimaanBarangClient read GetServerPenerimaanBarangClient write FServerPenerimaanBarangClient; property ServerCabangClient: TServerCabangClient read GetServerCabangClient write FServerCabangClient; property ServerLogAppObjectClient: TServerLogAppObjectClient read GetServerLogAppObjectClient write FServerLogAppObjectClient; property ServerUtilsClient: TServerUtilsClient read GetServerUtilsClient write FServerUtilsClient; property ServerReturSupplierClient: TServerReturSupplierClient read GetServerReturSupplierClient write FServerReturSupplierClient; property ServerGudangClient: TServerGudangClient read GetServerGudangClient write FServerGudangClient; property ServerLaporanClient: TServerLaporanClient read GetServerLaporanClient write FServerLaporanClient; property ServerCustomerInvoiceClient: TServerCustomerInvoiceClient read GetServerCustomerInvoiceClient write FServerCustomerInvoiceClient; property ServerPenjualanClient: TServerPenjualanClient read GetServerPenjualanClient write FServerPenjualanClient; property ServerPenerimaanKasClient: TServerPenerimaanKasClient read GetServerPenerimaanKasClient write FServerPenerimaanKasClient; property DSDataCLient: TDSDataClient read GetDSDataCLient write FDSDataCLient; property ServerPengeluaranKasClient: TServerPengeluaranKasClient read GetServerPengeluaranKasClient write FServerPengeluaranKasClient; property ServerSettingAppClient: TServerSettingAppClient read GetServerSettingAppClient write FServerSettingAppClient; property ServerTAGRequestClient: TServerTAGRequestClient read GetServerTAGRequestClient write FServerTAGRequestClient; property ServerTransferAntarGudang: TServerTransferAntarGudangClient read GetServerTransferAntarGudang write FServerTransferAntarGudang; property SettingApp: TSettingApp read GetSettingApp write FSettingApp; property ServerTransferAntarCabangKirimClient: TServerTransferAntarCabangKirimClient read GetServerTransferAntarCabangKirimClient write FServerTransferAntarCabangKirimClient; property ServerTransferAntarCabangTerimaClient: TServerTransferAntarCabangTerimaClient read GetServerTransferAntarCabangTerimaClient write FServerTransferAntarCabangTerimaClient; property ServerJurnalClient: TServerJurnalClient read GetServerJurnalClient write FServerJurnalClient; property ServerMenuClient: TServerMenuClient read GetServerMenuClient write FServerMenuClient; property ServerUserClient: TServerUserClient read GetServerUserClient write FServerUserClient; property ServerSettlementARAPClient: TServerSettlementARAPClient read GeTServerSettlementARAPClient write FServerSettlementARAPClient; property ServerAPClient: TServerAPClient read GetServerAPClient write FServerAPClient; property ServerPenarikanDepositClient: TServerPenarikanDepositClient read GetServerPenarikanDepositClient write FServerPenarikanDepositClient; published end; var ClientDataModule: TClientDataModule; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} constructor TClientDataModule.Create(AOwner: TComponent); begin inherited; FInstanceOwner := False; end; procedure TClientDataModule.DataModuleCreate(Sender: TObject); begin FreeAndNil(FCabang); ClientDataModule.DSRestConnection.PreserveSessionID := False; end; destructor TClientDataModule.Destroy; begin Cabang.Free; SettingApp.Free; ServerUOMClient.Free; ServerSupplierClient.Free; ServerBarangClient.Free; ServerGroupBarangClient.Free; ServerPenerimaanBarangClient.Free; ServerCabangClient.Free; ServerLogAppObjectClient.Free; ServerUtilsClient.Free; ServerReturSupplierClient.Free; ServerLaporanClient.Free; ServerPenjualanClient.Free; ServerGudangClient.Free; ServerAccountClient.Free; ServerPenerimaanKasClient.Free; ServerSettingAppClient.Free; ServerTransferAntarCabangKirimClient.Free; inherited; end; function TClientDataModule.GetCabang: tcabang; begin if FCabang = nil then begin FCabang := TCabang.Create; end; Result := FCabang; end; function TClientDataModule.GetServerUOMClient: TServerUOMClient; begin if FServerUOMClient <> nil then FreeAndNil(FServerUOMClient); FServerUOMClient:= TServerUOMClient.Create(DSRestConnection, FInstanceOwner); Result := FServerUOMClient; end; function TClientDataModule.GetServerSupplierClient: TServerSupplierClient; begin if FServerSupplierClient <> nil then FreeAndNil(FServerSupplierClient); FServerSupplierClient:= TServerSupplierClient.Create(DSRestConnection, FInstanceOwner); Result := FServerSupplierClient; end; function TClientDataModule.GetServerBarangClient: TServerBarangClient; begin if FServerBarangClient <> nil then FreeAndNil(FServerBarangClient); FServerBarangClient:= TServerBarangClient.Create(DSRestConnection, FInstanceOwner); Result := FServerBarangClient; end; function TClientDataModule.GetServerGroupBarangClient: TServerGroupBarangClient; begin if FServerGroupBarangClient <> nil then FreeAndNil(FServerGroupBarangClient); FServerGroupBarangClient:= TServerGroupBarangClient.Create(DSRestConnection, FInstanceOwner); Result := FServerGroupBarangClient; end; function TClientDataModule.GetServerPenerimaanBarangClient: TServerPenerimaanBarangClient; begin if FServerPenerimaanBarangClient <> nil then FreeAndNil(FServerPenerimaanBarangClient); FServerPenerimaanBarangClient:= TServerPenerimaanBarangClient.Create(DSRestConnection, FInstanceOwner); Result := FServerPenerimaanBarangClient; end; function TClientDataModule.GetServerCabangClient: TServerCabangClient; begin if FServerCabangClient <> nil then FreeAndNil(FServerCabangClient); FServerCabangClient:= TServerCabangClient.Create(DSRestConnection, FInstanceOwner); Result := FServerCabangClient; end; function TClientDataModule.GetServerLogAppObjectClient: TServerLogAppObjectClient; begin if FServerLogAppObjectClient <> nil then FreeAndNil(FServerLogAppObjectClient); FServerLogAppObjectClient:= TServerLogAppObjectClient.Create(DSRestConnection, FInstanceOwner); Result := FServerLogAppObjectClient; end; function TClientDataModule.GetServerUtilsClient: TServerUtilsClient; begin if FServerUtilsClient <> nil then FreeAndNil(FServerUtilsClient); FServerUtilsClient:= TServerUtilsClient.Create(DSRestConnection, FInstanceOwner); Result := FServerUtilsClient; end; function TClientDataModule.GetServerReturSupplierClient: TServerReturSupplierClient; begin if FServerReturSupplierClient <> nil then FreeAndNil(FServerReturSupplierClient); FServerReturSupplierClient:= TServerReturSupplierClient.Create(DSRestConnection, FInstanceOwner); Result := FServerReturSupplierClient; end; function TClientDataModule.GetServerGudangClient: TServerGudangClient; begin if FServerGudangClient <> nil then FreeAndNil(FServerGudangClient); FServerGudangClient:= TServerGudangClient.Create(DSRestConnection, FInstanceOwner); Result := FServerGudangClient; end; function TClientDataModule.GetServerLaporanClient: TServerLaporanClient; begin if FServerLaporanClient <> nil then FreeAndNil(FServerLaporanClient); FServerLaporanClient := TServerLaporanClient.Create(DSRestConnection, InstanceOwner); Result := FServerLaporanClient; end; function TClientDataModule.GetServerCustomerInvoiceClient: TServerCustomerInvoiceClient; begin if FServerCustomerInvoiceClient <> nil then FreeAndNil(FServerCustomerInvoiceClient); FServerCustomerInvoiceClient:= TServerCustomerInvoiceClient.Create(DSRestConnection, FInstanceOwner); Result := FServerCustomerInvoiceClient; end; function TClientDataModule.GetServerPenjualanClient: TServerPenjualanClient; begin if FServerPenjualanClient <> nil then FreeAndNil(FServerPenjualanClient); FServerPenjualanClient := TServerPenjualanClient.Create(DSRestConnection, FInstanceOwner); Result := FServerPenjualanClient; end; function TClientDataModule.GetServerAccountClient: TServerAccountClient; begin if FServerAccountClient <> nil then FreeAndNil(FServerAccountClient); FServerAccountClient:= TServerAccountClient.Create(DSRestConnection, FInstanceOwner); Result := FServerAccountClient; end; function TClientDataModule.GetServerRekBankClient: TServerRekBankClient; begin if FServerRekBankClient <> nil then FreeAndNil(FServerRekBankClient); FServerRekBankClient:= TServerRekBankClient.Create(DSRestConnection, FInstanceOwner); Result := FServerRekBankClient; end; function TClientDataModule.GetServerPenerimaanKasClient: TServerPenerimaanKasClient; begin if FServerPenerimaanKasClient <> nil then FreeAndNil(FServerPenerimaanKasClient); FServerPenerimaanKasClient:= TServerPenerimaanKasClient.Create(DSRestConnection, FInstanceOwner); Result := FServerPenerimaanKasClient; end; function TClientDataModule.GetDSDataCLient: TDSDataClient; begin if FDSDataCLient <> nil then FreeAndNil(FDSDataCLient); FDSDataCLient:= TDSDataClient.Create(DSRestConnection, FInstanceOwner); Result := FDSDataCLient; end; function TClientDataModule.GetServerPengeluaranKasClient: TServerPengeluaranKasClient; begin if FServerPengeluaranKasClient <> nil then FreeAndNil(FServerPengeluaranKasClient); FServerPengeluaranKasClient:= TServerPengeluaranKasClient.Create(DSRestConnection, FInstanceOwner); Result := FServerPengeluaranKasClient; end; function TClientDataModule.GetServerSettingAppClient: TServerSettingAppClient; begin if FServerSettingAppClient <> nil then FreeAndNil(FServerSettingAppClient); FServerSettingAppClient:= TServerSettingAppClient.Create(DSRestConnection, FInstanceOwner); Result := FServerSettingAppClient; end; function TClientDataModule.GetServerTAGRequestClient: TServerTAGRequestClient; begin if FServerTAGRequestClient <> nil then FreeAndNil(FServerTAGRequestClient); FServerTAGRequestClient := TServerTAGRequestClient.Create(DSRestConnection, FInstanceOwner); Result := FServerTAGRequestClient; end; function TClientDataModule.GetServerTransferAntarGudang: TServerTransferAntarGudangClient; begin if FServerTransferAntarGudang <> nil then FreeAndNil(FServerTransferAntarGudang); FServerTransferAntarGudang:= TServerTransferAntarGudangClient.Create(DSRestConnection, FInstanceOwner); Result := FServerTransferAntarGudang; end; function TClientDataModule.GetSettingApp: TSettingApp; begin if FSettingApp = nil then FSettingApp := TSettingApp.Create; Result := FSettingApp; end; function TClientDataModule.GetServerTransferAntarCabangKirimClient: TServerTransferAntarCabangKirimClient; begin if FServerTransferAntarCabangKirimClient <> nil then FreeAndNil(FServerTransferAntarCabangKirimClient); FServerTransferAntarCabangKirimClient := TServerTransferAntarCabangKirimClient.Create(ClientDataModule.DSRestConnection, FInstanceOwner); Result := FServerTransferAntarCabangKirimClient; end; function TClientDataModule.GetServerTransferAntarCabangTerimaClient: TServerTransferAntarCabangTerimaClient; begin if FServerTransferAntarCabangTerimaClient <> nil then FreeAndNil(FServerTransferAntarCabangTerimaClient); FServerTransferAntarCabangTerimaClient := TServerTransferAntarCabangTerimaClient.Create(ClientDataModule.DSRestConnection, FInstanceOwner); Result := FServerTransferAntarCabangTerimaClient; end; function TClientDataModule.GetServerJurnalClient: TServerJurnalClient; begin if FServerJurnalClient <> nil then FreeAndNil(FServerJurnalClient); FServerJurnalClient:= TServerJurnalClient.Create(DSRestConnection, FInstanceOwner); Result := FServerJurnalClient; end; function TClientDataModule.GetServerMenuClient: TServerMenuClient; begin if FServerMenuClient <> nil then FreeAndNil(FServerMenuClient); FServerMenuClient:= TServerMenuClient.Create(DSRestConnection, FInstanceOwner); Result := FServerMenuClient; end; function TClientDataModule.GetServerUserClient: TServerUserClient; begin if FServerUserClient <> nil then FreeAndNil(FServerUserClient); FServerUserClient:= TServerUserClient.Create(DSRestConnection, FInstanceOwner); Result := FServerUserClient; end; function TClientDataModule.GeTServerSettlementARAPClient: TServerSettlementARAPClient; begin if FServerSettlementARAPClient <> nil then FreeAndNil(FServerSettlementARAPClient); FServerSettlementARAPClient:= TServerSettlementARAPClient.Create(DSRestConnection, FInstanceOwner); Result := FServerSettlementARAPClient; end; function TClientDataModule.GetServerAPClient: TServerAPClient; begin if FServerAPClient <> nil then FreeAndNil(FServerAPClient); FServerAPClient:= TServerAPClient.Create(DSRestConnection, FInstanceOwner); Result := FServerAPClient; end; function TClientDataModule.GetServerPenarikanDepositClient: TServerPenarikanDepositClient; begin if FServerPenarikanDepositClient <> nil then FreeAndNil(FServerPenarikanDepositClient); FServerPenarikanDepositClient:= TServerPenarikanDepositClient.Create(DSRestConnection, FInstanceOwner); Result := FServerPenarikanDepositClient; end; end.
unit m_memo; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TMariaeMemo } TMariaeMemo = class(TMemo) private FChanged: Boolean; procedure SetChanged(AValue: Boolean); protected public constructor Create(MOwner: TComponent); override; procedure OnChange; procedure ResetChanged; published property Changed: Boolean read FChanged write SetChanged; end; procedure Register; implementation procedure Register; begin {$I m_memo_icon.lrs} RegisterComponents('Mariae Controls',[TMariaeMemo]); end; { TMariaeMemo } procedure TMariaeMemo.SetChanged(AValue: Boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; constructor TMariaeMemo.Create(MOwner: TComponent); begin inherited Create(MOwner); Self.ScrollBars := ssAutoVertical; end; procedure TMariaeMemo.OnChange; begin Self.SetChanged(True); end; procedure TMariaeMemo.ResetChanged; begin Self.SetChanged(False); end; end.
unit SortArray; interface procedure QuickSortArray(var aData: array of string; aLo, aHi: integer); implementation procedure QuickSortArray(var aData: array of string; aLo, aHi: integer); var iLo: integer; iHi: integer; iPivot: string; function Value(aIndex: integer): string; begin Result := aData[aIndex]; end; function Compare(aLeft, aRight: string): integer; begin if aLeft < aRight then exit(-1) else if aLeft > aRight then exit(+1) else exit(0) end; procedure Swap(var a, b: string); var t: string; begin t := a; a := b; b := t; end; begin iLo := aLo; iHi := aHi; iPivot := Value((iLo + iHi) div 2); repeat while (Compare(Value(iLo), iPivot) < 0) do Inc(iLo); while (Compare(Value(iHi), iPivot) > 0) do Dec(iHi); if iLo <= iHi then begin if iLo <> iHi then Swap(aData[iLo], aData[iHi]); Inc(iLo); Dec(iHi); end; until iLo > iHi; if iHi > aLo then QuickSortArray(aData, aLo, iHi); if iLo < aHi then QuickSortArray(aData, iLo, aHi); end; end.
unit kwVcmHistoryDeleteBackItem; {* Удаляет один элемент истории из списка Back. *Пример:* [code] моп::Поиск_Поиск_лекарственного_средства 'AT_PHARM_NAME' 'Аргинин' Search:SetAttribute 'AT_PHARM_ATC' 'A. Пищеварительный тракт и обмен веществ' Search:SetAttribute 'AT_PHARM_ATC' 'B. Препараты влияющие на кроветворение и кровь' Search:SetAttribute Ok OnTest vcm:history:DeleteBackItem [code] } // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Scripting\kwVcmHistoryDeleteBackItem.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "vcm_History_DeleteBackItem" MUID: (4E82CEBA0299) // Имя типа: "TkwVcmHistoryDeleteBackItem" {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCM)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces ; type _VCMWord_Parent_ = TtfwRegisterableWord; {$Include w:\common\components\gui\Garant\VCM\implementation\Scripting\VCMWord.imp.pas} TkwVcmHistoryDeleteBackItem = class(_VCMWord_) {* Удаляет один элемент истории из списка Back. *Пример:* [code] моп::Поиск_Поиск_лекарственного_средства 'AT_PHARM_NAME' 'Аргинин' Search:SetAttribute 'AT_PHARM_ATC' 'A. Пищеварительный тракт и обмен веществ' Search:SetAttribute 'AT_PHARM_ATC' 'B. Препараты влияющие на кроветворение и кровь' Search:SetAttribute Ok OnTest vcm:history:DeleteBackItem [code] } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; end;//TkwVcmHistoryDeleteBackItem {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCM) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCM)} uses l3ImplUses , vcmForm {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) , StdRes , vcmBase , afwAnswer //#UC START# *4E82CEBA0299impl_uses* //#UC END# *4E82CEBA0299impl_uses* ; {$Include w:\common\components\gui\Garant\VCM\implementation\Scripting\VCMWord.imp.pas} class function TkwVcmHistoryDeleteBackItem.GetWordNameForRegister: AnsiString; begin Result := 'vcm:History:DeleteBackItem'; end;//TkwVcmHistoryDeleteBackItem.GetWordNameForRegister procedure TkwVcmHistoryDeleteBackItem.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4E82CEBA0299_var* //#UC END# *4DAEEDE10285_4E82CEBA0299_var* begin //#UC START# *4DAEEDE10285_4E82CEBA0299_impl* if (vcmDispatcher.History <> nil) then vcmDispatcher.History.DeleteBackItem; //#UC END# *4DAEEDE10285_4E82CEBA0299_impl* end;//TkwVcmHistoryDeleteBackItem.DoDoIt initialization TkwVcmHistoryDeleteBackItem.RegisterInEngine; {* Регистрация vcm_History_DeleteBackItem } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCM) end.
unit Led; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs; type TLEDState=(LEDOn,LEDOff); TLEDColor=(LEDRed,LEDGreen,LEDBlue,LEDYellow,LEDMagenta,LEDCyan,LEDGray); TLED = class(TGraphicControl) private protected FState:TLEDState; FOnColor:TLEDColor; FOffColor:TLEDColor; FOldHeight:Integer; FOldWidth:Integer; procedure SetOnColor(Value:TLEDColor); procedure SetOffColor(Value:TLEDColor); procedure SetState(Value:TLEDState); public constructor Create(AOwner:TComponent);override; procedure Paint;override; published property Align; property DragCursor; property DragMode; property Enabled; property Height default 16; property LEDOffColor:TLEDColor read FOffColor write SetOffColor default LEDGray; property LEDOnColor:TLEDColor read FOnColor write SetOnColor default LEDRed; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property ParentShowHint; property ShowHint; property State:TLEDState read FState write SetState default LEDOff; property Visible; property Width default 16; end; procedure Register; implementation constructor TLED.Create(AOwner:TComponent); {Standardwerte setzen} begin inherited Create(AOwner); Height:=16; Width:=16; LEDOnColor:=LEDRed; LEDOffColor:=LEDGray; State:=LEDOff; Visible:=true; Enabled:=True; end; procedure TLED.Paint; {Bringt die LED auf den Bildschirm} var a,b,w,h:real; phi,diag:real; x,y:integer; procedure GetDarkColor; {Stift mit 'Dunkler Farbe'} begin if State=LEDOn then begin case FOnColor of LEDRed: Canvas.Pen.Color:=clMaroon; LEDGreen: Canvas.Pen.Color:=clGreen; LEDBlue: Canvas.Pen.Color:=clNavy; LEDYellow: Canvas.Pen.Color:=clOlive; LEDMagenta: Canvas.Pen.Color:=clPurple; LEDCyan: Canvas.Pen.Color:=clTeal; LEDGray: Canvas.Pen.Color:=clGray; end; end else begin case FOffColor of LEDRed: Canvas.Pen.Color:=clMaroon; LEDGreen: Canvas.Pen.Color:=clGreen; LEDBlue: Canvas.Pen.Color:=clNavy; LEDYellow: Canvas.Pen.Color:=clOlive; LEDMagenta: Canvas.Pen.Color:=clPurple; LEDCyan: Canvas.Pen.Color:=clTeal; LEDGray: Canvas.Pen.Color:=clGray; end; end; Canvas.Brush.Color:=Canvas.Pen.Color; end; procedure GetLightColor; {Stift mit 'Heller Farbe'} begin if FState=LEDOn then begin case FOnColor of LEDRed: Canvas.Pen.Color:=clRed; LEDGreen: Canvas.Pen.Color:=clLime; LEDBlue: Canvas.Pen.Color:=clBlue; LEDYellow: Canvas.Pen.Color:=clYellow; LEDMagenta: Canvas.Pen.Color:=clFuchsia; LEDCyan: Canvas.Pen.Color:=clAqua; LEDGray: Canvas.Pen.Color:=clSilver; end; end else begin case FOffColor of LEDRed: Canvas.Pen.Color:=clRed; LEDGreen: Canvas.Pen.Color:=clLime; LEDBlue: Canvas.Pen.Color:=clBlue; LEDYellow: Canvas.Pen.Color:=clYellow; LEDMagenta: Canvas.Pen.Color:=clFuchsia; LEDCyan: Canvas.Pen.Color:=clAqua; LEDGray: Canvas.Pen.Color:=clSilver; end; end; Canvas.Brush.Color:=Canvas.Pen.Color; end; begin with Canvas do begin {Umrandung der LED} Pen.Color:=clBlack; {außen unten} Arc(0,0,Width,Height,Width+1,0,0,Height+1); {innen oben} Arc(1,1,Width-1,Height-1,0,Height,Width,0); Pen.Color:=clWhite; {außen oben} Arc(0,0,Width,Height,0,Height,Width,0); {innen unten} Arc(1,1,Width-1,Height-1,Width+1,0,0,Height+1); {dunkler Keises} GetDarkColor; Ellipse(2,2,Width-2,Height-2); {Schatten} if ((FState=LEDOn)and(FOnColor=LEDGray))or ((FState=LEDOff)and(FOffColor=LEDGray)) then Pen.Color:=clBlack else Pen.Color:=clGray; Arc(2,2,Width-2,Height-2,Width div 2,Height-2,Width-2,Height div 2); Arc(6,6,Width-3,Height-3,Width div 2,Height-2,Width-2,Height div 2); {heller Kreis} GetLightColor; phi:=arctan(Height/Width); diag:=sqrt(sqr((Width-4)*cos(phi))+sqr((Height-4)*sin(phi))); a:=2*sqrt(sqr(0.5*(Height-4))+sqr(0.5*(Width-4)))-diag; b:=sqrt(sqr(0.625*(Height-4))+sqr(0.625*(Width-4)))-0.625*diag; w:=sin(0.5*Pi*phi)*0.5*(a-b); h:=sin(phi)*0.5*(a-b); Ellipse(trunc(2+w),trunc(2+h),trunc(2+w+5/8*Width), trunc(2+h+5/8*Height)); {weißer Lichtpunkt} Pen.Color:=clWhite; Brush.Color:=Pen.Color; x:=round(0.3*Width); y:=round(0.3*Height); Ellipse(x-1,y-1,x+1,y+1); end; end; procedure TLED.SetOffColor(Value:TLEDColor); {Farbe, wenn LED ausgeschaltet} begin if Value<>FOffColor then begin FOffColor:=Value; Invalidate; end; end; procedure TLED.SetOnColor(Value:TLEDColor); {Farbe, wenn LED eingeschaltet} begin if Value<>FOnColor then begin FOnColor:=Value; Invalidate; end; end; procedure TLED.SetState(Value:TLEDState); {Ein- oder Ausschalten der LED} begin if Value<>FState then begin FState:=Value; Invalidate; end; end; procedure Register; begin RegisterComponents('MPA', [TLED]); end; end.
unit evPhoneEdit; // Модуль: "w:\common\components\gui\Garant\Everest\qf\evPhoneEdit.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevPhoneEdit" MUID: (48D25DD8039D) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evEditControl , evQueryCardInt ; type TevPhoneEdit = class(TevEditControl, IevEditorPhoneField) private f_OtherField: Pointer; {* Ссылка на другое поле даты } f_IsStart: Boolean; {* Признак того, что дата задает начало интервала } protected function IsStart: Boolean; {* Контрол хранит начальную дату интервала. } function GetOtherField: IevEditorPhoneField; {* Другой контрол. } procedure Cleanup; override; {* Функция очистки полей объекта. } function GetIsClear: Boolean; override; procedure DoInitOtherField(const aValue: IevEditorControl; aIsStart: Boolean); override; procedure DoClearText; override; end;//TevPhoneEdit implementation uses l3ImplUses , SysUtils //#UC START# *48D25DD8039Dimpl_uses* //#UC END# *48D25DD8039Dimpl_uses* ; function TevPhoneEdit.IsStart: Boolean; {* Контрол хранит начальную дату интервала. } //#UC START# *47CD7F220315_48D25DD8039D_var* //#UC END# *47CD7F220315_48D25DD8039D_var* begin //#UC START# *47CD7F220315_48D25DD8039D_impl* Result := f_IsStart; //#UC END# *47CD7F220315_48D25DD8039D_impl* end;//TevPhoneEdit.IsStart function TevPhoneEdit.GetOtherField: IevEditorPhoneField; {* Другой контрол. } //#UC START# *47CD7F300065_48D25DD8039D_var* //#UC END# *47CD7F300065_48D25DD8039D_var* begin //#UC START# *47CD7F300065_48D25DD8039D_impl* Result := IevEditorPhoneField(f_OtherField); //#UC END# *47CD7F300065_48D25DD8039D_impl* end;//TevPhoneEdit.GetOtherField procedure TevPhoneEdit.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48D25DD8039D_var* //#UC END# *479731C50290_48D25DD8039D_var* begin //#UC START# *479731C50290_48D25DD8039D_impl* f_OtherField := nil; inherited; //#UC END# *479731C50290_48D25DD8039D_impl* end;//TevPhoneEdit.Cleanup function TevPhoneEdit.GetIsClear: Boolean; //#UC START# *48D24A66039B_48D25DD8039D_var* //#UC END# *48D24A66039B_48D25DD8039D_var* begin //#UC START# *48D24A66039B_48D25DD8039D_impl* Result := IsFieldEmpty and GetOtherField.IsFieldEmpty; //#UC END# *48D24A66039B_48D25DD8039D_impl* end;//TevPhoneEdit.GetIsClear procedure TevPhoneEdit.DoInitOtherField(const aValue: IevEditorControl; aIsStart: Boolean); //#UC START# *48D24AA202D1_48D25DD8039D_var* var l_Field: IevEditorPhoneField; //#UC END# *48D24AA202D1_48D25DD8039D_var* begin //#UC START# *48D24AA202D1_48D25DD8039D_impl* inherited; if Supports(aValue, IevEditorPhoneField, l_Field) then try f_OtherField := Pointer(l_Field); if aIsStart then //чтобы не возникало бесконечных циклов IevEditorPhoneField(f_OtherField).InitOtherField(Self, False); f_IsStart := aIsStart; finally l_Field := nil; end; //#UC END# *48D24AA202D1_48D25DD8039D_impl* end;//TevPhoneEdit.DoInitOtherField procedure TevPhoneEdit.DoClearText; //#UC START# *48D24C9F02F5_48D25DD8039D_var* //#UC END# *48D24C9F02F5_48D25DD8039D_var* begin //#UC START# *48D24C9F02F5_48D25DD8039D_impl* SetText(nil); IevEditorPhoneField(f_OtherField).Text := nil; Set_Valid(True); //#UC END# *48D24C9F02F5_48D25DD8039D_impl* end;//TevPhoneEdit.DoClearText end.
unit Model.InsumosTransportes; interface type TInsumosTransportes = class private var FID: Integer; FDescricao: String; FUnidade: String; FLog: String; public property ID: Integer read FID write FID; property Descricao: String read FDescricao write FDescricao; property Unidade: String read FUnidade write FUnidade; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFID: Integer; pFDescricao: String; pFUnidade: String; pFLog: String); overload; end; implementation constructor TInsumosTransportes.Create; begin inherited Create; end; constructor TInsumosTransportes.Create(pFID: Integer; pFDescricao: String; pFUnidade: String; pFLog: String); begin FID := pFID; FDescricao := pFDescricao; FUnidade := pFUnidade; FLog := pFLog; end; end.
unit parser; interface uses Classes, SysUtils, FastStrings; type PHTMLParser_Attribute = ^THTMLParser_Attribute; THTMLParser_Attribute = record Name: String; Value: String; end; THTMLParserTagType = ( pttNone, pttStartTag, pttEndTag, pttEmptyTag, pttContent, pttComment ); THTMLParser = class private AttrList: TList; procedure ClearAttrList; function GetCurrAttr(Index: Integer): THTMLParser_Attribute; function AddAttribute(Name, Value: String): Integer; public CurName: string; CurTagType: THTMLParserTagType; HTMLCode: string; CurPosition: Integer; CurContent: String; Ready: Boolean; property CurrAttr[Index: Integer]: THTMLParser_Attribute read GetCurrAttr; procedure StartParser; function Parse: Boolean; constructor Create; destructor Destroy; override; function AttrCount: Integer; end; function ReadTagValue(html: string; pos: Integer; var TagValue: string): Integer; implementation uses StrUtils; function THTMLParser.AddAttribute(Name, Value: String): Integer; var attr: PHTMLParser_Attribute; begin New(attr); attr^.Name := Name; attr^.Value := Value; Result := AttrList.Add(attr); end; function THTMLParser.AttrCount: Integer; begin Result := AttrList.Count; end; procedure THTMLParser.ClearAttrList; begin while AttrList.Count > 0 do begin { Hier war das Speicherleck: Dispose(AttrList[0]); Wenn Dispose nicht weis welchen Typ es freizugeben hat, Kann es keine Dynamischen String/Arrays mitfreigeben! Siehe Online-Hilfe "Finalize" Deswegen: } Dispose(PHTMLParser_Attribute(AttrList[0])); AttrList.Delete(0); end; end; constructor THTMLParser.Create; begin inherited; AttrList := TList.Create; end; destructor THTMLParser.Destroy; begin AttrList.Free; inherited; end; function THTMLParser.GetCurrAttr(Index: Integer): THTMLParser_Attribute; begin Result := THTMLParser_Attribute(AttrList[Index]^); end; function findfirst(s: string; c1, c2: char; pos: Integer): Integer; { Gibt die position des zuerst gefundenen Zeichens zurück, falls keines der beiden Zeichen gefunden wurde, wird length(s)+1 zurückgegeben! } var p: integer; begin Result := FastCharPos(s,c1,pos); p := FastCharPos(s,c2,pos); if (p > 0)and((Result = 0)or(p < Result)) then Result := p else if Result = 0 then Result := length(s)+1; end; function THTMLParser.Parse: Boolean; var ps, pe: Integer; s, aname, aval: string; begin ClearAttrList(); //Wenn am ende des strings angekommen -> fertig! If CurPosition >= length(HTMLCode) then begin Result := False; Ready := True; Exit; end; ps := CurPosition; //Wenn Letzter Tag ein Starttag war und "script" hieß, muss der nächste tag </script> sein! if (CurTagType = pttStartTag)and(LowerCase(CurName) = 'script') then CurPosition := FastPosNoCase(HTMLCode,'</script',length(HTMLCode),8,CurPosition) else CurPosition := FastCharPos(HTMLCode,'<',CurPosition); CurTagType := pttNone; //Wenn Ende erreicht, rest noch als content zurückgeben! if CurPosition = 0 then CurPosition := length(HTMLCode)+1; //teste auf content if (ps < CurPosition) then begin CurTagType := pttContent; CurContent := Copy(HTMLCode,ps,CurPosition-ps); Result := true; Exit; end; if (CurPosition > 0)and(HTMLCode[CurPosition+1] = '/') then begin CurTagType := pttEndTag; CurPosition := CurPosition+1; end else CurTagType := pttStartTag; //Tagname lesen pe := findfirst(HTMLCode,' ','>',CurPosition); if HTMLCode[pe-1] = '/' then pe := pe-1; CurName := Copy(HTMLCode,CurPosition+1,pe-CurPosition-1); //teste auf Comment if Copy(CurName,1,3) = '!--' then begin CurName := Copy(CurName,1,3); CurTagType := pttComment; pe := FastPos(HTMLCode,'-->',length(HTMLCode),3,CurPosition); CurContent := Copy(HTMLCode,CurPosition,pe-CurPosition+3); CurPosition := pe+3; Result := true; Exit; end; CurPosition := pe; while true do begin ps := FastCharPos(HTMLCode,'=',CurPosition); pe := FastCharPos(HTMLCode,'>',CurPosition); //Falls '>' zum abschluss des tags fehlt: if pe = 0 then pe := length(HTMLCode)+1; //Wenn Attribute vorhanden, dann lese die erst ein. Ansonsten breche ab! if (ps > 0)and(ps < pe) then begin aname := Trim(Copy(HTMLCode,CurPosition+1,ps-(CurPosition+1))); CurPosition := ReadTagValue(HTMLCode,ps+1,s); aval := s; AddAttribute(aname,aval); end else break; end; if (HTMLCode[pe-1] = '/')and(CurTagType = pttStartTag) then CurTagType := pttEmptyTag; CurPosition := pe+1; Result := True; end; procedure THTMLParser.StartParser; begin CurPosition := 1; CurName := ''; CurTagType := pttNone; Ready := False; end; function ReadTagValue(html: string; pos: Integer; var TagValue: string): Integer; var Quote: Char; pe, ps: Integer; begin Result := pos; Quote := UTF8Encode(html[Result])[1]; if not((Quote = '"')or(Quote = '''')) then begin ps := FastCharPos(html,' ',Result); pe := FastCharPos(html,'>',Result); // class=inactive> if (pe > 0)and((ps = 0)or(pe < ps)) then begin Result := pe; if html[Result-1] = '/' then Result := Result-1; end else Result := ps; if Result = 0 then Result := length(html)+1; end else begin pos := pos+1; while true do begin Result := FastCharPos(html,Quote,Result+1); if (Result = 0) then begin Result := FastCharPos(html,'>',Result+1); if (Result = 0) then Result := length(html)+1 else if html[Result-1] = '/' then Result := Result-1; break; end else if (not(html[Result-1] = '\')) then break; end; end; TagValue := Copy(html,pos,Result-pos); end; end.
program dictionary(output); type colour = (RED, GREEN, BLUE, WHITE); palette = array[colour] of integer; var ross : palette; i : colour; begin ross[RED] := 1; ross[GREEN] := 2; ross[BLUE] := 3; ROSS[WHITE] := 4; for i := RED to WHITE do write(ross[i], ' '); writeln; end.
algo : garage automobile BUT : cet algorithme trie des voitures dans deux garages ENTREE : les paramètres des voitures et des garages SORTIE : les donnée des voitures et des garages type garage= enregistrement nom :chaine num :entier adresse :chaine CP :entier ville :chaine pays :chaine tel :entier email :chaine finenregistrement type voitures= enregistrement marque :chaine modele :chaine energie :chaine puissancef :entier puissanceDYN :entier couleur :chaine option :chaine annee :entier prix :entier cote :entier datecirc :eniter age :entier plaque :chaine finenregistrement type f= fichier de garage type f2= fihcier de voiture procedure presentationgarage (variable g:garage) // demande et enregistre les données des garages DEBUT ECRIRE ('nom') LIRE (g.nom) ECRIRE ('numero') LIRE (g.num) ECRIRE ('adresse') LIRE (g.adresse) ECRIRE ('Code postale') LIRE (g.CP) ECRIRE ('ville') LIRE (g.ville) ECRIRE ('pays') LIRE (g.pays) ECRIRE ('telephone') LIRE (g.tel) ECRIRE ('adresse email') LIRE (g.email) FIN finprocedure procedure presentationvoiture (constante 2, variable v: voiture) //demande et enregistre les données des voitures DEBUT ECRIRE ('marque') LIRE (g.marque) ECRIRE ('modele') LIRE (g.modele) ECRIRE ('energie') LIRE (g.energie) ECRIRE ('puissance fiscale') LIRE (g.puissancef) ECRIRE ('puissance DYN') LIRE (g.puissanceDYN) ECRIRE ('couleur') LIRE (g.couleur) ECRIRE ('option') LIRE (g.option) ECRIRE ('annee') LIRE (g.annee) ECRIRE ('prix') LIRE (g.prix) ECRIRE ('cote argus') LIRE (g.cote) ECRIRE ('date de circulation') LIRE (g.datecirc) ECRIRE ('age ') LIRE (g.age) ECRIRE ('plaque') LIRE (g.plaque) FIN finprocedure procedure affichagegarage (variable g:garage) //affiche les données des garages DEBUT ECRIRE ('Garage'g.nom) ECRIRE ('numéros : ',g.num) ECRIRE ('adresse: 'g.num, g.adresse, g.CP, g.ville, g.pays) ECRIRE ('telephone : 'g.tel) ECRIRE ('mail : 'g.email) FIN finprocedure //mon but étais de crée un "cas parmis" affin que l'utilisateur puisse stocker les voitures dans les garages
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.Utils; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.Def; const CODES: array [0 .. 3] of byte = (0, 1, 3, 2); function GrayCode(i: integer): UINT32; inline; function EuclideanNorm(vector: TDoubleArray): double; procedure NormalizeVector(var vector: TDoubleArray; norm: double; threshold: double = 0.01); function FreqToIndex(freq: double; frame_size, sample_rate: integer): integer; // inline; function IndexToFreq(i, frame_size, sample_rate: integer): double; // inline; function FreqToOctave(freq: double; base: double = 440.0 / 16.0): double; // inline; procedure PrepareHammingWindow(var Data: TDoubleArray); procedure ApplyWindow(var Data: TDoubleArray; window: TDoubleArray; size: integer; scale: double); implementation uses {$IFDEF FPC} DaMath; {$ELSE} Math; {$ENDIF} function FreqToOctave(freq: double; base: double = 440.0 / 16.0): double; // inline; begin Result := log10(freq / base) / log10(2.0); // logarithmus dualis end; function IndexToFreq(i, frame_size, sample_rate: integer): double; // inline; begin Result := i * sample_rate / frame_size; end; function FreqToIndex(freq: double; frame_size, sample_rate: integer): integer; // inline; begin Result := round(frame_size * freq / sample_rate); end; function GrayCode(i: integer): UINT32; inline; begin Result := CODES[i]; end; procedure NormalizeVector(var vector: TDoubleArray; norm: double; threshold: double = 0.01); var i: integer; begin if (norm < threshold) then begin for i := 0 to Length(vector) - 1 do begin vector[i] := 0.0; end; end else begin for i := 0 to Length(vector) - 1 do begin vector[i] := vector[i] / norm; end; end; end; function EuclideanNorm(vector: TDoubleArray): double; var squares, Value: double; i: integer; begin squares := 0; for i := 0 to Length(vector) - 1 do begin Value := vector[i]; squares := squares + Value * Value; end; if squares > 0 then Result := Sqrt(squares) else Result := 0; end; procedure PrepareHammingWindow(var Data: TDoubleArray); var i, n: integer; scale: double; begin n := Length(Data); scale := TwoMath_Pi / (n - 1); for i := 0 to n - 1 do begin Data[i] := 0.54 - 0.46 * cos(scale * i); end; end; procedure ApplyWindow(var Data: TDoubleArray; window: TDoubleArray; size: integer; scale: double); var i: integer; begin i := 0; while (i < size) do begin Data[i] := Data[i] * window[i] * scale; Inc(i); end; end; end.
unit MVCBr.DatabaseModel; interface uses System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.DatabaseModel.Interf, Data.DB, MVCBr.PersistentModel; type IDatabaseModel = MVCBr.DatabaseModel.Interf.IDatabaseModel; // TQueryModelFactory<T: Class> É o construtor de Query // Generic: T:Class É a classe decendente de TDataset ligado ao framework utilizado TQueryModelFactory<T: Class> = class(TInterfacedObject, IQueryModel<T>) private FChangeProc: TProc<T>; FQuery: T; FDatabaseModel: IDatabaseModel; FColumns: String; FTable: string; FWhere: String; FOrderBy: String; FJoin: string; FGroupBy: string; public constructor create; virtual; destructor destroy; override; function This: TQueryModelFactory<T>; function Query:T; procedure DoChange; virtual; class Function New(ADatabaseModel: IDatabaseModel; AChangeProc: TProc<T>) : TQueryModelFactory<T>; function Table(Const ATable: string): IQueryModel<T>; function Where(Const AWhere: string): IQueryModel<T>; function OrderBy(Const AOrderBY: string): IQueryModel<T>; function Join(const AJoin: string): IQueryModel<T>; function GroupBy(Const AGroup: string): IQueryModel<T>; function Columns(const AColumns: string): IQueryModel<T>; function GetModel: IDatabaseModel; procedure SetModel(const AModel: IDatabaseModel); function sql: string; function Dataset: TDataset; end; // Classe base para implementação de acesso a banco de dados // Onde T: representa a classe de conexão // Q: a classe de query (TDataset type) TDatabaseModelFactory<T: class; Q: Class> = class(TDatabaseModelAbstract, IDatabaseModel) protected FOwner:TComponent; FConnection: T; public function GetOwned:TComponent; constructor create(); override; destructor destroy; override; // retorna interface base function ThisIntf: IDatabaseModel; // retorna o modelo abstract de herança para a classe function This: TDatabaseModelFactory<T, Q>; overload; // retorna a conexão ativa function GetConnection: T; // Seta a conexão ativa function Connection(const AConnection: T) : TDatabaseModelFactory<T, Q>; virtual; // inicializa nova Query // Params: AProcChange é chamada toda vez que um dado da query é alterada function NewQuery(const AProcChange: TProc<Q>): IQueryModel<Q>; virtual; end; implementation uses System.RTTI; { TQueryModelFactory } function TQueryModelFactory<T>.Columns(const AColumns: string): IQueryModel<T>; begin FColumns := AColumns; DoChange; end; constructor TQueryModelFactory<T>.create; var ctx: TRTTIContext; begin inherited create; FColumns := '*'; FQuery := TMVCBr.InvokeCreate<T>([nil]); if Assigned(FQuery) then if not TObject(FQuery).InheritsFrom(TDataset) then raise Exception.create('O tipo de classe não é uma herança de TDataset'); end; function TQueryModelFactory<T>.Dataset: TDataset; begin result := TDataset(FQuery); end; destructor TQueryModelFactory<T>.destroy; begin if Assigned(FQuery) then TObject(FQuery).DisposeOf; inherited; end; procedure TQueryModelFactory<T>.DoChange; begin if Assigned(FChangeProc) then FChangeProc(FQuery); end; function TQueryModelFactory<T>.GetModel: IDatabaseModel; begin result := FDatabaseModel; end; function TQueryModelFactory<T>.GroupBy(const AGroup: string): IQueryModel<T>; begin result := self; FGroupBy := FGroupBy; DoChange; end; function TQueryModelFactory<T>.Join(const AJoin: string): IQueryModel<T>; begin result := self; FJoin := AJoin; DoChange; end; class function TQueryModelFactory<T>.New(ADatabaseModel: IDatabaseModel; AChangeProc: TProc<T>): TQueryModelFactory<T>; begin result := TQueryModelFactory<T>.create(); result.FDatabaseModel := ADatabaseModel; result.FChangeProc := AChangeProc; end; function TQueryModelFactory<T>.OrderBy(const AOrderBY: string): IQueryModel<T>; begin result := self; FOrderBy := AOrderBY; DoChange; end; function TQueryModelFactory<T>.Query: T; begin result := FQuery; end; procedure TQueryModelFactory<T>.SetModel(const AModel: IDatabaseModel); begin FDatabaseModel := AModel; end; function TQueryModelFactory<T>.sql: string; begin result := 'select ' + FColumns + ' from ' + FTable; if FJoin <> '' then result := result + ' ' + FJoin; if FWhere <> '' then result := result + ' ' + FWhere; if FGroupBy <> '' then result := result + ' ' + FGroupBy; if FOrderBy <> '' then result := result + ' ' + FOrderBy; end; function TQueryModelFactory<T>.Table(const ATable: string): IQueryModel<T>; begin result := self; FTable := ATable; DoChange; end; function TQueryModelFactory<T>.This: TQueryModelFactory<T>; begin result := self; end; function TQueryModelFactory<T>.Where(const AWhere: string): IQueryModel<T>; begin result := self; FWhere := AWhere; DoChange; end; { TDatabaseModelFactory<T> } function TDatabaseModelFactory<T, Q>.Connection(const AConnection: T) : TDatabaseModelFactory<T, Q>; begin result := self; if FConnection = AConnection then FConnection := AConnection; end; constructor TDatabaseModelFactory<T, Q>.create; begin inherited; FConnection := TMVCBr.InvokeCreate<T>([ GetOwned ]); end; destructor TDatabaseModelFactory<T, Q>.destroy; begin inherited; end; function TDatabaseModelFactory<T, Q>.GetConnection: T; begin result := FConnection; end; function TDatabaseModelFactory<T, Q>.GetOwned: TComponent; begin result := FOwner; end; function TDatabaseModelFactory<T, Q>.NewQuery(const AProcChange: TProc<Q>) : IQueryModel<Q>; var Intf: IDatabaseModel; obj: TQueryModelFactory<Q>; begin Intf := self; obj := TQueryModelFactory<Q>.New(ThisIntf, AProcChange); obj.SetModel(Intf); result := obj; end; function TDatabaseModelFactory<T, Q>.This: TDatabaseModelFactory<T, Q>; begin result := self; end; function TDatabaseModelFactory<T, Q>.ThisIntf: IDatabaseModel; begin result := self; end; end.
{ Subroutine SST_W_C_NAME_COM_VAR (SYM) * * Set the output name of a variable in a common block. It is an error if * the output name is already set. * * In the C language, common blocks are emulated with variables that are * STRUCTs, and declared globally known. Each variable in the common block * becomes a field in the struct. * * The syntax for referring to one of these variables is * "<common block name>.<var name>". Since the common block variable names * are now in their own namespace, one further refinement is added. * If the variable name starts with the name of the common block followed * by an underscore, then that portion of the variable name is stripped off. * For the purposes of the stripping algorithm, only letters in the common * block name are taken into account, and any non-letters around or in the * common block name at the start of the variable name are also stripped off. * For example: * * COMMON BLOCK NAME ORIGINAL VAR NAME RESULTING VAR NAME * xxxx stuff stuff * rend rend_stuff stuff * rend2 rend_stuff stuff * xxx xxxx_zzz xxxx_zzz * xxx xxx2_zzz zzz } module sst_w_c_NAME_COM_VAR; define sst_w_c_name_com_var; %include 'sst_w_c.ins.pas'; procedure sst_w_c_name_com_var ( {set output name for var in common block} in out sym: sst_symbol_t); {symbol to set output name for} const max_msg_parms = 1; {max parameters we can pass to a message} var ind_c: string_index_t; {index into common block name string} ind_v: string_index_t; {index into variable name string} char_c, char_v: char; {characters extracted from com and var names} name_p_old: string_var_p_t; {saved pointer to original var input name} name: string_var132_t; {for making stripped variable name} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label char_v_next, skip_char_v, vname_start_set, no_strip; begin name.max := size_char(name.str); {init local var string} if sym.name_out_p <> nil then begin {symbol already has output name ?} sys_msg_parm_vstr (msg_parm[1], sym.name_in_p^); sys_message_bomb ('sst_c_write', 'name_out_already_exists', msg_parm, 1); end; with sym.name_in_p^: name_v, {NAME_V is input variable name} sym.var_com_p^.name_in_p^: name_c {NAME_C is common block input name} do begin ind_v := 0; {init index into variable name} for ind_c := 1 to name_c.len do begin {once for each character in com name} char_c := name_c.str[ind_c]; {get this common block name char} if (char_c >= 'a') and (char_c <= 'z') then begin {lower case letter ?} char_c := chr(ord(char_c) - ord('a') + ord('A')); {convert to upper case} end; if (char_c < 'A') or (char_c > 'Z') {common block name char not a letter ?} then next; {skip this char, go on to next} char_v_next: {back here to skip to next var name char} ind_v := ind_v + 1; {make index of new var name char} if ind_v > name_v.len then goto no_strip; {exhausted variable name string ?} char_v := name_v.str[ind_v]; {get this variable name char} if (char_v >= 'a') and (char_v <= 'z') then begin {lower case letter ?} char_v := chr(ord(char_v) - ord('a') + ord('A')); {convert to upper case} end; if (char_v < 'A') or (char_v > 'Z') {variable name char not a letter ?} then goto char_v_next; {skip this char, go on to next} if char_v = char_c then next; {these characters match, go to next} if {check for matched up to "_"} (ind_c > 1) and then {this is not first common block char ?} (name_c.str[ind_c - 1] = '_') {previous com block name char was "_" ?} then begin ind_v := ind_v - 2; {make index of last var char that matched} if ind_v < 0 then goto no_strip; goto skip_char_v; {done macthing var and com symbol names} end; goto no_strip; {definately no match} end; {back and try next common block name char} { * The start of the variable name does match the common block name by the * rules described above. Now make sure that the next meaningful variable * name character is an underscore, and set IND_V to the first character in * the variable name after the common block name is stripped off. } skip_char_v: {back here to skip the current var name char} ind_v := ind_v + 1; {make index of next var name char} if ind_v > name_v.len then goto no_strip; {exhausted variable name string ?} char_v := name_v.str[ind_v]; {get this variable name char} if char_v = '_' then begin {this is the character we were looking for} ind_v := ind_v + 1; {make index of first non-stripped char} goto vname_start_set; {IND_V set to first non-stripped char} end; if {this character is not a letter ?} ((char_v < 'a') or (char_v > 'z')) and ((char_v < 'A') or (char_v > 'Z')) then goto skip_char_v; {skip over non-letter characters until "_"} { * The start of the variable name did not match the common block name by * the rules described in the routine header comments. The input variable * name will be translated to the output variable name in the regular way. } no_strip: sst_w.name_sym^ (sym); {create output name in normal way} return; { * The start of the variable name did match the common block name by the * rules described in the routine header comments. IND_V is the index of * the first variable name character after the common block name is stripped * from the beginning. The stripped name will be temporarily installed * as the symbols input name. This will be used to derive the output name, * then the symbols input name pointer will be restored. } vname_start_set: if ind_v > name_v.len {nothing left after com name stripped off ?} then goto no_strip; string_substr ( {extract stripped name from var input name} name_v, {string to extract substring from} ind_v, {start index of substring} name_v.len, {ending index of substring} name); {output substring} end; {done with NAME_V and NAME_C abbreviations} name_p_old := sym.name_in_p; {save pointer to variables input name} sym.name_in_p := univ_ptr(addr(name)); {temp set stripped name as input name} sst_w.name_sym^ (sym); {set output name using stripped name as input} sym.name_in_p := name_p_old; {restore pointer to symbol's input name} end;
unit IBSystem; interface uses Classes, Collection, InterfaceCollection, Persistent, BackupInterfaces, MapStringToObject, SyncObjs, ClassStorageInt, MetaInstances, ClassStorage; const tidMetaMissionFamily = 'tidMetaMissionFamily'; tidMetaActionFamily = 'tidMetaActionFamily'; tidMetaHistoryFamily = 'tidMetaHistoryFamily'; tidMetaTrainingFamily = 'tidMetaTrainingFamily'; cidModelServerAction = 'cidModelServerAction'; const SKILL_COUNT = 10; const MAXTEAM_MEMBERS = 8; const AVAILABLE_CRIMINALS = 10; const HISTREQ_TYCOON = 0; HISTREQ_CRIMINAL = 1; HISTREQ_DATE = 2; HISTREQ_MISSION = 3; HISTREQ_TRAINING = 4; HISTREQ_TTEAM = 5; MAX_HISTREQUIREMENTS = 6; const FREQ_HOUR = 1; FREQ_DAY = 24; FREQ_WEEK = 7*FREQ_DAY; FREQ_MONTH = 31*FREQ_DAY; FREQ_YEAR = 365*FREQ_DAY; const ERR_SUCCEDEED = 0; ERR_TEAMINMISSION = 1; ERR_TOOMANYMEMBERS = 2; ERR_UNKNOWN = 3; ERR_NOMISSION = 4; ERR_TYCOONALREADYLOGGED = 5; ERR_NOSUCHTYCOON = 6; ERR_TYCOONNOTLOGGED = 7; ERR_TYCOONALREADYEXISTS = 8; ERR_TEAMALREADYEXISTS = 9; ERR_CRIMINALHIRED = 10; ERR_TEAMNOTLOCATED = 11; ERR_NOSUCHTEAM = 12; ERR_NOSUCHCRIMINAL = 13; ERR_NOSUCHMISSION = 14; ERR_TEAMNOTREADY = 15; ERR_UNABLETOASSIGNROLES = 16; ERR_INVALIDSTATUSCHANGE = 17; ERR_MAXERROR = 50; const TEAMSTATE_READY = 0; TEAMSTATE_UNLOCATED = 1; TEAMSTATE_INMISSION = 2; const CRIMSTATUS_ONTHEMARKET = 1; CRIMSTATUS_READY = 2; CRIMSTATUS_INMISSION = 3; CRIMSTATUS_CAPTURED = 4; CRIMSTATUS_DEAD = 5; CRIMSTATUS_TRAINING = 6; const MAX_ROLES = 9; MAX_SKILLS = 10; const ROLE_LEADER = 0; ROLE_DRIVER = 1; ROLE_GORILLA = 2; ROLE_ARTIFICER = 3; ROLE_STALKER = 4; ROLE_HACKER = 5; ROLE_DOCTOR = 6; ROLE_SNIPER = 7; ROLE_FALSIFIER = 8; const SKILL_LEADERSHIP = 0; SKILL_DRIVING = 1; SKILL_BRAWLING = 2; SKILL_FIREARMS = 3; SKILL_STALKING = 4; SKILL_COMPUTER = 5; SKILL_DEMOLITION = 6; SKILL_STEALTH = 7; SKILL_MEDICINE = 8; SKILL_FORGERY = 9; const // RDOGetCriminalList EXPERT_PREFIX = 'e_'; ROOKIE_PREFIX = 'r_'; const // Training States TRAININGSTATE_TRAINING = 1; TRAININGSTATE_PAUSED = 2; type TCriminalSex = ( csMale, csFemale ); TErrorCode = integer; type TLocationInformation = packed record Population : integer; Education : integer; PoliceCoverage : integer; end; TRoleInfo = packed record role : integer; skill : integer; end; TRoles = array[0..MAXTEAM_MEMBERS] of TRoleInfo; type TCriminal = class; TCriminalTycoon = class; TSkillCollection = class; TTeam = class; TMission = class; TCriminalMarket = class; TAction = class; CAction = class of TAction; THistoryItem = class; TTraining = class; TSimulationObject = class(TPersistent) public procedure Act( Frequency : integer ); virtual; abstract; end; TSimObjectInfo = class(TPersistent) public constructor Create( aSimObject : TSimulationObject; aFreq : integer ); public procedure Simulate; private fSimObject : TSimulationObject; fFreq : integer; fCurrTick : integer; public property SimObject : TSimulationObject read fSimObject; property Frequency : integer read fFreq; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TLocalCriminalMarket = class(TSimulationObject) public constructor Create( aLocation : string; aCriminalMarket : TCriminalMarket ); destructor Destroy; override; public procedure getCriminalList( ExpCriminals : TCollection; RookieCriminals : TCollection ); function extractCriminal( CriminalId : integer ) : TCriminal; procedure addExpertCriminal( Criminal : TCriminal ); public procedure Act( Frequency : integer ); override; private fLocation : string; fExperts : TCollection; fRookies : TCollection; fCriminalMarket : TCriminalMarket; private function GenerateCriminal : TCriminal; function findCriminal( CriminalId : integer; where : TCollection ) : TCriminal; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TCriminalMarket = class(TSimulationObject) public constructor Create; destructor Destroy; override; public procedure InitTexts; public procedure AddLocation( aLocation : string ); procedure getCriminalList( Location : string; ExpCriminals : TCollection; RookieCriminals : TCollection ); function HireCriminal( Location : string; CriminalId : integer ) : TCriminal; procedure FireCriminal( Location : string; Criminal : TCriminal ); function GenerateId : integer; private fLocations : TMapStringToObject; fLastId : integer; private // Criminal Generation fMaleNames : TStringList; fFemaleNames : TStringList; fLastNames : TStringList; fMalePictures : TStringList; fFemalePictures : TStringList; public property MaleNames : TStringList read fMaleNames; property FemaleNames : TStringList read fFemaleNames; property LastNames : TStringList read fLastNames; property MalePictures : TStringList read fMalePictures; property FemalePictures : TStringList read fFemalePictures; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure Act( Frequency : integer ); override; end; TIBClientView = class public constructor Create( aCriminalTycoon : TCriminalTycoon ); public procedure Report( aReport : string ); virtual; abstract; protected fTycoon : TCriminalTycoon; end; // data passed to the actions TInternalActionData = record Criminals : array[0..MAXTEAM_MEMBERS - 1] of TCriminal; CriminalCount : integer; Team : TTeam; end; TModelServerActionData = record Id : integer; Intensity : single; Radius : integer; end; TMetaAction = class(TMetaInstance) public constructor Create( id : string; actionClass : CAction; isInternal : boolean ); public function Instantiate( const Info ) : TAction; virtual; private fInternal : boolean; fActionClass : CAction; public property Internal : boolean read fInternal; end; TAction = class(TPersistent) public constructor Create( aMetaAction : TMetaAction ); public procedure Execute( const Info; var outcome : single ); virtual; abstract; procedure Init( const Info ); virtual; abstract; protected fMetaAction : TMetaAction; public property MetaAction : TMetaAction read fMetaAction; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TRequierements = array[0..MAX_HISTREQUIREMENTS] of integer; TMetaHistoryItem = class(TMetaInstance) public constructor Create( anId : string ); public procedure AddRequierement( Req : integer ); function Requires( Req : integer ) : boolean; function Instantiate : THistoryItem; private //fId : string; fRequirementCount : integer; fRequirements : TRequierements; public //property Id : string read fId; property RequirementCount : integer read fRequirementCount; property Requirements : TRequierements read fRequirements; end; THistoryItem = class(TPersistent) public constructor Create( aMetaHistoryItem : TMetaHistoryItem ); destructor Destroy; override; public procedure addRequierement( Req : integer; data : string ); function serialize : string; protected fMetaClass : TMetaHistoryItem; fData : TStringList; public property MetaClass : TMetaHistoryItem read fMetaClass; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TTownInfo = class(TPersistent) public constructor Create( aName : string ); private fName : string; public property Name : string read fName; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TIBSystem = class(TPersistent) public constructor Create; destructor Destroy; override; public procedure InitMissions; published // LogIn procedure function RDOLogCriminalIn( TycoonName : widestring ) : olevariant; procedure RDOLogCriminalOff( TycoonName : widestring ); function RDOCreateCriminalId( TycoonName : widestring; CriminalId : widestring ) : olevariant; // Tycoon Information function RDOGetTycoonInfo( TycoonId : integer ): olevariant; function RDOGetTeamInfo( TycoonId : integer; TeamName : widestring ): olevariant; function RDOCreateTeam( TycoonId : integer; TeamName : widestring ) : olevariant; function RDOSetTeamHeadQuarter( TycoonId : integer; TeamName : widestring; x, y : integer; Location : WideString ) : olevariant; // Criminals function RDOHireCriminal( TycoonId : integer; CriminalId : integer; TeamName : widestring ): olevariant; function RDOFireCriminal( TycoonId : integer; TeamName : widestring; CriminalId : integer ): olevariant; function RDOGetCriminalList( TycoonId : integer; TeamName : widestring ): olevariant; // Mission function RDOStartMission( TycoonId : integer; TeamName : widestring; MissionId : widestring; MissionInfo : widestring ): olevariant; function RDOAbortMission( TycoonId : integer; TeamName : widestring ): olevariant; public procedure Act; procedure HandleEvent( event : integer; var data ); procedure getLocationInformation( Location : string; var Info : TLocationInformation ); procedure addLocation( Location : string ); public // Simulation Objects procedure AddSimulationObject( aSimObject : TSimulationObject; Freq : integer ); procedure DeleteSimulationObject( aSimObject : TSimulationObject; Freq : integer ); public procedure AddCriminalHistoryItem( Criminal : TCriminal; Id : string; Date : string; Team : TTeam; Mission : TMission; Training : TTraining ); procedure AddTycoonHistoryItem( Tycoon : TCriminalTycoon; Id : string; Date : string; Team : TTeam; aCriminal : TCriminal ); procedure AddTeamHistoryItem( Team : TTeam; Id : string; Date : string; Tycoon : TCriminalTycoon; Mission : TMission; aCriminal : TCriminal ); private procedure Simulate; function CreateClientView( Tycoon : TCriminalTycoon ) : TIBClientView; private fCriminalTycoons : TMapStringToObject; fAgencies : TLockableCollection; fSimObjects : TLockableCollection; fCriminalMarket : TCriminalMarket; fClientViews : TLockableCollection; fLocations : TLockableCollection; //fDataFolder : string; private function getLocation( name : string ) : TTownInfo; private procedure SerializeCriminal( Prefix : string; Criminal : TCriminal; where : TStringList; idx : integer ); private // Critical Sections fSimulationSection : TCriticalSection; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TCriminalTycoon = class(TSimulationObject) public constructor Create( aIBSystem : TIBSystem; aCriminalName : string; aTycoonName : string ); destructor Destroy; override; public procedure addHistoryItem( Item : THistoryItem ); function getTeamByName( aName : string ) : TTeam; public procedure Act( Frequency : integer ); override; protected fCriminalName : string; fTycoonName : string; fTeams : TLockableCollection; fLogged : boolean; fClientView : TIBClientView; fHistory : TCollection; public property TycoonName : string read fTycoonName; property CriminalName : string read fCriminalName; property Logged : boolean read fLogged write fLogged; property Teams : TLockableCollection read fTeams; property ClientView : TIBClientView read fClientView write fClientView; property History : TCollection read fHistory; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TMetaMission = class(TMetaInstance) public function Instantiate( MissionInfo : string; Owner : TTeam; out Mission : TMission ) : TErrorCode; virtual; abstract; protected fName : string; public property Name : string read fName; end; TMission = class(TSimulationObject) public constructor Create( aOwner : TTeam; aMetaMission : TMetaMission ); virtual; public procedure StartMission; virtual; procedure ProceedWithMission; virtual; procedure EndMission; virtual; procedure Abort; virtual; procedure Escaped; virtual; public procedure Act( Frequency : integer ); override; protected fOwner : TTeam; fAbort : boolean; fEscaped : boolean; fMetaMission : TMetaMission; public property Owner : TTeam read fOwner; property MetaMission : TMetaMission read fMetaMission; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TTeam = class(TSimulationObject) public constructor Create( aName : string; aOwner : TCriminalTycoon ); destructor Destroy; override; public function AddCriminal( aCriminal : TCriminal ) : TErrorCode; function DeleteCriminal( aCriminal : TCriminal ) : TErrorCode; function FindCriminal( aName : string ) : TCriminal; function getCriminalById( CriminalId : integer ) : TCriminal; function AssignMission( aMission : TMission; MissionInfo : string ) : TErrorCode; function getCriminalForTask( role, skill : integer; assdRoleCount : integer; const assdRoles : TRoles ) : TCriminal; function setHeadquarter( x, y : integer; aLocation : string ) : TErrorCode; procedure addHistoryItem( HistoryItem : THistoryItem ); public procedure Act( Frequency : integer ); override; protected fName : string; fOwner : TCriminalTycoon; fCriminals : TLockableCollection; fLocation : TTownInfo; fState : integer; fMission : TMission; fHQX : integer; fHQY : integer; fHistory : TCollection; protected procedure Moved; public property Owner : TCriminalTycoon read fOwner; property Name : string read fName; property Criminals : TLockableCollection read fCriminals; property Location : TTownInfo read fLocation; property State : integer read fState; property Mission : TMission read fMission; property HQX : integer read fHQX; property HQY : integer read fHQY; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TCriminal = class(TSimulationObject) public constructor Create( aName : string; anAge : integer; aSex : TCriminalSex; aLocation : string; aPictureId : string; anId : integer ); destructor Destroy; override; public procedure addHistoryItem( Item : THistoryItem ); function setStatus( anewStatus : integer; var info ) : TErrorCode; function CheckStability( Skill : integer; PsiFactor : single ) : single; public procedure Act( Frequency : integer ); override; protected fName : string; fAge : integer; fSex : TCriminalSex; fSkills : TSkillCollection; fPictureId : string; fTeam : TTeam; fId : integer; fRole : integer; // status fStatus : integer; fStability : single; // History fHistory : TCollection; protected function getLocation : TTownInfo; public property Name : string read fName; property Id : integer read fId; property Age : integer read fAge; property Sex : TCriminalSex read fSex; property Skills : TSkillCollection read fSkills; property Team : TTeam read fTeam; property Status : integer read fStatus; property PictureId : string read fPictureId; property Role : integer read fRole; property Location : TTownInfo read getLocation; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TSkill = single; TSkillArray = array[0..SKILL_COUNT] of TSkill; TSkillCollection = class(TPersistent) public constructor Create; private fSkillCount : integer; fSkills : TSkillArray; public property Count : integer read fSkillCount write fSkillCount; property Skills : TSkillArray read fSkills write fSkills; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; // Trainings TMetaTraining = class(TMetaInstance) public procedure TrainingComplete( percent : integer; Trainee : TObject ); virtual; abstract; private fId : string; fDuration : integer; // in days fFrequency : integer; fName : string; public property Id : string read fId; property Duration : integer read fDuration; property Frequency : integer read fFrequency; property Name : string read fName; end; TTraining = class(TSimulationObject) public constructor Create( aMetaTraining : TMetaTraining; aTrainee : TObject ); public procedure Act( Frequency : integer ); override; public procedure Abort; virtual; procedure Pause; virtual; procedure Resume; virtual; protected fState : integer; fTrainee : TObject; fMetaTraining : TMetaTraining; fPercent : integer; fTimeElapsed : integer; fFrequency : integer; procedure Finished; virtual; public property Frequency : integer read fFrequency; property MetaTraining : TMetaTraining read fMetaTraining; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; var theIBSystem : TIBSystem; theMetaClassStorage : TClassStorage; implementation uses Windows, SysUtils, MissionEngine, TestClientView, Registry; const IB_KEY = 'Software\Oceanus\Five\ModelServer\'; var IBDataFolder : string = ''; function getIBDataFolder : string; var Reg : TRegistry; begin if IBDataFolder = '' then begin Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(IB_KEY, false) then IBDataFolder := Reg.ReadString('IBData'); end; result := IBDataFolder; end; // TSimObjectInfo constructor TSimObjectInfo.Create( aSimObject : TSimulationObject; aFreq : integer ); begin inherited Create; fSimObject := aSimObject; fFreq := aFreq; fCurrTick := aFreq; end; procedure TSimObjectInfo.Simulate; begin dec( fCurrTick ); if fCurrTick = 0 then begin fCurrTick := fFreq; fSimObject.Act( fFreq ); end; end; procedure TSimObjectInfo.LoadFromBackup(Reader : IBackupReader); begin inherited; Reader.ReadObject('SimObj', fSimObject, nil); fFreq := Reader.ReadInteger('Freq', 1); fCurrTick := Reader.ReadInteger('Tick', 1); end; procedure TSimObjectInfo.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteObjectRef('SimObj', fSimObject); Writer.WriteInteger('Freq', fFreq); Writer.WriteInteger('Tick', fCurrTick); end; // TLocalCriminalMarket constructor TLocalCriminalMarket.Create( aLocation : string; aCriminalMarket : TCriminalMarket ); begin inherited Create; fLocation := aLocation; fExperts := TCollection.Create( 10, rkBelonguer ); fRookies := TCollection.Create( 10, rkBelonguer ); fCriminalMarket := aCriminalMarket; end; destructor TLocalCriminalMarket.Destroy; begin fExperts.Free; fRookies.Free; inherited; end; procedure TLocalCriminalMarket.getCriminalList( ExpCriminals : TCollection; RookieCriminals : TCollection ); var i : integer; Crim : TCriminal; begin try for i := 0 to pred(fExperts.Count) do ExpCriminals.Insert( fExperts[i] ); for i := 0 to pred(fRookies.Count) do RookieCriminals.Insert( fRookies[i] ); if fRookies.Count < AVAILABLE_CRIMINALS then begin for i := fRookies.Count to AVAILABLE_CRIMINALS do begin Crim := GenerateCriminal(); fRookies.Insert( Crim ); RookieCriminals.Insert( Crim ); end; end; except end; end; function TLocalCriminalMarket.extractCriminal( CriminalId : integer ) : TCriminal; begin try result := findCriminal( CriminalId, fExperts ); if result <> nil then fExperts.Extract( result ) else begin result := findCriminal( CriminalId, fRookies ); if result <> nil then fRookies.Extract( result ) end; except result := nil; end; end; procedure TLocalCriminalMarket.addExpertCriminal( Criminal : TCriminal ); begin try if findCriminal( Criminal.Id, fExperts ) = nil then fExperts.Insert( Criminal ); except end; end; procedure TLocalCriminalMarket.Act( Frequency : integer ); begin end; function TLocalCriminalMarket.GenerateCriminal : TCriminal; const GENPARAM_COUNT = 5; const GEN_POPULATION = 0; GEN_EDUCATION = 1; GEN_POLICECOVERAGE = 2; GEN_MALE = 3; GEN_FEMALE = 4; type TSkillGenInfo = packed record MinValue : integer; MaxValue : integer; Importance : array[0..pred(GENPARAM_COUNT)] of integer; end; const GENCRIMINAL_INFO : array[0..pred(SKILL_COUNT)] of TSkillGenInfo = ( // POP EDU POL MALE FMALE (MinValue:0; MaxValue:40; Importance:( 20, 40, 0, 40, 20 )), // SKILL_LEADERSHIP (MinValue:50; MaxValue:70; Importance:( 40, 0, 40, 10, 10 )), // SKILL_DRIVING (MinValue:0; MaxValue:70; Importance:( 0, 0, 0, 100, 0 )), // SKILL_BRAWLING (MinValue:0; MaxValue:70; Importance:( 60, 30, 10, 0, 0 )), // SKILL_FIREARMS (MinValue:0; MaxValue:50; Importance:( 30, 50, 20, 0, 0 )), // SKILL_STALKING (MinValue:0; MaxValue:60; Importance:( 20, 80, 0, 0, 0 )), // SKILL_COMPUTER (MinValue:0; MaxValue:50; Importance:( 50, 20, 0, 30, 0 )), // SKILL_DEMOLITION (MinValue:0; MaxValue:100; Importance:( 20, 0, 20, 20, 40 )), // SKILL_STEALTH (MinValue:0; MaxValue:80; Importance:( 20, 80, 0, 0, 0 )), // SKILL_MEDICINE (MinValue:0; MaxValue:50; Importance:( 0, 100, 0, 0, 0 )) // SKILL_FORGERY ); GENPARAMS_VALUE : array[0..pred(GENPARAM_COUNT)] of integer = // POP EDUCATION POLICE MALE FEMALE ( 100000, 100, 100, 1, 1 ); function percent( value, maxValue : integer ) : integer; begin result := round( (value*100)/maxValue ); if result > 100 then result := 100; end; function applypercent( perc : integer; maxValue : integer ) : integer; begin result := round( (perc*maxValue)/100 ); end; function ParamToPercent( Param : integer; Value : integer ): integer; begin result := percent( Value, GENPARAMS_VALUE[Param] ); end; function GenerateSkill( Criminal : TCriminal; Info : TLocationInformation; Skill : integer ) : single; var p : integer; diff : integer; begin p := GENCRIMINAL_INFO[Skill].MinValue; diff := GENCRIMINAL_INFO[Skill].MaxValue - GENCRIMINAL_INFO[Skill].MinValue; p := p + random( applypercent( applypercent( ParamToPercent(GEN_POPULATION, Info.Population), GENCRIMINAL_INFO[Skill].Importance[GEN_POPULATION] ), diff )); p := p + random( applypercent( applypercent( ParamToPercent(GEN_EDUCATION, Info.Education), GENCRIMINAL_INFO[Skill].Importance[GEN_POPULATION] ), diff )); p := p + random( applypercent( applypercent( ParamToPercent(GEN_POLICECOVERAGE, Info.PoliceCoverage), GENCRIMINAL_INFO[Skill].Importance[GEN_POPULATION] ), diff )); p := p + random( applypercent( applypercent( ParamToPercent(GEN_MALE, integer(Criminal.Sex = csMale)), GENCRIMINAL_INFO[Skill].Importance[GEN_POPULATION] ), diff )); p := p + random( applypercent( applypercent( ParamToPercent(GEN_FEMALE, integer(Criminal.Sex = csFemale)), GENCRIMINAL_INFO[Skill].Importance[GEN_POPULATION] ), diff )); result := p/100; end; const MALE_PROB = 0.75; MALE_MINAGE = 18; MALE_AGERANGE = 65 - MALE_MINAGE; FEMALE_MINAGE = 20; FEMALE_AGERANGE = 50 - FEMALE_MINAGE; function GenerateName( Sex : TCriminalSex ) : string; begin case Sex of csMale : result := fCriminalMarket.MaleNames[random(fCriminalMarket.MaleNames.Count)]; csFemale : result := fCriminalMarket.FemaleNames[random(fCriminalMarket.FemaleNames.Count)]; end; result := result + ' ' + fCriminalMarket.LastNames[random(fCriminalMarket.LastNames.Count)]; end; function GenerateAge( Sex : TCriminalSex ) : integer; begin result := 25; // to avoid the compiler warning case Sex of csMale : result := MALE_MINAGE + random(MALE_AGERANGE); csFemale : result := FEMALE_MINAGE + random(FEMALE_AGERANGE); end; end; function GeneratePicture( Sex : TCriminalSex ) : string; begin result := ''; // same case Sex of csMale : result := fCriminalMarket.MalePictures[random(fCriminalMarket.MalePictures.Count)]; csFemale : result := fCriminalMarket.FemalePictures[random(fCriminalMarket.FemalePictures.Count)]; end; end; var aName : string; anAge : integer; aSex : TCriminalSex; aLocation : string; aPictureId : string; anId : integer; i : integer; LocInfo : TLocationInformation; begin try if random < MALE_PROB then aSex := csMale else aSex := csFemale; aLocation := fLocation; anId := fCriminalMarket.GenerateId; aName := GenerateName( aSex ); anAge := GenerateAge( aSex ); aPictureId := GeneratePicture( aSex ); result := TCriminal.Create( aName, anAge, aSex, aLocation, aPictureId, anId ); theIBSystem.getLocationInformation( aLocation, LocInfo ); //>> make this a function for i := 0 to pred(SKILL_COUNT) do result.Skills.fSkills[i] := GenerateSkill( result, LocInfo, i ); except result := nil; end; end; function TLocalCriminalMarket.findCriminal( CriminalId : integer; where : TCollection ) : TCriminal; var i : integer; found : boolean; begin i := 0; found := false; while (i < where.Count) and not found do begin found := TCriminal(where[i]).Id = CriminalId; if not found then inc( i ); end; if found then result := TCriminal(where[i]) else result := nil; end; procedure TLocalCriminalMarket.LoadFromBackup(Reader : IBackupReader); begin inherited; fLocation := Reader.ReadString('Loc', ''); Reader.ReadObject('Exps', fExperts, nil); if fExperts = nil then fExperts := TCollection.Create(10, rkBelonguer); Reader.ReadObject('Rookies', fRookies, nil); if fRookies = nil then fRookies := TCollection.Create(10, rkBelonguer); Reader.ReadObject('CrMrk', fCriminalMarket, nil); end; procedure TLocalCriminalMarket.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('Loc', fLocation); Writer.WriteLooseObject('Exps', fExperts); Writer.WriteLooseObject('Rookies', fRookies); Writer.WriteObjectRef('CrMrk', fCriminalMarket); end; // TCriminalMarket constructor TCriminalMarket.Create; begin inherited Create; fLocations := TMapStringToObject.Create( mmOwn ); fLastId := 0; InitTexts; end; destructor TCriminalMarket.Destroy; begin fLocations.Free; inherited; end; procedure TCriminalMarket.InitTexts; const MALENAME_FILE = 'males.txt'; FEMALENAME_FILE = 'females.txt'; LASTNAME_FILE = 'lastname.txt'; MALEPICTURE_FILE = 'malepics.txt'; FEMALEPICTURE_FILE = 'fempics.txt'; var MaleNamesFile : string; FemaleNameFile : string; LastNameFile : string; MalePictureFile : string; FemalePictureFile : string; DataFolder : string; begin DataFolder := getIBDataFolder + 'Names\'; fMaleNames := TStringList.Create; fFemaleNames := TStringList.Create; fLastNames := TStringList.Create; fMalePictures := TStringList.Create; fFemalePictures := TStringList.Create; MaleNamesFile := DataFolder + MALENAME_FILE; FemaleNameFile := DataFolder + FEMALENAME_FILE; LastNameFile := DataFolder + LASTNAME_FILE; MalePictureFile := DataFolder + MALEPICTURE_FILE; FemalePictureFile := DataFolder + FEMALEPICTURE_FILE; fMaleNames.LoadFromFile( MaleNamesFile ); fFemaleNames.LoadFromFile( FemaleNameFile ); fLastNames.LoadFromFile( LastNameFile ); fMalePictures.LoadFromFile( MalePictureFile ); fFemalePictures.LoadFromFile( FemalePictureFile ); end; procedure TCriminalMarket.AddLocation( aLocation : string ); begin try if fLocations.Items[aLocation] = nil then fLocations.Items[aLocation] := TLocalCriminalMarket.Create( aLocation, self ); except end; end; procedure TCriminalMarket.getCriminalList( Location : string; ExpCriminals : TCollection; RookieCriminals : TCollection ); var LocalMarket : TLocalCriminalMarket; begin try LocalMarket := TLocalCriminalMarket(fLocations.Items[Location]); if LocalMarket <> nil then LocalMarket.getCriminalList( ExpCriminals, RookieCriminals ); except end; end; function TCriminalMarket.HireCriminal( Location : string; CriminalId : integer ) : TCriminal; var LocalMarket : TLocalCriminalMarket; begin try LocalMarket := TLocalCriminalMarket(fLocations.Items[Location]); if LocalMarket <> nil then result := LocalMarket.extractCriminal( CriminalId ) else result := nil; except result := nil; end; end; procedure TCriminalMarket.FireCriminal( Location : string; Criminal : TCriminal ); var LocalMarket : TLocalCriminalMarket; begin try LocalMarket := TLocalCriminalMarket(fLocations.Items[Location]); if LocalMarket <> nil then begin Criminal.setStatus( CRIMSTATUS_ONTHEMARKET, self ); LocalMarket.addExpertCriminal( Criminal ); end; //>> notify except end; end; function TCriminalMarket.GenerateId : integer; begin result := fLastId; inc( fLastId ); end; procedure TCriminalMarket.LoadFromBackup(Reader : IBackupReader); begin inherited; Reader.ReadObject('Locations', fLocations, nil); fLastId := Reader.ReadInteger('LstId', 0); InitTexts; end; procedure TCriminalMarket.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteObject('Locations', fLocations); Writer.WriteInteger('LstId', fLastId); end; procedure TCriminalMarket.Act(Frequency : integer); begin end; // TIBClientView constructor TIBClientView.Create( aCriminalTycoon : TCriminalTycoon ); begin inherited Create; fTycoon := aCriminalTycoon; end; // TMetaAction constructor TMetaAction.Create( id : string; actionClass : CAction; isInternal : boolean ); begin inherited Create(id); fInternal := isInternal; fActionClass := actionClass; end; function TMetaAction.Instantiate( const Info ) : TAction; begin result := fActionClass.Create( self ); result.Init( Info ); end; // TAction constructor TAction.Create( aMetaAction : TMetaAction ); begin inherited Create; fMetaAction := aMetaAction; end; procedure TAction.LoadFromBackup(Reader : IBackupReader); var aux : string; begin inherited; aux := Reader.ReadString('MetaAct', ''); fMetaAction := TMetaAction(TheClassStorage.ClassById[tidMetaActionFamily, aux]); end; procedure TAction.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('MetaAct', fMetaAction.Id); end; // TMetaHistoryItem constructor TMetaHistoryItem.Create( anId : string ); begin inherited Create(anId); //fId := anId; end; procedure TMetaHistoryItem.AddRequierement( Req : integer ); begin fRequirements[fRequirementCount] := Req; inc( fRequirementCount ); end; function TMetaHistoryItem.Requires( Req : integer ) : boolean; var i : integer; found : boolean; begin i := 0; found := false; while (i < fRequirementCount) and not found do begin found := fRequirements[i] = Req; inc( i ); end; result := found; end; function TMetaHistoryItem.Instantiate : THistoryItem; begin result := THistoryItem.Create( self ); end; // THistoryItem constructor THistoryItem.Create( aMetaHistoryItem : TMetaHistoryItem ); begin inherited Create; fMetaClass := aMetaHistoryItem; fData := TStringList.Create; end; destructor THistoryItem.Destroy; begin fData.Free; inherited; end; procedure THistoryItem.addRequierement( Req : integer; data : string ); const REQUIEREMENT_TO_STR : array[0..pred(MAX_HISTREQUIREMENTS)] of string = ( 'TYCOON', 'CRIMINAL', 'DATE', 'MISSION', 'TRAINING', 'TTEAM' ); begin if fMetaClass.Requires( Req ) then fData.Values[REQUIEREMENT_TO_STR[Req]] := data; end; function THistoryItem.serialize : string; begin result := fData.Text; end; procedure THistoryItem.LoadFromBackup(Reader : IBackupReader); var aux : string; begin inherited; aux := Reader.ReadString('MetaItem', ''); fMetaClass := TMetaHistoryItem(TheClassStorage.ClassById[tidMetaHistoryFamily, aux]); Reader.ReadObject('Data', fData, nil); end; procedure THistoryItem.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('MetaItem', fMetaClass.Id); Writer.WriteObject('Data', fData); end; // TTownInfo constructor TTownInfo.Create( aName : string ); begin inherited Create; fName := aName; end; procedure TTownInfo.LoadFromBackup(Reader : IBackupReader); begin inherited; fName := Reader.ReadString('Name', ''); end; procedure TTownInfo.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('Name', fName); end; // TIBSystem constructor TIBSystem.Create; begin inherited Create; fCriminalTycoons := TMapStringToObject.Create( mmOwn ); fAgencies := TLockableCollection.Create( 10, rkBelonguer ); fSimObjects := TLockableCollection.Create( 10, rkBelonguer ); fClientViews := TLockableCollection.Create( 10, rkBelonguer ); fLocations := TLockableCollection.Create( 10, rkBelonguer ); fCriminalMarket := TCriminalMarket.Create; fSimulationSection := TCriticalSection.Create; InitMissions; end; destructor TIBSystem.Destroy; begin fCriminalTycoons.Free; fAgencies.Free; fSimObjects.Free; fClientViews.Free; fLocations.Free; fCriminalMarket.Free; fSimulationSection.Free; DestroyMissionLoader; inherited; end; procedure TIBSystem.InitMissions; begin InitMissionLoader; TheMetaMissionLoader.CheckDirectory( getIBDataFolder + '\Missions' ); end; function TIBSystem.RDOLogCriminalIn( TycoonName : widestring ) : olevariant; var Tycoon : TCriminalTycoon; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(fCriminalTycoons.Items[TycoonName]); if Tycoon <> nil then begin if not Tycoon.Logged then begin Tycoon.Logged := true; if (integer(Tycoon) < ERR_MAXERROR) then begin Tycoon.Free; result := ERR_UNKNOWN; end; if Tycoon.ClientView <> nil then Tycoon.ClientView.Free; Tycoon.ClientView := CreateClientView( Tycoon ); result := integer(Tycoon); end else result := ERR_TYCOONALREADYLOGGED; end else result := ERR_NOSUCHTYCOON; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; procedure TIBSystem.RDOLogCriminalOff( TycoonName : widestring ); var Tycoon : TCriminalTycoon; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(fCriminalTycoons.Items[TycoonName]); if Tycoon <> nil then begin if Tycoon.Logged then begin Tycoon.ClientView.Free; Tycoon.ClientView := nil; Tycoon.Logged := false; end; end; finally fSimulationSection.Leave; end; except end end; function TIBSystem.RDOCreateCriminalId( TycoonName : widestring; CriminalId : widestring ) : olevariant; var Tycoon : TCriminalTycoon; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(fCriminalTycoons.Items[TycoonName]); if Tycoon = nil then begin Tycoon := TCriminalTycoon.Create( self, CriminalId, TycoonName ); fCriminalTycoons.Items[TycoonName] := Tycoon; result := RDOLogCriminalIn( TycoonName ); end else result := ERR_TYCOONALREADYEXISTS; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; function TIBSystem.RDOGetTycoonInfo( TycoonId : integer ): olevariant; var Tycoon : TCriminalTycoon; Props : TStringList; i : integer; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Props := TStringList.Create; try //>> todo: gather all information needed (level, earnings, etc) Props.Values['CriminalName'] := Tycoon.CriminalName; //Teams for i := 0 to pred(Tycoon.Teams.Count) do Props.Values['Team' + IntToStr(i)] := TTeam(Tycoon.Teams[i]).Name; result := Props.Text; finally Props.Free; end; end else result := ''; finally fSimulationSection.Leave; end; except result := ''; end end; function TIBSystem.RDOGetTeamInfo( TycoonId : integer; TeamName : widestring ): olevariant; var Tycoon : TCriminalTycoon; Team : TTeam; Props : TStringList; i : integer; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Props := TStringList.Create; try Team := Tycoon.getTeamByName( TeamName ); if Team <> nil then begin //>> send other info like status // Criminals info for i := 0 to pred(Team.Criminals.Count) do SerializeCriminal( '', TCriminal(Team.Criminals[i]), Props, i ); result := Props.Text; end else result := ''; finally Props.Free; end; end else result := ''; finally fSimulationSection.Leave; end; except result := ''; end end; function TIBSystem.RDOCreateTeam( TycoonId : integer; TeamName : widestring ) : olevariant; var Tycoon : TCriminalTycoon; NewTeam : TTeam; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin if Tycoon.getTeamByName(TeamName) = nil then begin NewTeam := TTeam.Create( TeamName, Tycoon ); Tycoon.Teams.Insert( NewTeam ); result := ERR_SUCCEDEED; end else result := ERR_TEAMALREADYEXISTS; end else result := ERR_TYCOONNOTLOGGED; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; function TIBSystem.RDOSetTeamHeadQuarter( TycoonId : integer; TeamName : widestring; x, y : integer; Location : WideString ) : olevariant; var Tycoon : TCriminalTycoon; Team : TTeam; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Team := Tycoon.getTeamByName(TeamName); if Team <> nil then result := Team.setHeadquarter( x, y, Location ) else result := ERR_NOSUCHTEAM; end else result := ERR_TYCOONNOTLOGGED; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; function TIBSystem.RDOHireCriminal( TycoonId : integer; CriminalId : integer; TeamName : widestring ): olevariant; var Tycoon : TCriminalTycoon; Criminal : TCriminal; Team : TTeam; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Team := Tycoon.getTeamByName( TeamName ); if Team <> nil then begin if Team.Location <> nil then begin Criminal := fCriminalMarket.HireCriminal( Team.Location.Name, CriminalId ); if Criminal <> nil then begin if Criminal.setStatus( CRIMSTATUS_READY, Team ) = ERR_SUCCEDEED then begin result := Team.AddCriminal( Criminal ); end else result := ERR_UNKNOWN; end else result := ERR_CRIMINALHIRED; end else result := ERR_TEAMNOTLOCATED; end else result := ERR_NOSUCHTEAM; end else result := ERR_TYCOONNOTLOGGED; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; function TIBSystem.RDOFireCriminal( TycoonId : integer; TeamName : widestring; CriminalId : integer ): olevariant; var Tycoon : TCriminalTycoon; Criminal : TCriminal; Team : TTeam; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Team := Tycoon.getTeamByName( TeamName ); if Team <> nil then begin if Team.Location <> nil then begin Criminal := Team.getCriminalById( CriminalId ); if Criminal <> nil then begin fCriminalMarket.FireCriminal( Team.Location.Name, Criminal ); result := ERR_SUCCEDEED; end else result := ERR_NOSUCHCRIMINAL; end else result := ERR_TEAMNOTLOCATED; end else result := ERR_NOSUCHTEAM; end else result := ERR_TYCOONNOTLOGGED; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; function TIBSystem.RDOGetCriminalList( TycoonId : integer; TeamName : widestring ): olevariant; var Tycoon : TCriminalTycoon; Team : TTeam; ExpCriminals : TCollection; RookieCriminals : TCollection; i : integer; Criminals : TStringList; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Team := Tycoon.getTeamByName( TeamName ); if Team <> nil then begin if Team.Location <> nil then begin ExpCriminals := TCollection.Create( 10, rkUse ); RookieCriminals := TCollection.Create( 10, rkUse ); Criminals := TStringList.Create; try fCriminalMarket.getCriminalList( Team.Location.Name, ExpCriminals, RookieCriminals ); for i := 0 to pred(ExpCriminals.Count) do SerializeCriminal( EXPERT_PREFIX, TCriminal(ExpCriminals[i]), Criminals, i ); for i := 0 to pred(RookieCriminals.Count) do SerializeCriminal( ROOKIE_PREFIX, TCriminal(RookieCriminals[i]), Criminals, i ); result := Criminals.Text; finally ExpCriminals.Free; RookieCriminals.Free; Criminals.Free; end; end else result := ''; end else result := ''; end else result := ''; finally fSimulationSection.Leave; end; except result := ''; end end; function TIBSystem.RDOStartMission( TycoonId : integer; TeamName : widestring; MissionId : widestring; MissionInfo : widestring ): olevariant; var Tycoon : TCriminalTycoon; Team : TTeam; MetaMission : TMetaMission; Mission : TMission; res : TErrorCode; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Team := Tycoon.getTeamByName( TeamName ); if Team <> nil then begin if Team.State = TEAMSTATE_READY then begin MetaMission := TMetaMission(theMetaClassStorage.ClassById[tidMetaMissionFamily, MissionId]); if MetaMission <> nil then begin res := MetaMission.Instantiate( MissionInfo, Team, Mission ); if res = ERR_SUCCEDEED then begin result := Team.AssignMission( Mission, MissionInfo ); if result <> ERR_SUCCEDEED then Mission.Free else begin theIBSystem.AddSimulationObject( Team, FREQ_HOUR ); end; end else begin Mission.Free; result := res; end; end else result := ERR_NOSUCHMISSION; end else result := ERR_TEAMNOTREADY; end else result := ERR_NOSUCHTEAM; end else result := ERR_TYCOONNOTLOGGED; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; function TIBSystem.RDOAbortMission( TycoonId : integer; TeamName : widestring ): olevariant; var Tycoon : TCriminalTycoon; Team : TTeam; begin try fSimulationSection.Enter; try Tycoon := TCriminalTycoon(TycoonId); if Tycoon.Logged then begin Team := Tycoon.getTeamByName( TeamName ); if Team <> nil then begin if Team.State = TEAMSTATE_INMISSION then begin Team.Mission.Abort; result := ERR_SUCCEDEED; end else result := ERR_TEAMNOTREADY; end else result := ERR_NOSUCHTEAM; end else result := ERR_TYCOONNOTLOGGED; finally fSimulationSection.Leave; end; except result := ERR_UNKNOWN; end end; procedure TIBSystem.Act; begin fSimulationSection.Enter; try Simulate; finally fSimulationSection.Leave; end; end; procedure TIBSystem.HandleEvent( event : integer; var data ); begin end; procedure TIBSystem.getLocationInformation( Location : string; var Info : TLocationInformation ); begin //>> todo: use the modelserver Info.Population := 1000 + random( 700000 ); Info.Education := 10 + random( 90 ); Info.PoliceCoverage := 10 + random( 90 ); end; procedure TIBSystem.addLocation( Location : string ); begin fCriminalMarket.AddLocation( Location ); end; procedure TIBSystem.AddSimulationObject( aSimObject : TSimulationObject; Freq : integer ); begin try fSimObjects.Lock; try fSimObjects.Insert( TSimObjectInfo.Create( aSimObject, Freq ) ); finally fSimObjects.Unlock; end; except end; end; procedure TIBSystem.DeleteSimulationObject( aSimObject : TSimulationObject; Freq : integer ); var i : integer; found : boolean; begin try fSimObjects.Lock; try i := 0; found := false; while (i < fSimObjects.Count) and not found do begin if (TSimObjectInfo(fSimObjects[i]).Frequency = Freq) and (TSimObjectInfo(fSimObjects[i]).SimObject = aSimObject) then begin fSimObjects.AtDelete( i ); found := true; end; inc( i ); end; finally fSimObjects.Unlock; end; except end; end; procedure TIBSystem.AddCriminalHistoryItem( Criminal : TCriminal; Id : string; Date : string; Team : TTeam; Mission : TMission; Training : TTraining ); var MetaHistoryItem : TMetaHistoryItem; HistoryItem : THistoryItem; begin MetaHistoryItem := TMetaHistoryItem(theMetaClassStorage.ClassById[tidMetaHistoryFamily, Id]); if MetaHistoryItem <> nil then begin HistoryItem := MetaHistoryItem.Instantiate; HistoryItem.addRequierement( HISTREQ_DATE, Date ); if Mission <> nil then HistoryItem.addRequierement( HISTREQ_MISSION, Mission.MetaMission.Name ); if Training <> nil then HistoryItem.addRequierement( HISTREQ_TRAINING, Training.MetaTraining.Name ); if Team <> nil then HistoryItem.addRequierement( HISTREQ_TTEAM, Team.Name ); Criminal.addHistoryItem( HistoryItem ); end; end; procedure TIBSystem.AddTycoonHistoryItem( Tycoon : TCriminalTycoon; Id : string; Date : string; Team : TTeam; aCriminal : TCriminal ); var MetaHistoryItem : TMetaHistoryItem; HistoryItem : THistoryItem; begin MetaHistoryItem := TMetaHistoryItem(theMetaClassStorage.ClassById[tidMetaHistoryFamily, Id]); if MetaHistoryItem <> nil then begin HistoryItem := MetaHistoryItem.Instantiate; HistoryItem.addRequierement( HISTREQ_DATE, Date ); if Team <> nil then HistoryItem.addRequierement( HISTREQ_TTEAM, Team.Name ); if aCriminal <> nil then HistoryItem.addRequierement( HISTREQ_CRIMINAL, aCriminal.Name ); Tycoon.addHistoryItem( HistoryItem ); end; end; procedure TIBSystem.AddTeamHistoryItem( Team : TTeam; Id : string; Date : string; Tycoon : TCriminalTycoon; Mission : TMission; aCriminal : TCriminal ); var MetaHistoryItem : TMetaHistoryItem; HistoryItem : THistoryItem; begin MetaHistoryItem := TMetaHistoryItem(theMetaClassStorage.ClassById[tidMetaHistoryFamily, Id]); if MetaHistoryItem <> nil then begin HistoryItem := MetaHistoryItem.Instantiate; HistoryItem.addRequierement( HISTREQ_DATE, Date ); if Tycoon <> nil then HistoryItem.addRequierement( HISTREQ_TYCOON, Tycoon.CriminalName ); if aCriminal <> nil then HistoryItem.addRequierement( HISTREQ_CRIMINAL, aCriminal.Name ); if Mission <> nil then HistoryItem.addRequierement( HISTREQ_CRIMINAL, Mission.MetaMission.Name ); Team.addHistoryItem( HistoryItem ); end; end; procedure TIBSystem.Simulate; var i : integer; begin try fSimObjects.Lock; try for i := pred(fSimObjects.Count) downto 0 do TSimObjectInfo(fSimObjects[i]).Simulate; finally fSimObjects.Unlock; end; except end; end; function TIBSystem.CreateClientView( Tycoon : TCriminalTycoon ) : TIBClientView; begin result := TTestClientView.Create( Tycoon ); end; function TIBSystem.getLocation( name : string ) : TTownInfo; var found : boolean; i : integer; begin found := false; i := 0; while (i < fLocations.Count) and not found do begin found := CompareText( TTownInfo(fLocations[i]).Name, name ) = 0; inc( i ); end; if found then result := TTownInfo(fLocations[pred(i)]) else result := nil; end; procedure TIBSystem.SerializeCriminal( Prefix : string; Criminal : TCriminal; where : TStringList; idx : integer ); var i : integer; begin with Criminal, where do begin Values[Prefix + 'Name' + IntToStr(idx)] := Name; Values[Prefix + 'Sex' + IntToStr(idx)] := IntToStr(integer(Sex)); Values[Prefix + 'Picture' + IntToStr(idx)] := PictureId; Values[Prefix + 'Status' + IntToStr(idx)] := IntToStr(Status); Values[Prefix + 'Id' + IntToStr(idx)] := IntToStr(Id); for i := 0 to pred(SKILL_COUNT) do Values[Prefix + 'Skill' + IntToStr(i) + '_' + IntToStr(idx)] := FloatToStr(Skills.Skills[i]); end; end; procedure TIBSystem.LoadFromBackup(Reader : IBackupReader); begin inherited; Reader.ReadObject('Criminals', fCriminalTycoons, nil); Reader.ReadObject('Agencies', fAgencies, nil); Reader.ReadObject('SimObjs', fSimObjects, nil); Reader.ReadObject('CriminalMarket', fCriminalMarket, nil); fClientViews := TLockableCollection.Create(0, rkBelonguer); InitMissions; end; procedure TIBSystem.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteObject('Criminals', fCriminalTycoons); Writer.WriteObject('Agencies', fAgencies); Writer.WriteObject('SimObjs', fSimObjects); Writer.WriteObject('CriminalMarket', fCriminalMarket); end; // TCriminalTycoon constructor TCriminalTycoon.Create( aIBSystem : TIBSystem; aCriminalName : string; aTycoonName : string ); begin inherited Create; fCriminalName := aCriminalName; fTycoonName := aTycoonName; fTeams := TLockableCollection.Create( 5, rkBelonguer ); fHistory := TCollection.Create( 10, rkBelonguer ); end; destructor TCriminalTycoon.Destroy; begin fTeams.Free; fHistory.Free; inherited; end; procedure TCriminalTycoon.addHistoryItem( Item : THistoryItem ); begin fHistory.Insert( Item ); end; function TCriminalTycoon.getTeamByName( aName : string ) : TTeam; var i : integer; found : boolean; begin i := 0; found := false; while (i < fTeams.Count) and not found do begin found := CompareText( TTeam(fTeams[i]).Name, aName ) = 0; if not found then inc( i ); end; if found then result := TTeam(fTeams[i]) else result := nil; end; procedure TCriminalTycoon.Act( Frequency : integer ); begin end; procedure TCriminalTycoon.LoadFromBackup(Reader : IBackupReader); begin inherited; fCriminalName := Reader.ReadString('Name', ''); fTycoonName := Reader.ReadString('Tycoon', ''); Reader.ReadObject('Teams', fTeams, nil); Reader.ReadObject('History', fHistory, nil); end; procedure TCriminalTycoon.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('Name', fCriminalName); Writer.WriteString('Tycoon', fTycoonName); Writer.WriteObject('Teams', fTeams); Writer.WriteLooseObject('History', fHistory); end; // TMission constructor TMission.Create( aOwner : TTeam; aMetaMission : TMetaMission ); begin inherited Create; fOwner := aOwner; fMetaMission := aMetaMission; end; procedure TMission.StartMission; begin end; procedure TMission.ProceedWithMission; begin end; procedure TMission.EndMission; var i : integer; Criminal : TCriminal; begin for i := 0 to pred(fOwner.Criminals.Count) do begin Criminal := TCriminal(fOwner.Criminals[i]); case Criminal.Status of CRIMSTATUS_INMISSION : Criminal.setStatus( CRIMSTATUS_READY, fOwner ); //>> check when captured or dead and start trials etc... also add experience, charges, and history items end; end; //>> todo: change criminal status, apply charges, etc theIBSystem.DeleteSimulationObject( self, FREQ_HOUR ); end; procedure TMission.Abort; begin fAbort := true; end; procedure TMission.Escaped; begin fEscaped := true; end; procedure TMission.Act( Frequency : integer ); begin end; procedure TMission.LoadFromBackup(Reader : IBackupReader); var aux : string; begin inherited; aux := Reader.ReadString('MetaMission', ''); fMetaMission := TMetaMission(TheClassStorage.ClassById[tidMetaMissionFamily, aux]); Reader.ReadObject('Owner', fOwner, nil); fAbort := Reader.ReadBoolean('Aborted', false); fEscaped := Reader.ReadBoolean('Escaped', false); end; procedure TMission.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('MetaMission', fMetaMission.Id); Writer.WriteObject('Owner', fOwner); Writer.WriteBoolean('Aborted', fAbort); Writer.WriteBoolean('Escaped', fEscaped); end; // TTeam constructor TTeam.Create( aName : string; aOwner : TCriminalTycoon ); begin inherited Create; fName := aName; fOwner := aOwner; fCriminals := TLockableCollection.Create( 4, rkBelonguer ); fState := TEAMSTATE_UNLOCATED; fMission := nil; fHistory := TCollection.Create( 10, rkBelonguer ); end; destructor TTeam.Destroy; begin fCriminals.Free; fHistory.Free; inherited; end; function TTeam.AddCriminal( aCriminal : TCriminal ) : TErrorCode; begin try if fCriminals.Count < MAXTEAM_MEMBERS then begin fCriminals.Insert( aCriminal ); result := ERR_SUCCEDEED; //>> notify end else result := ERR_TOOMANYMEMBERS; except result := ERR_UNKNOWN; end; end; function TTeam.DeleteCriminal( aCriminal : TCriminal ) : TErrorCode; begin try fCriminals.Extract( aCriminal ); result := ERR_SUCCEDEED; except result := ERR_UNKNOWN; end; end; function TTeam.FindCriminal( aName : string ) : TCriminal; var i : integer; found : boolean; begin try fCriminals.Lock; try i := 0; found := false; while (i < fCriminals.Count) and not found do begin found := CompareText( TCriminal(fCriminals[i]).Name, aName ) = 0; if not found then inc( i ); end; if found then result := TCriminal(fCriminals[i]) else result := nil; finally fCriminals.Unlock; end; except result := nil; end; end; function TTeam.getCriminalById( CriminalId : integer ) : TCriminal; var i : integer; found : boolean; begin try fCriminals.Lock; try i := 0; found := false; while (i < fCriminals.Count) and not found do begin found := TCriminal(fCriminals[i]).Id = CriminalId; if not found then inc( i ); end; if found then result := TCriminal(fCriminals[i]) else result := nil; finally fCriminals.Unlock; end; except result := nil; end; end; function TTeam.AssignMission( aMission : TMission; MissionInfo : string ) : TErrorCode; var Props : TStringList; function CheckAndAssignRoles : boolean; var i : integer; CrimId : integer; Role : integer; Criminal : TCriminal; Error : boolean; begin try i := 0; Error := false; while (Props.IndexOfName('Role' + IntToStr(i)) <> -1) or Error do begin CrimId := StrToInt( Props.Values['Criminal' + IntToStr(i)]); Role := StrToInt( Props.Values['Role' + IntToStr(i)] ); Criminal := getCriminalById( CrimId ); if (Criminal <> nil) then Error := Criminal.setStatus( CRIMSTATUS_INMISSION, Role ) <> ERR_SUCCEDEED else Error := true; inc( i ); end; result := not Error; except result := false; end; end; begin try if fMission = nil then begin Props := TStringList.Create; try Props.Text := MissionInfo; if CheckAndAssignRoles then begin fMission := aMission; fMission.StartMission; fState := TEAMSTATE_INMISSION; result := ERR_SUCCEDEED; end else result := ERR_UNABLETOASSIGNROLES; finally Props.Free; end; end else result := ERR_TEAMINMISSION; except result := ERR_UNKNOWN; end; end; function TTeam.getCriminalForTask( role, skill : integer; assdRoleCount : integer; const assdRoles : TRoles ) : TCriminal; function FindAdequateCriminal : TCriminal; var i : integer; found : boolean; Crim : TCriminal; begin i := 0; found := false; Crim := nil; while (i < fCriminals.Count) and not found do begin Crim := TCriminal(fCriminals[i]); found := (Crim.Role = role) and (Crim.Status = CRIMSTATUS_INMISSION); if not found then inc( i ); end; if found then result := Crim else result := nil; end; function FindBestCriminalAvailable : TCriminal; function RoleNotAssigned( Criminal : TCriminal ): boolean; var i : integer; found : boolean; begin i := 0; found := false; while (i < assdRoleCount) and not found do begin found := assdRoles[i].role = Criminal.Role; inc( i ); end; result := not found; end; var i : integer; Crim : TCriminal; Crims : array[0..MAXTEAM_MEMBERS] of TCriminal; CrimCount : integer; maxskill : single; begin // build a list of idle criminals CrimCount := 0; for i := 0 to pred(fCriminals.Count) do begin Crim := TCriminal(fCriminals[i]); if (Crim.Status = CRIMSTATUS_INMISSION) and RoleNotAssigned( Crim ) then begin Crims[CrimCount] := Crim; inc( CrimCount ); end; end; // Find the one with better skills result := nil; maxskill := -100000; for i := 0 to pred(CrimCount) do if Crims[i].Skills.Skills[skill] > maxskill then begin maxskill := Crims[i].Skills.Skills[skill]; result := Crims[i]; end; end; begin try result := FindAdequateCriminal; if result = nil then result := FindBestCriminalAvailable; except result := nil; end; end; function TTeam.setHeadquarter( x, y : integer; aLocation : string ) : TErrorCode; procedure AssigHQ; begin fHQX := x; fHQY := y; fLocation := theIBSystem.getLocation( aLocation ); end; begin result := ERR_SUCCEDEED; case fState of TEAMSTATE_UNLOCATED : begin fState := TEAMSTATE_READY; AssigHQ; //>> notify event end; TEAMSTATE_READY : begin Moved; AssigHQ; end; TEAMSTATE_INMISSION : result := ERR_TEAMINMISSION; end; end; procedure TTeam.addHistoryItem( HistoryItem : THistoryItem ); begin fHistory.Insert( HistoryItem ); end; procedure TTeam.Act( Frequency : integer ); begin case fState of TEAMSTATE_INMISSION : fMission.ProceedWithMission; end; end; procedure TTeam.Moved; begin //>> todo: simulation of Acc risk and notification end; procedure TTeam.LoadFromBackup( Reader : IBackupReader ); begin inherited; fName := Reader.ReadString('Name', ''); Reader.ReadObject('Owner', fOwner, nil); Reader.ReadObject('Criminals', fCriminals, nil); fState := Reader.ReadInteger('State', TEAMSTATE_UNLOCATED); Reader.ReadObject('Mission', fMission, nil); fHQX := Reader.ReadInteger('HQX', 0); fHQY := Reader.ReadInteger('HQY', 0); Reader.ReadObject('Location', fLocation, nil); Reader.ReadObject('History', fHistory, nil); end; procedure TTeam.StoreToBackup ( Writer : IBackupWriter ); begin inherited; Writer.WriteString('Name', fName); Writer.WriteObjectRef('Owner', fOwner); Writer.WriteLooseObject('Criminals', fCriminals); Writer.WriteInteger('State', fState); Writer.WriteObject('Mission', fMission); Writer.WriteInteger('HQX', fHQX); Writer.WriteInteger('HQY', fHQY); Writer.WriteObjectRef('Location', fLocation); Writer.WriteLooseObject('History', fHistory); end; // TCriminal constructor TCriminal.Create( aName : string; anAge : integer; aSex : TCriminalSex; aLocation : string; aPictureId : string; anId : integer ); begin inherited Create; fName := aName; fId := anId; fAge := anAge; fSex := aSex; fSkills := TSkillCollection.Create; fPictureId := aPictureId; fStatus := CRIMSTATUS_ONTHEMARKET; fHistory := TCollection.Create( 10, rkBelonguer ); end; destructor TCriminal.Destroy; begin fSkills.Free; fHistory.Free; inherited; end; procedure TCriminal.addHistoryItem( Item : THistoryItem ); begin fHistory.Insert( Item ); end; function TCriminal.setStatus( anewStatus : integer; var info ) : TErrorCode; var aRole : integer absolute info; aTeam : TTeam absolute info; begin result := ERR_SUCCEDEED; case fStatus of CRIMSTATUS_ONTHEMARKET : case anewStatus of CRIMSTATUS_READY : begin fStatus := anewStatus; fTeam := aTeam; end; else result := ERR_INVALIDSTATUSCHANGE; end; CRIMSTATUS_READY : case anewStatus of CRIMSTATUS_INMISSION : begin fStatus := anewStatus; fRole := aRole; end; CRIMSTATUS_ONTHEMARKET : begin fStatus := anewStatus; fTeam := nil; end; else result := ERR_INVALIDSTATUSCHANGE; end; CRIMSTATUS_INMISSION : case anewStatus of CRIMSTATUS_READY : begin fStatus := anewStatus; end; CRIMSTATUS_ONTHEMARKET : begin fStatus := anewStatus; fTeam := nil; end; CRIMSTATUS_CAPTURED : begin fStatus := anewStatus; end; CRIMSTATUS_DEAD : begin fStatus := anewStatus; end; else result := ERR_INVALIDSTATUSCHANGE; end; end; end; function TCriminal.CheckStability( Skill : integer; PsiFactor : single ) : single; const STAB_BOUNDS : array[0..pred(SKILL_COUNT)] of single = ( 0.5, //SKILL_LEADERSHIP 0.2, //SKILL_DRIVING 0.05, //SKILL_BRAWLING 0.4, //SKILL_FIREARMS 0.7, //SKILL_STALKING 0.5, //SKILL_COMPUTER 0.2, //SKILL_DEMOLITION 0.5, //SKILL_STEALTH 0.8, //SKILL_MEDICINE 0.5 //SKILL_FORGERY ); const STABLEVEL_FRAGILE = 0; STABLEVEL_LUNATIC = 1; STABLEVEL_SOLID = 2; FRAGILE_BOUND = 0.5; LUNATIC_BOUND = 0.8; SOLID_BOUND = 1.0; function StabToLevel : integer; begin if fStability < FRAGILE_BOUND then result := STABLEVEL_FRAGILE else if fStability < LUNATIC_BOUND then result := STABLEVEL_LUNATIC else result := STABLEVEL_SOLID; end; function CalcFragileStability( aPsiFactor : single ) : single; begin result := (((fStability/FRAGILE_BOUND) - 7*PsiFactor - 1)*STAB_BOUNDS[Skill])/8; end; function CalcLunaticStability( aPsiFactor : single ) : single; var NoiseAmplitude : single; n : single; begin n := STAB_BOUNDS[Skill]; NoiseAmplitude := ((n/16 - n)*(fStability - FRAGILE_BOUND))/(LUNATIC_BOUND - FRAGILE_BOUND) + n; // NoiseAmplitude is the maximum possible noise for the PsiFactor NoiseAmplitude := NoiseAmplitude*PsiFactor; //apply PsiFactor percent (PsiFactor = 0 means no noise) result := NoiseAmplitude*(random*2 - 1); end; function CalcSolidStability( aPsiFactor : single ) : single; begin result := ln(fStability)/ln(10); end; begin case StabToLevel of STABLEVEL_FRAGILE : result := CalcFragileStability( PsiFactor ); STABLEVEL_LUNATIC : result := CalcLunaticStability( PsiFactor ); STABLEVEL_SOLID : result := CalcSolidStability( PsiFactor ); else result := 0; end; if result > STAB_BOUNDS[Skill] then result := STAB_BOUNDS[Skill] else if result < -STAB_BOUNDS[Skill] then result := -STAB_BOUNDS[Skill]; end; procedure TCriminal.Act( Frequency : integer ); begin end; function TCriminal.getLocation : TTownInfo; begin if fTeam <> nil then result := fTeam.Location else result := nil; end; procedure TCriminal.LoadFromBackup(Reader : IBackupReader); begin inherited; fName := Reader.ReadString('Name', ''); fAge := Reader.ReadInteger('Age', 25); fSex := TCriminalSex(Reader.ReadByte('Sex', byte(csMale))); Reader.ReadObject('Skills', fSkills, nil); fPictureId := Reader.ReadString('PicId', ''); Reader.ReadObject('Team', fTeam, nil); fId := Reader.ReadInteger('Id', 0); fRole := Reader.ReadInteger('Role', 0); // status fStatus := Reader.ReadInteger('Status', 0); fStability := Reader.ReadSingle('Stability', 0); // History Reader.ReadObject('History', fHistory, nil); end; procedure TCriminal.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('Name', fName); Writer.WriteInteger('Age', fAge); Writer.WriteByte('Sex', byte(fSex)); Writer.WriteLooseObject('Skills', fSkills); Writer.WriteString('PicId', fPictureId); Writer.WriteObjectRef('Team', fTeam); Writer.WriteInteger('Id', fId); Writer.WriteInteger('Role', fRole); // status Writer.WriteInteger('Status', fStatus); Writer.WriteSingle('Stability', fStability); // History Writer.WriteLooseObject('History', fHistory); end; // TSkillCollection constructor TSkillCollection.Create; begin inherited; fSkillCount := SKILL_COUNT; end; procedure TSkillCollection.LoadFromBackup(Reader : IBackupReader); var i : integer; begin inherited; fSkillCount := Reader.ReadInteger('Count', SKILL_COUNT); for i := 0 to pred(fSkillCount) do fSkills[i] := Reader.ReadSingle('', 0); end; procedure TSkillCollection.StoreToBackup(Writer : IBackupWriter); var i : integer; begin inherited; Writer.WriteInteger('Count', fSkillCount); for i := 0 to pred(fSkillCount) do Writer.WriteSingle(IntToStr(i), fSkills[i]); end; // TTraining constructor TTraining.Create( aMetaTraining : TMetaTraining; aTrainee : TObject ); begin inherited Create; fState := TRAININGSTATE_TRAINING; fMetaTraining := aMetaTraining; fPercent := 0; fTimeElapsed := 0; fTrainee := aTrainee; fFrequency := fMetaTraining.Frequency; end; procedure TTraining.Act( Frequency : integer ); begin case fState of TRAININGSTATE_TRAINING : begin inc( fTimeElapsed ); fPercent := trunc((fTimeElapsed/fMetaTraining.Duration)*100); if fPercent >= 100 then begin fMetaTraining.TrainingComplete( fPercent, fTrainee ); end; end; TRAININGSTATE_PAUSED : begin end; end; end; procedure TTraining.Abort; begin Finished; end; procedure TTraining.Pause; begin fState := TRAININGSTATE_PAUSED; end; procedure TTraining.Resume; begin fState := TRAININGSTATE_TRAINING; end; procedure TTraining.Finished; begin fMetaTraining.TrainingComplete( fPercent, fTrainee ); theIBSystem.DeleteSimulationObject( self, fFrequency ); end; procedure TTraining.LoadFromBackup(Reader : IBackupReader); var aux : string; begin inherited; aux := Reader.ReadString('Meta', ''); fMetaTraining := TMetaTraining(TheClassStorage.ClassById[tidMetaTrainingFamily, aux]); fState := Reader.ReadInteger('State', 0); Reader.ReadObject('Trainee', fTrainee, nil); fPercent := Reader.ReadInteger('Perc', 0); fTimeElapsed := Reader.ReadInteger('TimeElapsed', 0); fFrequency := Reader.ReadInteger('Frequency', 0); end; procedure TTraining.StoreToBackup(Writer : IBackupWriter); begin inherited; Writer.WriteString('Meta', fMetaTraining.Id); Writer.WriteInteger('State', fState); Writer.WriteObjectRef('Trainee', fTrainee); Writer.WriteInteger('Perc', fPercent); Writer.WriteInteger('TimeElapsed', fTimeElapsed); Writer.WriteInteger('Frequency', fFrequency); end; end.
{$I ok_sklad.inc} unit MetaBusinessPartner; interface uses MetaClass, MetaAddress, XMLDoc, XMLIntf, Classes; type MetaBPTypes = (MetaBPTypeCompany = 0, MetaBPTypePerson = 1, MetaBPTypeEmployee = 2, MetaBPTypeOwned = 3); MetaBPKinds = (MetaBPKindSupplier = 0, MetaBPKindClient = 1, MetaBPKindBarter = 3); MetaPersonPosTypes = (MetaPersonPosTypeChief = 0, MetaPersonPosTypeAccountant = 1, MetaPersonPosTypeOther = 2); TMetaBusinessPartner = class; TMetaPerson = class(TMetaClass) protected FSurname, FLastName: String; // FName is in TMetaClass FPhones: TStringList; FBirthday: TDateTime; FPosType: MetaPersonPosTypes; FCompanyID, FAddressID: Integer; // it's in DB // these are loaded on demand FCompany: TMetaBusinessPartner; FAddress: TMetaAddress; public constructor Create(const AParent: TMetaClass); destructor Destroy; override; procedure Clear; function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; property AddressID: Integer read FAddressID write FAddressID; property CompanyID: Integer read FCompanyID write FCompanyID; property Birthday: TDateTime read FBirthday write FBirthday; property Lastname: String read FLastname write FLastname; property Phones: TStringList read FPhones; property PosType: MetaPersonPosTypes read FPosType write FPosType; property Surname: String read FSurname write FSurname; end; //-------------------------------------------------------------- TMetaPersonList = class(TMetaClassList) protected // property processing function getItem(const idx: Integer): TMetaPerson; procedure setItem(const idx: Integer; const Value: TMetaPerson); public constructor Create(const AParent: TMetaClass); destructor Destroy; override; function Add(const Value: TMetaPerson): Integer; property Items[const idx: Integer]: TMetaPerson read getItem write setItem; default; end; // TMetaPersonList //---------------------------------------------------------------- //---------------------------------------------------------------- //---------------------------------------------------------------- TMetaBusinessPartner = class(TMetaClass) protected FType: Integer; // 0-Юридические лица, 1-Физические лица, 2-Служащие, 3-Наши предприятия FKind: Integer; // 0-Поставщик, 1-клиент, 2-микс FINN, FOKPO, FKPP, FCertNum: String; FPhones, FEMail, FWWW, FFax: String; FNotes: String; FPriceCategoryID: Integer; FVATPayer: Boolean; // personID data for physical person FPersonIDNum, FPersonIDSeries, FPersonIDName, FPersonIDIssuer: String; FPersonIDDate: TDateTime; FBirthDate: TDateTime; FPositionType: Integer; // 0-chief, 1-Partner, 2-Other (FPosition) FPosition: String; FUserID: Integer; // ID польз для сотрудника FFullName: String; FAddress, FjurAddress: TMetaAddress; FContactPerson: TMetaPersonList; FStartSaldo: Double; FStartSaldoDate: TDateTime; function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; procedure setType(const Value: Integer); procedure setKind(const Value: Integer); procedure setINN(const Value: String); procedure setOKPO(const Value: String); procedure setKPP(const Value: String); procedure setCertNum(const Value: String); procedure setPhones(const Value: String); procedure setEMail(const Value: String); procedure setWWW(const Value: String); procedure setFax(const Value: String); procedure setNotes(const Value: String); procedure setPriceCategoryID(const Value: Integer); procedure setVATPayer(const Value: Boolean); procedure setPersonIDNum(const Value: String); procedure setPersonIDSeries(const Value: String); procedure setPersonIDName(const Value: String); procedure setPersonIDIssuer(const Value: String); procedure setPersonIDDate(const Value: TDateTime); procedure setBirthDate(const Value: TDateTime); procedure setPositionType(const Value: Integer); procedure setPosition(const Value: String); procedure setUserID(const Value: Integer); procedure setFullName(const Value: String); procedure setStartSaldo(const Value: Double); procedure setStartSaldoDate(const Value: TDateTime); public constructor Create(const AParent: TMetaClass); destructor Destroy; override; procedure Clear; procedure loadXMLcallback(const topNode, cbNode: IXMLNode); // !!!!!!!! INCOMPLETE !!!!!!!! function loadData(const AID: Integer): Boolean; function saveData: boolean; property bpType: Integer read FType write setType; property Kind: Integer read FKind write setKind; property INN: String read FINN write setINN; property OKPO: String read FOKPO write setOKPO; property KPP: String read FKPP write setKPP; property CertNum: String read FCertNum write setCertNum; property Phones: String read FPhones write setPhones; property EMail: String read FEMail write setEMail; property WWW: String read FWWW write setWWW; property Fax: String read FFax write setFax; property Notes: String read FNotes write setNotes; property PriceCategoryID: Integer read FPriceCategoryID write setPriceCategoryID; property VATPayer: Boolean read FVATPayer write setVATPayer; property PersonIDNum: String read FPersonIDNum write setPersonIDNum; property PersonIDSeries: String read FPersonIDSeries write setPersonIDSeries; property PersonIDName: String read FPersonIDName write setPersonIDName; property PersonIDIssuer: String read FPersonIDIssuer write setPersonIDIssuer; property PersonIDDate: TDateTime read FPersonIDDate write setPersonIDDate; property BirthDate: TDateTime read FBirthDate write setBirthDate; property PositionType: Integer read FPositionType write setPositionType; property Position: String read FPosition write setPosition; property UserID: Integer read FUserID write setUserID; property FullName: String read FFullName write setFullName; // for companies property SurName: String read FFullName write setFullName; // for persons property FirstName: String read FName write setName; // for persons property Address: TMetaAddress read FAddress; property jurAddress: TMetaAddress read FjurAddress; property ContactPerson: TMetaPersonList read FContactPerson; property StartSaldo: Double read FStartSaldo write setStartSaldo; property StartSaldoDate: TDateTime read FStartSaldoDate write setStartSaldoDate; end; //-------------------------------------------------------------- TMetaBusinessPartnerList = class(TMetaClassList) protected // property processing function getItem(const idx: Integer): TMetaBusinessPartner; procedure setItem(const idx: Integer; const Value: TMetaBusinessPartner); public constructor Create(const AParent: TMetaClass); destructor Destroy; override; function Add(const Value: TMetaBusinessPartner): Integer; property Items[const idx: Integer]: TMetaBusinessPartner read getItem write setItem; default; end; // TMetaBusinessPartnerList //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== implementation uses DB, Dialogs, sysUtils, ClientData, prFun, prConst, ssCallbackConst, udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; //============================================================================================== constructor TMetaPersonList.Create(const AParent: TMetaClass); begin inherited; end; //============================================================================================== destructor TMetaPersonList.Destroy; begin inherited; end; //============================================================================================== function TMetaPersonList.Add(const Value: TMetaPerson): Integer; begin Result := FItems.Add(Value); setModified(True); end; //============================================================================================== function TMetaPersonList.getItem(const idx: Integer): TMetaPerson; begin Result := TMetaPerson(FItems[idx]); end; //============================================================================================== procedure TMetaPersonList.setItem(const idx: Integer; const Value: TMetaPerson); begin FItems[idx] := Value; setModified(True); end; //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== constructor TMetaPerson.Create(const AParent: TMetaClass); begin inherited; FPhones := TStringList.Create; FCompany := nil; FAddress := nil; Clear; end; //============================================================================================== procedure TMetaPerson.Clear; begin inherited; FSurname := ''; FLastName := ''; FPhones.Clear; FCompanyID := -1; FAddressID := -1; if FCompany <> nil then FCompany.Destroy; if FAddress <> nil then FAddress.Destroy; end; //============================================================================================== destructor TMetaPerson.Destroy; begin FPhones.Free; Clear; inherited; end; //============================================================================================== function TMetaPerson.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; var name, data: string; datefmt: TFormatSettings; begin Result := True; name := AnsiLowerCase(Node.NodeName); data := trim(Node.Text); //GetLocaleFormatSettings(..., datefmt); datefmt.DateSeparator := '-'; datefmt.TimeSeparator := ':'; datefmt.ShortDateFormat := 'yyyy-mm-dd'; try if name = 'birthday' then begin Birthday := strToDateTime(data, datefmt); Exit; end; except Ferror := ap_err_XML_badDate; Exit; end; try if name = 'companyid' then begin FCompanyID := StrToint(data); Exit; end else if name = 'addressid' then begin FAddressID := StrToint(data); Exit end; except Ferror := ap_err_XML_badData; Exit; end; if name = 'surname' then begin FSurname := data; end else if name = 'lastname' then begin FLastName := data; end else if name = 'phones' then begin FPhones.Text := data; end else if name = 'postype' then begin // MetaPersonPosTypeChief = 0, MetaPersonPosTypeAccountant = 1, MetaPersonPosTypeOther = 2 if data = 'chief' then FPosType := MetaPersonPosTypeChief else if data = 'accountant' then FPosType := MetaPersonPosTypeAccountant else if (data = 'other') or (data = 'employee') then FPosType := MetaPersonPosTypeOther; end else if name = 'address' then begin if FAddress = nil then FAddress.Create(Self); FAddress.loadXML(Node); end else Result := inherited loadXMLNode(Node, Node); end; //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== constructor TMetaBusinessPartnerList.Create(const AParent: TMetaClass); begin inherited; end; //============================================================================================== destructor TMetaBusinessPartnerList.Destroy; begin inherited; end; //============================================================================================== function TMetaBusinessPartnerList.getItem(const idx: Integer): TMetaBusinessPartner; begin Result := TMetaBusinessPartner(FItems[idx]); end; //============================================================================================== procedure TMetaBusinessPartnerList.setItem(const idx: Integer; const Value: TMetaBusinessPartner); begin FItems[idx] := Value; end; //============================================================================================== function TMetaBusinessPartnerList.Add(const Value: TMetaBusinessPartner): Integer; begin Result := FItems.Add(Value); setModified(True); end; //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== constructor TMetaBusinessPartner.Create(const AParent: TMetaClass); begin inherited; FAddress := TMetaAddress.Create(Self); FjurAddress := TMetaAddress.Create(Self); FContactPerson := TMetaPersonList.Create(Self); Clear; end; //============================================================================================== procedure TMetaBusinessPartner.Clear; begin inherited; FType := -1; FKind := -1; FINN := ''; FOKPO := ''; FKPP := ''; FCertNum := ''; FPhones := ''; FEMail := ''; FWWW := ''; FFax := ''; FNotes := ''; FPriceCategoryID := -1; FVATPayer := False; FPersonIDNum := ''; FPersonIDSeries := ''; FPersonIDName := ''; FPersonIDIssuer := ''; FPersonIDDate := 0.0; FBirthDate := 0.0; FPositionType := -1; FPosition := ''; FUserID := -1; FFullName := ''; FPersonIDDate := 0.0; FAddress.Clear; FjurAddress.Clear; FContactPerson.Clear; FStartSaldo := 0.0; FStartSaldoDate := 0.0; end; //============================================================================================== destructor TMetaBusinessPartner.Destroy; begin FAddress.Destroy; FjurAddress.Destroy; FContactPerson.Destroy; inherited; end; //============================================================================================== procedure TMetaBusinessPartner.setType(const Value: Integer); begin if FType = Value then Exit; FType := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setKind(const Value: Integer); begin if FKind = Value then Exit; FKind := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setINN(const Value: String); begin if FINN = Value then Exit; FINN := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setOKPO(const Value: String); begin if FOKPO = Value then Exit; FOKPO := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setKPP(const Value: String); begin if FKPP = Value then Exit; FKPP := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setCertNum(const Value: String); begin if FCertNum = Value then Exit; FCertNum := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPhones(const Value: String); begin if FPhones = Value then Exit; FPhones := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setEMail(const Value: String); begin if FEMail = Value then Exit; FEMail := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setWWW(const Value: String); begin if FWWW = Value then Exit; FWWW := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setFax(const Value: String); begin if FFax = Value then Exit; FFax := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setNotes(const Value: String); begin if FNotes = Value then Exit; FNotes := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPriceCategoryID(const Value: Integer); begin if FPriceCategoryID = Value then Exit; FPriceCategoryID := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setVATPayer(const Value: Boolean); begin if FVATPayer = Value then Exit; FVATPayer := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPersonIDNum(const Value: String); begin if FPersonIDNum = Value then Exit; FPersonIDNum := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPersonIDSeries(const Value: String); begin if FPersonIDSeries = Value then Exit; FPersonIDSeries := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPersonIDName(const Value: String); begin if FPersonIDName = Value then Exit; FPersonIDName := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPersonIDIssuer(const Value: String); begin if FPersonIDIssuer = Value then Exit; FPersonIDIssuer := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPersonIDDate(const Value: TDateTime); begin if FPersonIDDate = Value then Exit; FPersonIDDate := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setBirthDate(const Value: TDateTime); begin if FBirthDate = Value then Exit; FBirthDate := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPositionType(const Value: Integer); begin if FPositionType = Value then Exit; FPositionType := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setPosition(const Value: String); begin if FPosition = Value then Exit; FPosition := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setUserID(const Value: Integer); begin if FUserID = Value then Exit; FUserID := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setFullName(const Value: String); begin if FFullName = Value then Exit; FFullName := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setStartSaldo(const Value: Double); begin if FStartSaldo = Value then Exit; FStartSaldo := Value; setModified(True); end; //============================================================================================== procedure TMetaBusinessPartner.setStartSaldoDate(const Value: TDateTime); begin if FStartSaldoDate = Value then Exit; FStartSaldoDate := Value; setModified(True); end; //============================================================================================== function TMetaBusinessPartner.loadData(const AID: Integer): Boolean; begin Result := True; // !!!!!!!! INCOMPLETE !!!!!!!! with newDataSet do try try ProviderName := 'pKAgent_Get'; FetchParams; Params.ParamByName('KAID').AsInteger := AID; Open; if not IsEmpty then begin Self.Name := Fieldbyname('Name').asstring; bpType := fieldbyname('ktype').AsInteger; Kind := fieldbyname('kakind').AsInteger; if fieldbyname('birthdate').AsDateTime <> 0.0 then BirthDate := fieldbyname('birthdate').AsDateTime; FullName := fieldbyname('FullName').AsString; INN := fieldbyname('INN').AsString; OKPO := fieldbyname('OKPO').AsString; KPP := fieldbyname('kpp').AsString; CertNum := fieldbyname('CertNum').AsString; Phones := fieldbyname('Phone').AsString; Email := fieldbyname('Email').AsString; WWW := fieldbyname('WWW').AsString; Fax := fieldbyname('Fax').AsString; Notes := fieldbyname('Notes').AsString; VATPayer := (fieldbyname('ndspayer').AsInteger = 1); Position := FieldByName('job').AsString; if FieldByName('jobtype').IsNull then PositionType := 0 else PositionType := FieldByName('jobtype').AsInteger; if not FieldByName('ptypeid').IsNull then PriceCategoryID := FieldByName('ptypeid').AsInteger; if not FieldByName('startsaldo').IsNull then begin StartSaldoDate := FieldByName('startsaldodate').AsDateTime; StartSaldo := FieldByName('startsaldo').AsCurrency; end; if not FieldByName('userid').IsNull then UserID := FieldByName('userid').AsInteger; ID := AID; FNew := False; isModified := False; end; //if not IsEmpty Close; except Result := False; end; finally Free; end; // !!!!!!!! INCOMPLETE !!!!!!!! end; //============================================================================================== function TMetaBusinessPartner.saveData: Boolean; var NewRecord, FSetDef: Boolean; FLegalAddrID, FRealAddrID: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TMetaBusinessPartner.SaveData') else _udebug := nil;{$ENDIF} Result := False; clearError; if not isNew and not isModified then begin Exit; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; with newDataSet do try TrStart; try NewRecord := (ID <= 0); if NewRecord then FID := GetMaxID(dmData.SConnection, 'kagent', 'kaid'); FSetDef := False; if NewRecord and (FType = bpTypeOurCompany) then begin ProviderName := 'pKAgent_GetFirmsCount'; Open; FSetDef := Fields[0].AsInteger = 0; Close; end; if (FType = bpTypeEmployee) and (FUserID <> -1) then begin ProviderName := 'pKAgent_UpdUser'; FetchParams; Params.ParamByName('userid').AsInteger := FUserID; Execute; end; if NewRecord then ProviderName := 'pKAgent_Ins' else ProviderName := 'pKAgent_Upd'; FetchParams; Params.ParamByName('KAID').AsInteger := ID; Params.ParamByName('ktype').AsInteger := FType; Params.ParamByName('kakind').AsInteger := FKind; Params.ParamByName('Name').AsString := FName; if FBirthDate > 0.0 then Params.ParamByName('birthdate').AsDateTime := FBirthDate else begin Params.ParamByName('birthdate').DataType := ftDateTime; Params.ParamByName('birthdate').Clear; end; Params.ParamByName('FullName').AsString := FFullName; Params.ParamByName('INN').AsString := FINN; Params.ParamByName('OKPO').AsString := FOKPO; Params.ParamByName('kpp').AsString := FKPP; Params.ParamByName('CertNum').AsString := FCertNum; Params.ParamByName('Phone').AsString := Trim(FPhones); Params.ParamByName('EMail').AsString := Trim(FEMail); Params.ParamByName('WWW').AsString := Trim(FWWW); Params.ParamByName('Fax').AsString := Trim(FFax); Params.ParamByName('Address').AsString := Trim(FAddress.Street); Params.ParamByName('Country').AsString := Trim(FAddress.Country.Name); Params.ParamByName('District').AsString := Trim(FAddress.District); Params.ParamByName('City').AsString := Trim(FAddress.City); Params.ParamByName('PostIndex').AsString := Trim(Faddress.PostCode); Params.ParamByName('Notes').AsString := Trim(FNotes); if FUserID = -1 then begin Params.ParamByName('userid').DataType := ftInteger; Params.ParamByName('userid').Clear; end else Params.ParamByName('userid').AsInteger := FUserID; Params.ParamByName('deleted').AsInteger := 0; Params.ParamByName('ndspayer').AsInteger := BoolToInt(FVATPayer); if FPriceCategoryID = -1 then begin Params.ParamByName('ptypeid').DataType := ftInteger; Params.ParamByName('ptypeid').Clear; end else Params.ParamByName('ptypeid').AsInteger := FPriceCategoryID; Params.ParamByName('job').DataType := ftString; Params.ParamByName('job').Clear; Params.ParamByName('jobtype').DataType := ftInteger; Params.ParamByName('jobtype').Clear; if FType = bpTypeEmployee then begin if FPositionType = bpPosTypeOther then Params.ParamByName('job').AsString := FPosition else Params.ParamByName('jobtype').AsInteger := FPositionType; end; Execute; FLegalAddrID := 0; FRealAddrID := 0; if not NewRecord then begin ProviderName := 'pKAAddr_Get'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Open; if Locate('addrtype', 0, []) then FLegalAddrID := FieldByName('addrid').AsInteger; if Locate('addrtype', 1, []) then FRealAddrID := FieldByName('addrid').AsInteger; Close; end; if FLegalAddrID = 0 then begin ProviderName := 'pKAAddr_Ins'; FLegalAddrID := GetMaxID(dmData.SConnection, 'kaaddr', 'addrid'); end else ProviderName := 'pKAAddr_Upd'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Params.ParamByName('addrid').AsInteger := FLegalAddrID; Params.ParamByName('addrtype').AsInteger := 0; Params.ParamByName('Address').AsString := Trim(FjurAddress.Street); Params.ParamByName('Country').AsString := Trim(FjurAddress.Country.Name); Params.ParamByName('District').AsString := Trim(FjurAddress.District); Params.ParamByName('City').AsString := Trim(FjurAddress.City); Params.ParamByName('PostIndex').AsString := Trim(FjurAddress.PostCode); Execute; if FRealAddrID = 0 then begin ProviderName := 'pKAAddr_Ins'; FRealAddrID := GetMaxID(dmData.SConnection, 'kaaddr', 'addrid'); end else ProviderName := 'pKAAddr_Upd'; Params.ParamByName('addrid').AsInteger := FRealAddrID; Params.ParamByName('addrtype').AsInteger := 1; Params.ParamByName('Address').AsString := Trim(FAddress.Street); Params.ParamByName('Country').AsString := Trim(FAddress.Country.Name); Params.ParamByName('District').AsString := Trim(FAddress.District); Params.ParamByName('City').AsString := Trim(FAddress.City); Params.ParamByName('PostIndex').AsString := Trim(FAddress.PostCode); Execute; ProviderName := 'pKA_StartSaldoUpd'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; if FStartSaldo <> 0.0 then begin Params.ParamByName('startsaldo').AsCurrency := FStartSaldo; Params.ParamByName('startsaldodate').AsDateTime := FStartSaldoDate; end else begin Params.ParamByName('startsaldo').DataType := ftCurrency; Params.ParamByName('startsaldo').Clear; Params.ParamByName('startsaldodate').DataType := ftDateTime; Params.ParamByName('startsaldodate').Clear; end; Execute; // Person ID data for Physical person type if not NewRecord then begin ProviderName := 'pAgentDoc_Del'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Execute; end; if FType in [bpTypePerson, bpTypeEmployee] then begin ProviderName := 'pAgentDoc_Ins'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Params.ParamByName('docnum').AsString := FPersonIDNum; Params.ParamByName('docseries').AsString := FPersonIDSeries; Params.ParamByName('docname').AsString := FPersonIDName; Params.ParamByName('docwhoproduce').AsString := FPersonIDIssuer; if FPersonIDDate > 0.0 then Params.ParamByName('docdate').AsDateTime := FPersonIDDate else begin Params.ParamByName('docdate').DataType := ftDateTime; Params.ParamByName('docdate').Clear; end; Execute; end; (* if PersonsModified and DelAgentPersons(FID) // Запись всех AgentPersons then AddPersons(FID); if AccountModified then begin mdAccount.Filtered := False; mdAccount.First; while not mdAccount.Eof do begin if mdAccount.FieldByName('deleted').AsInteger = 1 then begin ProviderName := 'pAgentAccount_DelByID'; FetchParams; Params.ParamByName('accid').AsInteger := mdAccount.FieldByName('accid').AsInteger; Execute; end else begin if mdAccount.FieldByName('accid').AsInteger < 0 then ProviderName := 'pAgentAccount_Ins' else ProviderName := 'pAgentAccount_Upd'; FetchParams; if mdAccount.FieldByName('accid').AsInteger < 0 then Params.ParamByName('accid').AsInteger := GetMaxID(dmData.SConnection, 'agentaccount', 'accid') else Params.ParamByName('accid').AsInteger := mdAccount.FieldByName('accid').AsInteger; Params.ParamByName('kaid').AsInteger := FID; Params.ParamByName('bankid').AsInteger := mdAccount.FieldByName('bankid').AsInteger; Params.ParamByName('typeid').AsInteger := mdAccount.FieldByName('typeid').AsInteger; Params.ParamByName('accnum').AsString := mdAccount.FieldByName('accnum').AsString; Params.ParamByName('def').AsInteger := mdAccount.FieldByName('def').AsInteger; Execute; end; mdAccount.Next; end; end; if not NewRecord then begin ProviderName := 'pKADiscount_Del'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Execute; ProviderName := 'pKAMatDiscount_Del'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Execute; ProviderName := 'pKAMatGroupDiscount_Del'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Execute; end; if chbUseDiscount.Checked then begin ProviderName := 'pKADiscount_Ins'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Params.ParamByName('discforall').AsInteger := Integer(chbDiscAll.Checked); Params.ParamByName('disccustom').AsInteger := Integer(chbDiscCustom.Checked); Params.ParamByName('onvalue').AsFloat := edDiscAll.Value; Execute; mdDisc.First; while not mdDisc.Eof do begin if mdDisc.FieldByName('mtype').AsInteger = 0 then ProviderName := 'pKAMatDiscount_Ins' else ProviderName := 'pKAMatGroupDiscount_Ins'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; if mdDisc.FieldByName('mtype').AsInteger = 0 then Params.ParamByName('matid').AsInteger := mdDisc.FieldByName('id').AsInteger else Params.ParamByName('grpid').AsInteger := -mdDisc.FieldByName('id').AsInteger; Params.ParamByName('onvalue').AsFloat := mdDisc.FieldByName('onvalue').AsFloat; Execute; mdDisc.Next; end; end; if NewRecord and (FType = bpTypeOurCompany) and FSetDef then begin ProviderName := 'pKAgent_SetDef'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Params.ParamByName('def').AsInteger := 1; Execute; CurrEnt.KAID := FID; end; if FType = bpTypeOurCompany then begin ProviderName := 'pSQL'; FetchMacros; Params.Clear; Macros.ParamByName('sql').AsString := 'select * from rdb$generators where rdb$generator_name=''' + 'GEN_ENT_WBOUT' + IntToStr(FID) + ''''; Open; if IsEmpty then begin Close; Macros.ParamByName('sql').AsString := 'create generator gen_ent_wbout' + IntToStr(FID); Execute; end else Close; Macros.ParamByName('sql').AsString := 'select * from rdb$generators where rdb$generator_name=''' + 'GEN_ENT_ACCOUT' + IntToStr(FID) + ''''; Open; if IsEmpty then begin Close; Macros.ParamByName('sql').AsString := 'create generator gen_ent_accout' + IntToStr(FID); Execute; end else Close; Macros.ParamByName('sql').AsString := 'select * from rdb$generators where rdb$generator_name=''' + 'GEN_ENT_INV' + IntToStr(FID) + ''''; Open; if IsEmpty then begin Close; Macros.ParamByName('sql').AsString := 'create generator gen_ent_inv' + IntToStr(FID); Execute; end else Close; Macros.ParamByName('sql').AsString := 'select * from rdb$generators where rdb$generator_name=''' + 'GEN_ENT_ORDOUT' + IntToStr(FID) + ''''; Open; if IsEmpty then begin Close; Macros.ParamByName('sql').AsString := 'create generator gen_ent_ordout' + IntToStr(FID); Execute; end else Close; Macros.ParamByName('sql').AsString := 'set generator gen_ent_wbout' + IntToStr(FID) + ' to ' + IntToStr(edWBOutCurrNum.Value); Execute; Macros.ParamByName('sql').AsString := 'set generator gen_ent_accout' + IntToStr(FID) + ' to ' + IntToStr(edAOCurrNum.Value); Execute; Macros.ParamByName('sql').AsString := 'set generator gen_ent_inv' + IntToStr(FID) + ' to ' + IntToStr(edInvCurrNum.Value); Execute; Macros.ParamByName('sql').AsString := 'set generator gen_ent_ordout' + IntToStr(FID) + ' to ' + IntToStr(edOrdCurrNum.Value); Execute; if not NewRecord then begin ProviderName := 'pEntExParams_Del'; Macros.Clear; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Execute; end; ProviderName := 'pEntExParams_Ins'; FetchParams; Params.ParamByName('kaid').AsInteger := FID; Params.ParamByName('wtype').AsInteger := -1; Params.ParamByName('autonum').AsInteger := Integer(chbWBOutAutoNum.Checked); Params.ParamByName('preffix').AsString := edWBOutPrefix.Text; Params.ParamByName('suffix').AsString := edWBOutSuffix.Text; Params.ParamByName('gen').AsString := 'gen_ent_wbout' + IntToStr(FID); Execute; Params.ParamByName('wtype').AsInteger := 2; Params.ParamByName('autonum').AsInteger := Integer(chbAOAutoNum.Checked); Params.ParamByName('preffix').AsString := edAOPrefix.Text; Params.ParamByName('suffix').AsString := edAOSuffix.Text; Params.ParamByName('gen').AsString := 'gen_ent_accout' + IntToStr(FID); Execute; Params.ParamByName('wtype').AsInteger := -9; Params.ParamByName('autonum').AsInteger := Integer(chbInvAutoNum.Checked); Params.ParamByName('preffix').AsString := edInvPrefix.Text; Params.ParamByName('suffix').AsString := edInvSuffix.Text; Params.ParamByName('gen').AsString := 'gen_ent_inv' + IntToStr(FID); Execute; Params.ParamByName('wtype').AsInteger := -16; Params.ParamByName('autonum').AsInteger := Integer(chbOrdAutoNum.Checked); Params.ParamByName('preffix').AsString := edOrdPrefix.Text; Params.ParamByName('suffix').AsString := edOrdSuffix.Text; Params.ParamByName('gen').AsString := 'gen_ent_ordout' + IntToStr(FID); Execute; end; *) TrCommit; { if not NewRecord and (FType = bpTypeOurCompany) and FDef then begin CurrEnt.KAID := FID; end; if FType = bpTypeEmployee then begin if FPositionType = bp then begin EntDir := edFIO.Text; EntDirID := FID; end else if rbtBuh.Checked then begin EntBuh := edFIO.Text; EntBuhID := FID; end; end; } if FStartSaldo > 0.0 then DoRecalcKASaldo(dmData.SConnection, FID, FStartSaldoDate, rs('fmKAgent', 'RecalcBallance'), False); if RefreshAllClients then dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_KAGENTS); finally Free; end; except on e:exception do begin TrRollback; MessageDlg(e.Message, mtError, [mbOk], 0); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; end; // with newdataset try isModified := False; FNew := False; Result := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TMetaBusinessPartner.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; var name, data: String; datefmt: TFormatSettings; begin Result := True; Ferror := 0; //GetLocaleFormatSettings(..., datefmt); datefmt.DateSeparator := '-'; datefmt.TimeSeparator := ':'; datefmt.ShortDateFormat := 'yyyy-mm-dd'; name := AnsiLowerCase(Node.NodeName); data := trim(Node.Text); if name = 'address' then begin if FAddress = nil then FAddress := TMetaAddress.Create(Self); FAddress.loadXML(Node); Exit; end else if name = 'registrationaddress' then begin if FjurAddress = nil then FjurAddress := TMetaAddress.Create(Self); FjurAddress.loadXML(Node); Exit; end else if name = 'contactpersons' then begin if FContactPerson = nil then FContactPerson := TMetaPersonList.Create(Self); FContactPerson.loadXML(Node); Exit; end; //......................................................... try if name = 'personiddate' then begin FPersonIDDate := strToDateTime(data, datefmt); Exit; end else if name = 'birthdate' then begin FBirthDate := strToDateTime(data, datefmt); Exit; end else if name = 'startsaldodate' then begin FStartSaldoDate := strToDateTime(data, datefmt); Exit; end; except Ferror := ap_err_XML_badDate; Exit; end; //.................................................. try if name = 'type' then begin // 0-Юридические лица, 1-Физические лица, 2-Служащие, 3-Наши предприятия FType := StrToInt(data); Exit; end else if name = 'kind' then begin // 0-Поставщик, 1-клиент, 2-микс FKind := StrToInt(data); Exit; end else if name = 'pricecategoryid' then begin FPriceCategoryID := StrToInt(data); Exit; end else if name = 'positiontype' then begin // 0-chief, 1-Partner, 2-Other (FPosition) FPositionType := StrToInt(data); Exit; end else if name = 'userid' then begin // ID польз для сотрудника FUserID := StrToInt(data); Exit; end else if name = 'startsaldo' then begin FStartSaldo := StrToFloat(data); Exit; end; except Ferror := ap_err_XML_badData; Exit; end; //.................................................. if name = 'vatpayer' then begin FVATPayer := strToBool(data); Exit; end else if name = 'inn' then begin FINN := data; Exit; end else if name = 'okpo' then begin FOKPO := data; Exit; end else if name = 'kpp' then begin FKPP := data; Exit; end else if name = 'certnum' then begin FCertNum := data; Exit; end else if name = 'phones' then begin FPhones := data; Exit; end else if name = 'email' then begin FEMail := data; Exit; end else if name = 'www' then begin FWWW := data; Exit; end else if name = 'fax' then begin FFax := data; Exit; end else if name = 'notes' then begin FNotes := data; Exit; end else if name = 'personidnum' then begin FPersonIDNum := data; Exit; end else if name = 'personidseries' then begin FPersonIDSeries := data; Exit; end else if name = 'personidname' then begin FPersonIDName := data; Exit; end else if name = 'personidissuer' then begin FPersonIDIssuer := data; Exit; end else if name = 'position' then begin FPosition := data; Exit; end else if name = 'fullname' then begin FFullName := data; Exit; end; Result := inherited loadXMLNode(topNode, Node); end; //============================================================================================== procedure TMetaBusinessPartner.loadXMLcallback(const topNode, cbNode: IXMLNode); begin if AnsiLowerCase(topNode.NodeName) = 'address' then begin if AnsiLowerCase(cbNode.NodeName) = 'phone' then begin Phones := Phones + ' ' + trim(cbNode.Text); end //.................................................. else if AnsiLowerCase(cbNode.NodeName) = 'fax' then begin Fax := trim(cbNode.Text); end; end; // <Address> processing end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('MetaBusinessPartner', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit BaiduMapAPI.RoutePlanSearchService.Android; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 线路规划服务 单元 //官方链接:http://lbsyun.baidu.com/ //TAndroidBaiduMapPoiSearchService 百度地图 安卓线路规划服务 interface uses System.Classes, System.Types, FMX.Maps, Androidapi.JNI.JavaTypes, Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.baidu.mapapi.search, Androidapi.JNI.baidu.mapapi.model, BaiduMapAPI.RoutePlanSearchService; type TAndroidBaiduMapRoutePlanSearchService = class; TOnGetRoutePlanResultListener = class(TJavaLocal, JOnGetRoutePlanResultListener) private [weak]FRoutePlanSearchService:TAndroidBaiduMapRoutePlanSearchService; public procedure onGetWalkingRouteResult(P1: JWalkingRouteResult); cdecl; procedure onGetTransitRouteResult(P1: JTransitRouteResult); cdecl; procedure onGetMassTransitRouteResult(P1: JMassTransitRouteResult); cdecl; procedure onGetDrivingRouteResult(P1: JDrivingRouteResult); cdecl; procedure onGetIndoorRouteResult(P1: JIndoorRouteResult); cdecl; procedure onGetBikingRouteResult(P1: JBikingRouteResult); cdecl; constructor Create(RoutePlanSearchService: TAndroidBaiduMapRoutePlanSearchService); end; TAndroidBaiduMapRoutePlanSearchService = class(TBaiduMapRoutePlanSearchService) private FRoutePlanSearch:JRoutePlanSearch; FListener:TOnGetRoutePlanResultListener; function CreateBikingRoutePlanOption(option:TBikingRoutePlanOption):JBikingRoutePlanOption; function CreateDrivingRoutePlanOption(option:TDrivingRoutePlanOption):JDrivingRoutePlanOption; function CreateMassTransitRoutePlanOption(option:TMassTransitRoutePlanOption):JMassTransitRoutePlanOption; function CreateTransitRoutePlanOption(option:TTransitRoutePlanOption):JTransitRoutePlanOption; function CreateIndoorRoutePlanOption(option:TIndoorRoutePlanOption):JIndoorRoutePlanOption; function CreateWalkingRoutePlanOption(option:TWalkingRoutePlanOption):JWalkingRoutePlanOption; protected function DobikingSearch(option:TBikingRoutePlanOption):Boolean; override; function DodrivingSearch(option:TDrivingRoutePlanOption):Boolean; override; function DomasstransitSearch(option:TMassTransitRoutePlanOption):Boolean; override; function DotransitSearch(option:TTransitRoutePlanOption):Boolean; override; function DowalkingIndoorSearch(option:TIndoorRoutePlanOption):Boolean; override; function DowalkingSearch(option:TWalkingRoutePlanOption):Boolean; override; public constructor Create; destructor Destroy; override; end; //构造节点信息 function CreatePlanNode(Node:TPlanNode):JPlanNode; function CreateIndoorPlanNode(Node:TIndoorPlanNode):JIndoorPlanNode; //构造枚举类型 function CreateDrivingTrafficPolicy(DrivingTrafficPolicy:TDrivingTrafficPolicy):JDrivingRoutePlanOption_DrivingTrafficPolicy; function CreateDrivingPolicy(DrivingPolicy:TDrivingPolicy):JDrivingRoutePlanOption_DrivingPolicy; function CreateTacticsIncity(TacticsIncity:TTacticsIncity):JMassTransitRoutePlanOption_TacticsIncity; function CreateTacticsIntercity(TacticsIntercity:TTacticsIntercity):JMassTransitRoutePlanOption_TacticsIntercity; function CreateTransTypeIntercity(TransTypeIntercity:TTransTypeIntercity):JMassTransitRoutePlanOption_TransTypeIntercity; function CreateTransitPolicy(TransitPolicy:TTransitPolicy):JTransitRoutePlanOption_TransitPolicy; implementation uses Androidapi.Helpers; function CreateIndoorPlanNode(Node:TIndoorPlanNode):JIndoorPlanNode; begin Result:=TJIndoorPlanNode.JavaClass.init( TJLatLng.JavaClass.init(Node.location.Latitude, Node.location.Longitude), StringToJString(Node.footer)); end; function CreatePlanNode(Node:TPlanNode):JPlanNode; begin case Node.&type of Location:Result:=TJPlanNode.JavaClass.withLocation(TJLatLng.JavaClass.init(Node.location.Latitude, Node.location.Longitude)); CityCode:Result:=TJPlanNode.JavaClass.withCityCodeAndPlaceName(Node.cityCode, StringToJString(Node.name)); City:Result:=TJPlanNode.JavaClass.withCityNameAndPlaceName(StringToJString(Node.cityName), StringToJString(Node.name)); end; end; function CreateDrivingTrafficPolicy(DrivingTrafficPolicy:TDrivingTrafficPolicy):JDrivingRoutePlanOption_DrivingTrafficPolicy; begin case DrivingTrafficPolicy of ROUTE_PATH: Result:=TJDrivingRoutePlanOption_DrivingTrafficPolicy.JavaClass.ROUTE_PATH; ROUTE_PATH_AND_TRAFFIC: Result:=TJDrivingRoutePlanOption_DrivingTrafficPolicy.JavaClass.ROUTE_PATH_AND_TRAFFIC; end; end; function CreateDrivingPolicy(DrivingPolicy:TDrivingPolicy):JDrivingRoutePlanOption_DrivingPolicy; begin case DrivingPolicy of ECAR_AVOID_JAM: Result:=TJDrivingRoutePlanOption_DrivingPolicy.JavaClass.ECAR_AVOID_JAM; ECAR_DIS_FIRST: Result:=TJDrivingRoutePlanOption_DrivingPolicy.JavaClass.ECAR_DIS_FIRST; ECAR_FEE_FIRST: Result:=TJDrivingRoutePlanOption_DrivingPolicy.JavaClass.ECAR_FEE_FIRST; ECAR_TIME_FIRST: Result:=TJDrivingRoutePlanOption_DrivingPolicy.JavaClass.ECAR_TIME_FIRST; end; end; function CreateTacticsIncity(TacticsIncity:TTacticsIncity):JMassTransitRoutePlanOption_TacticsIncity; begin case TacticsIncity of ETRANS_LEAST_TIME: Result:=TJMassTransitRoutePlanOption_TacticsIncity.JavaClass.ETRANS_LEAST_TIME; ETRANS_LEAST_TRANSFER: Result:=TJMassTransitRoutePlanOption_TacticsIncity.JavaClass.ETRANS_LEAST_TRANSFER; ETRANS_LEAST_WALK: Result:=TJMassTransitRoutePlanOption_TacticsIncity.JavaClass.ETRANS_LEAST_WALK; ETRANS_NO_SUBWAY: Result:=TJMassTransitRoutePlanOption_TacticsIncity.JavaClass.ETRANS_NO_SUBWAY; ETRANS_SUBWAY_FIRST: Result:=TJMassTransitRoutePlanOption_TacticsIncity.JavaClass.ETRANS_SUBWAY_FIRST; ETRANS_SUGGEST: Result:=TJMassTransitRoutePlanOption_TacticsIncity.JavaClass.ETRANS_SUGGEST; end; end; function CreateTacticsIntercity(TacticsIntercity:TTacticsIntercity):JMassTransitRoutePlanOption_TacticsIntercity; begin case TacticsIntercity of TTacticsIntercity.ETRANS_LEAST_PRICE: Result:=TJMassTransitRoutePlanOption_TacticsIntercity.JavaClass.ETRANS_LEAST_PRICE; TTacticsIntercity.ETRANS_LEAST_TIME: Result:=TJMassTransitRoutePlanOption_TacticsIntercity.JavaClass.ETRANS_LEAST_TIME; TTacticsIntercity.ETRANS_START_EARLY: Result:=TJMassTransitRoutePlanOption_TacticsIntercity.JavaClass.ETRANS_START_EARLY; end; end; function CreateTransTypeIntercity(TransTypeIntercity:TTransTypeIntercity):JMassTransitRoutePlanOption_TransTypeIntercity; begin case TransTypeIntercity of ETRANS_COACH_FIRST: Result:=TJMassTransitRoutePlanOption_TransTypeIntercity.JavaClass.ETRANS_COACH_FIRST; ETRANS_PLANE_FIRST: Result:=TJMassTransitRoutePlanOption_TransTypeIntercity.JavaClass.ETRANS_PLANE_FIRST; ETRANS_TRAIN_FIRST: Result:=TJMassTransitRoutePlanOption_TransTypeIntercity.JavaClass.ETRANS_TRAIN_FIRST; end; end; function CreateTransitPolicy(TransitPolicy:TTransitPolicy):JTransitRoutePlanOption_TransitPolicy; begin case TransitPolicy of EBUS_NO_SUBWAY: Result:=TJTransitRoutePlanOption_TransitPolicy.JavaClass.EBUS_NO_SUBWAY; EBUS_TIME_FIRST: Result:=TJTransitRoutePlanOption_TransitPolicy.JavaClass.EBUS_TIME_FIRST; EBUS_TRANSFER_FIRST: Result:=TJTransitRoutePlanOption_TransitPolicy.JavaClass.EBUS_TRANSFER_FIRST; EBUS_WALK_FIRST: Result:=TJTransitRoutePlanOption_TransitPolicy.JavaClass.EBUS_WALK_FIRST; end; end; { TAndroidBaiduMapRoutePlanSearchService } constructor TAndroidBaiduMapRoutePlanSearchService.Create; begin FRoutePlanSearch:= TJRoutePlanSearch.JavaClass.newInstance; FListener:=TOnGetRoutePlanResultListener.Create(Self); FRoutePlanSearch.setOnGetRoutePlanResultListener(FListener); end; function TAndroidBaiduMapRoutePlanSearchService.CreateBikingRoutePlanOption( option: TBikingRoutePlanOption): JBikingRoutePlanOption; var PlanOption:JBikingRoutePlanOption; begin PlanOption:=TJBikingRoutePlanOption.JavaClass.init .from(CreatePlanNode(option.from)) .&to(CreatePlanNode(option.&to)); end; function TAndroidBaiduMapRoutePlanSearchService.CreateDrivingRoutePlanOption( option: TDrivingRoutePlanOption): JDrivingRoutePlanOption; var i:integer; List:JList; PlanOption:JDrivingRoutePlanOption; begin PlanOption:=TJDrivingRoutePlanOption.JavaClass.init .from(CreatePlanNode(option.from)) .&to(CreatePlanNode(option.&to)) .currentCity(StringToJString(option.CityName)) .trafficPolicy(CreateDrivingTrafficPolicy(option.trafficPolicy)) .policy(CreateDrivingPolicy(option.Policy)); //途经点 if Length(option.wayPoints)>0 then begin List:=TJList.Create; for i := 0 to Length(option.wayPoints)-1 do begin List.add(CreatePlanNode(option.wayPoints[i])); end; PlanOption.passBy(List); end; end; function TAndroidBaiduMapRoutePlanSearchService.CreateIndoorRoutePlanOption( option: TIndoorRoutePlanOption): JIndoorRoutePlanOption; var PlanOption:JIndoorRoutePlanOption; begin PlanOption:=TJIndoorRoutePlanOption.JavaClass.init .from(CreateIndoorPlanNode(option.from)) .&to(CreateIndoorPlanNode(option.&to)); end; function TAndroidBaiduMapRoutePlanSearchService.CreateMassTransitRoutePlanOption( option: TMassTransitRoutePlanOption): JMassTransitRoutePlanOption; var PlanOption:JMassTransitRoutePlanOption; begin PlanOption:=TJMassTransitRoutePlanOption.JavaClass.init .from(CreatePlanNode(option.from)) .&to(CreatePlanNode(option.&to)) .coordType(StringToJString(option.CoordType)) .tacticsIncity(CreateTacticsIncity(option.TacticsIncity)) .tacticsIntercity(CreateTacticsIntercity(option.TacticsIntercity)) .transtypeintercity(CreateTransTypeIntercity(option.TransTypeIntercity)) .pageSize(option.PageSize) .pageIndex(option.PageIndex); end; function TAndroidBaiduMapRoutePlanSearchService.CreateTransitRoutePlanOption( option: TTransitRoutePlanOption): JTransitRoutePlanOption; var PlanOption:JTransitRoutePlanOption; begin PlanOption:=TJTransitRoutePlanOption.JavaClass.init .from(CreatePlanNode(option.from)) .&to(CreatePlanNode(option.&to)) .city(StringToJString(option.CityName)) .policy(CreateTransitPolicy(option.Policy)) end; function TAndroidBaiduMapRoutePlanSearchService.CreateWalkingRoutePlanOption( option: TWalkingRoutePlanOption): JWalkingRoutePlanOption; var PlanOption:JWalkingRoutePlanOption; begin PlanOption:=TJWalkingRoutePlanOption.JavaClass.init .from(CreatePlanNode(option.from)) .&to(CreatePlanNode(option.&to)); end; destructor TAndroidBaiduMapRoutePlanSearchService.Destroy; begin FListener.Free; FRoutePlanSearch.destroy; FRoutePlanSearch:=nil; inherited; end; function TAndroidBaiduMapRoutePlanSearchService.DobikingSearch( option: TBikingRoutePlanOption): Boolean; begin Result:=FRoutePlanSearch.bikingSearch(CreateBikingRoutePlanOption(option)); end; function TAndroidBaiduMapRoutePlanSearchService.DodrivingSearch( option: TDrivingRoutePlanOption): Boolean; begin Result:=FRoutePlanSearch.drivingSearch(CreateDrivingRoutePlanOption(option)); end; function TAndroidBaiduMapRoutePlanSearchService.DomasstransitSearch( option: TMassTransitRoutePlanOption): Boolean; begin Result:=FRoutePlanSearch.masstransitSearch(CreateMassTransitRoutePlanOption(option)); end; function TAndroidBaiduMapRoutePlanSearchService.DotransitSearch( option: TTransitRoutePlanOption): Boolean; begin Result:=FRoutePlanSearch.transitSearch(CreateTransitRoutePlanOption(option)); end; function TAndroidBaiduMapRoutePlanSearchService.DowalkingIndoorSearch( option: TIndoorRoutePlanOption): Boolean; begin Result:=FRoutePlanSearch.walkingIndoorSearch(CreateIndoorRoutePlanOption(option)); end; function TAndroidBaiduMapRoutePlanSearchService.DowalkingSearch( option: TWalkingRoutePlanOption): Boolean; begin Result:=FRoutePlanSearch.walkingSearch(CreateWalkingRoutePlanOption(option)); end; { TOnGetRoutePlanResultListener } constructor TOnGetRoutePlanResultListener.Create( RoutePlanSearchService: TAndroidBaiduMapRoutePlanSearchService); begin FRoutePlanSearchService:=RoutePlanSearchService; end; procedure TOnGetRoutePlanResultListener.onGetBikingRouteResult( P1: JBikingRouteResult); begin end; procedure TOnGetRoutePlanResultListener.onGetDrivingRouteResult( P1: JDrivingRouteResult); begin end; procedure TOnGetRoutePlanResultListener.onGetIndoorRouteResult( P1: JIndoorRouteResult); begin end; procedure TOnGetRoutePlanResultListener.onGetMassTransitRouteResult( P1: JMassTransitRouteResult); begin end; procedure TOnGetRoutePlanResultListener.onGetTransitRouteResult( P1: JTransitRouteResult); begin end; procedure TOnGetRoutePlanResultListener.onGetWalkingRouteResult( P1: JWalkingRouteResult); begin end; end.
unit fmuPrintTest; interface uses // VCL Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, // This untPages, untDriver, Spin; type { TfmLock } TfmPrintTest = class(TPage) grpPrintLock: TGroupBox; lblRepCount2: TLabel; lblRepCount: TLabel; lblErrCount2: TLabel; lblErrCount: TLabel; lblSpeed: TLabel; lblTxSpeed: TLabel; Label1: TLabel; lblErrRate: TLabel; lblTimeLeft2: TLabel; lblTimeLeft: TLabel; Label2: TLabel; lblCommandTime: TLabel; btnStartPrintWithLock: TButton; btnStopPrintWithLock: TButton; chbStopOnError: TCheckBox; lblSpeedPrinting: TLabel; grpSpeedPrintTest: TGroupBox; lblStringCount: TLabel; btnStartSpeedPrintTest: TButton; lblSpeed_: TLabel; btnStopSpeedPrintTest: TButton; grpTestFonts: TGroupBox; btnFonts: TButton; sePrintCount: TSpinEdit; procedure btnStartPrintWithLockClick(Sender: TObject); procedure btnStopPrintWithLockClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnFontsClick(Sender: TObject); procedure btnStartSpeedPrintTestClick(Sender: TObject); procedure btnStopSpeedPrintTestClick(Sender: TObject); private StopFlag: Boolean; end; implementation {$R *.DFM} { TfmLock } procedure TfmPrintTest.btnStartPrintWithLockClick(Sender: TObject); procedure Wait(T2: DWORD); var T1: DWORD; begin T1 := GetTickCount; repeat Application.ProcessMessages; until GetTickCount - T1 > T2; end; var i: Integer; Speed: Integer; ErrRate: Double; TimeLeft: DWORD; TickCount: DWORD; ProcessID: DWORD; RepCount: Integer; ErrCount: Integer; ResultCode: Integer; begin RepCount := 0; ErrCount := 0; ResultCode := 0; StopFlag := False; btnStopPrintWithLock.Enabled := True; btnStartPrintWithLock.Enabled := False; TickCount := GetTickCount; try repeat Inc(RepCount); try ResultCode := Driver.LockPort; except end; if ResultCode <> 0 then begin ResultCode := 0; Wait(100); end else try GetWindowThreadProcessId(Application.Handle, @ProcessID); Driver.StringForPrinting := '-------------------------------'; ResultCode := Driver.PrintString; Driver.WaitForPrinting; for i := 1 to 10 do begin Driver.StringForPrinting := IntToStr(i)+': Строка для печати(ID:'+IntToStr(ProcessID)+')'; ResultCode := Driver.PrintString; Driver.WaitForPrinting; if ResultCode <> 0 then Break; end; Driver.CutType := True; Driver.FeedDocument; Driver.CutCheck; finally Driver.UnlockPort; Wait(500); // Чтобы другие тоже могли захватить порт end; if ResultCode <> 0 then Inc(ErrCount); TimeLeft := GetTickCount - TickCount; if TimeLeft = 0 then Continue; Speed := Trunc(RepCount*1000/TimeLeft); ErrRate := ErrCount*100/RepCount; lblRepCount.Caption := IntToStr(RepCount); lblErrCount.Caption := IntToStr(ErrCount); lblTxSpeed.Caption := IntToStr(Speed); lblErrRate.Caption := Format('%.2f', [ErrRate]); lblTimeLeft.Caption := IntToStr(Trunc(TimeLeft/1000)); lblCommandTime.Caption := IntToStr(Trunc(TimeLeft/RepCount)); Application.ProcessMessages; if (ResultCode <> 0)and(chbStopOnError.Checked) then Exit; until StopFlag; finally Driver.Disconnect; btnStopPrintWithLock.Enabled := False; btnStartPrintWithLock.Enabled := True; end; end; procedure TfmPrintTest.btnStopPrintWithLockClick(Sender: TObject); begin StopFlag := True; end; procedure TfmPrintTest.FormClose(Sender: TObject; var Action: TCloseAction); begin StopFlag := True; end; // Тест печати шрифтов procedure TfmPrintTest.btnFontsClick(Sender: TObject); var i: Integer; Count: Integer; CharCount: Integer; S: string; begin EnableButtons(False); try Driver.UseReceiptRibbon := True; Driver.UseJournalRibbon := False; S := '01234567890123456789012345678901234567890' + '0123456789012345678901234567890123456789012345678901234567890123456789'; // Шрифт 1 есть всегда Driver.FontType := 1; if Driver.GetFontMetrics <> 0 then Exit; Count := Driver.FontCount; for i := 1 to Count do begin Driver.FontType := i; if Driver.GetFontMetrics <> 0 then Break; CharCount := 40; if Driver.CharWidth > 0 then CharCount := Trunc(Driver.PrintWidth/Driver.CharWidth); Driver.StringForPrinting := Format('%s %d', ['Шрифт', i]); if Driver.PrintStringWithFont <> 0 then Break; Driver.StringForPrinting := Copy(S, 1, CharCount); if Driver.PrintStringWithFont <> 0 then Break; end; finally EnableButtons(True); end; end; // Тест скорости печати procedure TfmPrintTest.btnStartSpeedPrintTestClick(Sender: TObject); var i: Integer; Count: Integer; PrintSpeed: Double; TickCount: Integer; StartTickCount: Integer; begin EnableButtons(False); btnStopSpeedPrintTest.Enabled := True; try PrintSpeed := 0; StopFlag := False; lblSpeedPrinting.Caption := ''; Application.ProcessMessages; Count := sePrintCount.Value; StartTickCount := GetTickCount; Driver.FontType := 1; Driver.UseReceiptRibbon := True; Driver.UseJournalRibbon := False; for i := 1 to Count do begin if StopFlag then Break; Driver.StringForPrinting := 'Строка ' + IntToStr(i); if Driver.PrintString <> 0 then Break; TickCount := Integer(GetTickCount) - StartTickCount; if TickCount > 0 then PrintSpeed := (i * 1000)/TickCount; lblSpeedPrinting.Caption := Format('%.3f', [PrintSpeed]); Application.ProcessMessages; end; finally EnableButtons(True); btnStopSpeedPrintTest.Enabled := False; end; end; procedure TfmPrintTest.btnStopSpeedPrintTestClick(Sender: TObject); begin StopFlag := True; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Data.Json, RemObjects.Elements.EUnit; type JsonTokenizerTest = public class (Test) private Tokenizer: JsonTokenizer := nil; method SkipTo(Token: JsonTokenKind); method Expect(Expected: JsonTokenKind); method Expect(ExpectedToken: JsonTokenKind; ExpectedValue: String); public method EmptyObject; method SimpleObjectStringValue; method SpaceTest; method SimpleObjectIntValue; method SimpleQuoteInString; method SimpleObjectFloatValue; method LowcaseFloatValue; method SimpleObjectLongValue; method SimpleObjectBigIntegerValue; method SimpleDigitArray; method SimpleStringArray; method ArrayOfEmptyObjects; method LowercaseUnicodeText; method UppercaseUnicodeText; method NonProtectedSlash; method SimpleObjectNullValue; method SimpleObjectTrueValue; method SimpleObjectFalseValue; method SimpleObjectDoubleValue; method MultiValuesObject; method NestedObject; method SimpleArraySingleValue; method MultiValuesArray; method ArrayWithNestedObjects; method NonProtectedKeys; method NonProtectedString; end; implementation method JsonTokenizerTest.EmptyObject; begin Tokenizer := new JsonTokenizer("{}"); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleObjectStringValue; begin Tokenizer := new JsonTokenizer('{ "v":"1"}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "1"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SpaceTest; begin Tokenizer := new JsonTokenizer("{ ""v"" :""1"" }"); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "1"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleObjectIntValue; begin Tokenizer := new JsonTokenizer('{"v":1}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "1"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleQuoteInString; begin Tokenizer := new JsonTokenizer('{ "v":"ab''c"}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "ab'c"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleObjectFloatValue; begin Tokenizer := new JsonTokenizer('{ "PI":3.141E-10}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "PI"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "3.141E-10"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.LowcaseFloatValue; begin Tokenizer := new JsonTokenizer('{ "PI":3.141e-10}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "PI"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "3.141e-10"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleObjectLongValue; begin Tokenizer := new JsonTokenizer('{ "v":12345123456789}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "12345123456789"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleObjectBigIntegerValue; begin Tokenizer := new JsonTokenizer('{ "v":123456789123456789123456789}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "123456789123456789123456789"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleDigitArray; begin Tokenizer := new JsonTokenizer('[1,2,3,4]'); Expect(JsonTokenKind.ArrayStart); for i: Int32 := 1 to 4 do begin Expect(JsonTokenKind.Number, i.ToString); if i < 4 then Expect(JsonTokenKind.ValueSeperator); end; Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleStringArray; begin Tokenizer := new JsonTokenizer('["1","2","3","4"]'); Expect(JsonTokenKind.ArrayStart); for i: Int32 := 1 to 4 do begin Expect(JsonTokenKind.String, i.ToString); if i < 4 then Expect(JsonTokenKind.ValueSeperator); end; Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.ArrayOfEmptyObjects; begin Tokenizer := new JsonTokenizer('[ {}, {}, []]'); Expect(JsonTokenKind.ArrayStart); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.ArrayStart); Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.LowercaseUnicodeText; begin Tokenizer := new JsonTokenizer('{ "v":"\u0275\u023e"}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "ɵȾ"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.UppercaseUnicodeText; begin Tokenizer := new JsonTokenizer('{ "v":"\u0275\u023E"}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "ɵȾ"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.NonProtectedSlash; begin Tokenizer := new JsonTokenizer('{ "v":"http://foo"}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "http://foo"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleObjectNullValue; begin Tokenizer := new JsonTokenizer('{ "v": null}'); SkipTo(JsonTokenKind.NameSeperator); Tokenizer.Next; Assert.AreEqual(Tokenizer.Token, JsonTokenKind.Null); end; method JsonTokenizerTest.SimpleObjectTrueValue; begin Tokenizer := new JsonTokenizer('{ "v": true}'); SkipTo(JsonTokenKind.NameSeperator); Tokenizer.Next; Assert.AreEqual(Tokenizer.Token, JsonTokenKind.True); end; method JsonTokenizerTest.SimpleObjectFalseValue; begin Tokenizer := new JsonTokenizer('{ "v": false}'); SkipTo(JsonTokenKind.NameSeperator); Tokenizer.Next; Assert.AreEqual(Tokenizer.Token, JsonTokenKind.False); end; method JsonTokenizerTest.SimpleObjectDoubleValue; begin Tokenizer := new JsonTokenizer('{ "v":1.7976931348623157E308}'); SkipTo(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "1.7976931348623157E308"); end; method JsonTokenizerTest.MultiValuesObject; begin Tokenizer := new JsonTokenizer('{ "a":1.7E308, "b": 42, "c": null, "d": "string"}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "1.7E308"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.String, "b"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "42"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.String, "c"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Null); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.String, "d"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "string"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SkipTo(Token: JsonTokenKind); begin repeat Tokenizer.Next; until (Tokenizer.Token = Token) or (Tokenizer.Token = JsonTokenKind.EOF); end; method JsonTokenizerTest.NestedObject; begin Tokenizer := new JsonTokenizer('{ "v": "abc", "a": { "v": "abc"}}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "abc"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "v"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "abc"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.SimpleArraySingleValue; begin Tokenizer := new JsonTokenizer('["a"]'); Expect(JsonTokenKind.ArrayStart); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.MultiValuesArray; begin Tokenizer := new JsonTokenizer('["a", 1, null, true]'); Expect(JsonTokenKind.ArrayStart); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.Number, "1"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.Null); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.True); Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.ArrayWithNestedObjects; begin Tokenizer := new JsonTokenizer('[{"a": 1, "b": "abc"}, {"a": 2, "b": "bca"}]'); Expect(JsonTokenKind.ArrayStart); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "1"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.String, "b"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "abc"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "2"); Expect(JsonTokenKind.ValueSeperator); Expect(JsonTokenKind.String, "b"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.String, "bca"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.ArrayEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.Expect(Expected: JsonTokenKind); begin Tokenizer.Next; Assert.AreEqual(Tokenizer.Token, Expected); end; method JsonTokenizerTest.Expect(ExpectedToken: JsonTokenKind; ExpectedValue: String); begin Tokenizer.Next; Assert.AreEqual(Tokenizer.Token, ExpectedToken); Assert.AreEqual(Tokenizer.Value, ExpectedValue); end; method JsonTokenizerTest.NonProtectedKeys; begin Tokenizer := new JsonTokenizer('{a: 1}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.Identifier, "a"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Number, "1"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; method JsonTokenizerTest.NonProtectedString; begin Tokenizer := new JsonTokenizer('{"a": abc}'); Expect(JsonTokenKind.ObjectStart); Expect(JsonTokenKind.String, "a"); Expect(JsonTokenKind.NameSeperator); Expect(JsonTokenKind.Identifier, "abc"); Expect(JsonTokenKind.ObjectEnd); Expect(JsonTokenKind.EOF); end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit OraDBLink; interface uses Classes, SysUtils, Ora, OraStorage, DB, DBQuery, Forms, Dialogs, VirtualTable; type TDBLink = class(TObject) private FDB_LINK, FOWNER: string; FPUBLIC_LINK: Boolean; FHOST: string; FUSER_NAME, FPASSWORD, FCREATED: string; FMode: TMode; FOraSession: TOraSession; function GetStatus: string; function GetDBLinkDetail: String; public property DB_LINK: String read FDB_LINK write FDB_LINK; property USER_NAME: String read FUSER_NAME write FUSER_NAME; property HOST: String read FHOST write FHOST; property OWNER: String read FOWNER write FOWNER; property PASSWORD: String read FPASSWORD write FPASSWORD; property CREATED: String read FCREATED write FCREATED; property PUBLIC_LINK: Boolean read FPUBLIC_LINK write FPUBLIC_LINK; property Status: String read GetStatus; property Mode: TMode read FMode write FMode; property OraSession: TOraSession read FOraSession write FOraSession; procedure SetDDL; function GetDDL: string; function GetAlterDDL: string; function CreateDBLink(Script: string) : boolean; function AlterDBLink(Script: string) : boolean; function DropDBLink: boolean; constructor Create; destructor Destroy; override; end; function GetDBLinks(OwnerName: string): string; implementation uses Util, frmSchemaBrowser, OraScripts, Languages; resourcestring strDBLinkDropped = 'DB Link %s has been dropped.'; strDBLinkAltered = 'DB Link %s has been altered.'; strDBLinkCreated = 'DB Link %s has been created.'; function GetDBLinks(OwnerName: string): string; begin result := 'select * from ALL_DB_LINKS ' +' where OWNER = '+Str(OwnerName) +' order by DB_LINK '; end; constructor TDBLink.Create; begin inherited; end; destructor TDBLink.destroy; begin inherited; end; function TDBLink.GetDBLinkDetail: String; begin Result := 'Select * ' +' from ALL_DB_LINKS ' +'WHERE DB_LINK = :pName ' +' AND OWNER = :pOwner '; end; function TDBLink.GetStatus: string; var q1: TOraQuery; begin q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetObjectStatusSQL; q1.ParamByName('pOName').AsString := FDB_LINK; q1.ParamByName('pOType').AsString := 'DB LINK'; q1.ParamByName('pOwner').AsString := FOWNER; q1.Open; result := FDB_LINK+' ( Created: '+q1.FieldByName('CREATED').AsString +' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString +' Status: '+q1.FieldByName('STATUS').AsString +' )'; q1.Close; end; procedure TDBLink.SetDDL; var q1: TOraQuery; begin if FDB_LINK = '' then exit; if FOWNER = '' then exit; q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetDBLinkDetail; q1.ParamByName('pName').AsString := FDB_LINK; q1.ParamByName('pOwner').AsString := FOWNER; q1.Open; FDB_LINK := q1.FieldByName('DB_LINK').AsString; FUSER_NAME := q1.FieldByName('USERNAME').AsString; FHOST := q1.FieldByName('HOST').AsString; FOWNER := q1.FieldByName('OWNER').AsString; FCREATED := q1.FieldByName('CREATED').AsString; FPASSWORD := '"<pwd>"'; Q1.close; end; function TDBLink.GetDDL: string; begin if FPUBLIC_LINK then result := 'CREATE PUBLIC DATABASE LINK '+DB_LINK+ln else result := 'CREATE DATABASE LINK '+DB_LINK+ln; if (FPASSWORD <> '') and (FUSER_NAME <> '') then result := result +' CONNECT TO '+FUSER_NAME+ln +' IDENTIFIED BY '+FPASSWORD+ln; if (FHOST <> '') then result := result +' USING '+str(FHOST); result := result +';'; end; function TDBLink.GetAlterDDL: string; begin result := 'DROP DATABASE LINK '+DB_LINK+ ';'+ln +GetDDL; end; function TDBLink.CreateDBLink(Script: string) : boolean; begin result := false; if DB_LINK = '' then exit; result := ExecSQL(Script, Format(ChangeSentence('strDBLinkCreated',strDBLinkCreated),[DB_LINK]), FOraSession); end; function TDBLink.AlterDBLink(Script: string) : boolean; begin result := false; if DB_LINK = '' then exit; result := ExecSQL(Script, Format(ChangeSentence('strDBLinkAltered',strDBLinkAltered),[DB_LINK]), FOraSession); end; function TDBLink.DropDBLink: boolean; var FSQL: string; begin result := false; if DB_LINK = '' then exit; FSQL := 'drop DATABASE LINK '+DB_LINK; result := ExecSQL(FSQL, Format(ChangeSentence('strDBLinkDropped',strDBLinkDropped),[DB_LINK]), FOraSession); end; end.
{*************************************************************** * Unit Name: GX_Bookmarks * Authors : Thomas Mueller http://blog.dummzeuch.de ****************************************************************} unit GX_Bookmarks; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ToolsAPI, ExtCtrls, Menus, Types, GX_Experts, GX_BaseForm, GX_IdeDock, GX_BookmarkList; type TfmGxBookmarksForm = class(TfmIdeDockForm) lb_Bookmarks: TListBox; tim_Update: TTimer; pm_Bookmarks: TPopupMenu; mi_Delete: TMenuItem; mi_Add: TMenuItem; mi_Edit: TMenuItem; mi_DeleteAll: TMenuItem; procedure lb_BookmarksDblClick(Sender: TObject); procedure tim_UpdateTimer(Sender: TObject); procedure mi_DeleteClick(Sender: TObject); procedure mi_AddClick(Sender: TObject); procedure mi_EditClick(Sender: TObject); procedure lb_BookmarksDrawItem(Control: TWinControl; Index: Integer; _Rect: TRect; State: TOwnerDrawState); procedure mi_DeleteAllClick(Sender: TObject); private FBookmarks: TBookmarkList; function GetEditView(var _SourceEditor: IOTASourceEditor; var _EditView: IOTAEditView): Boolean; procedure Init; procedure SetBookmark(const _ModuleName: string; _LineNo: Integer; _BmIdx: Integer = -1); procedure DeleteBookmark(const _ModuleName: string; _BmIdx: Integer); procedure AddBookmarks(const _ModuleName: string; _EditView: IOTAEditView; _Bookmarks: TBookmarkList); function HasChanged(_NewBookmarks: TBookmarkList): Boolean; public constructor Create(_Owner: TComponent); override; destructor Destroy; override; end; implementation {$R *.dfm} uses {$IFOPT D+}GX_DbugIntf, {$ENDIF} Windows, Graphics, GX_GExperts, GX_ConfigurationInfo, GX_OtaUtils, GX_GenericUtils, GX_NTAEditServiceNotifier, GX_dzVclUtils, GX_EditBookmark; {$IFDEF GX_VER170_up} type ///<summary> /// We implement INTAEditServicesNotifier only to get a notification when the EditViewActivated /// method is called. This in turn calls the OnEditorViewActivated event. </summary> // todo -otwm -cCleanup: Merge this code with the duplicate in GX_HideNavbar TEditServiceNotifier = class(TGxNTAEditServiceNotifier, INTAEditServicesNotifier) private type TOnEditorViewActivatedEvent = procedure(_Sender: TObject; _EditView: IOTAEditView) of object; var FOnEditorViewActivated: TOnEditorViewActivatedEvent; protected // INTAEditServicesNotifier procedure EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); override; public constructor Create(_OnEditorViewActivated: TOnEditorViewActivatedEvent); end; {$ENDIF} type TGxBookmarksExpert = class(TGX_Expert) private {$IFDEF GX_VER170_up} FNotifierIdx: Integer; procedure EditorViewActivated(_Sender: TObject; _EditView: IOTAEditView); {$ENDIF} protected procedure SetActive(New: Boolean); override; public constructor Create; override; destructor Destroy; override; function GetActionCaption: string; override; class function GetName: string; override; function HasConfigOptions: Boolean; override; function HasMenuItem: Boolean; override; procedure Execute(Sender: TObject); override; end; var fmBookmarks: TfmGxBookmarksForm = nil; BookmarksExpert: TGxBookmarksExpert = nil; { TGxBookmarksExpert } constructor TGxBookmarksExpert.Create; begin inherited Create; {$IFDEF GX_VER170_up} if Assigned(BorlandIDEServices) then begin FNotifierIdx := (BorlandIDEServices as IOTAEditorServices).AddNotifier( TEditServiceNotifier.Create(EditorViewActivated)); end; {$ENDIF} BookmarksExpert := Self; end; destructor TGxBookmarksExpert.Destroy; begin BookmarksExpert := nil; {$IFDEF GX_VER170_up} if FNotifierIdx <> 0 then (BorlandIDEServices as IOTAEditorServices).RemoveNotifier(FNotifierIdx); {$ENDIF} FreeAndNil(fmBookmarks); inherited Destroy; end; procedure TGxBookmarksExpert.SetActive(New: Boolean); begin if New <> Active then begin inherited SetActive(New); if New then IdeDockManager.RegisterDockableForm(TfmGxBookmarksForm, fmBookmarks, 'fmGxBookmarksForm') else begin IdeDockManager.UnRegisterDockableForm(fmBookmarks, 'fmGxBookmarksForm'); FreeAndNil(fmBookmarks); end; end; end; procedure TGxBookmarksExpert.Execute(Sender: TObject); begin if fmBookmarks = nil then begin fmBookmarks := TfmGxBookmarksForm.Create(nil); end; fmBookmarks.Init; IdeDockManager.ShowForm(fmBookmarks); EnsureFormVisible(fmBookmarks); end; {$IFDEF GX_VER170_up} procedure TGxBookmarksExpert.EditorViewActivated(_Sender: TObject; _EditView: IOTAEditView); begin if Assigned(fmBookmarks) then fmBookmarks.Init; end; {$ENDIF} function TGxBookmarksExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Editor Bookmarks'; begin Result := SMenuCaption; end; class function TGxBookmarksExpert.GetName: string; begin Result := 'BookmarksExpert'; end; function TGxBookmarksExpert.HasConfigOptions: Boolean; begin Result := False; end; function TGxBookmarksExpert.HasMenuItem: Boolean; begin Result := True; end; { TfmGxBookmarksForm } constructor TfmGxBookmarksForm.Create(_Owner: TComponent); begin inherited; if Assigned(BookmarksExpert) then BookmarksExpert.SetFormIcon(Self); end; destructor TfmGxBookmarksForm.Destroy; begin fmBookmarks := nil; FreeAndNil(FBookmarks); inherited; end; function TfmGxBookmarksForm.GetEditView(var _SourceEditor: IOTASourceEditor; var _EditView: IOTAEditView): Boolean; begin Result := False; if not GxOtaTryGetCurrentSourceEditor(_SourceEditor) then Exit; //==> if _SourceEditor.EditViewCount = 0 then Exit; //==> _EditView := _SourceEditor.GetEditView(0); Result := Assigned(_EditView); end; procedure TfmGxBookmarksForm.AddBookmarks(const _ModuleName: string; _EditView: IOTAEditView; _Bookmarks: TBookmarkList); var i: Integer; BmPos: TOTACharPos; begin for i := 0 to 19 do begin BmPos := _EditView.BookmarkPos[i]; if BmPos.Line <> 0 then begin _Bookmarks.Add(i, BmPos.Line, BmPos.CharIndex, _ModuleName); end; end; end; function TfmGxBookmarksForm.HasChanged(_NewBookmarks: TBookmarkList): Boolean; var i: Integer; bm1: TBookmark; bm2: Pointer; begin Result := True; if not Assigned(FBookmarks) or (_NewBookmarks.Count <> FBookmarks.Count) then Exit; for i := 0 to _NewBookmarks.Count - 1 do begin bm1 := _NewBookmarks[i]; bm2 := FBookmarks[i]; if not bm1.IsSame(bm2) then Exit; end; Result := False; end; procedure TfmGxBookmarksForm.Init; var SourceEditor: IOTASourceEditor; EditView: IOTAEditView; i: Integer; bm: TBookmark; NewBookmarks: TBookmarkList; s: string; begin tim_Update.Enabled := False; try if not GetEditView(SourceEditor, EditView) then Exit; NewBookmarks := TBookmarkList.Create; try AddBookmarks(SourceEditor.Filename, EditView, NewBookmarks); if HasChanged(NewBookmarks) then begin FreeAndNil(FBookmarks); FBookmarks := NewBookmarks; NewBookmarks := nil; lb_Bookmarks.Items.Clear; for i := 0 to FBookmarks.Count - 1 do begin bm := FBookmarks[i]; lb_Bookmarks.AddItem(Format('%d [%d] %s', [bm.Number, bm.Line, ExtractFileName(bm.Module)]), bm); if bm.Line > 1 then s := ' ' + GxOtaGetEditorLineAsString(EditView, bm.Line - 1) else s := ' ' + CRLF; s := s + '> ' + GxOtaGetEditorLineAsString(EditView, bm.Line); s := s + ' ' + GxOtaGetEditorLineAsString(EditView, bm.Line + 1); bm.Text := s; end; end; finally FreeAndNil(NewBookmarks); end; finally tim_Update.Enabled := True; end; end; procedure TfmGxBookmarksForm.tim_UpdateTimer(Sender: TObject); begin Init; end; procedure TfmGxBookmarksForm.lb_BookmarksDblClick(Sender: TObject); resourcestring SCouldNotOpenFile = 'Could not open file %s'; var bm: TBookmark; fn: string; Module: IOTAModule; SourceEditor: IOTASourceEditor; EditView: IOTAEditView; begin if not TListBox_GetSelectedObject(lb_Bookmarks, Pointer(bm)) then Exit; fn := bm.Module; if not GxOtaMakeSourceVisible(fn) then raise Exception.CreateFmt(SCouldNotOpenFile, [fn]); Module := GxOtaGetModule(fn); if not Assigned(Module) then Exit; SourceEditor := GxOtaGetSourceEditorFromModule(Module, fn); if not Assigned(SourceEditor) then Exit; SourceEditor.Show; if not GxOtaTryGetTopMostEditView(SourceEditor, EditView) then Exit; EditView.BookmarkGoto(bm.Number); EditView.MoveViewToCursor; GxOtaFocusCurrentIDEEditControl; EditView.Paint; end; function TryGetEditView(const _fn: string; out _EditView: IOTAEditView): Boolean; var SourceEditor: IOTASourceEditor; begin SourceEditor := GxOtaGetSourceEditor(_fn); Result := Assigned(SourceEditor) and (SourceEditor.EditViewCount > 0); if Result then _EditView := SourceEditor.EditViews[0]; end; procedure TfmGxBookmarksForm.DeleteBookmark(const _ModuleName: string; _BmIdx: Integer); var EditView: IOTAEditView; SaveCursorPos: TOTAEditPos; BmEditPos: TOTAEditPos; begin if not TryGetEditView(_ModuleName, EditView) then Exit; if EditView.BookmarkPos[_BmIdx].Line <> 0 then begin SaveCursorPos := EditView.GetCursorPos; try BmEditPos.Line := EditView.BookmarkPos[_BmIdx].Line; BmEditPos.Col := EditView.BookmarkPos[_BmIdx].CharIndex; EditView.SetCursorPos(BmEditPos); EditView.BookmarkToggle(_BmIdx); finally EditView.SetCursorPos(SaveCursorPos); EditView.Paint; end; end; end; procedure TfmGxBookmarksForm.SetBookmark(const _ModuleName: string; _LineNo: Integer; _BmIdx: Integer = -1); var EditView: IOTAEditView; i: Integer; SaveCursorPos: TOTAEditPos; BmEditPos: TOTAEditPos; begin if not TryGetEditView(_ModuleName, EditView) then Exit; if _BmIdx < 0 then begin // no bookmark index was given, find the first one that's free for i := 0 to 19 do begin if EditView.BookmarkPos[i].Line = 0 then begin _BmIdx := i; break; end; end; if _BmIdx < 0 then Exit; // no free bookmark index found end; SaveCursorPos := EditView.GetCursorPos; try BmEditPos.Line := _LineNo; BmEditPos.Col := 1; EditView.SetCursorPos(BmEditPos); EditView.BookmarkRecord(_BmIdx); finally EditView.SetCursorPos(SaveCursorPos); end; end; procedure TfmGxBookmarksForm.mi_AddClick(Sender: TObject); var SourceEditor: IOTASourceEditor; EditView: IOTAEditView; ModuleName: string; LineNo: Integer; BmIndex: Integer; begin if not GetEditView(SourceEditor, EditView) then Exit; try ModuleName := SourceEditor.Filename; LineNo := EditView.CursorPos.Line; if not TfmEditBookmarks.Execute(Self, ModuleName, LineNo, BmIndex) then Exit; SetBookmark(ModuleName, LineNo, BmIndex); finally Init; end; end; procedure TfmGxBookmarksForm.mi_DeleteClick(Sender: TObject); var bm: TBookmark; begin if not TListBox_GetSelectedObject(lb_Bookmarks, Pointer(bm)) then Exit; DeleteBookmark(bm.Module, bm.Number); end; procedure TfmGxBookmarksForm.mi_DeleteAllClick(Sender: TObject); var i: integer; bm: TBookmark; begin for i := lb_bookmarks.Items.Count - 1 downto 0 do begin bm := TBookmark(lb_Bookmarks.Items.Objects[i]); DeleteBookmark(bm.Module, bm.Number); end; end; procedure TfmGxBookmarksForm.mi_EditClick(Sender: TObject); var bm: TBookmark; ModuleName: string; LineNo: Integer; begin if not TListBox_GetSelectedObject(lb_Bookmarks, Pointer(bm)) then Exit; try ModuleName := bm.Module; LineNo := bm.Line; if not TfmEditBookmarks.Execute(Self, ModuleName, LineNo) then Exit; SetBookmark(ModuleName, LineNo, bm.Number); finally Init; end; end; procedure TfmGxBookmarksForm.lb_BookmarksDrawItem(Control: TWinControl; Index: Integer; _Rect: TRect; State: TOwnerDrawState); resourcestring SLine = 'Line %d'; var LbCanvas: TCanvas; bm: TBookmark; procedure PaintFileHeader(_Rect: TRect); var TopColor: TColor; BottomColor: TColor; i: Integer; FileNameWidth: Integer; FileString: string; LineText: string; begin TopColor := clBtnHighlight; BottomColor := clBtnShadow; LbCanvas.Brush.Color := clBtnFace; LbCanvas.Font.Color := clBtnText; LbCanvas.FillRect(_Rect); _Rect.Right := _Rect.Right + 2; if odSelected in State then Frame3D(LbCanvas, _Rect, BottomColor, TopColor, 1) else Frame3D(LbCanvas, _Rect, TopColor, BottomColor, 1); i := LbCanvas.TextWidth('00'); FileString := ExtractFileName(bm.Module); LbCanvas.TextOut(_Rect.Left + i + 8, _Rect.Top, FileString); LbCanvas.TextOut(_Rect.Left + 3, _Rect.Top, IntToStr(bm.Number)); LineText := Format(SLine, [bm.Line]); FileNameWidth := LbCanvas.TextWidth(LineText) + 10; if (LbCanvas.TextWidth(FileString) + i + 10) <= _Rect.Right - FileNameWidth then LbCanvas.TextOut(lb_Bookmarks.ClientWidth - FileNameWidth, _Rect.Top, LineText); end; procedure PaintLines(_Rect: TRect); var TextTop: Integer; sl: TStringList; i: Integer; LineText: string; s: string; BGNormal: TColor; BGBookmark: TColor; begin if [odSelected, odFocused] * State = [odSelected, odFocused] then begin BGNormal := clHighLight; LbCanvas.Font.Color := clHighLightText; BGBookmark := BGNormal; end else begin BGNormal := clWindow; LbCanvas.Font.Color := clWindowText; BGBookmark := RGB(250, 255, 230); end; LbCanvas.Brush.Color := BGNormal; LbCanvas.FillRect(_Rect); TextTop := _Rect.Top + 1; sl := TStringList.Create; try sl.Text := bm.Text; for i := 0 to sl.Count - 1 do begin s := sl[i]; LineText := Copy(s, 2, 255); s := Copy(s, 1, 1); if s = '>' then begin LbCanvas.Brush.Color := BGBookmark; LbCanvas.FillRect(Rect(_Rect.Left, TextTop, _Rect.Right, TextTop + 16)); end else LbCanvas.Brush.Color := BGNormal; LbCanvas.TextOut(_Rect.Left, TextTop, LineText); Inc(TextTop, 16); end; finally sl.Free; end; end; begin LbCanvas := lb_Bookmarks.Canvas; if Assigned(lb_Bookmarks.Items.Objects[Index]) then begin bm := TBookmark(lb_Bookmarks.Items.Objects[Index]); PaintFileHeader(Rect(_Rect.Left, _Rect.Top, _Rect.Right, _Rect.Top + 16)); PaintLines(Rect(_Rect.Left, _Rect.Top + 16, _Rect.Right, _Rect.Bottom)); end; end; {$IFDEF GX_VER170_up} { TEditServiceNotifier } constructor TEditServiceNotifier.Create(_OnEditorViewActivated: TOnEditorViewActivatedEvent); begin inherited Create; FOnEditorViewActivated := _OnEditorViewActivated; end; procedure TEditServiceNotifier.EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); begin if Assigned(FOnEditorViewActivated) then FOnEditorViewActivated(Self, EditView); end; {$ENDIF} initialization RegisterGX_Expert(TGxBookmarksExpert); end.
unit Quick.Serializer.Intf; interface uses SysUtils, {$IFNDEF FPC} rtti; {$ELSE} Rtti, rttiutils; {$ENDIF} type TSerializerOptions = class private fUseEnumNames : Boolean; fUseJsonCaseSense : Boolean; fUseBase64Stream : Boolean; fUseNullStringsAsEmpty : Boolean; fUseGUIDWithBrackets: Boolean; fUseGUIDLowercase: Boolean; public property UseEnumNames : Boolean read fUseEnumNames write fUseEnumNames; property UseJsonCaseSense : Boolean read fUseJsonCaseSense write fUseJsonCaseSense; property UseBase64Stream : Boolean read fUseBase64Stream write fUseBase64Stream; property UseNullStringsAsEmpty : Boolean read fUseNullStringsAsEmpty write fUseNullStringsAsEmpty; property UseGUIDWithBrackets : Boolean read fUseGUIDWithBrackets write fUseGUIDWithBrackets; property UseGUIDLowercase : Boolean read fUseGUIDLowercase write fUseGUIDLowercase; end; ISerializer = interface ['{CA26F7AE-F1FE-41BE-9C23-723A687F60D1}'] function JsonToObject(aType: TClass; const aJson: string): TObject; overload; function JsonToObject(aObject: TObject; const aJson: string): TObject; overload; function ObjectToJson(aObject : TObject; aIndent : Boolean = False): string; function ValueToJson(const aValue : TValue; aIndent : Boolean = False) : string; function Options : TSerializerOptions; end; implementation end.
unit UPRT_COMPORT; interface uses UPRT, Windows; type TPRT_COMPORT = class(TPRT_ABSTRACT) protected FComName:String; hCom:THandle; FBaudRate:Cardinal; RxQue,TxQue:Integer; private procedure SetBaudRate(const Value: Cardinal); procedure RebuildDCB; procedure SetComName(const Value: String); procedure CheckQueues; public CheckRLSD: Boolean; constructor Create; destructor Destroy;override; function Opened:Boolean; property ComName:String read FComName write SetComName; property BaudRate:Cardinal read FBaudRate write SetBaudRate; public // interface function Open:HRESULT;override; procedure Close;override; function RxSize():Integer;override; function Rx(var Data; MaxSize:Integer):Integer;override; procedure Tx(const Data; DataSize:Integer);override; function ProcessIO:Integer;override; end; implementation constructor TPRT_COMPORT.Create(); begin hCom:=INVALID_HANDLE_VALUE; end; destructor TPRT_COMPORT.Destroy; begin Close; end; function TPRT_COMPORT.Opened: Boolean; begin Result := hCom <> INVALID_HANDLE_VALUE; end; procedure TPRT_COMPORT.SetBaudRate(const Value: Cardinal); begin FBaudRate := Value; if Opened then RebuildDCB; end; procedure TPRT_COMPORT.RebuildDCB; var DCB:TDCB; CTO:TCommTimeouts; begin if not Opened then exit; GetCommState(hCom, DCB); DCB.BaudRate := BaudRate; DCB.Parity := NOPARITY; DCB.Stopbits := ONESTOPBIT; DCB.Bytesize := 8; DCB.Flags := 0; SetCommState(hCom, DCB); GetCommTimeouts(hCom, CTO); CTO.ReadIntervalTimeout := MAXDWORD; CTO.ReadTotalTimeoutMultiplier := 0; CTO.ReadTotalTimeoutConstant := 0; SetCommTimeouts(hCom, CTO); end; //******************** begin of PRT interface function TPRT_COMPORT.Open:HRESULT; begin if Opened then Result:=E_UNEXPECTED else begin hCom := CreateFile(PCHAR(ComName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0); RxQue := 0; if Opened then Result:=S_OK else Result:=GetLastError(); RebuildDCB; EscapeCommFunction(hcom, SETDTR); EscapeCommFunction(hcom, SETRTS); PurgeComm(hCom,PURGE_RXCLEAR or PURGE_TXCLEAR); end; end; procedure TPRT_COMPORT.Close; begin if Opened then begin EscapeCommFunction(hcom, CLRRTS); EscapeCommFunction(hcom, CLRDTR); Windows.CloseHandle(hCom); hCom:=INVALID_HANDLE_VALUE; end; end; function TPRT_COMPORT.RxSize:Integer; begin if Opened then Result := RxQue else Result := -1; end; function TPRT_COMPORT.Rx(var Data; MaxSize:Integer):Integer; var N:Cardinal; begin if Opened then begin Windows.ReadFile(hCom,Data,MaxSize,N,nil); Result:=N; end else Result:=-1; end; procedure TPRT_COMPORT.Tx(const Data; DataSize:Integer); var N:Cardinal; begin Windows.WriteFile(hCom,Data,DataSize,N,nil); end; function TPRT_COMPORT.ProcessIO:Integer; var modemStat: Cardinal; begin Result:=0; if not Opened then exit; if CheckRLSD then begin if GetCommModemStatus(hCom, modemStat) and (modemStat and MS_RLSD_ON = 0) then exit else Result:=Result or IO_UP; end else Result:=Result or IO_UP; CheckQueues; if RxQue > 0 then Result:=Result or IO_RX; if TxQue <= 16 then begin Result:=Result or IO_TX; if TxQue=0 then Result:=Result or IO_TXEMPTY; end; end; //******************** end of PRT interface procedure TPRT_COMPORT.SetComName(const Value: String); begin FComName := Value; if Opened then begin Close; Open; end; end; procedure TPRT_COMPORT.CheckQueues; var ComStat: TComStat; Errors: DWORD; begin if ClearCommError(hCom, Errors, @ComStat) then begin TxQue:=ComStat.cbOutQue; RxQue:=ComStat.cbInQue; end else begin TxQue:=MaxInt; RxQue:=-1; end; end; end.
unit frmInIOCPFileServer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, fmIOCPSvrInfo, iocp_base, iocp_clients, iocp_server, iocp_sockets, iocp_managers, iocp_msgPacks; type TFormInIOCPFileServer = class(TForm) Memo1: TMemo; InIOCPServer1: TInIOCPServer; btnStart: TButton; btnStop: TButton; InClientManager1: TInClientManager; InFileManager1: TInFileManager; InMessageManager1: TInMessageManager; FrameIOCPSvrInfo1: TFrameIOCPSvrInfo; procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure InClientManager1Login(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure FormCreate(Sender: TObject); procedure InFileManager1BeforeDownload(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InFileManager1BeforeUpload(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InFileManager1QueryFiles(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InFileManager1AfterDownload(Sender: TObject; Params: TReceiveParams; Document: TIOCPDocument); procedure InFileManager1AfterUpload(Sender: TObject; Params: TReceiveParams; Document: TIOCPDocument); procedure InFileManager1DeleteFile(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InFileManager1RenameFile(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InFileManager1SetWorkDir(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InIOCPServer1AfterOpen(Sender: TObject); procedure InIOCPServer1AfterClose(Sender: TObject); private { Private declarations } FAppDir: String; public { Public declarations } end; var FormInIOCPFileServer: TFormInIOCPFileServer; implementation uses iocp_log, iocp_varis, iocp_utils; {$R *.dfm} procedure TFormInIOCPFileServer.btnStartClick(Sender: TObject); begin // 注:InFileManager1.ShareStream = True 可以共享下载文件流 Memo1.Lines.Clear; iocp_log.TLogThread.InitLog; // 开启日志 InIOCPServer1.Active := True; // 开启服务 FrameIOCPSvrInfo1.Start(InIOCPServer1); // 开始统计 end; procedure TFormInIOCPFileServer.btnStopClick(Sender: TObject); begin InIOCPServer1.Active := False; // 停止服务 FrameIOCPSvrInfo1.Stop; // 停止统计 iocp_log.TLogThread.StopLog; // 停止日志 end; procedure TFormInIOCPFileServer.FormCreate(Sender: TObject); begin // 准备工作路径 FAppDir := ExtractFilePath(Application.ExeName); // 客户端数据存放路径(2.0改名称) iocp_Varis.gUserDataPath := FAppDir + 'client_data\'; MyCreateDir(FAppDir + 'log'); // 建目录 MyCreateDir(FAppDir + 'temp'); // 建目录 // 建测试的用户路径 MyCreateDir(iocp_Varis.gUserDataPath); // 建目录 MyCreateDir(iocp_Varis.gUserDataPath + 'user_a'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_a\data'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_a\msg'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_a\temp'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b\data'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b\msg'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b\temp'); end; procedure TFormInIOCPFileServer.InClientManager1Login(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin if (Params.Password <> '') then begin Result.Role := crAdmin; // 测试广播要用的权限(2.0改) Result.ActResult := arOK; // 登记属性, 自动设置用户数据路径(注册时建) InClientManager1.Add(Params.Socket, crAdmin); // 有离线消息时要加入(如文件互传) end else Result.ActResult := arFail; end; procedure TFormInIOCPFileServer.InFileManager1AfterDownload(Sender: TObject; Params: TReceiveParams; Document: TIOCPDocument); begin memo1.Lines.Add('下载完毕:' + ExtractFileName(Document.FileName)); end; procedure TFormInIOCPFileServer.InFileManager1AfterUpload(Sender: TObject; Params: TReceiveParams; Document: TIOCPDocument); begin // 上传文件完毕 // Sender: TBusiWorker // Socket:TIOCPSocket // Document:TIOCPDocument // 有两种上传方式:atFileUpload、atFileSendTo // 如果 Document.UserName 不为空, // 则说明是互传文件,要通知对方下载或保存信息给对方登录时提取。 memo1.Lines.Add('上传完毕:' + ExtractFileName(Document.FileName)); // 新版调整推送方法,ToUser 可以是列表,直接调用即可: if (Params.ToUser <> '') then // 互传的文件,通知 ToUser 下载 InMessageManager1.PushMsg(Params, Params.ToUser); // 唤醒或保存到离线文件 end; procedure TFormInIOCPFileServer.InFileManager1BeforeDownload(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 下载文件(要使用相对路径) if (Params.Action = atFileDownChunk) then begin // 测试下载大文件 memo1.Lines.Add('准备下载(续传):' + 'F:\Backup\jdk-8u77-windows-i586.exe'); // F:\Backup\Ghost\WIN-7-20190228.GHO InFileManager1.OpenLocalFile(Result, 'F:\Backup\jdk-8u77-windows-i586.exe'); // F:\Backup\Ghost\WIN-7-20190228.GHO end else begin memo1.Lines.Add('准备下载:' + 'F:\Backup\jdk-8u77-windows-i586.exe'); // gUserDataPath + Params.FileName); InFileManager1.OpenLocalFile(Result, 'F:\Backup\jdk-8u77-windows-i586.exe'); end; end; procedure TFormInIOCPFileServer.InFileManager1BeforeUpload(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 上传文件(到用户数据路径) // 2.0 在内部自动判断文件是否存在,存在则换一个文件名 Memo1.Lines.Add('准备上传: ' + Params.FileName); // 如果免登录,可以使用这种方法接收: // Params.CreateAttachment('存放路径'); InFileManager1.CreateNewFile(Params); end; procedure TFormInIOCPFileServer.InFileManager1DeleteFile(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 请求删除文件,应在客户端先确认 if DeleteFile(Params.Socket.Envir^.WorkDir + Params.FileName) then Result.ActResult := arOK else Result.ActResult := arFail; end; procedure TFormInIOCPFileServer.InFileManager1QueryFiles(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 查询当前工作目录下的文件 InFileManager1.ListFiles(Params, Result); end; procedure TFormInIOCPFileServer.InFileManager1RenameFile(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 改工作目录下的文件名 if RenameFile(Params.Socket.Envir^.WorkDir + Params.FileName, Params.Socket.Envir^.WorkDir + Params.NewFileName) then Result.ActResult := arOK else Result.ActResult := arFail; end; procedure TFormInIOCPFileServer.InFileManager1SetWorkDir(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 设置工作目录(不能超出允许的工作目录范围) // if True then InFileManager1.SetWorkDir(Result, Params.Directory); // 2.0 改名 // else // Result.ActResult := arFail; end; procedure TFormInIOCPFileServer.InIOCPServer1AfterClose(Sender: TObject); begin btnStart.Enabled := not InIOCPServer1.Active; btnStop.Enabled := InIOCPServer1.Active; end; procedure TFormInIOCPFileServer.InIOCPServer1AfterOpen(Sender: TObject); begin btnStart.Enabled := not InIOCPServer1.Active; btnStop.Enabled := InIOCPServer1.Active; memo1.Lines.Add('IP:' + InIOCPServer1.ServerAddr); memo1.Lines.Add('Port:' + IntToStr(InIOCPServer1.ServerPort)); end; end.
unit uMainDataSet; interface uses System.Classes, Datasnap.DBClient; type TMainDataSet = class(TClientDataSet) procedure CheckBrowseMode; procedure CheckEditMode; public constructor Create(AOwner: TComponent); override; class procedure CopyDataSet(const aSourceMainDataSet: TMainDataSet; var aDestMainDataSet: TMainDataSet); procedure ReloadData; procedure DeleteAllRecords; end; implementation uses System.Variants, System.TypInfo, Data.DB, System.SysUtils; { TMainDataSet } procedure TMainDataSet.CheckBrowseMode; begin (*** It checks if is DataSet in edit or insert mode end then post data ***) if ((Self as TClientDataSet).State = dsEdit) or ((Self as TClientDataSet).State = dsInsert) then begin (Self as TClientDataSet).Post; end; end; procedure TMainDataSet.CheckEditMode; begin (*** It cheks if is DataSet in edit mode, if not then switch it ***) if ((Self as TClientDataSet).State <> dsEdit) then begin (Self as TClientDataSet).Edit; end; end; class procedure TMainDataSet.CopyDataSet(const aSourceMainDataSet: TMainDataSet; var aDestMainDataSet: TMainDataSet); var lNewMainDataSet: TMainDataSet; begin (*** Function return MainDataSet instance with structure of aSourceMainDataSet ***) lNewMainDataSet := TMainDataSet.Create(aSourceMainDataSet.Owner); lNewMainDataSet.CommandText := aSourceMainDataSet.CommandText; lNewMainDataSet.ProviderName := aSourceMainDataSet.ProviderName; lNewMainDataSet.Name := aSourceMainDataSet.Name + 'x'; lNewMainDataSet.Data := aSourceMainDataSet.Data; aDestMainDataSet := lNewMainDataSet; end; constructor TMainDataSet.Create(AOwner: TComponent); begin inherited; Self.Name := 'MainDataSet' + IntToStr(Random(1000000)); end; procedure TMainDataSet.DeleteAllRecords; begin (*** Delete all records from dataset ***) if (RecordCount < 1) or IsEmpty then Exit; First; while not Eof do begin Delete; end; end; procedure TMainDataSet.ReloadData; begin Self.Close; Self.Open; end; end.
unit LogDll; interface uses SocketComp; procedure Log(LogId, Info : string); procedure InitSocket(id : string; aSocket : TClientSocket); implementation uses Windows, SysUtils, FileCtrl, Classes, SyncObjs, Registry; const LogsKey = '\Software\Oceanus\Five\logs\'; var LogLock : TCriticalSection = nil; Logs : TStringList = nil; BasePath : string = ''; InitModule : boolean = true; CurDate : TDateTime = 0; DateStr : string = ''; function FindLogSocket(id : string) : TClientSocket; var idx : integer; begin id := lowercase(id); idx := Logs.Indexof(id); if idx <> -1 then result := TClientSocket(Logs.Objects[idx]) else result := nil; end; procedure InitLogs; var Reg : TRegistry; begin LogLock := TCriticalSection.Create; Logs := TStringList.Create; // Init BasePath Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(LogsKey, false) then begin BasePath := trim(Reg.ReadString('Path')); if (BasePath <> '') and (BasePath[length(BasePath)] <> '\') then BasePath := BasePath + '\'; end else BasePath := ExtractFilePath(paramstr(0)) + 'Logs\'; FileCtrl.ForceDirectories(BasePath); end; procedure InitModuleName; var fullPath : string; module : string; ext : string; begin fullPath := paramstr(0); module := ExtractFileName(fullPath); ext := ExtractFileExt(module); SetLength(module, length(module) - length(ext)); InitModule := false; BasePath := BasePath + UpperCase(module) + '\'; FileCtrl.ForceDirectories(BasePath); end; procedure InitDate; begin DateStr := FormatDateTime(' yy-mm-dd', Now); end; procedure DoneLogs; begin LogLock.Free; Logs.Free; end; procedure LogToFile( LogId, Info : string ); var filename : string; LogFile : Text; begin LogLock.Acquire; if InitModule then InitModuleName; if CurDate <> Date then InitDate; try filename := BasePath + LogId + DateStr + '.log'; AssignFile( LogFile, filename ); try Append( LogFile ); except Rewrite( LogFile ); end; try writeln( LogFile, Info ); finally CloseFile( LogFile ); end; finally LogLock.Release end; end; procedure Log( LogId, Info : string ); begin LogToFile(LogId, Info); end; { procedure Log( LogId, Info : string ); var Socket : TClientSocket; begin LogLock.Acquire; try Socket := FindLogSocket(LogId); if Socket <> nil then Socket.Socket.SendText(Info) else LogToFile(LogId, Info); finally LogLock.Release; end; end; } procedure InitSocket(id : string; aSocket : TClientSocket); begin end; { var idx : integer; begin LogLock.Acquire; try idx := Logs.IndexOf(lowercase(id)); if idx <> -1 then Logs.Delete(idx); if aSocket <> nil then Logs.AddObject(lowercase(id), aSocket); finally LogLock.Release; end; end; } initialization InitLogs; finalization //DoneLogs; end.
{ Subroutine SST_STRH_INFO (STR_H,FNAM,LNUM) * * Get the source file name and line number of the first character indicated * by the source string handle STR_H. FNAM is the returned file name, and LNUM * is the returned line number within that file. } module sst_STRH_INFO; define sst_strh_info; %include 'sst2.ins.pas'; procedure sst_strh_info ( {get info from handle to source string} in str_h: syo_string_t; {handle to source characters} in out fnam: univ string_var_arg_t; {name of source file for first char} out lnum: sys_int_machine_t); {source file line number of first char} begin sst_charh_info (str_h.first_char, fnam, lnum); end;
unit MultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProviderUnit; interface uses SysUtils, BaseOptimizationParametersProviderUnit, AddressUnit, RouteParametersUnit, OptimizationParametersUnit; type TMultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProvider = class(TBaseOptimizationParametersProvider) protected function MakeAddresses(): TArray<TAddress>; override; function MakeRouteParameters(): TRouteParameters; override; /// <summary> /// After response some fields are changed from request. /// </summary> procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); override; public end; implementation { TMultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProvider } uses DateUtils, EnumsUnit, UtilsUnit; procedure TMultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProvider.CorrectForResponse( OptimizationParameters: TOptimizationParameters); begin inherited; end; function TMultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProvider.MakeAddresses: TArray<TAddress>; var FirstAddress: TAddress; begin Result := TArray<TAddress>.Create(); FirstAddress := TAddress.Create( '3634 W Market St, Fairlawn, OH 44333', 41.135762259364, -81.629313826561, 300); //indicate that this is a departure stop // single depot routes can only have one departure depot FirstAddress.IsDepot := True; //together these two specify the time window of a destination //seconds offset relative to the route start time for the open availability of a destination FirstAddress.TimeWindowStart := 28800; //seconds offset relative to the route end time for the open availability of a destination FirstAddress.TimeWindowEnd := 29465; AddAddress(FirstAddress, Result); AddAddress(TAddress.Create('1218 Ruth Ave, Cuyahoga Falls, OH 44221', 41.143505096435, -81.46549987793, 300, 29465, 30529), Result); AddAddress(TAddress.Create('512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 30529, 33479), Result); AddAddress(TAddress.Create('512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 33479, 33944), Result); AddAddress(TAddress.Create('3495 Purdue St, Cuyahoga Falls, OH 44221', 41.162971496582, -81.479049682617, 300, 33944, 34801), Result); AddAddress(TAddress.Create('1659 Hibbard Dr, Stow, OH 44224', 41.194505989552, -81.443351581693, 300, 34801, 36366), Result); AddAddress(TAddress.Create('2705 N River Rd, Stow, OH 44224', 41.145240783691, -81.410247802734, 300, 36366, 39173), Result); AddAddress(TAddress.Create('10159 Bissell Dr, Twinsburg, OH 44087', 41.340042114258, -81.421226501465, 300, 39173, 41617), Result); AddAddress(TAddress.Create('367 Cathy Dr, Munroe Falls, OH 44262', 41.148578643799, -81.429229736328, 300, 41617, 43660), Result); AddAddress(TAddress.Create('367 Cathy Dr, Munroe Falls, OH 44262', 41.148579, -81.42923, 300, 43660, 46392), Result); AddAddress(TAddress.Create('512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 46392, 48089), Result); AddAddress(TAddress.Create('559 W Aurora Rd, Northfield, OH 44067', 41.315116882324, -81.558746337891, 300, 48089, 48449), Result); AddAddress(TAddress.Create('3933 Klein Ave, Stow, OH 44224', 41.169467926025, -81.429420471191, 300, 48449, 50152), Result); AddAddress(TAddress.Create('2148 8th St, Cuyahoga Falls, OH 44221', 41.136692047119, -81.493492126465, 300, 50152, 51682), Result); AddAddress(TAddress.Create('3731 Osage St, Stow, OH 44224', 41.161357879639, -81.42293548584, 300, 51682, 54379), Result); AddAddress(TAddress.Create('3862 Klein Ave, Stow, OH 44224', 41.167895123363, -81.429973393679, 300, 54379, 54879), Result); AddAddress(TAddress.Create('138 Northwood Ln, Tallmadge, OH 44278', 41.085464134812, -81.447411775589, 300, 54879, 56613), Result); AddAddress(TAddress.Create('3401 Saratoga Blvd, Stow, OH 44224', 41.148849487305, -81.407363891602, 300, 56613, 57052), Result); AddAddress(TAddress.Create('5169 Brockton Dr, Stow, OH 44224', 41.195003509521, -81.392700195312, 300, 57052, 59004), Result); AddAddress(TAddress.Create('5169 Brockton Dr, Stow, OH 44224', 41.195003509521, -81.392700195312, 300, 59004, 60027), Result); AddAddress(TAddress.Create('458 Aintree Dr, Munroe Falls, OH 44262', 41.1266746521, -81.445808410645, 300, 60027, 60375), Result); AddAddress(TAddress.Create('512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 60375, 63891), Result); AddAddress(TAddress.Create('2299 Tyre Dr, Hudson, OH 44236', 41.250511169434, -81.420433044434, 300, 63891, 65277), Result); AddAddress(TAddress.Create('2148 8th St, Cuyahoga Falls, OH 44221', 41.136692047119, -81.493492126465, 300, 65277, 68545), Result); end; function TMultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProvider.MakeRouteParameters: TRouteParameters; begin Result := TRouteParameters.Create(); // specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers Result.AlgorithmType := TAlgorithmType.CVRP_TW_MD; Result.StoreRoute := False; // set an arbitrary route name // this value shows up in the website, and all the connected mobile device Result.RouteName := 'Multiple Depot, Multiple Driver with 24 Stops, Time Window'; // the route start date in UTC, unix timestamp seconds (Tomorrow) Result.RouteDate := 53583232; //TUtils.ConvertToUnixTimestamp(IncDay(Now, 1)); // the time in UTC when a route is starting (7AM) Result.RouteTime := 60 * 60 * 7; // the maximum duration of a route Result.RouteMaxDuration := 86400; Result.VehicleCapacity := '1'; Result.VehicleMaxDistanceMI := '10000'; Result.Optimize := TOptimize.Distance; Result.DistanceUnit := TDistanceUnit.MI; Result.DeviceType := TDeviceType.Web; Result.TravelMode := TTravelMode.Driving; Result.Metric := TMetric.Geodesic; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clCryptRandom; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$ELSE} System.Classes, {$ENDIF} clUtils, clCryptUtils, clConfig, clCryptAPI, clWUtils; type TclRandom = class(TclConfigObject) public procedure Fill(var ABuffer: TclByteArray; AStart, ALen: Integer); virtual; abstract; end; TclCryptApiRandom = class(TclRandom) private FContext: HCRYPTPROV; function GenContext: HCRYPTPROV; public constructor Create; override; destructor Destroy; override; procedure Fill(var ABuffer: TclByteArray; AStart, ALen: Integer); override; end; function GenerateRandomData(ASize: Integer): TclByteArray; overload; function GenerateRandomData(ASize: Integer; const ACSP: string; AProviderType: Integer): TclByteArray; overload; procedure GenerateRandomData(AData: TclCryptData; ASize: Integer); overload; procedure GenerateRandomData(AData: TclCryptData; ASize: Integer; const ACSP: string; AProviderType: Integer); overload; implementation function GenerateRandomData(ASize: Integer): TclByteArray; begin Result := GenerateRandomData(ASize, '', 0); end; function GenerateRandomData(ASize: Integer; const ACSP: string; AProviderType: Integer): TclByteArray; var data: TclCryptData; begin data := TclCryptData.Create(ASize); try GenerateRandomData(data, ASize, ACSP, AProviderType); Result := data.ToBytes(); finally data.Free(); end; end; procedure GenerateRandomData(AData: TclCryptData; ASize: Integer); begin GenerateRandomData(AData, ASize, '', 0); end; procedure GenerateRandomData(AData: TclCryptData; ASize: Integer; const ACSP: string; AProviderType: Integer); var context: HCRYPTPROV; pCSP: PclChar; provType: Integer; begin if (AData.DataSize <> ASize) then begin AData.Allocate(ASize); end; if (ACSP <> '') then begin pCSP := PclChar(GetTclString(ACSP)); provType := AProviderType; end else begin pCSP := DefaultProvider; provType := DefaultProviderType; end; if not CryptAcquireContext(@context, nil, pCSP, provType, CRYPT_VERIFYCONTEXT) then begin RaiseCryptError('CryptAcquireContext'); end; try if not CryptGenRandom(context, AData.DataSize, AData.Data) then begin RaiseCryptError('CryptGenRandom'); end; finally if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; { TclCryptApiRandom } constructor TclCryptApiRandom.Create; begin inherited Create(); FContext := nil; end; destructor TclCryptApiRandom.Destroy; begin if (FContext <> nil) then begin CryptReleaseContext(FContext, 0); end; inherited Destroy(); end; procedure TclCryptApiRandom.Fill(var ABuffer: TclByteArray; AStart, ALen: Integer); var p: Pointer; begin p := Pointer(TclIntPtr(ABuffer) + SizeOf(Byte) * AStart); if not CryptGenRandom(GenContext(), ALen, p) then begin RaiseCryptError('CryptGenRandom'); end; end; function TclCryptApiRandom.GenContext: HCRYPTPROV; begin if (FContext = nil) then begin if not CryptAcquireContext(@FContext, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) then //TODO replace all CryptAcquireContext and use the same CSP begin RaiseCryptError('CryptAcquireContext'); end; end; Result := FContext; end; end.
unit KM_CommonTypes; interface type TKMByteSet = set of Byte; TByteSet = set of Byte; //Legasy support for old scripts TBooleanArray = array of Boolean; TBoolean2Array = array of array of Boolean; TKMByteArray = array of Byte; TKMByte2Array = array of TKMByteArray; TKMByteSetArray = array of TKMByteSet; PKMByte2Array = ^TKMByte2Array; TKMWordArray = array of Word; TKMWord2Array = array of array of Word; PKMWordArray = ^TKMWordArray; TKMCardinalArray = array of Cardinal; PKMCardinalArray = ^TKMCardinalArray; TSmallIntArray = array of SmallInt; TIntegerArray = array of Integer; TInteger2Array = array of array of Integer; TAnsiStringArray = array of AnsiString; TSingleArray = array of Single; TSingle2Array = array of array of Single; TStringArray = array of string; TKMCharArray = array of Char; TRGBArray = array of record R,G,B: Byte end; TKMStaticByteArray = array [0..MaxInt - 1] of Byte; PKMStaticByteArray = ^TKMStaticByteArray; TEvent = procedure of object; TPointEvent = procedure (Sender: TObject; const X,Y: Integer) of object; TPointEventSimple = procedure (const X,Y: Integer) of object; TPointEventFunc = function (Sender: TObject; const X,Y: Integer): Boolean of object; TBooleanEvent = procedure (aValue: Boolean) of object; TBooleanObjEvent = procedure (Sender: TObject; aValue: Boolean) of object; TIntegerEvent = procedure (aValue: Integer) of object; TIntBoolEvent = procedure (aIntValue: Integer; aBoolValue: Boolean) of object; TObjectIntegerEvent = procedure (Sender: TObject; X: Integer) of object; TSingleEvent = procedure (aValue: Single) of object; TAnsiStringEvent = procedure (const aData: AnsiString) of object; TUnicodeStringEvent = procedure (const aData: UnicodeString) of object; TUnicodeStringWDefEvent = procedure (const aData: UnicodeString = '') of object; TUnicodeStringEventProc = procedure (const aData: UnicodeString); TUnicode2StringEventProc = procedure (const aData1, aData2: UnicodeString); TUnicodeStringObjEvent = procedure (Obj: TObject; const aData: UnicodeString) of object; TUnicodeStringObjEventProc = procedure (Sender: TObject; const aData: UnicodeString); TUnicodeStringBoolEvent = procedure (const aData: UnicodeString; aBool: Boolean) of object; TGameStartEvent = procedure (const aData: UnicodeString; Spectating: Boolean) of object; TResyncEvent = procedure (aSender: ShortInt; aTick: cardinal) of object; TIntegerStringEvent = procedure (aValue: Integer; const aText: UnicodeString) of object; TBooleanFunc = function(Obj: TObject): Boolean of object; TBooleanWordFunc = function (aValue: Word): Boolean of object; TBooleanStringFunc = function (aValue: String): Boolean of object; TBooleanFuncSimple = function: Boolean of object; TBoolIntFuncSimple = function (aValue: Integer): Boolean of object; TObjectIntBoolEvent = procedure (Sender: TObject; aIntValue: Integer; aBoolValue: Boolean) of object; {$IFDEF WDC} TAnonProc = reference to procedure; TAnonBooleanFn = reference to function: Boolean; {$ENDIF} TKMAnimLoop = packed record Step: array [1 .. 30] of SmallInt; Count: SmallInt; MoveX, MoveY: Integer; end; //Message kind determines icon and available actions for Message TKMMessageKind = ( mkText, //Mission text message mkHouse, mkUnit, mkQuill //Utility message (warnings in script loading) ); TWonOrLost = (wolNone, wolWon, wolLost); TKMCustomScriptParam = (cspTHTroopCosts, cspMarketGoldPrice); TKMCustomScriptParamData = record Added: Boolean; Data: UnicodeString; end; TKMAIType = (aitNone, aitClassic, aitAdvanced); TKMAITypeSet = set of TKMAIType; TKMUserActionType = (uatNone, uatKeyDown, uatKeyUp, uatKeyPress, uatMouseDown, uatMouseUp, uatMouseMove, uatMouseWheel); TKMUserActionEvent = procedure (aActionType: TKMUserActionType) of object; TKMCustomScriptParamDataArray = array [TKMCustomScriptParam] of TKMCustomScriptParamData; TKMPlayerColorMode = (pcmNone, pcmColors, pcmAllyEnemy, pcmTeams); const WonOrLostText: array [TWonOrLost] of UnicodeString = ('None', 'Won', 'Lost'); implementation end.
unit FiveTypes; interface uses Controls, Graphics, Protocol, GameTypes; // Accidents type PLandAccidentInfo = ^TLandAccidentInfo; TLandAccidentInfo = record vclass : integer; img : TGameImage; end; // Extended selections type TFiveObjKind = (okBuilding, okRoad, okRailroad, okNone); type TFiveObjInfo = record r, c: integer; case Kind : TFiveObjKind of okBuilding : (company, classid : word); okRoad : (); okRailroad : (); end; type TOnObjectClickedRetCode = (ocGoOn, ocDone, ocAbort); type TOnMouseOnObjectRetCode = (mooCanSelect, mooCannotSelect ); type TSelectionId = integer; type TOnObjectClicked = function (SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnObjectClickedRetCode of object; TOnMouseOnObject = function (SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnMouseOnObjectRetCode of object; type PSelectionKind = ^TSelectionKind; TSelectionKind = record Id : TSelectionId; Cursor : TCursor; OnMouseOnObject : TOnMouseOnObject; OnObjectClicked : TOnObjectClicked; end; // Area selections type TAreaExclusion = (axWater, axConcrete, axRoad, axRailroad, axBuilding); TAreaExclusions = set of TAreaExclusion; // Options type TSoundsPanning = (spNormal, spInverted); implementation end.
unit Demo; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses Classes, SysUtils, tfBytes; procedure RunDemo; implementation procedure RunDemo; var A1, A2, A3: ByteArray; P: PByte; I, L: Integer; Sum: Integer; B: Byte; begin // initialization examples A1:= ByteArray(1); A2:= ByteArray.FromBytes([2, 3, 4]); { also possible A2:= ByteArray.Allocate(3); A2[0]:= 2; A2[1]:= 3; A2[2]:= 4; or else (Delphi only; FPC 2.6 does not support array constructors): A2:= TBytes.Create(2, 3, 4); } Writeln('A1 = ', A1.ToString, '; Hash: ', IntToHex(A1.HashCode, 8), '; Len: ', A1.Len); Writeln('A2 = ', A2.ToString, '; Hash: ', IntToHex(A2.HashCode, 8), '; Len: ', A2.Len); // concatenation A3:= A1 + A2; Writeln('A3 = A1 + A2 = ', A3.ToString); // indexed access to array elements: Sum:= 0; for I:= 0 to A3.Len - 1 do begin Inc(Sum, A3[I]); end; Writeln('Sum of elements = ', Sum); // for .. in iteration: Sum:= 0; for B in A3 do begin Inc(Sum, B); end; Writeln('Sum of elements = ', Sum); // fast access to array elements: P:= A3.RawData; L:= A3.Len; Sum:= 0; while (L > 0) do begin Inc(Sum, P^); Inc(P); Dec(L); end; Writeln('Sum of elements = ', Sum); // bitwise 'xor': Writeln('A2 xor A3 = ', (A2 xor A3).ToString); // fluent coding Writeln(ByteArray.FromText('ABCDEFGHIJ').Insert(3, ByteArray.FromText(' 123 ')).Reverse.ToText); end; end.
unit Location; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Sensors, System.Sensors.Components, FMX.TabControl, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.WebBrowser, FMX.Memo; type TForm1 = class(TForm) TabControl1: TTabControl; Layout1: TLayout; Switch1: TSwitch; TabItem1: TTabItem; TabItem2: TTabItem; LocationSensor1: TLocationSensor; ListBox1: TListBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; AniIndicator1: TAniIndicator; WebBrowser1: TWebBrowser; Memo1: TMemo; TabItem3: TTabItem; ListBoxItem3: TListBoxItem; ListBoxItem4: TListBoxItem; ListBoxItem5: TListBoxItem; procedure Switch1Switch(Sender: TObject); procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); procedure TabControl1Change(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } NewLocation: TLocationCoord2D; Geocoder1: TGeocoder; procedure GeocodeReverseDone(const Address: TCivicAddress); public { Public declarations } end; var Form1: TForm1; implementation uses TypInfo; {$R *.fmx} procedure TForm1.FormCreate(Sender: TObject); begin NewLocation := TLocationCoord2D.Create(38.158176,-2.738167); end; procedure TForm1.GeocodeReverseDone(const Address: TCivicAddress); type StringArray = array of String; var titles, values: StringArray; newData: String; idx: Integer; begin with Address do Memo1.Text := 'AdminArea: ' + AdminArea + #13#10 + 'CountryCode: ' + CountryCode + #13#10 + 'CountryName: ' + CountryName + #13#10 + 'FeatureName: ' + FeatureName + #13#10 + 'Locality: ' + Locality + #13#10 + 'PostalCode: ' + PostalCode + #13#10 + 'SubAdminArea: ' + SubAdminArea + #13#10 + 'SubLocality: ' + SubLocality + #13#10 + 'SubThoroughfare: ' + SubThoroughfare + #13#10 + 'Thoroughfare: ' + Thoroughfare; end; procedure TForm1.LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); var aURL: String; begin Self.NewLocation := NewLocation; ListBoxItem1.ItemData.Detail := Format('%5.4f', [NewLocation.Latitude]); ListBoxItem2.ItemData.Detail := Format('%5.4f', [NewLocation.Longitude]); if Assigned(LocationSensor1.Sensor) then with LocationSensor1.Sensor do begin ListBoxItem3.ItemData.Detail := Format('%5.4f', [Altitude]); ListBoxItem4.ItemData.Detail := Format('%5.4f', [TrueHeading]); ListBoxItem5.ItemData.Detail := Format('%5.4f', [Speed]); end; aURL := 'http://bing.com/maps/default.aspx?cp=' + ListBoxItem1.ItemData.Detail + '~' + ListBoxItem2.ItemData.Detail + '&lvl=15'; WebBrowser1.Navigate(aURL); AniIndicator1.Visible := False; end; procedure TForm1.Switch1Switch(Sender: TObject); begin LocationSensor1.Active := Switch1.IsChecked; AniIndicator1.Enabled := Switch1.IsChecked; end; procedure TForm1.TabControl1Change(Sender: TObject); function GeocoderAvailable: Boolean; begin if not Assigned(Geocoder1) then begin if Assigned(TGeocoder.Current) then Geocoder1 := TGeocoder.Current.Create; if Assigned(Geocoder1) then Geocoder1.OnGeocodeReverse := GeocodeReverseDone; end; Result := Assigned(Geocoder1); end; begin if TabControl1.ActiveTab = TabItem3 then if GeocoderAvailable and not Geocoder1.Geocoding then Geocoder1.GeocodeReverse(NewLocation); end; end.
unit Image_on_demand; interface uses windows,classes,streaming_class_lib, syncObjs, pngImage, command_class_lib,graphics, IGraphicObject_commands, ExtCtrls, Types, pngimageAdvanced; type TLogProc = procedure (text: string); TGetImageProc = function: TExtendedPngObject of object; IGetPngThread = interface ['{3726C791-0100-44DA-8D5A-E900A4EB6A62}'] function GetImage: TExtendedPngObject; procedure SetImage(value: TExtendedPngObject); //в основном потоке, без особенностей procedure Halt; end; IGetPngScale = interface (IGetPngThread) ['{6DC20893-9FC9-4FFB-8864-69D7D4064831}'] function GetScale: Real; end; TAbstractGetImageThread = class (TThread, IGetPngThread) private fRefCount: Integer; fEvent: TEvent; fBitmap: TExtendedPngObject; fExceptionHandled: boolean; protected function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public procedure Halt; constructor Create; virtual; destructor Destroy; override; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function GetImage: TExtendedPngObject; procedure SetImage(value: TExtendedPngObject); end; TLoadBitmapThread = class (TAbstractGetImageThread, IGetPngThread) //будет отвечать за картинку головой! private fFilename: string; protected procedure Execute; override; public constructor Create(aOnTerminate: TNotifyEvent;filename: string=''); reintroduce; overload; end; TScalingThread = class (TAbstractGetImageThread, IGetPngThread, IGetPngScale) private fGetImageIntf: IGetPngThread; //ссылка на оригинальную картинку fScale: Real; protected procedure Execute; override; public constructor Create(aGetImageIntf: IGetPngThread; ascale: Real); reintroduce; overload; procedure UpdateRect(aRect: TRect); virtual; function GetScale: Real; end; T2to3ScalingThread = class (TScalingThread,IGetPngThread,IGetPngScale) protected procedure Execute; override; public procedure UpdateRect(aRect: TRect); override; end; TBrushShape = (bsSquare,bsRound); TRasterImageDocument = class (TDocumentWithImage, IConstantComponentName) private fScaleNumber: Integer; fPrimaryColor: TColor; fSecondaryColor: TColor; fBrushSize: Integer; fBrushShape: TBrushShape; fLoadThread: IGetPngThread; fScalingThreads: array of IGetPngScale; fScaleLevelsReadyEvent: TEvent; fSizesChanged: Boolean; procedure LoadThreadTerminate(Sender: TObject); procedure WaitScaleLevelsReady; function GetBtmp: TExtendedPngObject; procedure SetBtmp(value: TExtendedPngObject); public PercentDone: Integer; //инкапсуляция ни к черту Image: TImage; ChangeRect: TRect; //0,0,0,0 озн. пустую область onSavingProgress: TSavingProgressReport; procedure AddToChangeRect(const A: TRect); procedure SizesChanged; constructor Create(aOwner: TComponent); override; constructor CreateFromImageFile(aFileName: string); constructor LoadFromFile(const aFilename: string); override; destructor Destroy; override; function Get_Image: TImage; override; function Get_Scaled_Btmp: TExtendedPNGObject; function Get_Scale: real; override; procedure SaveAndFree; //имя файла уже задано в документе procedure FreeWithoutSaving; procedure SaveToFile(const filename: string); override; procedure Change; override; procedure ZoomIn; procedure ZoomOut; published property Btmp: TExtendedPNGObject read GetBtmp write SetBtmp stored false; property Scale: Real read Get_Scale stored false; property PrimaryColor: TColor read fPrimaryColor write fPrimaryColor; property SecondaryColor: TColor read fSecondaryColor write fSecondaryColor; property BrushSize: Integer read fBrushSize write fBrushSize; property BrushShape: TBrushShape read fBrushShape write fBrushShape; property ScaleNumber: integer read fScaleNumber write fScaleNumber; end; TDocumentsSavingProgress = class (TObject) private fAllDocsClearEvent: TEvent; //возвращаемся к истокам - работало неплохо fPrefetchedDoc: TRasterImageDocument; procedure ThreadTerminate(Sender: TObject); procedure WaitForAllDocsClearEvent; public fDocumentsSaving: TThreadList; onSaveThreadTerminate: TNotifyEvent; Log: TLogProc; constructor Create; destructor Destroy; override; function LoadDocFromFile(filename: string): TAbstractDocument; procedure PrefetchDocument(doc: TRasterImageDocument); //пусть загрузит на всякий случай function Count: Integer; //debug function AsText: string; //debug end; TSaveDocThread = class (TThread) private fPercentDone: Integer; //а как результат для GetProgress //вполне подходит Terminated procedure CallProgress; function GetProgressFromThread(Sender: TObject; PercentDone: Integer): boolean; protected procedure Execute; override; procedure DoTerminate; override; //вызывается из Thread'a и должна выкинуть поток //из списка, после чего мирно удалиться public fDoc: TRasterImageDocument; constructor Create(doc: TRasterImageDocument); end; procedure CoverRect(var Orig: TRect;const newRect: TRect); //почти как UnionRect, но более специализированная var DocumentsSavingProgress: TDocumentsSavingProgress; //для TRasterImageDocument implementation uses SysUtils,strUtils,math,typinfo,forms; procedure CoverRect(var Orig: TRect; const newRect: TRect); begin if IsRectEmpty(Orig) then Orig:=newRect else if not IsRectEmpty(newRect) then begin Orig.Left:=min(Orig.Left,newRect.Left); Orig.Right:=max(Orig.Right,newRect.Right); Orig.Top:=min(Orig.Top,newRect.Top); Orig.Bottom:=max(Orig.Bottom,newRect.Bottom); end; end; (* TAbstractGetImageThread *) (* этот объект является "владельцем" изображения, которое должен получить либо из файла, либо обработав какой-то другой объект, поддерживающий интерфейс IGetPngThread. Если мы обратимся к этому объекту, пока изображение еще не загружено, выполнение приостановится до тех пор, пока - загрузится изображение, мы получим его и продолжим работу - будет выполнен метод Terminate, объект возратит nil и уничтожится при первой возможности *) function TAbstractGetImageThread._AddRef: Integer; begin Result := InterlockedIncrement(FRefCount); end; function TAbstractGetImageThread._Release: Integer; begin Result := InterlockedDecrement(FRefCount); if Result = 0 then Destroy; end; function TAbstractGetImageThread.QueryInterface(const IID: TGUID; out obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; constructor TAbstractGetImageThread.Create; begin inherited Create(true); fEvent:=TEvent.Create(nil,true,false,''); end; destructor TAbstractGetImageThread.Destroy; begin //должен запуститься лишь тогда, когда никто не указывает на нас, поэтому //все просто. WaitFor; fBitmap.Free; fEvent.Free; inherited; end; procedure TAbstractGetImageThread.Halt; begin Terminate; fEvent.SetEvent; end; function TAbstractGetImageThread.GetImage: TExtendedPngObject; begin case fEvent.WaitFor(20000) of wrTimeout: raise Exception.Create('GetImage.fEvent timeout'); wrError: raise Exception.Create('GetImage.fEvent error'); wrAbandoned: raise Exception.Create('GetImage.fEvent abandoned'); end; if (FatalException=nil) or fExceptionHandled then if Terminated then Result:=nil else Result:=fBitmap else begin fExceptionHandled:=true; Raise Exception.Create(Exception(FatalException).Message); end; end; procedure TAbstractGetImageThread.SetImage(value: TExtendedPngObject); begin GetImage.Free; fBitmap:=value; end; (* TLoadBitmapThread *) (* Загружает картинку из файла *) constructor TLoadBitmapThread.Create(aOnTerminate: TNotifyEvent; filename: string=''); begin inherited Create; //TAbstractGetImageThread.Create OnTerminate:=aOnTerminate; fFileName:=filename; //priority:=tpNormal; FreeOnTerminate:=false; fBitmap:=TExtendedPngObject.Create; Resume; end; procedure TLoadBitmapThread.Execute; var ext: string; pic: TPicture; begin try if fFileName<>'' then begin ext:=Uppercase(ExtractFileExt(fFileName)); if ext='.PNG' then fBitmap.LoadFromFile(fFileName) else begin pic:=TPicture.Create; try pic.LoadFromFile(fFileName); if pic.Graphic is TBitmap then fBitmap.Assign(TBitmap(pic.Graphic)) else fBitmap.Canvas.Draw(0,0,pic.Graphic); finally pic.Free; end; end; end; finally fEvent.SetEvent; end; end; (* TScalingThread *) constructor TScalingThread.Create(aGetImageIntf: IGetPngThread; aScale: Real); begin inherited Create; fGetImageIntf:=aGetImageIntf; fScale:=aScale; //priority:=tpNormal; FreeOnTerminate:=false; Resume; end; procedure TScalingThread.Execute; var img: TExtendedPNGObject; begin //чувствуется, придется самостоятельно реализовывать масштабирование img:=fGetImageIntf.GetImage; //возможно ожидание, когда нам дадут, наконец, картинку if Assigned(img) and not Terminated then fBitmap:=img.Get2TimesDownScaled; fEvent.SetEvent; end; procedure T2to3ScalingThread.Execute; var img: TExtendedPNGObject; begin img:=fGetImageIntf.GetImage; if Assigned(img) and not Terminated then fBitmap:=img.Get2To3DownScaled; fEvent.SetEvent; end; procedure TScalingThread.UpdateRect(aRect: TRect); begin fGetImageIntf.GetImage.DownScale2TimesInto(aRect,fBitmap); end; procedure T2to3ScalingThread.UpdateRect(aRect: TRect); begin fGetImageIntf.GetImage.DownScale2To3Into(aRect,fBitmap); end; function TScalingThread.GetScale: Real; begin Result:=fScale; end; (* TSaveDocThread *) constructor TSaveDocThread.Create(doc: TRasterImageDocument); begin inherited Create(true); fDoc:=doc; DocumentsSavingProgress.fAllDocsClearEvent.ResetEvent; Assert(Assigned(fDoc)); //сначала предупредим всех, что мы сохраняемся DocumentsSavingProgress.fDocumentsSaving.Add(fDoc); onTerminate:=documentsSavingProgress.ThreadTerminate; FreeOnTerminate:=true; Priority:=tpLower; Resume; end; function TSaveDocThread.GetProgressFromThread(Sender: TObject; PercentDone: Integer): Boolean; begin //перевалочный пункт между потоками - протискиваемся сквозь synchronize fPercentDone:=PercentDone; Synchronize(CallProgress); Result:=not Terminated; end; procedure TSaveDocThread.CallProgress; begin if assigned(fDoc.onSavingProgress) then if not fDoc.onSavingProgress(self,fPercentDone) then Terminate; end; procedure TSaveDocThread.Execute; var INeedAVacation: Boolean; i: Integer; begin Assert(Assigned(fDoc)); fDoc.Btmp.onSavingProgress:=GetProgressFromThread; fDoc.CriticalSection.Acquire; try SafeSaveToFile(fDoc.SaveToFile,fDoc.FileName); // fDoc.SaveToFile(fDoc.FileName); //весьма вероятна ошибка (файл используется и др) finally fDoc.CriticalSection.Release; end; //при возникновении искл. ситуации документ остаётся висеть в списке - пользователь //должен либо перезапустить поток сохранения (retry) //либо отменить сохранение //если мы в списке, значит, пора уходить, а вот если нет, значит народ уже передумал try with DocumentsSavingProgress.fDocumentsSaving.LockList do begin i:=IndexOf(fDoc); INeedAVacation:=(i>=0); if INeedAVacation then Delete(i); end; finally DocumentsSavingProgress.fDocumentsSaving.UnlockList; end; if INeedAVacation then fDoc.Release; end; procedure TSaveDocThread.DoTerminate; var INeedAVacation: Boolean; begin try with DocumentsSavingProgress.fDocumentsSaving.LockList do INeedAVacation:=(Count=0); finally DocumentsSavingProgress.fDocumentsSaving.UnlockList; end; if INeedAVacation then DocumentsSavingProgress.fAllDocsClearEvent.SetEvent; inherited; //вызов onTerminate //если осн. поток застрял на AllDocsClearEvent.WaitFor, то мы застрянем здесь же //пока последний из могикан наконец не создаст это событие //похоже, что onTerminate при этом не будут обработаны, поскольку уже началось //уничтожение формы. //но это даже хорошо, хотя FastMM4 выругается. end; (* TDocumentsSavingProgress *) constructor TDocumentsSavingProgress.Create; begin fDocumentsSaving:=TThreadList.Create; fDocumentsSaving.Duplicates:=dupIgnore; // fDocumentsSaving.Duplicates:=dupError; fAllDocsClearEvent:=TEvent.Create(nil,false,true,''); //не хотим имени, чтобы //одновременно запущенные 2 проги не "сцепились" end; procedure TDocumentsSavingProgress.ThreadTerminate(Sender: TObject); begin if Assigned(onSaveThreadTerminate) then onSaveThreadTerminate(Sender); end; procedure TDocumentsSavingProgress.WaitForAllDocsClearEvent; var i: Integer; begin i:=0; while i<120 do begin case fAllDocsClearEvent.WaitFor(500) of wrSignaled: Exit; wrError: raise Exception.Create('WaitForAllDocsClearEvent error'); wrAbandoned: raise Exception.Create('WaitForAllDocsClearEvent abandoned'); end; CheckSynchronize(500); inc(i); end; raise Exception.Create('WaitForAllDocsClearEvent timeout'); end; destructor TDocumentsSavingProgress.Destroy; //var i: Integer; begin if Assigned(fPrefetchedDoc) then fPrefetchedDoc.SaveAndFree; // fPrefetchedDoc.Release; try log('wait for all docs saved and cleared'); log('number of docs: ' + IntToStr(Count)); log(AsText); WaitForAllDocsClearEvent; finally fAllDocsClearEvent.Free; fDocumentsSaving.Free; inherited Destroy; end; end; function TDocumentsSavingProgress.LoadDocFromFile(filename: string): TAbstractDocument; var i: Integer; doc: TAbstractDocument; begin Result:=nil; if Assigned(fPrefetchedDoc) and (fPrefetchedDoc.FileName=filename) then begin Result:=fPrefetchedDoc; fPrefetchedDoc:=nil; end; try with fDocumentsSaving.LockList do for i:=0 to Count-1 do begin doc:=TAbstractDocument(Items[i]); if doc.FileName=filename then begin //этот проект у нас сохраняется - надо ему "сказать", чтобы не спешил освобождать //память, а ссылку можем сразу дать, внут. крит. секция не позволит изменить док. //пока он не сохранится в нынешнем виде Result:=doc; //удалим его из списка "на сохранение и удаление" - он поймет Delete(i); break; end; end; finally fDocumentsSaving.UnlockList; end; end; procedure TDocumentsSavingProgress.PrefetchDocument(doc: TRasterImageDocument); begin // FreeAndNil(fPrefetchThread); //если уже загружется другой документ - мы передумали if Assigned(fPrefetchedDoc) then begin //debug log('releasing prefetched '+ExtractFileName(fPrefetchedDoc.FileName)+'; addr='+IntToHex(Integer(fPrefetchedDoc),8)); fPrefetchedDoc.SaveAndFree; end; // fPrefetchedDoc.SaveAndFree; //потихоньку уничтожается, в т.ч из списка уйти должна fPrefetchedDoc:=doc; if Assigned(doc) then begin log('prefetched doc: '+ExtractFileName(fPrefetchedDoc.FileName)+'; addr='+IntToHex(Integer(fPrefetchedDoc),8)); //документ загр. сразу, а вот картинку он тянет фоновым потоком log('list count: '+IntToStr(count)); log('list of docs in progress (saving and destroying):'); log(AsText); end; end; function TDocumentsSavingProgress.Count: Integer; begin with fDocumentsSaving.LockList do Result:=Count; fDocumentsSaving.UnlockList; end; function TDocumentsSavingProgress.AsText: string; var i: Integer; begin with fDocumentsSaving.LockList do begin for i:=0 to Count-1 do Result:=Result+IntToHex(Integer(Items[i]),8)+': '+TRasterImageDocument(Items[i]).FileName+#13+#10; end; fDocumentsSaving.UnlockList; end; (* TRasterImageDocument *) constructor TRasterImageDocument.Create(aOwner: TComponent); begin inherited Create(aOwner); fLoadThread:=TLoadBitmapThread.Create(LoadThreadTerminate); BrushSize:=10; PrimaryColor:=clWhite; fScaleLevelsReadyEvent:=TEvent.Create(nil,true,false,''); end; constructor TRasterImageDocument.CreateFromImageFile(aFileName: string); begin Create(nil); fLoadThread.Halt; fLoadThread:=TLoadBitmapThread.Create(LoadThreadTerminate,aFileName); end; constructor TRasterImageDocument.LoadFromFile(const aFilename: string); var s: string; begin inherited LoadFromFile(aFilename); s:=ExtractFilePath(aFilename); s:=LeftStr(s,Length(s)-5); //выкинули \DLRN fLoadThread.Halt; fLoadThread:=TLoadBitmapThread.Create(LoadThreadTerminate,s+ChangeFileExt(ExtractFileName(aFilename),'.png')); end; destructor TRasterImageDocument.Destroy; var i: Integer; begin fLoadThread.Halt; for i:=0 to Length(fScalingThreads)-1 do fScalingThreads[i].Halt; fScaleLevelsReadyEvent.Free; inherited Destroy; end; function TRasterImageDocument.Get_Image: TImage; begin Result:=Image; end; procedure TRasterImageDocument.WaitScaleLevelsReady; var i: Integer; begin i:=0; while i<120 do begin case fScaleLevelsReadyEvent.WaitFor(500) of wrSignaled: Exit; wrError: raise Exception.Create('WaitScaleLevelsReady error'); wrAbandoned: raise Exception.Create('WaitScaleLevelsReady abandoned'); end; CheckSynchronize(500); inc(i); end; raise Exception.Create('WaitScaleLevelsReady timeout'); end; function TRasterImageDocument.Get_Scale: Real; begin WaitScaleLevelsReady; assert((scaleNumber>=0) and (scaleNumber<=Length(fScalingThreads))); if scaleNumber=0 then Result:=1 else Result:=fScalingThreads[scaleNumber-1].GetScale; end; function TRasterImageDocument.Get_Scaled_Btmp: TExtendedPngObject; begin WaitScaleLevelsReady; assert((scaleNumber>=0) and (scaleNumber<=Length(fScalingThreads))); if scaleNumber=0 then Result:=fLoadThread.GetImage else Result:=fScalingThreads[scaleNumber-1].GetImage; end; procedure TRasterImageDocument.SaveAndFree; begin if Assigned(self) then TSaveDocThread.Create(self); end; procedure TRasterImageDocument.FreeWithoutSaving; begin if Assigned(self) then with documentsSavingProgress.fDocumentsSaving.LockList do remove(self); Destroy; end; procedure TRasterImageDocument.SaveToFile(const filename: string); var s,fn1: string; begin if Changed or not FileExists(filename) then inherited SaveToFile(filename); s:=ExtractFilePath(filename); s:=LeftStr(s,Length(s)-5); fn1:=s+ChangeFileExt(ExtractFileName(filename),'.png'); If Changed or not FileExists(fn1) then SafeSaveToFile(btmp.SmartSaveToFile,fn1); // btmp.SmartSaveToFile(fn1); initial_pos:=UndoTree.current; new_commands_added:=false; end; function TRasterImageDocument.GetBtmp: TExtendedPngObject; begin Result:=fLoadThread.GetImage; end; procedure TRasterImageDocument.SetBtmp(value: TExtendedPngObject); begin fLoadThread.SetImage(value); end; procedure TRasterImageDocument.LoadThreadTerminate(Sender: TObject); var t: string; i,c: Integer; s: Real; thread: TLoadBitmapThread; begin thread:=Sender as TLoadBitmapThread; if Assigned(thread.FatalException) then begin t:=Format('Не удалось загрузить изображение %s: %s', [thread.fFilename,Exception(thread.FatalException).Message]); Application.MessageBox(@t[1],'AMBIC'); Exit; end; //ладно, смасштабируем здесь. Пока ровно через 2 if (thread.fBitmap.Width=0) or (Thread.fBitmap.Height=0) then Exit; c:=Floor(log2(min(Thread.fBitmap.Width,Thread.fBitmap.Height)))-1; SetLength(fScalingThreads,2*c); s:=2/3; fScalingThreads[0]:=T2to3ScalingThread.Create(fLoadThread,s); fScalingThreads[1]:=TScalingThread.Create(fLoadThread,s*3/4); for i:=1 to c-1 do begin s:=s/2; fScalingThreads[2*i]:=TScalingThread.Create(fScalingThreads[2*(i-1)],s); fScalingThreads[2*i+1]:=TScalingThread.Create(fScalingThreads[2*i-1],s*3/4); end; fScaleLevelsReadyEvent.SetEvent; end; procedure TRasterImageDocument.AddToChangeRect(const A: TRect); begin CoverRect(ChangeRect,A); end; procedure TRasterImageDocument.SizesChanged; begin fSizesChanged:=true; end; procedure TRasterImageDocument.Change; var i: Integer; begin //прорисуем изменения, причем при первом включении ChangeRect должен равняться //всему изображению! if fSizesChanged then begin fScalingThreads[0].SetImage(btmp.Get2To3DownScaled); fScalingThreads[1].SetImage(btmp.Get2TimesDownScaled); for i:=0 to (Length(fScalingThreads) div 2)-2 do begin fScalingThreads[i*2+2].SetImage(fScalingThreads[i*2].GetImage.Get2TimesDownscaled); fScalingThreads[i*2+3].SetImage(fScalingThreads[i*2+1].GetImage.Get2TimesDownscaled); end; end else if not IsRectEmpty(ChangeRect) then begin btmp.DownScale2To3Into(ChangeRect,fScalingThreads[0].getImage); btmp.DownScale2TimesInto(ChangeRect,fScalingThreads[1].getImage); for i:=0 to (Length(fScalingThreads) div 2)-2 do begin fScalingThreads[i*2].GetImage.DownScale2TimesInto(ChangeRect,fScalingThreads[i*2+2].getImage); fScalingThreads[i*2+1].GetImage.DownScale2TimesInto(ChangeRect,fScalingThreads[i*2+3].getImage); end; end; fSizesChanged:=false; ChangeRect:=Rect(0,0,0,0); inherited Change; end; procedure TRasterImageDocument.ZoomIn; begin if fScaleNumber>0 then begin dec(fScaleNumber); Change; end; end; procedure TRasterImageDocument.ZoomOut; begin if fScaleNumber<Length(fScalingThreads) then begin inc(fScaleNumber); Change; end; end; initialization RegisterClasses([TRasterImageDocument]); DocumentsSavingProgress:=TDocumentsSavingProgress.Create; finalization DocumentsSavingProgress.Free; end.
unit ObjectUtils; interface uses SysUtils, TypInfo, CoreTypes, Transfer; type EInvalidProperty = class(Exception); type IEnumFieldNames = IEnumNames; IEnumPropertyNames = IEnumNames; IEnumMethodNames = IEnumStrings; type TEnumFieldNames = class(TInterfacedObject, IEnumFieldNames) public constructor Create(aClass : TClass); private // IEnumFields function Next(out which : array of string) : integer; function Skip(count : integer) : integer; procedure Reset; private fClass : TClass; fCurrent : TClass; fCount : integer; fOffset : ^shortstring; procedure UpdateNewClass; end; type TEnumPropertyNames = class(TInterfacedObject, IEnumPropertyNames) public constructor Create(aClass : TClass); destructor Destroy; override; private // IEnumFields function Next(out which : array of string) : integer; function Skip(count : integer) : integer; procedure Reset; private fList : PPropList; fCount : integer; fIndex : integer; end; type TEnumMethodNames = class(TInterfacedObject, IEnumMethodNames) public constructor Create(aClass : TClass); private // IEnumFields function Next(out which : array of string) : integer; function Skip(count : integer) : integer; procedure Reset; private fClass : TClass; fCurrent : TClass; fCount : integer; fOffset : pchar; procedure UpdateNewClass; end; type TObjectPropertyStorage = class(TInterfacedObject, IPropertyStorage) public constructor Create(obj : TObject; build : boolean); private // IPropertyStorage function GetClass : string; function GetName : string; function SetName(const which : string) : boolean; function GetProperty(const name : string) : string; function IPropertyStorage.SetProperty = CreateProperty; function CreateProperty(const name, value : string) : boolean; function EnumProperties : IEnumNames; function OpenStorage(const name : string) : IPropertyStorage; function CreateStorage(const theClass, name : string) : IPropertyStorage; function EnumChildren : IEnumNames; private fObject : TObject; fName : string; fBuild : boolean; constructor InternalCreate(obj : TObject; build : boolean; const name : string); function GetMethodString(Info : PPropInfo) : string; procedure SetMethodString(Info : PPropInfo; const which : string); function ExtractMethodAddr(const from : string) : pointer; function FindFieldClass(const name : string) : TClass; end; implementation type PFieldClassTable = ^TFieldClassTable; TFieldClassTable = packed record Count : smallint; Classes : array[word] of ^TClass; end; function GetFieldClassTable(aClass : TClass) : PFieldClassTable; var aux : pointer; begin aux := pointer(pointer(pchar(aClass) + vmtFieldTable)^); if aux <> nil then Result := pointer(pointer(pchar(aux) + 2)^) else Result := nil; end; // TEnumFieldNames constructor TEnumFieldNames.Create(aClass : TClass); begin inherited Create; fClass := aClass; Reset; end; function TEnumFieldNames.Next(out which : array of string) : integer; begin Result := 0; while (Result <= high(which)) and (fCurrent <> nil) do begin which[Result] := fOffset^; inc(Result); dec(fCount); if fCount > 0 then inc(pchar(fOffset), length(fOffset^) + 7) else begin fCurrent := fCurrent.ClassParent; if fCurrent <> nil then UpdateNewClass; end; end; end; function TEnumFieldNames.Skip(count : integer) : integer; begin Result := 0; while (Result < count) and (fCurrent <> nil) do begin inc(Result); dec(fCount); if fCount > 0 then inc(pchar(fOffset), length(fOffset^) + 7) else begin fCurrent := fCurrent.ClassParent; if fCurrent <> nil then UpdateNewClass; end; end; end; procedure TEnumFieldNames.Reset; begin fCurrent := fClass; UpdateNewClass; end; procedure TEnumFieldNames.UpdateNewClass; var aux : pointer; begin aux := pointer(pointer(pchar(fCurrent) + vmtFieldTable)^); while (aux = nil) and (fCurrent <> nil) do begin fCurrent := fCurrent.ClassParent; if fCurrent <> nil then aux := pointer(pointer(pchar(fCurrent) + vmtFieldTable)^); end; if aux <> nil then begin fCount := word(aux^); fOffset := @shortstring(pointer(pchar(aux) + 12)^); end; end; // TEnumPropertyNames constructor TEnumPropertyNames.Create(aClass : TClass); var TypeInfo : PTypeInfo; begin inherited Create; TypeInfo := aClass.ClassInfo; if TypeInfo <> nil then begin fCount := GetTypeData(TypeInfo).PropCount; getmem(fList, fCount*sizeof(fList[0])); GetPropInfos(TypeInfo, fList); end; end; destructor TEnumPropertyNames.Destroy; begin freemem(fList); inherited; end; function TEnumPropertyNames.Next(out which : array of string) : integer; begin Result := 0; while (Result <= high(which)) and (fIndex < fCount) do begin which[Result] := fList[fIndex].Name; inc(Result); inc(fIndex); end; end; function TEnumPropertyNames.Skip(count : integer) : integer; begin Result := 0; while (Result < count) and (fIndex < fCount) do begin inc(Result); inc(fIndex); end; end; procedure TEnumPropertyNames.Reset; begin fIndex := 0; end; // TEnumMethodNames constructor TEnumMethodNames.Create(aClass : TClass); begin inherited Create; fClass := aClass; Reset; end; function TEnumMethodNames.Next(out which : array of string) : integer; type pstr = ^shortstring; begin Result := 0; while (Result <= high(which)) and (fCurrent <> nil) do begin which[Result] := pstr(fOffset + 6)^; inc(Result); dec(fCount); if fCount > 0 then inc(fOffset, word(pointer(fOffset)^)) else begin fCurrent := fCurrent.ClassParent; if fCurrent <> nil then UpdateNewClass; end; end; end; function TEnumMethodNames.Skip(count : integer) : integer; begin Result := 0; while (Result < count) and (fCurrent <> nil) do begin inc(Result); dec(fCount); if fCount > 0 then inc(fOffset, word(pointer(fOffset)^)) else begin fCurrent := fCurrent.ClassParent; if fCurrent <> nil then UpdateNewClass; end; end; end; procedure TEnumMethodNames.Reset; begin fCurrent := fClass; UpdateNewClass; end; procedure TEnumMethodNames.UpdateNewClass; var aux : pointer; begin aux := pointer(pointer(pchar(fCurrent) + vmtMethodTable)^); while (aux = nil) and (fCurrent <> nil) do begin fCurrent := fCurrent.ClassParent; if fCurrent <> nil then aux := pointer(pointer(pchar(fCurrent) + vmtMethodTable)^); end; if aux <> nil then begin fCount := word(aux^); fOffset := pchar(aux) + sizeof(word); end; end; // TObjectPropertyStorage constructor TObjectPropertyStorage.Create(obj : TObject; build : boolean); begin inherited Create; assert((obj <> nil) and (obj.ClassInfo <> nil)); fObject := obj; fBuild := build; end; function TObjectPropertyStorage.GetClass : string; begin Result := fObject.ClassName; end; function TObjectPropertyStorage.GetName : string; begin Result := fName; end; function TObjectPropertyStorage.SetName(const which : string) : boolean; begin Result := false; end; function TObjectPropertyStorage.GetProperty(const name : string) : string; var info : PPropInfo; begin info := GetPropInfo(fObject.ClassInfo, name); if info <> nil then case info.PropType^.Kind of tkChar, tkInteger, tkEnumeration, tkSet, tkWChar : Result := IntToStr(GetOrdProp(fObject, info)); tkFloat : Result := FloatToStr(GetFloatProp(fObject, info)); tkString, tkLString, tkWString : Result := GetStrProp(fObject, info); tkVariant : Result := GetVariantProp(fObject, info); tkClass : Result := '[' + GetTypeData(info.PropType^).ClassType.ClassName + ']'; tkMethod : Result := GetMethodString(info); else raise EInvalidProperty.Create(info.Name); end else Result := ''; end; function TObjectPropertyStorage.CreateProperty(const name, value : string) : boolean; var info : PPropInfo; begin info := GetPropInfo(fObject.ClassInfo, name); Result := info <> nil; if Result then case info.PropType^.Kind of tkChar, tkInteger, tkEnumeration, tkSet, tkWChar : SetOrdProp(fObject, info, StrToInt(value)); tkFloat : SetFloatProp(fObject, info, StrToFloat(value)); tkString, tkLString, tkWString : SetStrProp(fObject, info, value); tkVariant : SetVariantProp(fObject, info, value); tkClass : ; // assert(which = '[' + TypeData.ClassType.ClassName + ']'); tkMethod : SetMethodString(info, value); else raise EInvalidProperty.Create(info.Name); end; end; function TObjectPropertyStorage.EnumProperties : IEnumNames; begin Result := TEnumPropertyNames.Create(fObject.ClassType); end; function TObjectPropertyStorage.OpenStorage(const name : string) : IPropertyStorage; var aux : ^TObject; begin aux := fObject.FieldAddress(name); if (aux <> nil) and (aux^ <> nil) then Result := TObjectPropertyStorage.InternalCreate(aux^, fBuild, name) else Result := nil; end; function TObjectPropertyStorage.CreateStorage(const theClass, name : string) : IPropertyStorage; var aux : ^TObject; begin aux := fObject.FieldAddress(name); if aux <> nil then begin if (aux^ = nil) and fBuild and (theClass <> '') then aux^ := FindFieldClass(theClass).Create; if aux^ <> nil then Result := TObjectPropertyStorage.InternalCreate(aux^, fBuild, name) else Result := nil; end else Result := nil; end; function TObjectPropertyStorage.EnumChildren : IEnumNames; begin Result := TEnumFieldNames.Create(fObject.ClassType); end; constructor TObjectPropertyStorage.InternalCreate(obj : TObject; build : boolean; const name : string); begin Create(obj, build); fName := name; end; function TObjectPropertyStorage.GetMethodString(Info : PPropInfo) : string; type TParam = packed record Flags : TParamFlags; ParamName : ShortString; TypeName : ShortString; end; TParamList = array[1..1024] of TParam; var TypeData : PTypeData; Method : TMethod; i : integer; begin Method := GetMethodProp(fObject, Info); assert(fObject = Method.Data); TypeData := GetTypeData(Info.PropType^); if (TypeData.MethodKind = mkFunction) or (TypeData.MethodKind = mkSafeFunction) then Result := 'function ' else Result := 'procedure '; Result := Result + fObject.ClassName + '.' + fObject.MethodName(Method.Code) + '('; for i := 1 to TypeData.ParamCount do begin with TParamList((@TypeData.ParamList)^)[i] do begin if pfVar in Flags then Result := Result + 'var ' else if pfConst in Flags then Result := Result + 'const ' else if pfOut in Flags then Result := Result + 'out '; Result := Result + ParamName + ' : '; if pfArray in Flags then Result := Result + 'array of '; if pfAddress in Flags then Result := Result + '^'; if pfReference in Flags then Result := Result + '&'; Result := Result + TypeName; end; if i < ParamCount then Result := Result + ', '; end; Result := Result + ')'; if (TypeData.MethodKind = mkFunction) or (TypeData.MethodKind = mkSafeFunction) then Result := Result + ShortString((@TParamList((@TypeData.ParamList)^)[ParamCount + 1])^); // ResultType end; procedure TObjectPropertyStorage.SetMethodString(Info : PPropInfo; const which : string); var Method : TMethod; begin Method.Data := fObject; Method.Code := ExtractMethodAddr(which); SetMethodProp(fObject, Info, Method); end; function TObjectPropertyStorage.ExtractMethodAddr(const from : string) : pointer; var aux : pchar; buffer : array[byte] of char; len : integer; begin aux := StrScan(pchar(from), '.') + 1; assert((aux <> nil) and (aux[-1] = '.')); len := StrScan(aux, '(') - aux; assert(aux[len] = '('); StrLCopy(buffer, aux, len); Result := fObject.MethodAddress(string(buffer)); end; function TObjectPropertyStorage.FindFieldClass(const name : string) : TClass; var i : integer; ClassTable : PFieldClassTable; ClassType : TClass; begin Result := nil; ClassType := fObject.ClassType; while (ClassType <> nil) and (Result = nil) do begin ClassTable := GetFieldClassTable(ClassType); if ClassTable <> nil then begin i := 0; repeat if CompareText(ClassTable.Classes[i].ClassName, name) = 0 then Result := ClassTable.Classes[i]^; inc(i); until (i >= ClassTable.Count) or (Result <> nil); end; ClassType := ClassType.ClassParent; end; assert(Result <> nil); end; end.
unit uConfiguracao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uTDPNumberEditXE8, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, uCRUDConfiguracao, Data.DB, Vcl.Grids, Vcl.DBGrids; type TFConfiguracao = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; edtAno: TMaskEdit; Label2: TLabel; edtAliquotaIsenta: TDPTNumberEditXE8; edtValorIRPF: TDPTNumberEditXE8; Label3: TLabel; btnFechar: TBitBtn; btnExcluir: TBitBtn; btnGravar: TBitBtn; dbConfiguracao: TDBGrid; procedure btnFecharClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure edtAnoExit(Sender: TObject); procedure dbConfiguracaoDblClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure edtAliquotaIsentaExit(Sender: TObject); private vloConfiguracao : TCRUDConfiguracao; procedure pcdAtualizaGRid; procedure pcdLimpaCamposConfiguracao; { Private declarations } public { Public declarations } end; var FConfiguracao: TFConfiguracao; implementation {$R *.dfm} uses uPrincipal, uDMPrincipal; procedure TFConfiguracao.btnExcluirClick(Sender: TObject); begin vloConfiguracao.CONFIG_ANO := edtAno.Text; try vloConfiguracao.pcdExcluiConfiguracao; pcdAtualizaGRid; pcdLimpaCamposConfiguracao; except on E:Exception do begin Fprincipal.pcdMensagem(E.Message); end; end; end; procedure TFConfiguracao.btnFecharClick(Sender: TObject); begin Close; end; procedure TFConfiguracao.btnGravarClick(Sender: TObject); begin if Trim(edtAno.Text) = '' then begin Fprincipal.pcdMensagem('Ano obrigatório'); edtAno.SetFocus; Abort; end else begin if not Fprincipal.fncValidaAno(edtAno.Text) then begin edtAno.SetFocus; Abort; end; end; if edtAliquotaIsenta.Value = 0 then begin Fprincipal.pcdMensagem('Alíquota Isenção obrigatória'); edtAliquotaIsenta.SetFocus; Abort; end; if edtValorIRPF.Value = 0 then begin Fprincipal.pcdMensagem('Valor Limite para Imposto de Renda obrigatório'); edtValorIRPF.SetFocus; Abort; end; vloConfiguracao.CONFIG_ANO := edtAno.Text; vloConfiguracao.CONFIG_PORCENTAGEMISENTO := edtAliquotaIsenta.Value; vloConfiguracao.CONFIG_VALORDECLARARIR := edtValorIRPF.Value; try vloConfiguracao.pcdGravaConfiguracao; pcdAtualizaGRid; pcdLimpaCamposConfiguracao; except on E:Exception do begin Fprincipal.pcdMensagem(E.Message); end; end; end; procedure TFConfiguracao.dbConfiguracaoDblClick(Sender: TObject); begin edtAno.Text := DMPrincipal.FDConfiguracaoCONFIG_ANO.AsString; edtAliquotaIsenta.Value := DMPrincipal.FDConfiguracaoCONFIG_PORCENTAGEMISENTO.AsFloat; edtValorIRPF.Value := DMPrincipal.FDConfiguracaoCONFIG_VALORDECLARARIR.AsFloat; end; procedure TFConfiguracao.edtAliquotaIsentaExit(Sender: TObject); begin if edtAliquotaIsenta.Value > 100 then begin Fprincipal.pcdMensagem('Não é permitido alíquota maior do que 100 (Cem).'); edtAliquotaIsenta.Value := 0; edtAliquotaIsenta.SetFocus; Abort; end; end; procedure TFConfiguracao.edtAnoExit(Sender: TObject); begin if Trim(edtAno.Text) <> '' then begin if Fprincipal.fncValidaAno(edtAno.Text) then begin vloConfiguracao.pcdRetornaValorFaturadoANO(edtAno.Text); edtAliquotaIsenta.Value := vloConfiguracao.poRetornoConfig.CONFIG_PORCENTAGEMISENTO; edtValorIRPF.Value := vloConfiguracao.poRetornoConfig.CONFIG_VALORDECLARARIR; end else begin edtAno.SetFocus; end; end; end; procedure TFConfiguracao.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(vloConfiguracao) then FreeAndNil(vloConfiguracao); end; procedure TFConfiguracao.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Perform(WM_NEXTDLGCTL, 0, 0); Key := #0; end; end; procedure TFConfiguracao.FormShow(Sender: TObject); begin vloConfiguracao := TCRUDConfiguracao.Create(DMPrincipal.poConexao); pcdAtualizaGRid; end; procedure TFConfiguracao.pcdAtualizaGRid; begin DMPrincipal.FDConfiguracao.Close; DMPrincipal.FDConfiguracao.SQL.Clear; DMPrincipal.FDConfiguracao.SQL.Add('SELECT CONFIG_ANO, CONFIG_PORCENTAGEMISENTO, CONFIG_VALORDECLARARIR FROM CONFIGURACAO ORDER BY CONFIG_ANO DESC'); DMPrincipal.FDConfiguracao.Open(); end; procedure TFConfiguracao.pcdLimpaCamposConfiguracao; begin edtAno.Clear; edtValorIRPF.Value := 0; edtAliquotaIsenta.Value := 0; if edtAno.CanFocus then edtAno.SetFocus; end; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit ShowCertUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, OverbyteIcsWSocket, Buttons; type // Визуализирует сертификат. Пользователь может его принять или отвергнуть TShowCertForm = class(TForm) CertGroupBox: TGroupBox; LblIssuer: TLabel; LblSubject: TLabel; LblSerial: TLabel; LblValidAfter: TLabel; LblValidBefore: TLabel; LblShaHash: TLabel; LblCertExpired: TLabel; LblIssuerMemo: TMemo; AcceptCertButton: TBitBtn; RefuseCertButton: TBitBtn; procedure AcceptCertButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } AcceptedCertsList: TStringList; CertHash: string; public { Public declarations } CertAccepted: Boolean; procedure TranslateForm; function CheckAccepted(Hash: string): Boolean; procedure ShowCert(const Cert: TX509Base); end; {$ENDREGION} implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, VarsUnit, UtilsUnit; {$ENDREGION} const AcceptedCertsFile = 'Certificates.txt'; {$REGION 'TranslateForm'} procedure TShowCertForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); end; {$ENDREGION} {$REGION 'AcceptCertButtonClick'} procedure TShowCertForm.AcceptCertButtonClick(Sender: TObject); begin // Принимаем и сохраняем в файл сертификат // Добавляем в лист хэш сертификата AcceptedCertsList.Add(CertHash); // Сохраняем лист хешей сертификатов в файл if Assigned(AcceptedCertsList) then begin AcceptedCertsList.SaveToFile(V_ProfilePath + AcceptedCertsFile); // Уничтожаем лист хешей сертификатов FreeAndNil(AcceptedCertsList); end; CertAccepted := True; // Закрываем модальное окно ModalResult := MrOk; end; {$ENDREGION} {$REGION 'CheckAccepted'} function TShowCertForm.CheckAccepted(Hash: string): Boolean; begin Result := False; if Assigned(AcceptedCertsList) then begin // Если нашли в листе сертификатов этот хэш, то ОК if AcceptedCertsList.IndexOf(Hash) > -1 then Result := True; end; end; {$ENDREGION} {$REGION 'FormCreate'} procedure TShowCertForm.FormCreate(Sender: TObject); begin // Присваиваем иконку окну и кнопке MainForm.AllImageList.GetIcon(173, Icon); MainForm.AllImageList.GetBitmap(139, RefuseCertButton.Glyph); MainForm.AllImageList.GetBitmap(140, AcceptCertButton.Glyph); // Переводим окно на другие языки TranslateForm; // Создаём лист для загрузки хэшей сертификатов AcceptedCertsList := TStringList.Create; // Загружаем файл сертификатов if FileExists(V_ProfilePath + AcceptedCertsFile) then AcceptedCertsList.LoadFromFile(V_ProfilePath + AcceptedCertsFile); CertAccepted := False; end; {$ENDREGION} {$REGION 'ShowCert'} procedure TShowCertForm.ShowCert(const Cert: TX509Base); begin // Заполняем поля формы with Cert do begin CertHash := Text2Hex(Sha1Hash); LblIssuerMemo.Text := IssuerOneLine; LblSubject.Caption := LblSubject.Caption + C_TN + C_BN + SubjectCName; LblSerial.Caption := LblSerial.Caption + C_TN + C_BN + IntToStr(SerialNum); LblValidAfter.Caption := LblValidAfter.Caption + C_TN + C_BN + DateToStr(ValidNotAfter); LblValidBefore.Caption := LblValidBefore.Caption + C_TN + C_BN + DateToStr(ValidNotBefore); LblShaHash.Caption := LblShaHash.Caption + C_TN + C_BN + CertHash; // Отображаем сообщение если сертификат просрочен LblCertExpired.Visible := HasExpired; end; end; {$ENDREGION} end.
{ Copyright © 1999 by Harris Software Ltd Author:Kyley Harris Kyley@HarrisSoftware.com ------------------------------------------------------------------------------} unit uHssStringList; interface uses SysUtils, Classes; type THssStringList = class(TStringList) private FAppendStringsIndex: integer; procedure SetAppendStringsIndex(const Value: integer); public function CompareStrings(const S1, S2: string): Integer; override; function MarkerPosition(Marker:string;AbsoluteMarker:boolean=false):integer; procedure InsertStrings(AStrings:TStrings;AtIndex:integer); procedure AppendStrings(AStrings:TStrings); procedure ExtractStrings(AFrom,ATO:integer;AInto:TStrings); procedure ExtractUpToMarker(AStrings:TStrings;Marker:string); procedure TrimLines; function InsertStringsAtMarker(AStrings:String;Marker:string;DeleteMarker:boolean=true): Boolean; overload; function InsertStringsAtMarker(AStrings:TStrings;Marker:string;DeleteMarker:boolean=true): Boolean; overload; property AppendStringsIndex:integer read FAppendStringsIndex write SetAppendStringsIndex; end; implementation { THssStringList } procedure THssStringList.AppendStrings(AStrings: TStrings); var i:integer; begin if AppendStringsIndex > Count then FAppendStringsIndex := Count; BeginUpdate; for i := AStrings.Count -1 downto 0 do InsertObject(FAppendStringsIndex,AStrings[i],AStrings.Objects[i]); Inc(FAppendStringsIndex,AStrings.Count); EndUpdate; end; function THssStringList.CompareStrings(const S1, S2: string): Integer; begin // if CaseSensitive then result := CompareStr(S1,s2); // else // result := CompareTextShaPas5_a(s1,s2); end; procedure THssStringList.ExtractStrings(AFrom, ATO: integer; AInto: TStrings); var i:integer; begin Assert(AFrom >= 0); Assert(ATo < Count); Assert( ATo >= AFrom ); for i := AFrom to ATo do begin if assigned(AInto) then AInto.Add(Strings[AFrom]); Delete(AFrom); end; end; procedure THssStringList.ExtractUpToMarker(AStrings: TStrings; Marker: string); var AMarkerPosition:integer; begin AMarkerPosition := MarkerPosition(Marker); if AMarkerPosition = -1 then begin AStrings.AddStrings(self); Clear; end else begin if AMarkerPosition >= 0 then ExtractStrings(0,AMarkerPosition-1,AStrings); Delete(0); end; end; procedure THssStringList.InsertStrings(AStrings: TStrings; AtIndex: integer); var i:integer; begin if AtIndex > Count then AtIndex := Count; BeginUpdate; for i := AStrings.Count -1 downto 0 do InsertObject(AtIndex,AStrings[i],AStrings.Objects[i]); EndUpdate; end; function THssStringList.InsertStringsAtMarker(AStrings: string; Marker: string; DeleteMarker: boolean): Boolean; var sl: TStringList; begin sl := TStringList.Create; sl.Text := astrings; Result := InsertStringsAtMarker(sl, Marker, DeleteMarker); sl.Free; end; function THssStringList.InsertStringsAtMarker(AStrings: TStrings; Marker: string;DeleteMarker:boolean): Boolean; var AMarkerPosition:integer; begin AMarkerPosition := MarkerPosition(Marker); result := AMarkerPosition <> -1; if result then begin if Assigned(AStrings) then InsertStrings(AStrings,AMarkerPosition+1); if DeleteMarker then Delete(AMarkerPosition); end; end; function THssStringList.MarkerPosition(Marker: string;AbsoluteMarker:boolean): integer; var i:integer; s:string; begin if not AbsoluteMarker then Marker := UpperCase(format('<#%s>',[Marker])) else Marker := Trim(UpperCase(marker)); for i := 0 to Count -1 do begin s := Trim(Strings[i]); if Pos(Marker,UpperCase(s)) > 0 then begin result := i; exit; end; end; result := -1; end; procedure THssStringList.SetAppendStringsIndex(const Value: integer); begin FAppendStringsIndex := Value; end; procedure THssStringList.TrimLines; begin while (Count > 0) and (Trim(Strings[0]) = '') do Delete(0); while (Count > 0) and (Trim(Strings[Count-1]) = '') do Delete(Count-1); end; initialization end.