text
stringlengths
14
6.51M
unit ParseClass; interface uses OObjects, SysUtils; const MaxArg = 4; var Missing: array[0..1] of Integer = (Integer($FFFFFFFF), Integer($FFFFFFFF)); FNan: Double absolute Missing; type TVarType = (vtDouble, vtBoolean, vtString, vtLeftBracket, vtRightBracket, vtComma); PDouble = ^Double; EParserException = class(Exception); PExpressionRec = ^TExpressionRec; TExprWord = class; TArgsArray = record Res: Double; Args: array[0..MaxArg - 1] of PDouble; ExprWord: TExprWord; //can be used to notify the object to update end; TDoubleFunc = procedure(Expr: PExpressionRec); TExpressionRec = record //used both as linked tree and linked list for maximum evaluation efficiency Oper: TDoubleFunc; Next: PExpressionRec; Res: Double; ExprWord: TExprWord; case Byte of 0: ( Args: array[0..MaxArg - 1] of PDouble; //can be used to notify the object to update ); 1: (ArgList: array[0..MaxArg - 1] of PExpressionRec); end; TExprCollection = class(TNoOwnerCollection) public function NextOper(IStart: Integer): Integer; procedure Check; procedure EraseExtraBrackets; end; TExprWord = class private FName: string; FDoubleFunc: TDoubleFunc; protected function GetIsOper: Boolean; virtual; function GetAsString: string; virtual; function GetIsVariable: Boolean; function GetCanVary: Boolean; virtual; function GetVarType: TVarType; virtual; function GetNFunctionArg: Integer; virtual; public constructor Create(AName: string; ADoubleFunc: TDoubleFunc); function AsPointer: PDouble; virtual; property AsString: string read GetAsString; property DoubleFunc: TDoubleFunc read FDoubleFunc; property IsOper: Boolean read GetIsOper; property CanVary: Boolean read GetCanVary; property isVariable: Boolean read GetIsVariable; property VarType: TVarType read GetVarType; property NFunctionArg: Integer read GetNFunctionArg; property Name: string read FName; end; TExpressList = class(TSortedCollection) public function KeyOf(Item: Pointer): Pointer; override; function Compare(Key1, Key2: PAnsiChar): Integer; override; end; TDoubleConstant = class(TExprWord) private FValue: Double; public function AsPointer: PDouble; override; constructor Create(AName: string; AValue: string); constructor CreateAsDouble(AName: string; AValue: double); // not overloaded to support older Delphi versions property Value: Double read FValue write FValue; end; TBooleanConstant = class(TDoubleConstant) protected function GetVarType: TVarType; override; end; TGeneratedVariable = class(TDoubleConstant) private FAsString: string; FVarType: TVarType; protected function GetVarType: TVarType; override; function GetAsString: string; override; function GetCanVary: Boolean; override; public constructor Create(AName: string); property VarType read GetVarType write FVarType; property AsString: string read GetAsString write FAsString; end; TDoubleVariable = class(TExprWord) private FValue: PDouble; protected function GetCanVary: Boolean; override; public function AsPointer: PDouble; override; constructor Create(AName: string; AValue: PDouble); end; TStringConstant = class(TExprWord) private FValue: string; protected function GetVarType: TVarType; override; function GetAsString: string; override; public constructor Create(AValue: string); end; TLeftBracket = class(TExprWord) function GetVarType: TVarType; override; end; TRightBracket = class(TExprWord) protected function GetVarType: TVarType; override; end; TComma = class(TExprWord) protected function GetVarType: TVarType; override; end; PString = ^string; TStringVariable = class(TExprWord) private FValue: PString; protected function GetVarType: TVarType; override; function GetAsString: string; override; function GetCanVary: Boolean; override; public constructor Create(AName: string; AValue: PString); end; TFunction = class(TExprWord) private FIsOper: Boolean; FOperPrec: Integer; FNFunctionArg: Integer; protected function GetIsOper: Boolean; override; function GetNFunctionArg: Integer; override; public constructor Create(AName: string; ADoubleFunc: TDoubleFunc; ANFunctionArg: Integer); constructor CreateOper(AName: string; ADoubleFunc: TDoubleFunc; ANFunctionArg: Integer; AIsOper: Boolean; AOperPrec: Integer); property OperPrec: Integer read FOperPrec; end; TVaryingFunction = class(TFunction) // Functions that can vary for ex. random generators // should be TVaryingFunction to be sure that they are // always evaluated protected function GetCanVary: Boolean; override; end; TBooleanFunction = class(TFunction) protected function GetVarType: TVarType; override; end; TOper = (op_eq, op_gt, op_lt, op_ge, op_le, op_in); const ListChar = ','; {the delimiter used with the 'in' operator: e.g., ('a' in 'a,b') =True ('c' in 'a,b') =False} type TLogicalStringOper = class(TExprWord) private Oper: TOper; FLeftArg: TExprWord; FRightArg: TExprWord; protected function GetCanVary: Boolean; override; function GetVarType: TVarType; override; public constructor Create(AOper: string; ALeftArg: TExprWord; ARightArg: TExprWord); function Evaluate: Boolean; end; procedure _Variable(Param: PExpressionRec); procedure _LogString(Param: PExpressionRec); implementation uses Math; procedure _Variable(Param: PExpressionRec); begin with Param^ do Res := Args[0]^; end; procedure _LogString(Param: PExpressionRec); begin with Param^ do Res := Byte(TLogicalStringOper(ExprWord).Evaluate); end; { TExpressionWord } function TExprWord.AsPointer: PDouble; begin Result := nil; end; constructor TExprWord.Create(AName: string; ADoubleFunc: TDoubleFunc); begin FName := LowerCase(AName); FDoubleFunc := ADoubleFunc; end; function TExprWord.GetAsString: string; begin Result := ''; end; function TExprWord.GetCanVary: Boolean; begin Result := False; end; function TExprWord.GetIsOper: Boolean; begin Result := False; end; function TExprWord.GetIsVariable: Boolean; begin Result := @FDoubleFunc = @_Variable end; function TExprWord.GetNFunctionArg: Integer; begin Result := 0; end; function TExprWord.GetVarType: TVarType; begin Result := vtDouble; end; { TDoubleConstant } function TDoubleConstant.AsPointer: PDouble; begin Result := @FValue; end; constructor TDoubleConstant.Create(AName, AValue: string); begin inherited Create(AName, _Variable); if AValue <> '' then FValue := StrToFloat(AValue) else FValue := FNan; end; constructor TDoubleConstant.CreateasDouble(AName: string; AValue: double); begin inherited Create(AName, _Variable); FValue := AValue; end; { TStringConstant } function TStringConstant.GetAsString: string; begin Result := FValue; end; constructor TStringConstant.Create(AValue: string); begin inherited Create(AValue, _Variable); if (AValue[1] = '''') and (AValue[Length(AValue)] = '''') then FValue := Copy(AValue, 2, Length(AValue) - 2) else FValue := AValue; end; function TStringConstant.GetVarType: TVarType; begin Result := vtString; end; { TDoubleVariable } function TDoubleVariable.AsPointer: PDouble; begin Result := FValue; end; constructor TDoubleVariable.Create(AName: string; AValue: PDouble); begin inherited Create(AName, _Variable); FValue := AValue; end; function TDoubleVariable.GetCanVary: Boolean; begin Result := True; end; { TFunction } constructor TFunction.Create(AName: string; ADoubleFunc: TDoubleFunc; ANFunctionArg: Integer); begin CreateOper(AName, ADoubleFunc, ANFunctionArg, False, 0); //to increase compatibility don't use default parameters end; constructor TFunction.CreateOper(AName: string; ADoubleFunc: TDoubleFunc; ANFunctionArg: Integer; AIsOper: Boolean; AOperPrec: Integer); begin inherited Create(AName, ADoubleFunc); FNFunctionArg := ANFunctionArg; if FNFunctionArg > MaxArg then raise EParserException.Create('Too many arguments'); FIsOper := AIsOper; FOperPrec := AOperPrec; end; function TFunction.GetIsOper: Boolean; begin Result := FIsOper; end; function TFunction.GetNFunctionArg: Integer; begin Result := FNFunctionArg; end; { TLeftBracket } function TLeftBracket.GetVarType: TVarType; begin Result := vtLeftBracket; end; { TExpressList } function TExpressList.Compare(Key1, Key2: PAnsiChar): Integer; begin Result := StrIComp(Pchar(Key1), Pchar(Key2)); end; function TExpressList.KeyOf(Item: Pointer): Pointer; begin Result := Pchar(TExprWord(Item).Name); end; { TRightBracket } function TRightBracket.GetVarType: TVarType; begin Result := vtRightBracket; end; { TComma } function TComma.GetVarType: TVarType; begin Result := vtComma; end; { TExprCollection } procedure TExprCollection.Check; var brCount, I: Integer; begin brCount := 0; for I := 0 to Count - 1 do begin case TExprWord(Items[I]).VarType of vtLeftBracket: Inc(brCount); vtRightBracket: Dec(brCount); end; end; if brCount <> 0 then raise EParserException.Create('Unequal brackets'); end; procedure TExprCollection.EraseExtraBrackets; var I: Integer; brCount: Integer; begin if (TExprWord(Items[0]).VarType = vtLeftBracket) then begin brCount := 1; I := 1; while (I < Count) and (brCount > 0) do begin case TExprWord(Items[I]).VarType of vtLeftBracket: Inc(brCount); vtRightBracket: Dec(brCount); end; Inc(I); end; if (brCount = 0) and (I = Count) and (TExprWord(Items[I - 1]).VarType = vtRightBracket) then begin for I := 0 to Count - 3 do Items[I] := Items[I + 1]; Count := Count - 2; EraseExtraBrackets; //Check if there are still too many brackets end; end; end; function TExprCollection.NextOper(IStart: Integer): Integer; var brCount: Integer; begin brCount := 0; Result := IStart; while (Result < Count) and ((brCount > 0) or (TExprWord(Items[Result]).NFunctionArg <= 0)) do begin case TExprWord(Items[Result]).VarType of vtLeftBracket: Inc(brCount); vtRightBracket: Dec(brCount); end; Inc(Result); end; end; { TStringVariable } function TStringVariable.GetAsString: string; begin if (FValue^[1] = '''') and (FValue^[Length(FValue^)] = '''') then Result := Copy(FValue^, 2, Length(FValue^) - 2) else Result := FValue^ end; constructor TStringVariable.Create(AName: string; AValue: PString); begin inherited Create(AName, _Variable); FValue := AValue; end; function TStringVariable.GetVarType: TVarType; begin Result := vtString; end; function TStringVariable.GetCanVary: Boolean; begin Result := True; end; { TLogicalStringOper } constructor TLogicalStringOper.Create(AOper: string; ALeftArg, ARightArg: TExprWord); begin inherited Create(AOper, _LogString); // ,0,True,0); if AOper = '=' then Oper := op_eq else if AOper = '>' then Oper := op_gt else if AOper = '<' then Oper := op_lt else if AOper = '>=' then Oper := op_ge else if AOper = '<=' then Oper := op_le else if AOper = 'in' then Oper := op_in else raise EParserException.Create(AOper + ' is not a valid string operand'); FLeftArg := ALeftArg; FRightArg := ARightArg; end; function TLogicalStringOper.Evaluate: Boolean; var S1, S2: string; function inStr(sLookfor: string; sData: string): boolean; var loop: integer; subString: string; begin result := False; loop := pos(listChar, sData); while loop > 0 do begin subString := copy(sData, 1, loop - 1); sData := copy(sData, loop + 1, length(sData)); if substring = slookfor then begin result := true; break; end; loop := pos(listChar, sData); end; if slookfor = sData then result := true; end; begin S1 := FLeftArg.AsString; S2 := FRightArg.AsString; case Oper of op_eq: Result := S1 = S2; op_gt: Result := S1 > S2; op_lt: Result := S1 < S2; op_ge: Result := S1 >= S2; op_le: Result := S1 <= S2; op_in: Result := inStr(S1, s2); else Result := False; end; end; function TLogicalStringOper.GetCanVary: Boolean; begin Result := FLeftArg.CanVary or FRightArg.CanVary; end; function TLogicalStringOper.GetVarType: TVarType; begin Result := vtBoolean; end; { TBooleanFunction } function TBooleanFunction.GetVarType: TVarType; begin Result := vtBoolean; end; { TGeneratedVariable } constructor TGeneratedVariable.Create(AName: string); begin inherited Create(AName, ''); FAsString := ''; FVarType := vtDouble; end; function TGeneratedVariable.GetAsString: string; begin Result := FAsString; end; function TGeneratedVariable.GetCanVary: Boolean; begin Result := True; end; function TGeneratedVariable.GetVarType: TVarType; begin Result := FVarType; end; { TVaryingFunction } function TVaryingFunction.GetCanVary: Boolean; begin Result := True; end; { TBooleanConstant } function TBooleanConstant.GetVarType: TVarType; begin Result := vtBoolean; end; end.
unit uPrinc; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.DateUtils, Math, Vcl.Mask; type TPessoa = class private FDtNascimento: TDate; public property DtNascimento: TDate read FDtNascimento write FDtNascimento; end; TPessoaHelper = class helper for TPessoa private function GetIdade: Integer; public property Idade: Integer read GetIdade; end; TIntHelper = record helper for Integer public function ParaStringIdade:String; end; TVsDoubleHelper = record helper for Extended public function Arredondar: Double; function TruArr(cIAT: Char): Double; end; TForm1 = class(TForm) btnExemplo1: TButton; btnExemplo2: TButton; edtEx2: TEdit; btnExemplo3: TButton; cbEx3: TComboBox; procedure btnExemplo1Click(Sender: TObject); procedure btnExemplo2Click(Sender: TObject); procedure btnExemplo3Click(Sender: TObject); private Pessoa: TPessoa; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function TIntHelper.ParaStringIdade: String; var fteste: Integer; begin Result := Format('Apenas %d anos!', [Self]); end; procedure TForm1.btnExemplo1Click(Sender: TObject); var n: Integer; begin Pessoa := TPessoa.Create; try Pessoa.DtNascimento := StrToDate('26/11/1988'); ShowMessage(Pessoa.Idade.ParaStringIdade); finally Pessoa.Free; end; end; { TPessoaHelper } function TPessoaHelper.GetIdade: integer; begin Result := YearsBetween(Self.DtNascimento,Now); end; { TVsDoubleHelper } function TVsDoubleHelper.Arredondar: Double; begin Result := Math.SimpleRoundTo(Self, -3); end; procedure TForm1.btnExemplo2Click(Sender: TObject); var capivara: Extended; begin capivara := StrtoFloat(edtEx2.Text); ShowMessage(capivara.Arredondar.ToString); end; procedure TForm1.btnExemplo3Click(Sender: TObject); begin if cbEx3.ItemIndex = 0 then ShowMessage(StrToFloat(edtEx2.Text).TruArr('T').ToString) else if cbEx3.ItemIndex = 1 then ShowMessage(StrToFloat(edtEx2.Text).TruArr('A').ToString) else ShowMessage('Opção inválida'); end; function TVsDoubleHelper.TruArr(cIAT: Char): Double; begin if (cIAT = 'A') then Result := Math.SimpleRoundTo(Self, -3) else if (cIAT = 'T') then Result := Trunc(Self) else Result := Self; end; end.
program antrian_praktik_dokter; uses crt; const max = 20; type AntrianDokter = record no_antrian:array[1..max] of byte; //array didalam record front,rear:0..max; end; type rec_pasien = record kode_pasien,nama,diagnosa:string; end; larikpasien = array[1..max] of rec_pasien; // array record var antrian:AntrianDokter; pasien:larikpasien; pil,i,jumpas,nom:byte; function isFull(Q:AntrianDokter):Boolean; begin if Q.rear=max then isFull:=true else isFull:=False; end; function isEmpty(Q:AntrianDokter):Boolean; begin if Q.rear=0 then isEmpty:=true else isEmpty:=False; end; procedure ambil_antrian(var Q:AntrianDokter); begin WriteLn('Selamat datang di antrian Dokter budi'); Inc(nom); WriteLn('anda mendapatkan antrian nomor ',nom); Inc(Q.rear); Q.no_antrian[Q.rear]:=nom; WriteLn('mohon bersabar menunggu '); end; procedure cetak_antrian(var Q:AntrianDokter); begin WriteLn('Daftar Antrian saat ini di praktek dokter budi'); WriteLn('-----------------------------------'); WriteLn('Posisi No_Antrian'); for i:=Q.front to Q.rear do WriteLn(i:4,' ',Q.no_antrian[i]:4); WriteLn('-----------------------------------'); WriteLn('saat ini yang mengantri : ',Q.rear,'orang'); end; procedure layanan_dokter(var Q:AntrianDokter;var p:larikpasien); var kode:String; label ulang; begin WriteLn('selamat datang di layanan dokter budi '); WriteLn('Pasien nomor ',Q.no_antrian[Q.front],' silahkan menunggu ruang praktek '); // menggeser posisi yang sedang antri for i:=Q.front to Q.rear-1 do begin Q.no_antrian[i]:=Q.no_antrian[i+1]; end; Dec(Q.rear); // menangani si pasien yang ada di ruangang praktek WriteLn('kami akan mencatat data pasien '); ulang: Write('masukkan nomor kode pasien ');ReadLn(kode); // validasi for i:=1 to jumpas do begin if p[i].kode_pasien = kode then begin WriteLn('kode salah , ulangi '); goto ulang; end; end; // kode sudah valid Inc(jumpas); p[jumpas].kode_pasien:=kode; Write('masukkan nama pasien ');ReadLn(p[jumpas].nama); Write('diagnosa pasien : ');ReadLn(p[jumpas].diagnosa); end; procedure cetak_pasien(var P:larikpasien); begin WriteLn('Daftar pasien yang berobat '); WriteLn('praktek dokter budi'); WriteLn('-------------------------------'); WriteLn('no kode nama diagnosa'); WriteLn('-------------------------------'); for i:=1 to jumpas do WriteLn(i:2,' ',P[i].kode_pasien:4,' ',P[i].nama:10,' ',P[i].diagnosa:15); WriteLn('-------------------------------'); end; procedure layanan_prioritas(var Q:AntrianDokter;var P:larikpasien); var kode:String;prio,pos:byte;ada:Boolean; label ulang; begin ada:=false; WriteLn('selamat datang di layanan prioritas dokter budi'); write('masukkan nomor antrian yang akan di prioritaskan : ');ReadLn(prio); // mencari si nomer prioritas di antrian dan mencatat posisinya for i:=Q.front to Q.rear do begin if Q.no_antrian[i]=prio then begin ada:=true; pos:=i; end; end; if not ada then WriteLn('nomor antrian ',prio,' tidak ada di pasien yang sedang antri saat ini ') else begin WriteLn('pasien nomor ',Q.no_antrian[pos],'silahkan menuju ruang praktek '); // menggeser posisi yang sedang antri di belakang antrian prioritas for i:=pos to Q.rear-1 do begin Q.no_antrian[i]:=Q.no_antrian[i+1]; end; Dec(Q.rear); // menangani si pasien yang ada di ruang praktek WriteLn('kami akan mencatat data pasien '); ulang: Write('masukkan nomor kode pasien : ');ReadLn(kode); // validasi for i:=1 to jumpas do begin if p[i].kode_pasien = kode then begin WriteLn('kode salah , ulangi '); goto ulang; end; end; // kode sudah valid Inc(jumpas); p[jumpas].kode_pasien:=kode; Write('masukkan nama pasien ');ReadLn(p[jumpas].nama); Write('diagnosa pasien : ');ReadLn(p[jumpas].diagnosa); WriteLn('semoga lekas sembbuh :)'); end; end; procedure keluar_antrian(var Q:AntrianDokter); var nomor:Byte;ada:Boolean;pos:Byte;ya:char; begin ada:=false; WriteLn('Keluar antrian dokter '); write('masukkan nomor antrian yang akan keluar : ');readln(nomor); for i:=Q.front to Q.rear do begin if Q.no_antrian[i]=nomor then begin ada:=true;pos:=i; end; end; if not ada then WriteLn('nomor antrian ',nomor,' tidak ditemukan') else begin WriteLn('nomor antrian ',nomor,' ada di posisi ',pos); Write('yakin akan keluar dari antrian <y/t> ? : ');ReadLn(ya); if (ya='Y') or (ya='y') then begin WriteLn('terimakasih semoga anda sehat selalu '); // keluarkan dan menggeser yang ada dibelakangnya for i:=pos to Q.rear do Q.no_antrian[i]:=Q.no_antrian[i+1]; Dec(Q.rear); end else WriteLn('nomor antrian ',nomor,' tidak jadi keluar antrian '); end; end; // main program begin // inisialisasi antrian.front:=1; antrian.rear:=0; jumpas:=0; nom:=0; repeat clrscr; WriteLn('layanan antrian dokter'); WriteLn('1. Ambil Antrian '); WriteLn('2. Layanan Pasien '); WriteLn('3. cetak pasien yang sedang antri '); WriteLn('4. cetak pasien yang sudah dilayani '); WriteLn('5. prioritas layanan '); WriteLn('6. keluar dari antrian '); WriteLn('0. exit'); Write('pilih layanan ');ReadLn(pil); case pil of 1:if isFull(antrian) then WriteLn('maaf hari ini hanya melayani ',max,' pasien saja ') else ambil_antrian(antrian); 2:if isEmpty(antrian) then WriteLn('sedang tidak ada antrian ') else layanan_dokter(antrian,pasien); 3:if isEmpty(antrian) then WriteLn('sedang tidak ada antrian ') else cetak_antrian(antrian); 4:if jumpas=0 then WriteLn('belum ada pasien yang sudah dilayani ') else cetak_pasien(pasien); 5:if isEmpty(antrian) then WriteLn('sedang tidak ada antrian ') else layanan_prioritas(antrian,pasien); 6:if isEmpty(antrian) then WriteLn('sedang tidak ada antrian ') else keluar_antrian(antrian); 0:WriteLn('terimakasih ') else WriteLn('anda salah pilih jurusan '); end; ReadLn; until pil = 0; end.
unit UProcesoCorreccionFolios; interface uses Windows, Sysutils, StrUtils, IOUtils, classes, DB, DBClient, ZDataset, UDAOCaptura, UFolioCaptura,URegistroCaptura, UFtpGestor, UFtpImagen, Ucliente, UDMAplicacion; type TProcesoCaptura = class private FDatosCaptura : TRegistroCaptura; FDatosCliente : TCliente; FDatosFolio : TFolioCaptura; FDatosPersonasFolio : TList; FDatosMTIANI : TDataSource; FFondos : TDataSource; FSeriesDocumentales : TDataSource; FTiposIdentificacion : TDataSource; {METODOS PROPIOS} public qr:TZQuery; {CONSTRUCTORES} constructor Create; destructor Destroy; {PROPIEDADES} property DatosCaptura : TRegistroCaptura read FDatosCaptura; property DatosCliente : TCliente read FDatosCliente; property DatosFolio : TFolioCaptura read FDatosFolio; property DatosPersonasFolio : TList read FDatosPersonasFolio; property Fondos : TDataSource read FFondos; property SeriesDocumentales : TDataSource read FSeriesDocumentales; property TiposIdentificacion : TDataSource read FTiposIdentificacion; property DatosMTIANI : TDataSource read FDatosMTIANI; Procedure DescargarImagen; Procedure GuardarRegistroCaptura; procedure ObtenerDatosFolio; function ObtenerDatosANI (p_DescTipoIden: string; p_numedocu: string; p_primnomb:string; p_primapel:string): TDataSource; function ObtenerDatosMTI(p_identipo: variant; p_numedocu: string; p_primnomb:string; p_primapel:string): TDataSource; Procedure ObtenerFolioCaptura (p_descseridocu: string); Procedure ObtenerFondos; Procedure ObtenerSeriesDocumentales; Procedure ObtenerTiposIdentificacion; procedure RegistrarFolio(p_ObseNove: string); Procedure RegistrarNovedadSinCaptura; Procedure TerminarGuardarFolio(p_ObseNove: string); Procedure VerificarVersion(p_NombModu: string; p_VersModu: string; p_VeriRuta: Boolean); end; implementation Uses UCaptura; var DAOCaptura: TDAOCaptura; ListArch : TSearchRec; Procedure TProcesoCaptura.DescargarImagen; var ConexFTP : TFtpGestor; CarpFtpp : string; CarpLoca : string; DatosFTP : TFtpImagen; begin try DatosFTP := TFtpImagen.Create; ConexFTP := TFtpGestor.Create(DatosFTP.HostFtpImg,DatosFTP.UsuarioFtpImg, DatosFTP.PasswordFtpImg,DatosFTP.PuertoFtpImg); ConexFTP.ConectarFTP; FDatosFolio.ImagenLocal := FDatosCliente.RutaCaptura + FDatosFolio.NombreImagen; if TDirectory.Exists(FDatosCliente.RutaCaptura) then TDirectory.Delete(FDatosCliente.RutaCaptura,TRUE); TDirectory.CreateDirectory(FDatosCliente.RutaCaptura); ConexFTP.BajarArchivo(DatosFTP.CarpetaRaizFtpImg+FDatosFolio.RutaFtp,FDatosFolio.NombreImagen, FDatosCliente.RutaCaptura ); ConexFTP.DesconectarFTP; ConexFTP.Free; DatosFTP.Free; except on e:exception do raise Exception.Create('No es posible Descargar la Imagen [' + FDatosFolio.NombreImagen + '] en el equipo local.' + #10#13 + '* ' + e.Message); end; end; Procedure TProcesoCaptura.GuardarRegistroCaptura; begin try with DAOCaptura do begin IniciarTransaccion; if (FDatosCaptura.DescripcionFuenteIdentificacion = 'MTI-BASEDATOS') or (FDatosCaptura.DescripcionFuenteIdentificacion = 'MTI-CAPTURA') then FDatosCaptura.IdIdentificacion:= AgregarNuevaIdentificacion(FDatosCaptura.DescripcionTipoIdentificacion, FDatosCaptura.DescripcionFuenteIdentificacion, FDatosCaptura.NumeroDocumento, FDatosCaptura.PrimerNombre, FDatosCaptura.SegundoNombre, FDatosCaptura.PrimerApellido, FDatosCaptura.SegundoApellido); AgregarIdentificacionFolio(FDatosCaptura.IdFolio, FDatosCaptura.IdIdentificacion, FDatosCaptura.Observacion,FDatosCaptura.DescripcionTipoIdentificacion, FDatosCaptura.NumeroDocumento); {SE VERIFICA SI ES EL PRIMER REGISTRO AGREAGADO PARA REGISTRAR LOS DATOS DE LA PLANILLA, ÚNICAMENTE SI EXISTE ALGUNA DE LAS FECHAS: DE NOMINA, DE PAGO O PERIODO DE COTIZACIÓN} if (FDatosPersonasFolio.Count = 0) and (FDatosFolio.NovedadesFolio.Count = 0) then if (FDatosFolio.FechaNomina <> '') or (FDatosFolio.PeriodoCotizacion <> '') or (FDatosFolio.FechaPagoBanco <> '') then AgregarDatosPanilla(FDatosCaptura.IdFolio,FDatosFolio.TipoPlanilla, FDatosFolio.IdFondo, FDatosFolio.FechaNomina, FDatosFolio.PeriodoCotizacion, FDatosFolio.FechaPagoBanco); {SE REGISTRA EN LA LISTA DATOSPERSONASFOLIO LA NUEVA INFORMACION CAPTURADA} FDatosPersonasFolio.Add(DatosCaptura); {SI ES UN FOLIO DE HISTORIAS LABORALES SE CIERRA DE UNA VEZ} if FDatosFolio.DescTipoSerieDocum = 'HISTORIAS LABORALES' then RegistrarFolio(''); {SE ENVIA NULO PORQUE NO HAY OBSERVACION DEL FOLIO} FinalizarTransaccion; end; except on e:exception do begin DAOCaptura.CancelarTransaccion; if FDatosFolio.DescTipoSerieDocum = 'HISTORIAS LABORALES' then raise Exception.Create('No es posible Guardar el Registro de la Captura ' + 'y cerrar el Folio.' +#10#13 + '* ' + e.Message) else raise Exception.Create('No es posible Guardar el Registro de la Captura.' + #10#13 + '* ' + e.Message); end; end; end; function TProcesoCaptura.ObtenerDatosANI (p_DescTipoIden: string; p_numedocu: string; p_primnomb:string; p_primapel:string): TDataSource; begin FDatosMTIANI:= DAOCaptura.ConsultarDatosANI(p_DescTipoIden,p_numedocu, p_primnomb, p_primapel); end; Procedure TProcesoCaptura.ObtenerDatosFolio; begin DescargarImagen; FDatosPersonasFolio := DAOCaptura.ConsultarPersonasFolio(FDatosFolio.idfolio); end; function TProcesoCaptura.ObtenerDatosMTI (p_identipo: variant; p_numedocu: string; p_primnomb:string; p_primapel:string): TDataSource; begin FDatosMTIANI:= DAOCaptura.ConsultarDatosMTI(p_identipo, p_numedocu, p_primnomb,p_primapel); end; Procedure TProcesoCaptura.ObtenerFolioCaptura (p_descseridocu: string); begin FDatosFolio:= DAOCaptura.AsignarFolio(p_descseridocu,paramstr(1)); end; Procedure TProcesoCaptura.ObtenerFondos; begin FFondos:= DAOCaptura.ConsultarFondos; end; Procedure TProcesoCaptura.ObtenerSeriesDocumentales; begin FSeriesDocumentales:= DAOCaptura.ConsultarSeriesDocumentales; end; Procedure TProcesoCaptura.ObtenerTiposIdentificacion; begin FTiposIdentificacion:= DAOCaptura.ConsultarTiposIdentificacion; end; procedure TProcesoCaptura.RegistrarFolio(p_ObseNove: string); {ESTE PROCEDIMIENTO GUARDA EN BD LA INFORMACION DEL FOLIO CUANDO SE SELECCIONA LA OPCION DE TERMINAR Y GUARDAR O CUANDO SE GRABA UN REGISTRO EN UN FOLIO DE HISTORIAS LABORALES} begin with DAOCaptura do begin if p_ObseNove <> '' then AgregarNovedadFolio(FDatosFolio.IdFolio, FDatosFolio.IdTarea, p_ObseNove, 'F'); DesbloquearFolio(FDatosFolio.IdFolio, 'CAPTURA'); {SE VERIFICA SI A LA CARPETA YA SE LE CAPTURARON TODOS LOS FOLIOS QUE SON CAPTURABLES} if VerificarCarpetaCompleta(FDatosFolio.IdCarpeta) then begin if (DatosFolio.DescTipoSerieDocum = 'HISTORIAS LABORALES') then {PROCEDIMIENTO PARA DESPLEGAR DOCUMENTO A LOS FOLIOS NO CAPTURABLES EN HISTORIAS LABORALES} AsignarCapturaFoliosNoCapturables(FDatosFolio.IdCarpeta); CambiarEstadoCarpeta(FDatosFolio.IdCarpeta); end; end; end; Procedure TProcesoCaptura.RegistrarNovedadSinCaptura; begin try with DAOCaptura do begin IniciarTransaccion; AgregarNovedadFolio(FDatosFolio.IdFolio, FDatosFolio.IdTarea, FDatosCaptura.Observacion,'R'); {SE VERIFICA SI ES EL PRIMER REGISTRO AGREAGADO PARA REGISTRAR LOS DATOS DE LA PLANILLA, ÚNICAMENTE SI EXISTE ALGUNA DE LAS FECHAS: DE NOMINA, DE PAGO O PERIODO DE COTIZACIÓN} if (FDatosPersonasFolio.Count = 0) and (FDatosFolio.NovedadesFolio.Count = 0) then if (FDatosFolio.FechaNomina <> '') or (FDatosFolio.PeriodoCotizacion <> '') or (FDatosFolio.FechaPagoBanco <> '') then AgregarDatosPanilla(FDatosCaptura.IdFolio,FDatosFolio.TipoPlanilla, FDatosFolio.IdFondo, FDatosFolio.FechaNomina, FDatosFolio.PeriodoCotizacion, FDatosFolio.FechaPagoBanco); FDatosFolio.NovedadesFolio.Add(FDatosCaptura.Observacion); FinalizarTransaccion; end; except on e:exception do begin DAOCaptura.CancelarTransaccion; raise Exception.Create('No es posible registrar la Novedad del Registro del Folio [' + FDatosFolio.NombreImagen + '].' + #10#13 + '* ' + e.Message); end; end; end; Procedure TProcesoCaptura.TerminarGuardarFolio(p_ObseNove: string); begin try with DAOCaptura do begin IniciarTransaccion; RegistrarFolio(p_ObseNove); FinalizarTransaccion; end; except on e:exception do begin DAOCaptura.CancelarTransaccion; if p_ObseNove <> '' then raise Exception.Create('No es posible registrar la Novedad de la Imagen [' + FDatosFolio.NombreImagen + '].' + #10#13 + '* ' + e.Message) else raise Exception.Create('No es posible Terminar y Guardar el Folio [' + FDatosFolio.NombreImagen + '].' + #10#13 + '* ' + e.Message); end; end; end; {$REGION 'CONSTRUTOR AND DESTRUCTOR'} constructor TProcesoCaptura.Create; begin try DAOCaptura := TDAOCaptura.create; FDatosCliente := TCliente.create; FDatosCaptura := TRegistroCaptura.Create; FDatosFolio := TFolioCaptura.Create; FTiposIdentificacion:= TDataSource.create(nil); FDatosPersonasFolio := TList.Create; FDatosCliente.ConfigurarCliente; except on e:Exception do raise Exception.Create('No es posible Inicializar Componentes. ' + #10#13 + '* ' + e.Message); end; end; destructor TProcesoCaptura.Destroy; begin DAOCaptura.Free; FDatosCliente.Free; FDatosCaptura.Free; FDatosFolio.Free; FDatosPersonasFolio.Free; end; {$ENDREGION} {$REGION 'GETTERS AND SETTERS'} {$ENDREGION} end.
{********************************************************** * Copyright (c) Zeljko Cvijanovic Teslic RS/BiH * www.zeljus.com * Created by: 30-8-15 19:28:32 ***********************************************************} unit AZCScrollButons; {$mode objfpc}{$H+} {$modeswitch unicodestrings} {$namespace zeljus.com.scrollbuttons} interface uses androidr15, Rjava; type { AZCScroolButton } AZCScroolButton = class(AWLinearLayout) private fContext: ACContext; fButtons: JUArrayList; fHorizontalScropllView : AWHorizontalScrollView; fLinearLayout: AWLinearLayout; private procedure SetButtons(AValue: JUArrayList); public constructor create(para1: ACContext; aButonWidth: integer = 66); overload; procedure RefreshView; public property Buttons: JUArrayList read fButtons write SetButtons; end; implementation uses AZCDialogs; { AZCScroolButton } procedure AZCScroolButton.SetButtons(AValue: JUArrayList); begin if fButtons=AValue then Exit; fButtons:=AValue; end; constructor AZCScroolButton.create(para1: ACContext; aButonWidth: integer = 66); var Params: AWLinearLayout.InnerLayoutParams; begin fContext := para1; inherited Create(fContext); fLinearLayout:= AWLinearLayout.create(fContext); fHorizontalScropllView := AWHorizontalScrollView.Create(fContext); Params:= AWLinearLayout.InnerLayoutParams.Create( AWLinearLayout.InnerLayoutParams.WRAP_CONTENT , aButonWidth); //sirina button-a addView(fHorizontalScropllView, AVViewGroup_LayoutParams(params)); fButtons := JUArrayList.create; end; procedure AZCScroolButton.RefreshView; var i: integer; bt: AWButton; begin fLinearLayout.removeAllViews; fHorizontalScropllView.removeAllViews; for i:=0 to fButtons.size - 1 do begin fLinearLayout.addView(AVView(fButtons.get(i)) ); end; fHorizontalScropllView.addView(fLinearLayout); end; end.
unit FHIRIndexBase; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, System.Generics.Collections, AdvObjects, AdvObjectLists, AdvGenerics, FHIRBase, FHIRTypes, FHIRConstants, FHIRResources; type TFhirIndex = class (TAdvObject) private FResourceType : String; FKey: Integer; FName: String; FDescription : String; FSearchType: TFhirSearchParamTypeEnum; FTargetTypes : TArray<String>; FURI: String; FPath : String; FUsage : TFhirSearchXpathUsageEnum; FMapping : String; FExpression: TFHIRPathExpressionNode; procedure SetExpression(const Value: TFHIRPathExpressionNode); public destructor Destroy; override; function Link : TFhirIndex; Overload; function Clone : TFhirIndex; Overload; procedure Assign(source : TAdvObject); Override; property ResourceType : String read FResourceType write FResourceType; property Name : String read FName write FName; Property Description : String read FDescription write FDescription; Property Key : Integer read FKey write FKey; Property SearchType : TFhirSearchParamTypeEnum read FSearchType write FSearchType; Property TargetTypes : TArray<String> read FTargetTypes write FTargetTypes; Property URI : String read FURI write FURI; Property Path : String read FPath; Property Usage : TFhirSearchXpathUsageEnum read FUsage; Property Mapping : String read FMapping write FMapping; property expression : TFHIRPathExpressionNode read FExpression write SetExpression; function specifiedTarget : String; function summary : String; end; TFhirIndexList = class (TAdvObjectList) private function GetItemN(iIndex: integer): TFhirIndex; protected function ItemClass : TAdvObjectClass; override; public function Link : TFhirIndexList; Overload; function getByName(atype : String; name : String): TFhirIndex; function add(aResourceType : String; name, description : String; aType : TFhirSearchParamTypeEnum; aTargetTypes : Array of String; path : String; usage : TFhirSearchXpathUsageEnum): TFhirIndex; overload; function add(aResourceType : String; name, description : String; aType : TFhirSearchParamTypeEnum; aTargetTypes : Array of String; path : String; usage : TFhirSearchXpathUsageEnum; url : String): TFhirIndex; overload; function add(resourceType : String; sp : TFhirSearchParameter): TFhirIndex; overload; Property Item[iIndex : integer] : TFhirIndex read GetItemN; default; function listByType(aType : String) : TAdvList<TFhirIndex>; end; TFhirComposite = class (TAdvObject) private FResourceType : String; FKey: Integer; FName: String; FComponents : TDictionary<String, String>; public Constructor Create; override; Destructor Destroy; override; function Link : TFhirComposite; Overload; function Clone : TFhirComposite; Overload; procedure Assign(source : TAdvObject); Override; property ResourceType : String read FResourceType write FResourceType; property Name : String read FName write FName; Property Key : Integer read FKey write FKey; Property Components : TDictionary<String, String> read FComponents; end; TFhirCompositeList = class (TAdvObjectList) private function GetItemN(iIndex: integer): TFhirComposite; protected function ItemClass : TAdvObjectClass; override; public function Link : TFhirCompositeList; Overload; function getByName(aType : String; name : String): TFhirComposite; procedure add(aResourceType : String; name : String; components : array of String); overload; Property Item[iIndex : integer] : TFhirComposite read GetItemN; default; end; implementation { TFhirIndex } procedure TFhirIndex.assign(source: TAdvObject); begin inherited; FKey := TFhirIndex(source).FKey; FName := TFhirIndex(source).FName; FSearchType := TFhirIndex(source).FSearchType; FResourceType := TFhirIndex(source).FResourceType; TargetTypes := TFhirIndex(source).TargetTypes; end; function TFhirIndex.Clone: TFhirIndex; begin result := TFhirIndex(Inherited Clone); end; destructor TFhirIndex.Destroy; begin FExpression.Free; inherited; end; function TFhirIndex.Link: TFhirIndex; begin result := TFhirIndex(Inherited Link); end; procedure TFhirIndex.SetExpression(const Value: TFHIRPathExpressionNode); begin FExpression.Free; FExpression := Value; end; function TFhirIndex.specifiedTarget: String; var a : String; s : String; begin result := ''; for a in ALL_RESOURCE_TYPE_NAMES do for s in FTargetTypes do if s = a then if result = '' then result := a else exit(''); end; function TFhirIndex.summary: String; begin result := name+' : '+CODES_TFhirSearchParamTypeEnum[SearchType]; end; { TFhirIndexList } function TFhirIndexList.add(aResourceType : String; name, description : String; aType : TFhirSearchParamTypeEnum; aTargetTypes : Array of String; path : String; usage : TFhirSearchXpathUsageEnum) : TFHIRIndex; begin result := add(aResourceType, name, description, aType, aTargetTypes, path, usage, 'http://hl7.org/fhir/SearchParameter/'+aResourceType+'-'+name.Replace('[', '').Replace(']', '')); end; function TFhirIndexList.add(aResourceType : String; name, description : String; aType : TFhirSearchParamTypeEnum; aTargetTypes : Array of String; path : String; usage : TFhirSearchXpathUsageEnum; url: String) : TFHIRIndex; var ndx : TFhirIndex; i : integer; begin ndx := TFhirIndex.Create; try ndx.ResourceType := aResourceType; ndx.name := name; ndx.SearchType := aType; SetLength(ndx.FTargetTypes, length(aTargetTypes)); for i := 0 to length(ndx.TargetTypes)-1 do ndx.FTargetTypes[i] := aTargetTypes[i]; ndx.URI := url; ndx.description := description; ndx.FPath := path; ndx.FUsage := usage; inherited add(ndx.Link); result := ndx; finally ndx.free; end; end; function TFhirIndexList.add(resourceType : String; sp: TFhirSearchParameter) : TFhirIndex; var targets : TArray<String>; i : integer; begin SetLength(targets, sp.targetList.Count); for i := 0 to sp.targetList.Count - 1 do targets[i] := sp.targetList[i].value; result := add(resourceType, sp.name, sp.description, sp.type_, targets, '', sp.xpathUsage); end; function TFhirIndexList.getByName(atype, name: String): TFhirIndex; var i : integer; begin i := 0; result := nil; while (result = nil) and (i < Count) do begin if SameText(item[i].name, name) and SameText(item[i].FResourceType, atype) then result := item[i]; inc(i); end; end; function TFhirIndexList.GetItemN(iIndex: integer): TFhirIndex; begin result := TFhirIndex(ObjectByIndex[iIndex]); end; function TFhirIndexList.ItemClass: TAdvObjectClass; begin result := TFhirIndex; end; function TFhirIndexList.Link: TFhirIndexList; begin result := TFhirIndexList(Inherited Link); end; function TFhirIndexList.listByType(aType: String): TAdvList<TFhirIndex>; var i : integer; begin result := TAdvList<TFhirIndex>.create; try for i := 0 to Count - 1 do if (Item[i].ResourceType = aType) then result.Add(Item[i].Link); result.link; finally result.Free; end; end; { TFhirComposite } procedure TFhirComposite.Assign(source: TAdvObject); var s : String; begin inherited; FResourceType := TFhirComposite(source).FResourceType; FKey := TFhirComposite(source).FKey; FName := TFhirComposite(source).FName; for s in TFhirComposite(source).FComponents.Keys do FComponents.Add(s, TFhirComposite(source).FComponents[s]); end; function TFhirComposite.Clone: TFhirComposite; begin result := TFhirComposite(inherited Clone); end; constructor TFhirComposite.Create; begin inherited; FComponents := TDictionary<String,String>.create; end; destructor TFhirComposite.Destroy; begin FComponents.Free; inherited; end; function TFhirComposite.Link: TFhirComposite; begin result := TFhirComposite(inherited Link); end; { TFhirCompositeList } procedure TFhirCompositeList.add(aResourceType: string; name: String; components: array of String); var ndx : TFhirComposite; i : integer; begin ndx := TFhirComposite.Create; try ndx.ResourceType := aResourceType; ndx.name := name; i := 0; while (i < length(components)) do begin ndx.Components.Add(components[i], components[i+1]); inc(i, 2); end; inherited add(ndx.Link); finally ndx.free; end; end; function TFhirCompositeList.getByName(aType: String; name: String): TFhirComposite; var i : integer; begin i := 0; result := nil; while (result = nil) and (i < Count) do begin if SameText(item[i].name, name) and (item[i].FResourceType = atype) then result := item[i]; inc(i); end; end; function TFhirCompositeList.GetItemN(iIndex: integer): TFhirComposite; begin result := TFhirComposite(ObjectByIndex[iIndex] ); end; function TFhirCompositeList.ItemClass: TAdvObjectClass; begin result := TFhirComposite; end; function TFhirCompositeList.Link: TFhirCompositeList; begin result := TFhirCompositeList(inherited Link); end; end.
unit frmHelpUnit; {$mode objfpc}{$H+} interface uses {$ifdef windows}windows, {$endif}LCLIntf, LCLType, Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TfrmHelp } TfrmHelp = class(TForm) Image1: TImage; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Image1Click(Sender: TObject); private attachedform: TCustomForm; ftutorialtag: string; procedure fixsize; procedure attachedformboundschange(Sender: TObject); public procedure Attach(f: TCustomForm; tutorialtag: string); end; var frmHelp: TfrmHelp; implementation { TfrmHelp } procedure TfrmHelp.attachedformboundschange(Sender: TObject); var bw: integer; begin bw:=GetSystemMetrics(SM_CXEDGE); left:=attachedform.left+attachedform.Width+bw*2; top:=attachedform.top; end; procedure TfrmHelp.fixsize; begin clientwidth:=ScaleX(64,96); clientheight:=ScaleY(64,96); end; procedure TfrmHelp.Attach(f: TCustomForm; tutorialtag: string); begin attachedform:=f; ftutorialtag:=tutorialtag; f.OnChangeBounds:=@attachedformboundschange; attachedformboundschange(self); show; end; procedure TfrmHelp.FormCreate(Sender: TObject); var key: dword; begin //only works on forms in windows 7 and earlier, but also works on child components in windows 8 and later {$ifdef windows} if SetWindowLong(handle, GWL_EXSTYLE, GetWindowLong(handle, GWL_EXSTYLE) or WS_EX_LAYERED)=0 then exit; //not supported, go look at the green background key:=clLime; SetLayeredWindowAttributes(handle, clLime,0, LWA_COLORKEY); fixsize; {$endif} //ShowInTaskBar:=stNever; end; procedure TfrmHelp.FormShow(Sender: TObject); begin fixsize; end; procedure TfrmHelp.Image1Click(Sender: TObject); begin {$ifdef windows} ShellExecute(0, PChar('open'), PChar('https://cheatengine.org/tutorial.php?tutorial='+ftutorialtag),PChar(''), PChar(''), SW_SHOW); {$else} OpenURL('https://cheatengine.org/tutorial.php?tutorial='+ftutorialtag); {$endif} end; initialization {$I frmHelpUnit.lrs} end.
unit CommonObjectSelector; interface uses BaseObjects; type IObjectSelector = interface function GetSelectedObject: TIDObject; procedure SetSelectedObject(AValue: TIDObject); property SelectedObject: TIDObject read GetSelectedObject write SetSelectedObject; procedure SetMultiSelect(const Value: boolean); function GetMultiSelect: boolean; property MultiSelect: boolean read GetMultiSelect write SetMultiSelect; function GetSelectedObjects: TIDObjects; procedure SetSelectedObjects(AValue: TIDObjects); property SelectedObjects: TIDObjects read GetSelectedObjects write SetSelectedObjects; procedure ReadSelectedObjects; end; implementation end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFE_TRANSPORTE] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfeTransporteVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, NfeTransporteReboqueVO, NfeTransporteVolumeVO; type [TEntity] [TTable('NFE_TRANSPORTE')] TNfeTransporteVO = class(TVO) private FID: Integer; FID_TRANSPORTADORA: Integer; FID_NFE_CABECALHO: Integer; FMODALIDADE_FRETE: Integer; FCPF_CNPJ: String; FNOME: String; FINSCRICAO_ESTADUAL: String; FEMPRESA_ENDERECO: String; FNOME_MUNICIPIO: String; FUF: String; FVALOR_SERVICO: Extended; FVALOR_BC_RETENCAO_ICMS: Extended; FALIQUOTA_RETENCAO_ICMS: Extended; FVALOR_ICMS_RETIDO: Extended; FCFOP: Integer; FMUNICIPIO: Integer; FPLACA_VEICULO: String; FUF_VEICULO: String; FRNTC_VEICULO: String; FVAGAO: String; FBALSA: String; //Usado no lado cliente para controlar quais registros serão persistidos FPersiste: String; // Grupo X - X22 FListaNfeTransporteReboqueVO: TObjectList<TNfeTransporteReboqueVO>; //0:5 // Grupo X - X26 FListaNfeTransporteVolumeVO: TObjectList<TNfeTransporteVolumeVO>; //0:5000 public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_TRANSPORTADORA', 'Id Transportadora', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdTransportadora: Integer read FID_TRANSPORTADORA write FID_TRANSPORTADORA; [TColumn('ID_NFE_CABECALHO', 'Id Nfe Cabecalho', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfeCabecalho: Integer read FID_NFE_CABECALHO write FID_NFE_CABECALHO; [TColumn('MODALIDADE_FRETE', 'Modalidade Frete', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property ModalidadeFrete: Integer read FMODALIDADE_FRETE write FMODALIDADE_FRETE; [TColumn('CPF_CNPJ', 'Cpf Cnpj', 112, [ldGrid, ldLookup, ldCombobox], False)] property CpfCnpj: String read FCPF_CNPJ write FCPF_CNPJ; [TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('INSCRICAO_ESTADUAL', 'Inscricao Estadual', 112, [ldGrid, ldLookup, ldCombobox], False)] property InscricaoEstadual: String read FINSCRICAO_ESTADUAL write FINSCRICAO_ESTADUAL; [TColumn('EMPRESA_ENDERECO', 'Empresa Endereco', 450, [ldGrid, ldLookup, ldCombobox], False)] property EmpresaEndereco: String read FEMPRESA_ENDERECO write FEMPRESA_ENDERECO; [TColumn('NOME_MUNICIPIO', 'Nome Municipio', 450, [ldGrid, ldLookup, ldCombobox], False)] property NomeMunicipio: String read FNOME_MUNICIPIO write FNOME_MUNICIPIO; [TColumn('UF', 'Uf', 16, [ldGrid, ldLookup, ldCombobox], False)] property Uf: String read FUF write FUF; [TColumn('VALOR_SERVICO', 'Valor Servico', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorServico: Extended read FVALOR_SERVICO write FVALOR_SERVICO; [TColumn('VALOR_BC_RETENCAO_ICMS', 'Valor Bc Retencao Icms', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorBcRetencaoIcms: Extended read FVALOR_BC_RETENCAO_ICMS write FVALOR_BC_RETENCAO_ICMS; [TColumn('ALIQUOTA_RETENCAO_ICMS', 'Aliquota Retencao Icms', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaRetencaoIcms: Extended read FALIQUOTA_RETENCAO_ICMS write FALIQUOTA_RETENCAO_ICMS; [TColumn('VALOR_ICMS_RETIDO', 'Valor Icms Retido', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIcmsRetido: Extended read FVALOR_ICMS_RETIDO write FVALOR_ICMS_RETIDO; [TColumn('CFOP', 'Cfop', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Cfop: Integer read FCFOP write FCFOP; [TColumn('MUNICIPIO', 'Municipio', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Municipio: Integer read FMUNICIPIO write FMUNICIPIO; [TColumn('PLACA_VEICULO', 'Placa Veiculo', 56, [ldGrid, ldLookup, ldCombobox], False)] property PlacaVeiculo: String read FPLACA_VEICULO write FPLACA_VEICULO; [TColumn('UF_VEICULO', 'Uf Veiculo', 16, [ldGrid, ldLookup, ldCombobox], False)] property UfVeiculo: String read FUF_VEICULO write FUF_VEICULO; [TColumn('RNTC_VEICULO', 'Rntc Veiculo', 160, [ldGrid, ldLookup, ldCombobox], False)] property RntcVeiculo: String read FRNTC_VEICULO write FRNTC_VEICULO; [TColumn('VAGAO', 'Vagao', 160, [ldGrid, ldLookup, ldCombobox], False)] property Vagao: String read FVAGAO write FVAGAO; [TColumn('BALSA', 'Balsa', 160, [ldGrid, ldLookup, ldCombobox], False)] property Balsa: String read FBALSA write FBALSA; [TColumn('PERSISTE', 'Persiste', 60, [], True)] property Persiste: String read FPersiste write FPersiste; [TManyValuedAssociation('ID_NFE_TRANSPORTE','ID')] property ListaNfeTransporteReboqueVO: TObjectList<TNfeTransporteReboqueVO> read FListaNfeTransporteReboqueVO write FListaNfeTransporteReboqueVO; [TManyValuedAssociation('ID_NFE_TRANSPORTE','ID')] property ListaNfeTransporteVolumeVO: TObjectList<TNfeTransporteVolumeVO> read FListaNfeTransporteVolumeVO write FListaNfeTransporteVolumeVO; end; implementation constructor TNfeTransporteVO.Create; begin inherited; FListaNfeTransporteReboqueVO := TObjectList<TNfeTransporteReboqueVO>.Create; FListaNfeTransporteVolumeVO := TObjectList<TNfeTransporteVolumeVO>.Create; end; destructor TNfeTransporteVO.Destroy; begin FreeAndNil(FListaNfeTransporteReboqueVO); FreeAndNil(FListaNfeTransporteVolumeVO); inherited; end; initialization Classes.RegisterClass(TNfeTransporteVO); finalization Classes.UnRegisterClass(TNfeTransporteVO); end.
unit uOpenPictureForm; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} //============================================================================== interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, ExtDlgs, StdCtrls, BZColors, BZGraphic, BZBitmap, BZImageViewer, BZBitmapIO; type { TOpenPictureForm } TOpenPictureForm = class(TForm) Panel1 : TPanel; Panel2 : TPanel; OPD : TOpenPictureDialog; btnOpen : TButton; btnCancel : TButton; btnOk : TButton; ImageViewer : TBZImageViewer; btnClear : TButton; procedure btnClearClick(Sender : TObject); procedure btnOpenClick(Sender : TObject); private public constructor Create(AOwner: TComponent); override; function Execute(APicture : TBZPicture) : Boolean; end; function OpenPictureForm : TOpenPictureForm; procedure ReleaseOpenPictureForm; implementation {$R *.lfm} var vOpenPictureForm : TOpenPictureForm; function OpenPictureForm : TOpenPictureForm; begin if not Assigned(vOpenPictureForm) then vOpenPictureForm := TOpenPictureForm.Create(nil); Result := vOpenPictureForm; end; procedure ReleaseOpenPictureForm; begin if Assigned(vOpenPictureForm) then begin vOpenPictureForm.Free; vOpenPictureForm:=nil; end; end; { TOpenPictureForm } constructor TOpenPictureForm.Create(AOwner : TComponent); begin inherited Create(AOwner); OPD.Filter := GetBZImageFileFormats.BuildDialogFilters; end; procedure TOpenPictureForm.btnClearClick(Sender : TObject); begin ImageViewer.Picture.Bitmap.Clear(clrTransparent); ImageViewer.Invalidate; end; procedure TOpenPictureForm.btnOpenClick(Sender : TObject); begin if OPD.Execute then begin ImageViewer.Picture.LoadFromFile(OPD.FileName); ImageViewer.Invalidate; end; end; function TOpenPictureForm.Execute(APicture : TBZPicture) : Boolean; begin Result := (ShowModal = mrOk); if Result then begin APicture.Bitmap.Assign(ImageViewer.Picture.Bitmap); end; end; initialization finalization ReleaseOpenPictureForm; end.
{$reference 'Solid.Arduino.dll'} unit ArduinoUno; interface ///Последовательное соединение с Arduino type ardSession = Solid.Arduino.ArduinoSession; ///Режим пина type Pmode = Solid.Arduino.Firmata.PinMode; ///Состояние пина type pinstate = Solid.Arduino.Firmata.PinState; ///Режимы пина type mode = (DigitalOutput, DigitalInput, AnalogInput, AnalogOutput); ///Состояния пина type state = (HIGH, LOW); ///Класс для работы с ArduinoUno Arduino = class private ///Последовательное соединение с Arduino _conn : ardSession; ///Номер пина pinNumber : integer; ///Процедура для установки номера пина procedure PinNS(index : integer); public ///Конструктор класса Arduino для установки соединения constructor Create(); ///Функция для установки номера пина function Pin(index : integer): Arduino; ///Процедура для установки режима пина procedure SetMode(_mode: mode); ///Процедура для установки цифрового состояния пина procedure SetState(_state: state); ///Процедура для установки цифрового состояния пина procedure SetState(_state: boolean); ///Процедура для установки аналогового состояния пина procedure SetState(_state: integer); ///Функция для считывания режима и состояния пина function GetState(): pinstate; end; implementation procedure Arduino.PinNS(index : integer); begin pinNumber := index; end; constructor Arduino.Create(); begin _conn := new ardSession(Solid.Arduino.EnhancedSerialConnection.Find()); end; function Arduino.Pin(index : integer): Arduino; begin self.PinNS(index); Result := self; end; procedure Arduino.SetMode(_mode: mode); begin case _mode of mode.DigitalOutput : _conn.SetDigitalPinMode(pinNumber, Pmode.DigitalOutput); mode.DigitalInput : _conn.SetDigitalPinMode(pinNumber, Pmode.DigitalInput); mode.AnalogOutput : _conn.SetDigitalPinMode(pinNumber, Pmode.ServoControl); mode.AnalogInput : _conn.SetDigitalPinMode(pinNumber, Pmode.AnalogInput); end; end; procedure Arduino.SetState(_state: state); begin case _state of state.HIGH : _conn.SetDigitalPin(pinNumber, true); state.LOW : _conn.SetDigitalPin(pinNumber, false); end; end; procedure Arduino.SetState(_state: boolean); begin _conn.SetDigitalPin(pinNumber, _state); end; procedure Arduino.SetState(_state: integer); begin _conn.SetDigitalPin(pinNumber, _state); end; function Arduino.GetState(): pinstate; begin Result := _conn.GetPinState(pinNumber); end; end.
unit PKey; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Beinhaltet die Keytask, die Tastatureingaben entgegen nimmt, und verarbeitet. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface procedure KeyTask; implementation uses RTKernel, RTKeybrd, RTTextIO, Types, PTypes, Tools, Semas, Leader, LeadMB, THMsg, PlayMsg, Logger, LoggerMB, DispMB, PIPXSnd; procedure ShowKeySettings(var F: text); (***************************************************************************** Beschreibung: Zeigt die Tastenbelegung an. In: F: text: Dateivariable des Menuefensters Out: - *****************************************************************************) begin Write(f, FormFeed); WriteLn(f, '[S] Spiel starten'); WriteLn(f, '[B] Spiel beenden'); WriteLn(f, '[+] Max. CPU-Bedenkzeit inkrementieren'); WriteLn(f, '[-] Max. CPU-Bedenkzeit dekrementieren'); WriteLn(f, '[PrtScr] Spielstein klauen'); WriteLn(f, '[Esc] Programm beenden', #$A#$D); end; {$F+} procedure KeyTask; (***************************************************************************** Beschreibung: Keytask. In: - Out: - *****************************************************************************) var Key: char; GameStarted: boolean; KeyIn, KeyOut: text; LeaderMessage: TLeaderMessage; CPUTaskHandle: TaskHandle; PlayerMessage: TPlayerMessage; DisplayMessage: TDisplayMessage; begin Debug('Wurde erzeugt'); { Fenster erzeugen } Debug('Erzeuge Fenster'); NewWindow(KeyIn, KeyOut, cKeyWindowFirstCol, cKeyWindowFirstRow, cKeyWindowLastCol, cKeyWindowLastRow, cKeyWindowColor, ' ' + cKeyTaskName + ' '); Debug('Fenster erzeugt'); { Tastenbelegung anzeigen } ShowKeySettings(KeyOut); { Spielleitertaskhandle empfangen } Debug('Warte auf CPU-Spielertaskhandle'); THMsg.Receive(CPUTaskHandle); Debug('CPU-Spielertaskhandle empfangen'); { Spiel als nicht gestartet markieren } GameStarted := false; while true do begin { Auf Tastendruck warten } Key := UpCase(RTKeybrd.ReadKey); case Key of { Spiel starten } 'S': begin { Ueberpruefen, ob Spiel bereits gestartet ist } if not GameStarted then begin { Spiel als gestartet markieren } GameStarted := true; { Ereignis in der Startsemaphore speichern } Signal(StartSemaphore); end; end; { Spiel beenden } 'B': begin { Pruefen, ob Spiel gestartet ist } if GameStarted then begin { Spiel als nicht gestoppt markieren } GameStarted := false; { Spielleiter benachrichtigen } LeaderMessage.Kind := lemkEndGame; LeadMB.PutFront(Leader.Mailbox, LeaderMessage); end; end; { Escape } { Programmende } #27: begin { Sicherheitsabfrage } Write(KeyOut, 'Programm wirklich beenden? [J]/[N]'); repeat { Auf J oder N warten } Key := UpCase(RTKeybrd.ReadKey); if Key = 'J' then begin { Darstellungsrechner und Logger benachrichtigen } DisplayMessage.Kind := dmkExit; DispMB.Put(PIPXSnd.Mailbox, DisplayMessage); LoggerMessage.Kind := lomkExit; LoggerMB.Put(Logger.Mailbox, LoggerMessage); end; until (Key = 'J') or (Key = 'N'); { Tastenbelegung anzeigen } ShowKeySettings(KeyOut); end; { CPU-Bedenkzeit inkrementieren } '+': begin { Entsprechende Nachricht an den CPU-Spieler senden } PlayerMessage.Kind := plmkIncrementMaxTimeLimit; PlayMsg.Send(CPUTaskHandle, PlayerMessage); end; { CPU-Bedenkzeit dekrementieren } '-': begin { Entsprechende Nachricht an den CPU-Spieler senden } PlayerMessage.Kind := plmkDecrementMaxTimeLimit; PlayMsg.Send(CPUTaskHandle, PlayerMessage); end; { Taskinformationen in die Logdatei schreiben } 'T': begin Debug(''); end; { Sondertasten auslassen } #0: Key := UpCase(RTKeybrd.ReadKey); end; end; end; end.
unit dmAttributes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fdac.dmdoc, MemTableDataEh, Db, DataDriverEh, MemTableEh, FireDAC.Comp.Client, VkVariable, VkVariableBinding, VkVariableBindingDialog, uDocDescription, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet; type TAttributesDm = class(TDocDm) procedure DataModuleCreate(Sender: TObject); procedure MemTableEhDocAfterOpen(DataSet: TDataSet); procedure MemTableEhDocBeforePost(DataSet: TDataSet); private { Private declarations } procedure LocalOnChangeVariable(Sender: TObject); protected procedure DoOnInitVariables(ASender: TObject; AInsert: Boolean); procedure DoStoreVariables(Sender: TObject; AStatus: TUpdateStatus); public { Public declarations } class function GetDm: TDocDm;override; procedure Open(AId: LargeInt); procedure OnDocStruInitialize(Sender: TObject); procedure DoOnFillKeyFields(Sender: TObject); function ValidFmEditItems(Sender:TObject):Boolean;override; end; var AttributesDm: TAttributesDm; implementation uses fdac.dmmain, uLog, systemconsts, fdac.docBinding, frameObjectsGr; {$R *.dfm} { TDmAttributes } procedure TAttributesDm.DataModuleCreate(Sender: TObject); begin inherited; SqlManager.InitCommonParams('ATTRIBUTELIST','IDATTRIBUTE','GEN_ATTRIBUTELIST_ID'); SqlManager.SelectSQL.Add('SELECT al.*, attl.name as typename, obj.name as groupname '); SqlManager.SelectSQL.Add('FROM attributelist al'); SqlManager.SelectSQL.Add('LEFT OUTER JOIN attributetypelist attl ON attl.idtypeattribute = al.attributetype'); SqlManager.SelectSQL.Add('LEFT OUTER JOIN objects obj ON obj.idobject = al.idgroup'); SqlManager.SelectSQL.Add('WHERE al.id=:id'); DocStruDescriptionList.Add('id','','ID','ID',4,'',4,False,True,nil); DocStruDescriptionList.Add('idattribute','','IDATTRIBUTE','IDATTRIBUTE',4,'',4,False,True,nil); DocStruDescriptionList.Add('name','','Наименование','Наименование',60,'',60,True,False, TBindingDescription.GetBindingDescription(TEditVkVariableBinding)); DocStruDescriptionList.Add('attributetype','','Тип','Тип',40,'',40,False,True, TBindingDescription.GetBindingDescription(TComboBoxVkVariableBinding)); DocStruDescriptionList.Add('typename','','Тип','Тип',40,'',40,True,False, nil); DocStruDescriptionList.Add('nlen','','Размер','Размер',10,'',10,True,False, TBindingDescription.GetBindingDescription(TEditVkVariableBinding)); DocStruDescriptionList.Add('ndec','','Точность','Точность',10,'',10,True,False, TBindingDescription.GetBindingDescription(TEditVkVariableBinding)); DocStruDescriptionList.Add('groupname','idgroup','Группа','Группа',60,'',60,True,False, TDocMEditBoxBindingDescription.GetDocMEditBoxBindingDescription('TObjectsGrFrame',nil)); DocStruDescriptionList.Add('isunique','','Уник.','Признак уникальности',10,'',10,True,False, TBindingDescription.GetBindingDescription(TCheckBoxVkVariableBinding)); DocStruDescriptionList.Add('notempty','','Зап.','Обязательно к заполнению',10,'',10,True,False, TBindingDescription.GetBindingDescription(TCheckBoxVkVariableBinding)); DocStruDescriptionList.OnInitialize := OnDocStruInitialize; DocStruDescriptionList.GetDocStruDescriptionItem('name').bNotEmpty := True; DocStruDescriptionList.GetDocStruDescriptionItem('attributetype').bNotEmpty := True; DocStruDescriptionList.GetDocStruDescriptionItem('nlen').bNotEmpty := True; DocValidator.NotNullList.Add('name'); DocValidator.NotNullList.Add('attributetype'); OnInitVariables := DoOnInitvariables; // OnFillKeyFields := DoOnFillKeyFields; OnStoreVariables := DoStorevariables; // DocVariableList.VarByName('ctype').OnChangeVariable := LocalOnChangeVariable; end; procedure TAttributesDm.DoOnFillKeyFields(Sender: TObject); begin if DocvariableList.VarByName('idattribute').AsLargeInt=0 then DocvariableList.VarByName('idattribute').AslargeInt := DmMain.GenId('IDATTRIBUTE'); end; procedure TAttributesDm.DoOnInitVariables(ASender: TObject; AInsert: Boolean); begin if AInsert then begin DocVariableList.VarByName('id').AsLargeInt := FDQueryDoc.ParamByName('ID').AsLargeInt; DocVariableList.VarByName('isunique').AsBoolean := False; DocVariableList.VarByName('notempty').AsBoolean := False; DocVariableList.VarByName('idgroup').AsLargeInt := 0; DocVariableList.VarByName('attributetype').AsLargeInt := 0; end end; procedure TAttributesDm.DoStoreVariables(Sender: TObject; AStatus: TUpdateStatus); begin if AStatus= usInserted then begin DocVariableList.VarByName('IDATTRIBUTE').AsLargeInt := MainDm.GenId('IDATTRIBUTE'); end; end; class function TAttributesDm.GetDm: TDocDm; begin Result := TAttributesDm.Create(MainDm); end; procedure TAttributesDm.LocalOnChangeVariable(Sender: TObject); begin if Sender = DocVariableList.VarByName('attributetype') then begin if DocVariableList.VarByName('attributetype').InitValue = DocVariableList.VarByName('attributetype').AsLargeInt then begin DocvariableList.VarByName('nlen').AsInteger := DocvariableList.VarByName('nlen').InitValue; DocvariableList.VarByName('ndec').AsInteger := DocvariableList.VarByName('ndec').InitValue; end else begin case DocVariableList.VarByName('attributetype').AsLargeInt of TA_STRING : begin DocvariableList.VarByName('nlen').AsInteger := 100; DocvariableList.VarByName('ndec').AsInteger := 0; end; TA_NUMERIC : begin DocvariableList.VarByName('nlen').AsInteger := 15; DocvariableList.VarByName('ndec').AsInteger := 2; end; else DocvariableList.VarByName('nlen').AsInteger := 4; DocvariableList.VarByName('ndec').AsInteger := 0; end; end; end; end; procedure TAttributesDm.MemTableEhDocAfterOpen(DataSet: TDataSet); begin inherited; DocVariableList.VarByName('attributetype').OnChangeVariable := LocalOnChangeVariable; end; procedure TAttributesDm.MemTableEhDocBeforePost(DataSet: TDataSet); begin if DataSet.FieldByName('ID').AsLargeInt=0 then begin DataSet.FieldByName('ID').ReadOnly := False; DataSet.FieldByName('ID').AslargeInt := MainDm.GenId('IDATTRIBUTE'); end; inherited; end; procedure TAttributesDm.OnDocStruInitialize(Sender: TObject); var _Item: TVkVariableBinding; _proc: TOnRequest; begin { _Item := DocStruDescriptionList.GetDocStruDescriptionItem(DocStruDescriptionList.IndexOfName('ctype')); _Item. } Assert(Sender is TVkVariableBinding,'Invalid type'); _Item := TVkVariableBinding(Sender); if SameText(_Item.Name, 'attributetype') then begin _proc := procedure (AQuery: TFDQuery) begin while not AQuery.Eof do begin TItemComboBox(_Item.oControl).Items.Add(AQuery.FieldByName('name').AsString); AQuery.Next; end; end; DmMain.DoRequest(' SELECT * FROM attributetypelist ORDER BY idtypeattribute',[],nil,_proc); end; if SameText(_Item.Name, 'idgroup') then begin TObjectsGrFrame(TCustomDocFmVkVariableBinding(_Item).DocMEditBox.DocFm.FrameDoc).RootIdGroup := FDQueryDoc.ParamByName('ID').AsLargeInt; end; end; procedure TAttributesDm.Open(AId: largeInt); begin FDQueryDoc.Close; FDQueryDoc.SQL.Clear; FDQueryDoc.SQL.Text := SqlManager.SelectSQL.Text; try FDQueryDoc.ParamByName('id').AsLargeInt := AId; MemTableEhDoc.Open; except on E: Exception do begin LogMessage(' DmAttributes:'+#13#10+E.Message+#13#10+FDQueryDoc.SQL.Text); end; end; end; function TAttributesDm.ValidFmEditItems(Sender: TObject): Boolean; //var _Items: TVkVariableBindingCollection; begin { _Items := if True then} Result := Inherited; end; end.
unit uFrmWorkerClass; interface uses Windows, uFrmGrid, Controls, Classes, dxSkinsCore, SysUtils, uFrmBar, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsDefaultPainters, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxSkinsdxBarPainter, cxTextEdit, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ActnList, dxBar, DBClient, cxClasses, ExtCtrls, cxGridLevel, cxGridCustomView, cxGrid, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog; type TFrmWorkerClass = class(TFrmGrid) ClmnClassID: TcxGridDBColumn; ClmnClassName: TcxGridDBColumn; ClmnRemark: TcxGridDBColumn; procedure FormShow(Sender: TObject); procedure GrdbtblvwDataKeyPress(Sender: TObject; var Key: Char); procedure actNewExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure grdbtblvwDataDblClick(Sender: TObject); private procedure QueryWorkerClass(ALocate: Boolean = False; AValue: string = ''); function IsAdmin: Boolean; procedure DoShowWorkerClassEdit(AAction: string); public end; var FrmWorkerClass: TFrmWorkerClass; implementation uses HJYForms, uFrmWorkerClassEdit, UMsgBox, uSysObj; {$R *.dfm} function TFrmWorkerClass.IsAdmin: Boolean; var lClassID: string; begin lClassID := CdsData.FindField('ClassID').AsString; Result := SameText(lClassID, 'admin'); end; procedure TFrmWorkerClass.QueryWorkerClass(ALocate: Boolean; AValue: string); var lStrSql: string; begin lStrSql := 'select * from WorkerClass where (IsDelete=0 or IsDelete is null) order by ClassID'; if not DBAccess.ReadDataSet(lStrSql, CdsData) then begin ShowMsg('获取角色信息失败!'); Exit; end; if ALocate and (AValue <> '') then if cdsData.Active and not cdsData.IsEmpty then cdsData.Locate('ClassID', AValue, [loCaseInsensitive]); end; procedure TFrmWorkerClass.actDeleteExecute(Sender: TObject); const DelWorkerClassSQL = 'update WorkerClass set IsDelete=1, DeleteMan=''%s'', '+ ' DeleteTime=%s, EditTime=%s where Guid=''%s'''; var lClassGuid, lStrSql: string; begin if CdsData.Active and not CdsData.IsEmpty then begin if IsAdmin then begin ShowMsg('“系统管理员”不允许删除!'); Exit; end; if not ShowConfirm('您确定要删除当前选择的角色信息吗?') then Exit; lClassGuid := cdsData.FindField('Guid').AsString; lStrSql := Format(DelWorkerClassSQL, [Sys.WorkerInfo.WorkerID, Sys.DateStr, Sys.DateStr, lClassGuid]); if not DBAccess.ExecuteSQL(lStrSql) then begin ShowMsg('角色信息删除失败,请重新操作!'); Exit; end; QueryWorkerClass; end; end; procedure TFrmWorkerClass.actEditExecute(Sender: TObject); begin inherited; if CdsData.Active and not CdsData.IsEmpty then begin if IsAdmin then begin ShowMsg('“系统管理员”不允许修改!'); Exit; end; DoShowWorkerClassEdit('Edit'); end; end; procedure TFrmWorkerClass.actNewExecute(Sender: TObject); begin inherited; if cdsData.Active then DoShowWorkerClassEdit('Append'); end; procedure TFrmWorkerClass.actRefreshExecute(Sender: TObject); begin QueryWorkerClass; end; procedure TFrmWorkerClass.DoShowWorkerClassEdit(AAction: string); begin FrmWorkerClassEdit := TFrmWorkerClassEdit.Create(nil); try FrmWorkerClassEdit.OperAction := AAction; if AAction = 'Append' then FrmWorkerClassEdit.OnRefreshAfterPost := Self.QueryWorkerClass else begin with FrmWorkerClassEdit, cdsData do begin edtClassGuid.Text := FindField('Guid').AsString; edtClassID.Text := FindField('ClassID').AsString; edtClassName.Text := FindField('ClassName').AsString; edtRemark.Text := FindField('Remark').AsString; end; end; if FrmWorkerClassEdit.ShowModal = mrOk then QueryWorkerClass(True, Trim(FrmWorkerClassEdit.edtClassID.Text)); finally FreeAndNil(FrmWorkerClassEdit); end; end; procedure TFrmWorkerClass.FormShow(Sender: TObject); begin inherited; QueryWorkerClass; end; procedure TFrmWorkerClass.grdbtblvwDataDblClick(Sender: TObject); begin actEditExecute(nil); end; procedure TFrmWorkerClass.GrdbtblvwDataKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then actEditExecute(nil); end; initialization HJYFormManager.RegisterForm(TFrmWorkerClass); end.
unit UntValidarEventosController; interface uses ACBrReinfEventos, TypInfo, System.Rtti, ACBrReinf, System.Classes, Dialogs, SysUtils, System.IniFiles, pcnConversaoReinf; type rParametrosValidaPropriedades = record objItem: TObject; nomeClasse: String; MsgErro: String; IdRegistro: String; end; TValidarEventosController = class private FTabela: Integer; FACBrReinf: TACBrReinf; procedure pValidaPropriedades(dados: rParametrosValidaPropriedades; var MsgErro: String; var IdRegistro: String); function fValidarDadosExportacao(listaEventos: TOwnedCollection; nTabela: Integer; out MsgErro: String): Boolean; overload; function GetItensExportacaoACBr(AACBrReinf: TACBrReinf; nTabela: Integer): TOwnedCollection; public constructor Create(AACBrReinf: TACBrReinf); function fValidarDadosExportacao(nTabela: Integer; out MsgErro: String): Boolean; overload; end; implementation uses pcnReinfR1000, pcnReinfR1070, pcnReinfR2010, pcnReinfR2020, pcnReinfR2030, pcnReinfR2040, pcnReinfR2050, pcnReinfR2060, pcnReinfR2070, pcnReinfR2098, pcnReinfR2099, pcnReinfR3010, pcnReinfR9000; { TValidarEventos } procedure TValidarEventosController.pValidaPropriedades(dados: rParametrosValidaPropriedades; var MsgErro: String; var IdRegistro: String); var ctxRtti: TRttiContext; typRtti: TRttiType; prpRtti: TRttiProperty; valor: TValue; objeto: TObject; classe: TClass; nValor: Integer; cNome, valorEnum: String; cNomeClassePai: String; novosDados: rParametrosValidaPropriedades; begin ctxRtti := TRttiContext.Create; Try Try typRtti := ctxRtti.GetType(dados.objItem.ClassType); { Propertys de uma classe } For prpRtti In typRtti.GetProperties Do Begin { Pular qualquer propriedade herdada } cNomeClassePai := TRttiInstanceType(prpRtti.Parent).MetaclassType.ClassName; If ( cNomeClassePai <> dados.nomeClasse ) Then Continue; valor := prpRtti.GetValue(dados.objItem); { Validar se for coleção } If ( valor.TypeInfo.Kind = TTypeKind.tkEnumeration ) Then Begin cNome := valor.TypeInfo.Name; valorEnum := valor.ToString; nValor := GetEnumValue(valor.TypeInfo, valorEnum); Try If ( nValor = -1 ) Then MsgErro := MsgErro + sLineBreak + ' ' + Copy(cNomeClassePai,2,Length(cNomeClassePai)-1) + '.' + cNome; Except On E: Exception Do Begin ShowMessage(E.Message); End; End; End { Chamar de forma recursiva a função se for uma classe } Else If ( valor.TypeInfo.Kind = TTypeKind.tkClass ) Then Begin classe := valor.TypeData.ClassType; objeto := valor.AsType<TObject>; novosDados.nomeClasse := valor.TypeInfo.Name; novosDados.objItem := objeto; { Recursividade } pValidaPropriedades(novosDados, MsgErro, IdRegistro); End; End; Except On E: Exception Do Begin ShowMessage(E.Message); End; End; Finally ctxRtti.Free; End; end; function TValidarEventosController.fValidarDadosExportacao(listaEventos: TOwnedCollection; nTabela: Integer; out MsgErro: String): Boolean; var ctxRtti: TRttiContext; evento: TObject; dados: rParametrosValidaPropriedades; nContador: Integer; todosErros: String; begin Result := True; If Not Assigned(listaEventos) Then Exit; FTabela := nTabela; dados.nomeClasse := listaEventos.Items[0].ClassName; ctxRtti := TRttiContext.Create; Try nContador := 0; For evento In TOwnedCollection(listaEventos) Do Begin Try dados.objItem := evento; dados.MsgErro := ''; dados.IdRegistro := ''; pValidaPropriedades(dados, dados.MsgErro, dados.IdRegistro); nContador := nContador+1; If ( Trim(dados.MsgErro) <> '' ) Then Begin dados.MsgErro := '[Evento nº: '+IntToStr(nContador)+']' + dados.MsgErro; todosErros := todosErros + dados.MsgErro + sLineBreak + sLineBreak; End; Except On E: Exception Do Begin ShowMessage(E.Message); End; End; End; If ( Trim(todosErros) <> '' ) Then Begin Result := False; todosErros := 'Lista de campos não preenchidos: ' + sLineBreak + sLineBreak + todosErros; MsgErro := todosErros; End; Finally ctxRtti.Free; End; end; constructor TValidarEventosController.Create(AACBrReinf: TACBrReinf); begin FACBrReinf := AACBrReinf; end; function TValidarEventosController.fValidarDadosExportacao(nTabela: Integer; out MsgErro: String): Boolean; var validaDadosExportacao: TOwnedCollection; begin validaDadosExportacao := GetItensExportacaoACBr(FACBrReinf, nTabela); Result := fValidarDadosExportacao(validaDadosExportacao, nTabela, MsgErro); end; function TValidarEventosController.GetItensExportacaoACBr( AACBrReinf: TACBrReinf; nTabela: Integer): TOwnedCollection; begin Case nTabela Of 1000: Result := AACBrReinf.Eventos.ReinfEventos.R1000; 1070: Result := AACBrReinf.Eventos.ReinfEventos.R1070; 2010: Result := AACBrReinf.Eventos.ReinfEventos.R2010; 2020: Result := AACBrReinf.Eventos.ReinfEventos.R2020; 2030: Result := AACBrReinf.Eventos.ReinfEventos.R2030; 2040: Result := AACBrReinf.Eventos.ReinfEventos.R2040; 2050: Result := AACBrReinf.Eventos.ReinfEventos.R2050; 2060: Result := AACBrReinf.Eventos.ReinfEventos.R2060; 2070: Result := AACBrReinf.Eventos.ReinfEventos.R2070; 2098: Result := AACBrReinf.Eventos.ReinfEventos.R2098; 2099: Result := AACBrReinf.Eventos.ReinfEventos.R2099; 3010: Result := AACBrReinf.Eventos.ReinfEventos.R3010; 9000: Result := AACBrReinf.Eventos.ReinfEventos.R9000; End; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Image.Utils; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$if defined(fpc) and defined(Android) and defined(cpuarm)} {$define UsePNGExternalLibrary} {$else} {$undef UsePNGExternalLibrary} {$ifend} interface uses SysUtils, Classes, Math, PasVulkan.Types; procedure RGBAAlphaBleeding(const aData:Pointer;const aWidth,aHeight:TpvSizeInt;const a16Bit:Boolean=false); implementation uses PasVulkan.Utils; procedure RGBAAlphaBleeding(const aData:Pointer;const aWidth,aHeight:TpvSizeInt;const a16Bit:Boolean); const Offsets:array[0..8,0..1] of TpvInt32=((-1,-1),(0,-1),(1,-1),(-1,0),(0,0),(1,0),(-1,1),(0,1),(1,1)); type TpvSizeIntArray=array of TpvSizeInt; var Size,i,j,k,Index,x,y,s,t,CountPending,CountNextPending,p,Count:TpvSizeInt; r,g,b:TpvInt32; Opaque:array of TpvUInt8; Loose:array of Boolean; Pending,NextPending:TpvSizeIntArray; IsLoose:boolean; begin Opaque:=nil; Loose:=nil; Pending:=nil; NextPending:=nil; try Size:=aWidth*aHeight; SetLength(Opaque,Size); SetLength(Loose,Size); SetLength(Pending,Size); SetLength(NextPending,Size); FillChar(Opaque[0],Size*SizeOf(TpvUInt8),#0); FillChar(Loose[0],Size*SizeOf(Boolean),#0); FillChar(Pending[0],Size*SizeOf(TpvSizeInt),#0); FillChar(NextPending[0],Size*SizeOf(TpvSizeInt),#0); CountPending:=0; j:=3; for i:=0 to Size-1 do begin if ((not a16Bit) and (PpvUInt8Array(aData)^[j]=0)) or (a16Bit and (PpvUInt16Array(aData)^[j]=0)) then begin IsLoose:=true; y:=i div aWidth; x:=i-(y*aWidth); for k:=Low(Offsets) to High(Offsets) do begin s:=Offsets[k,0]; t:=Offsets[k,1]; if ((x+s)>=0) and ((x+s)<aWidth) and ((y+t)>=0) and ((y+t)<aHeight) then begin Index:=j+((s+(t*aWidth)) shl 2); if ((not a16Bit) and (PpvUInt8Array(aData)^[Index]<>0)) or (a16Bit and (PpvUInt16Array(aData)^[Index]<>0)) then begin IsLoose:=false; break; end; end; end; if IsLoose then begin Loose[i]:=true; end else begin Pending[CountPending]:=i; inc(CountPending); end; end else begin Opaque[i]:=$ff; end; inc(j,4); end; while CountPending>0 do begin CountNextPending:=0; for p:=0 to CountPending-1 do begin j:=Pending[p]; i:=j shl 2; y:=j div aWidth; x:=j-(y*aWidth); r:=0; g:=0; b:=0; Count:=0; for k:=Low(Offsets) to High(Offsets) do begin s:=Offsets[k,0]; t:=Offsets[k,1]; if ((x+s)>=0) and ((x+s)<aWidth) and ((y+t)>=0) and ((y+t)<aHeight) then begin Index:=j+(s+(t*aWidth)); if (Opaque[Index] and 1)<>0 then begin Index:=Index shl 2; if a16Bit then begin inc(r,PpvUInt16Array(aData)^[Index+0]); inc(g,PpvUInt16Array(aData)^[Index+1]); inc(b,PpvUInt16Array(aData)^[Index+2]); end else begin inc(r,PpvUInt8Array(aData)^[Index+0]); inc(g,PpvUInt8Array(aData)^[Index+1]); inc(b,PpvUInt8Array(aData)^[Index+2]); end; inc(Count); end; end; end; if Count>0 then begin if a16Bit then begin PpvUInt16Array(aData)^[i+0]:=r div Count; PpvUInt16Array(aData)^[i+1]:=g div Count; PpvUInt16Array(aData)^[i+2]:=b div Count; end else begin PpvUInt8Array(aData)^[i+0]:=r div Count; PpvUInt8Array(aData)^[i+1]:=g div Count; PpvUInt8Array(aData)^[i+2]:=b div Count; end; Opaque[j]:=$fe; for k:=Low(Offsets) to High(Offsets) do begin s:=Offsets[k,0]; t:=Offsets[k,1]; if ((x+s)>=0) and ((x+s)<aWidth) and ((y+t)>=0) and ((y+t)<aHeight) then begin Index:=j+(s+(t*aWidth)); if Loose[Index] then begin Loose[Index]:=false; NextPending[CountNextPending]:=Index; inc(CountNextPending); end; end; end; end else begin NextPending[CountNextPending]:=j; inc(CountNextPending); end; end; if CountNextPending>0 then begin for p:=0 to CountPending-1 do begin Opaque[Pending[p]]:=Opaque[Pending[p]] shr 1; end; end; TpvSwap<TpvSizeIntArray>.Swap(Pending,NextPending); CountPending:=CountNextPending; end; finally Opaque:=nil; Loose:=nil; Pending:=nil; NextPending:=nil; end; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela de Encerramento do Exercício para o módulo Contabilidade The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (alberteije@gmail.com) @version 2.0 ******************************************************************************* } unit UContabilEncerramentoExercicio; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, ContabilEncerramentoExeCabVO, ContabilEncerramentoExeCabController, Tipos, Atributos, Constantes, LabeledCtrls, JvToolEdit, Mask, JvExMask, JvBaseEdits, Math, StrUtils, ActnList, Generics.Collections, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, Controller; type [TFormDescription(TConstantes.MODULO_CONTABILIDADE, 'Encerramento do Exercício')] TFContabilEncerramentoExercicio = class(TFTelaCadastro) DSContabilEncerramentoExercicioDetalhe: TDataSource; CDSContabilEncerramentoExercicioDetalhe: TClientDataSet; PanelMestre: TPanel; PageControlItens: TPageControl; tsItens: TTabSheet; PanelItens: TPanel; GridDetalhe: TJvDBUltimGrid; EditDataInicio: TLabeledDateEdit; EditDataInclusao: TLabeledDateEdit; EditMotivo: TLabeledEdit; EditDataFim: TLabeledDateEdit; CDSContabilEncerramentoExercicioDetalheID: TIntegerField; CDSContabilEncerramentoExercicioDetalheID_CONTABIL_CONTA: TIntegerField; CDSContabilEncerramentoExercicioDetalheID_CONTABIL_ENCERRAMENTO_EXE: TIntegerField; CDSContabilEncerramentoExercicioDetalheSALDO_ANTERIOR: TFMTBCDField; CDSContabilEncerramentoExercicioDetalheVALOR_DEBITO: TFMTBCDField; CDSContabilEncerramentoExercicioDetalheVALOR_CREDITO: TFMTBCDField; CDSContabilEncerramentoExercicioDetalheSALDO: TFMTBCDField; procedure FormCreate(Sender: TObject); procedure GridDblClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; procedure LimparCampos; override; procedure ControlaBotoes; override; procedure ControlaPopupMenu; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; procedure ConfigurarLayoutTela; end; var FContabilEncerramentoExercicio: TFContabilEncerramentoExercicio; implementation uses ULookup, Biblioteca, UDataModule, ContabilEncerramentoExeDetVO; {$R *.dfm} {$REGION 'Controles Infra'} procedure TFContabilEncerramentoExercicio.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TContabilEncerramentoExeCabVO; ObjetoController := TContabilEncerramentoExeCabController.Create; inherited; end; procedure TFContabilEncerramentoExercicio.LimparCampos; begin inherited; CDSContabilEncerramentoExercicioDetalhe.EmptyDataSet; end; procedure TFContabilEncerramentoExercicio.ConfigurarLayoutTela; begin PanelEdits.Enabled := True; if StatusTela = stNavegandoEdits then begin PanelMestre.Enabled := False; PanelItens.Enabled := False; end else begin PanelMestre.Enabled := True; PanelItens.Enabled := True; end; end; procedure TFContabilEncerramentoExercicio.ControlaBotoes; begin inherited; BotaoImprimir.Visible := False; end; procedure TFContabilEncerramentoExercicio.ControlaPopupMenu; begin inherited; MenuImprimir.Visible := False; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFContabilEncerramentoExercicio.DoInserir: Boolean; begin Result := inherited DoInserir; ConfigurarLayoutTela; if Result then begin EditMotivo.SetFocus; end; end; function TFContabilEncerramentoExercicio.DoEditar: Boolean; begin Result := inherited DoEditar; ConfigurarLayoutTela; if Result then begin EditMotivo.SetFocus; end; end; function TFContabilEncerramentoExercicio.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('ContabilEncerramentoExeCabController.TContabilEncerramentoExeCabController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('ContabilEncerramentoExeCabController.TContabilEncerramentoExeCabController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFContabilEncerramentoExercicio.DoSalvar: Boolean; var ContabilEncerramentoExercicioDetalhe: TContabilEncerramentoExeDetVO; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TContabilEncerramentoExeCabVO.Create; TContabilEncerramentoExeCabVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id; TContabilEncerramentoExeCabVO(ObjetoVO).Motivo := EditMotivo.Text; TContabilEncerramentoExeCabVO(ObjetoVO).DataInicio := EditDataInicio.Date; TContabilEncerramentoExeCabVO(ObjetoVO).DataFim := EditDataFim.Date; TContabilEncerramentoExeCabVO(ObjetoVO).DataInclusao := EditDataInclusao.Date; // Detalhes TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO := TObjectList<TContabilEncerramentoExeDetVO>.Create; CDSContabilEncerramentoExercicioDetalhe.DisableControls; CDSContabilEncerramentoExercicioDetalhe.First; while not CDSContabilEncerramentoExercicioDetalhe.Eof do begin ContabilEncerramentoExercicioDetalhe := TContabilEncerramentoExeDetVO.Create; ContabilEncerramentoExercicioDetalhe.Id := CDSContabilEncerramentoExercicioDetalheID.AsInteger; ContabilEncerramentoExercicioDetalhe.IdContabilEncerramentoExe := TContabilEncerramentoExeCabVO(ObjetoVO).Id; ContabilEncerramentoExercicioDetalhe.IdContabilConta := CDSContabilEncerramentoExercicioDetalheID_CONTABIL_CONTA.AsInteger; ContabilEncerramentoExercicioDetalhe.SaldoAnterior := CDSContabilEncerramentoExercicioDetalheSALDO_ANTERIOR.AsExtended; ContabilEncerramentoExercicioDetalhe.ValorDebito := CDSContabilEncerramentoExercicioDetalheVALOR_DEBITO.AsExtended; ContabilEncerramentoExercicioDetalhe.ValorCredito := CDSContabilEncerramentoExercicioDetalheVALOR_CREDITO.AsExtended; ContabilEncerramentoExercicioDetalhe.Saldo := CDSContabilEncerramentoExercicioDetalheSALDO.AsExtended; TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO.Add(ContabilEncerramentoExercicioDetalhe); CDSContabilEncerramentoExercicioDetalhe.Next; end; CDSContabilEncerramentoExercicioDetalhe.EnableControls; if StatusTela = stInserindo then begin TController.ExecutarMetodo('ContabilEncerramentoExeCabController.TContabilEncerramentoExeCabController', 'Insere', [TContabilEncerramentoExeCabVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TContabilEncerramentoExeCabVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('ContabilEncerramentoExeCabController.TContabilEncerramentoExeCabController', 'Altera', [TContabilEncerramentoExeCabVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFContabilEncerramentoExercicio.GridDblClick(Sender: TObject); begin inherited; ConfigurarLayoutTela; end; procedure TFContabilEncerramentoExercicio.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TContabilEncerramentoExeCabVO(TController.BuscarObjeto('ContabilEncerramentoExeCabController.TContabilEncerramentoExeCabController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditMotivo.Text := TContabilEncerramentoExeCabVO(ObjetoVO).Motivo; EditDataInicio.Date := TContabilEncerramentoExeCabVO(ObjetoVO).DataInicio; EditDataFim.Date := TContabilEncerramentoExeCabVO(ObjetoVO).DataFim; EditDataInclusao.Date := TContabilEncerramentoExeCabVO(ObjetoVO).DataInclusao; // Preenche as grids internas com os dados das Listas que vieram no objeto TController.TratarRetorno<TContabilEncerramentoExeDetVO>(TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO, True, True, CDSContabilEncerramentoExercicioDetalhe); // Limpa as listas para comparar posteriormente se houve inclusões/alterações e subir apenas o necessário para o servidor TContabilEncerramentoExeCabVO(ObjetoVO).ListaContabilEncerramentoExeDetVO.Clear; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; ConfigurarLayoutTela; end; {$ENDREGION} /// EXERCICIO /// Implemente as rotinas automáticas no sistema end.
unit UnitMenu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, jpeg; type TFormMenu = class(TForm) MainMenu1: TMainMenu; Panel1: TPanel; Image1: TImage; Opes1: TMenuItem; Cadastro1: TMenuItem; CadastroCliente1: TMenuItem; Locao1: TMenuItem; N1: TMenuItem; Sair1: TMenuItem; EntradadeProduto1: TMenuItem; Cheques1: TMenuItem; Utilitrios1: TMenuItem; Calculadora1: TMenuItem; Internet1: TMenuItem; Word1: TMenuItem; Excel1: TMenuItem; procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Sair1Click(Sender: TObject); procedure Cadastro1Click(Sender: TObject); procedure CadastroCliente1Click(Sender: TObject); procedure Locao1Click(Sender: TObject); procedure EntradadeProduto1Click(Sender: TObject); procedure Cheques1Click(Sender: TObject); procedure Calculadora1Click(Sender: TObject); procedure Word1Click(Sender: TObject); procedure Excel1Click(Sender: TObject); procedure Internet1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMenu: TFormMenu; implementation uses UnitInicial, UnitCadastro, UnitCheque, UnitCliente, UnitLocacao, UnitEntrada, UnitProduto; {$R *.DFM} procedure TFormMenu.FormActivate(Sender: TObject); begin FormInicial.Timer1.Enabled:=False; FormInicial.Hide; end; procedure TFormMenu.FormClose(Sender: TObject; var Action: TCloseAction); begin FormInicial.Close; end; procedure TFormMenu.Sair1Click(Sender: TObject); begin FormInicial.Close; end; procedure TFormMenu.Cadastro1Click(Sender: TObject); begin Application.CreateForm (TFormProduto, FormProduto); FormProduto.TabelaProduto.Open; FormProduto.ShowModal; FormProduto.Release; end; procedure TFormMenu.CadastroCliente1Click(Sender: TObject); begin Application.CreateForm (TFormCliente, FormCliente); FormCliente.TabelaCliente.Open; FormCliente.ShowModal; FormCliente.Release; end; procedure TFormMenu.Locao1Click(Sender: TObject); begin Application.CreateForm (TFormPedido,FormPedido); FormPedido.TabelaPedido.Open; FormPedido.TabelaPedidoItem.Open; FormPedido.ListaClientes.Close; FormPedido.ListaProduto.Close; FormPedido.TabelaSoma.Close; FormPedido.PagePedido.ActivePageIndex:=0; FormPedido.ShowModal; FormPedido.Release; end; procedure TFormMenu.EntradadeProduto1Click(Sender: TObject); begin Application.CreateForm (TFormEntrada, FormEntrada); FormEntrada.TabelaEntrada.Open; FormEntrada.TabelaProduto.Open; FormEntrada.TabelaVenda.open; formEntrada.PageEntrada.ActivePageIndex:=0; FormEntrada.ShowModal; FormEntrada.Release; end; procedure TFormMenu.Cheques1Click(Sender: TObject); begin Application.CreateForm (TFormCheque, FormEntrada); FormEntrada.TabelaEntrada.Open; FormEntrada.ShowModal; FormEntrada.Release; end; procedure TFormMenu.Calculadora1Click(Sender: TObject); begin WinExec ('Calc.exe',SW_Show); end; procedure TFormMenu.Word1Click(Sender: TObject); begin WinExec ('C:\Arquivos de programas\Microsoft Office\Office\WinWord',SW_Show); end; procedure TFormMenu.Excel1Click(Sender: TObject); begin WinExec ('C:\Arquivos de programas\Microsoft Office\Office\Excel',SW_Show); end; procedure TFormMenu.Internet1Click(Sender: TObject); begin WinExec ('C:\Arquivos de programas\Internet Explorer\Iexplore',SW_Show); end; end.
(* @file UVector2i.pas * @author Willi Schinmeyer * @date 2011-10-30 * * The TVector2i type. I put it in its own unit to prevent cyclic dependencies. *) unit UVector2i; interface type (* @brief a 2 dimensional integer vector *) TVector2i = record x, y : integer; end; (* @brief Vector additin *) operator +(lhs, rhs : TVector2i) result : TVector2i; implementation operator +(lhs, rhs : TVector2i) result : TVector2i; begin result.x := lhs.x + rhs.x; result.y := lhs.y + rhs.y; end; begin end.
unit UMain; interface uses Windows, ULogger, UServer, UServerTypes; type TProgram = class class procedure Main(); end; implementation class procedure TProgram.Main; var server: IServer; buffer: string; logger: ILogger; begin SetConsoleTitle('Ip Server'); {$IFDEF DEBUG} logger := TConsoleLogger.Create(); {$ELSE} logger := TStubLogger.Create(); {$ENDIF} logger.Log('Type q and press Enter for exit', elNotice); server := TServer.Create(logger); server.Start(); repeat ReadLn(buffer); if buffer = 'q' then Break; until false; server := nil; logger := nil; end; end.
unit HS4D; interface uses HS4D.Interfaces; type THS4D = class(TInterfacedObject, iHS4D) private FCredencial : iHS4DCredential; public constructor Create; destructor Destroy; override; class function New : iHS4D; function Credential : iHS4DCredential; function SendFile : iHS4DSend; function GetFile : iHS4DGet; end; implementation uses HS4D.Send, HS4D.Get, HS4D.Credential; { THS4D } constructor THS4D.Create; begin end; function THS4D.Credential: iHS4DCredential; begin if not Assigned(FCredencial) then FCredencial := THS4DCredential.New(Self); Result := FCredencial; end; destructor THS4D.Destroy; begin inherited; end; function THS4D.GetFile: iHS4DGet; begin Result:= THSD4Get.new(Self); end; class function THS4D.New: iHS4D; begin Result:= self.Create; end; function THS4D.SendFile: iHS4DSend; begin Result:= THS4DSend.new(Self); end; end.
unit customTypes; interface type TArray = array of string; TChar = set of char; TErrors = (ENoError, EInvChar {= $0001}, ELongOp {= $0002}, ENotEnoughOps {= $0004}, ENotEnoughBrackets, ELexemsBoundaryExeeded {= $0008}); TCharType = (CUnexpected, CSpecial, CLetter, CSign, CDelimeter); tCountAr = array of record //stores operands and operators and their count lex: String; num: integer; isOperator: boolean; end; const ERRORMSG: array [TErrors] of string = ( 'Everything is good! ', 'ERROR! Invalid character detected', 'ERROR! Too long operand detected', 'ERROR! Not enough operands! Last readed:', 'ERROR! Number of ''('' and '')'' symbols doesnt match', 'ERROR! Parser exeeded number of readed lexems!'); Letters : TChar = ['A'..'Z', 'a'..'z', '_', '0'..'9', '@', '^', '.', '#', '$']; Signs : TChar = ['~', ':', '=', '/', '\', '+', '-', '*', '%', '&', '|', '<', '>', '?', {';',} '''', ',', '"']; Delimeters : TChar = ['{', '}', '[', ']', '(', ')', ';', ',']; STR_VARIABLE_HEADER = ' int byte short long boolean char double float '; { TYPES = ' int byte short long boolean char double float void '; PREFIXES = ' final private public protected static volatile transient native strictfp abstract synchronized new '; POSTFIXES = ' extends throws implements '; // if classes ignored? STRUCTURES = ' class interface package enum '; //enum???? CYCLES = ' do for while '; JUMPES = ' break return continue '; IGNORED = ' import class package'; //until the EoL ENTRIES = ' ( { = < : ? assert catch if else case switch default try catch finally throw'; //;????? } MAJORENTRIES = ' ( { [ = ? : assert if switch try throw '; MINORENTRIES = ' else case default catch finally '; CYCLES = ' do for while '; JUMPES = ' break return continue '; SUPER_IGNORED = ' import class package enum '; //until the EoL IGNORED = 'new class interface package extends throws implements final private public protected static volatile transient native strictfp abstract synchronized new int byte short long boolean char double float void String '; OP_SIGNS = ' ~ / \ + - * % & | '' , " ; < > '; DSIGNS = ' <= >= == != ++ -- || && '; BLACKLIST = ' } ] ) '; var nLexems: integer; implementation end.
unit Guias; interface uses SysUtils, Classes, ExtCtrls, Graphics; type TTipo_Entidade = (teSindicato, teFederacao, teConfederacao, teCees); {Classe para gerar código de barras para boletos} TCodigoBarra = class private fCodigo: string; {Dados que serão incluídos no código de barras} function GetLinhaDigitavel : string; {Retorna a representação numérica do código de barras} function Define2de5 : string; {Define o formato do código de barras INTERCALADO 2 DE 5, retornando a seqüência de 0 e 1 que será usada para gerar a imagem do código de barras} function GetImagem : TImage; {Gera a imagem do código de barras} public property Codigo : string read fCodigo write fCodigo; property LinhaDigitavel : string read GetLinhaDigitavel; property Imagem : TImage read GetImagem; end; {TEndereco representa o endereço de cedentes ou sacados} TEstado = string[2]; TCEP = string[8]; TEndereco = class(TPersistent) public fRua, fNumero, fComplemento, fBairro, fCidade, fEMail : string; fEstado : TEstado; fCEP : TCEP; procedure Assign(AEndereco: TEndereco); reintroduce; published property Rua : string read fRua write fRua; property Numero : string read fNumero write fNumero; property Complemento : string read fComplemento write fComplemento; property Bairro : string read fBairro write fBairro; property Cidade : string read fCidade write fCidade; property Estado : TEstado read fEstado write fEstado; property CEP : TCEP read fCEP write fCEP; property EMail : string read fEMail write fEMail; end; {Dados sobre os cedentes ou sacados} TPessoa = class(TPersistent) private fNome : string; fEndereco : TEndereco; public constructor Create; destructor Destroy; override; procedure Assign(APessoa: TPessoa); reintroduce; published property Nome : string read fNome write fNome; property Endereco : TEndereco read fEndereco write fEndereco; end; {Dados completos sobre o cedente - Classe derivada de TgbPessoa} TCedente = class(TPessoa) private fCNPJ, fSICAS_Completo, fSICAS_Simples, fCNAE : string; public procedure Assign(ACedente: TCedente); published property CNPJ : string read fCNPJ write fCNPJ; property SICAS_Completo : string read fSICAS_Completo write fSICAS_Completo; property SICAS_Simples : string read fSICAS_Simples write fSICAS_Simples; property CNAE : string read fCNAE write fCNAE; end; {Dados completos sobre o sacado - Classe derivada de TgbPessoa} TContribuinte = string[12]; TSacado = class(TPessoa) private fContribuinte : TContribuinte; fContribuinte_Mask : string; fCapital_Social : real; public procedure Assign(ASacado: TSacado); published property Contribuinte : TContribuinte read fContribuinte write fContribuinte; property Contribuinte_Mask : string read fContribuinte_Mask write fContribuinte_Mask; property Capital_Social : real read fCapital_Social write fCapital_Social; end; {Dados sobre os cedentes ou sacados} TValores = class(TPersistent) private fContribuicao, fAbatimento, fDeducao, fMulta, fAcrescimo : real; public constructor Create; destructor Destroy; override; procedure Assign(AValores: TValores); reintroduce; published property Contribuicao: real read fContribuicao write fContribuicao; property Abatimento : real read fAbatimento write fAbatimento; property Deducao : real read fDeducao write fDeducao; property Multa : real read fMulta write fMulta; property Acrescimo : real read fAcrescimo write fAcrescimo; end; TGuias = class(TComponent) private { Private declarations } fVencimento :TDateTime; fExercicio :String; fMensagem :TStringList; fCedente :TCedente; fSacado :TSacado; fValores :TValores; fEspecie :String; fTipo_Entidade :TTipo_Entidade; // procedure PrepararBoleto(ABoleto: TImp_GRCS); function GerarCodigoBarra : TCodigoBarra; procedure SetMensagem(Texto: TStringList); protected { Protected declarations } public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; property CodigoBarra : TCodigoBarra read GerarCodigoBarra; procedure Assign(AGuia: TGuias); // procedure Visualizar; // procedure Imprimir; published { Published declarations } property Vencimento :TDateTime read fVencimento write fVencimento; property Exercicio :string read fExercicio write fExercicio; property Mensagem :TStringList read fMensagem write SetMensagem; property Cedente :TCedente read fCedente write fCedente; property Sacado :TSacado read fSacado write fSacado; property Valores :TValores read fValores write fValores; property Especie :string read fEspecie write fEspecie; property Tipo_Entidade :TTipo_Entidade read fTipo_Entidade write fTipo_Entidade; end; procedure Register; function Formatar(Texto : string; TamanhoDesejado : integer; AcrescentarADireita : boolean = true; CaracterAcrescentar : char = ' ') : string; function Modulo11(Valor: String; Base: Integer = 9; Resto : boolean = false) : string; function CalcularFatorVencimento(DataDesejada : TDateTime) : string; implementation function CalcularFatorVencimento(DataDesejada : TDateTime) : string; {O fator de vencimento é a quantidade de dias entre 07/Nov/1997 e a data de vencimento do título} begin Result := IntToStr( Trunc(DataDesejada - EncodeDate(1997,10,07))); end; function Modulo11(Valor: String; Base: Integer = 9; Resto : boolean = false) : string; { Rotina muito usada para calcular dígitos verificadores Pega-se cada um dos dígitos contidos no parâmetro VALOR, da direita para a esquerda e multiplica-se pela seqüência de pesos 2, 3, 4 ... até BASE. Por exemplo: se a base for 9, os pesos serão 2,3,4,5,6,7,8,9,2,3,4,5... Se a base for 7, os pesos serão 2,3,4,5,6,7,2,3,4... Soma-se cada um dos subprodutos. Divide-se a soma por 11. Faz-se a operação 11-Resto da divisão e devolve-se o resultado dessa operação como resultado da função Modulo11. Obs.: Caso o resultado seja maior que 9, deverá ser substituído por 0 (ZERO). } var Soma : integer; Contador, Peso, Digito : integer; begin Soma := 0; Peso := 2; for Contador := Length(Valor) downto 1 do begin Soma := Soma + (StrToInt(Valor[Contador]) * Peso); if Peso < Base then Peso := Peso + 1 else Peso := 2; end; if Resto then Result := IntToStr(Soma mod 11) else begin Digito := 11 - (Soma mod 11); if (Digito > 9) then Digito := 0; Result := IntToStr(Digito); end end; function Formatar(Texto : string; TamanhoDesejado : integer; AcrescentarADireita : boolean = true; CaracterAcrescentar : char = ' ') : string; { OBJETIVO: Eliminar caracteres inválidos e acrescentar caracteres à esquerda ou à direita do texto original para que a string resultante fique com o tamanho desejado Texto : Texto original TamanhoDesejado: Tamanho que a string resultante deverá ter AcrescentarADireita: Indica se o carácter será acrescentado à direita ou à esquerda TRUE - Se o tamanho do texto for MENOR que o desejado, acrescentar carácter à direita Se o tamanho do texto for MAIOR que o desejado, eliminar últimos caracteres do texto FALSE - Se o tamanho do texto for MENOR que o desejado, acrescentar carácter à esquerda Se o tamanho do texto for MAIOR que o desejado, eliminar primeiros caracteres do texto CaracterAcrescentar: Carácter que deverá ser acrescentado } 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; {TCodigoBarra} function TCodigoBarra.Define2de5 : string; {Traduz dígitos do código de barras para valores de 0 e 1, formando um código do tipo Intercalado 2 de 5} var CodigoAuxiliar : string; Start : string; Stop : string; T2de5 : array[0..9] of string; Codifi : string; I : integer; begin Result := 'Erro'; Start := '0000'; Stop := '100'; T2de5[0] := '00110'; T2de5[1] := '10001'; T2de5[2] := '01001'; T2de5[3] := '11000'; T2de5[4] := '00101'; T2de5[5] := '10100'; T2de5[6] := '01100'; T2de5[7] := '00011'; T2de5[8] := '10010'; T2de5[9] := '01010'; { Digitos } for I := 1 to length(Codigo) do begin if pos(Codigo[I],'0123456789') <> 0 then Codifi := Codifi + T2de5[StrToInt(Codigo[I])] else Exit; end; {Se houver um número ímpar de dígitos no Código, acrescentar um ZERO no início} if odd(length(Codigo)) then Codifi := T2de5[0] + Codifi; {Intercalar números - O primeiro com o segundo, o terceiro com o quarto, etc...} I := 1; CodigoAuxiliar := ''; while I <= (length(Codifi) - 9)do begin CodigoAuxiliar := CodigoAuxiliar + Codifi[I] + Codifi[I+5] + Codifi[I+1] + Codifi[I+6] + Codifi[I+2] + Codifi[I+7] + Codifi[I+3] + Codifi[I+8] + Codifi[I+4] + Codifi[I+9]; I := I + 10; end; { Acrescentar caracteres Start e Stop } Result := Start + CodigoAuxiliar + Stop; end; function TCodigoBarra.GetLinhaDigitavel : string; var Campo1, Campo2, Campo3, Campo4: string; begin Campo1 := Copy(Codigo, 1, 11) ; Campo1 := Campo1 + Modulo11(Campo1); Campo2 := Copy(Codigo, 12, 11); Campo2 := Campo2 + Modulo11(Campo2); Campo3 := Copy(Codigo, 23, 11); Campo3 := Campo3 + Modulo11(Campo3); Campo4 := Copy(Codigo, 34, 11); Campo4 := Campo4 + Modulo11(Campo4); Result := Campo1 + ' - ' + Campo2 + ' - ' + Campo3 + ' - ' + Campo4; end; function TCodigoBarra.GetImagem : TImage; const CorBarra = clBlack; CorEspaco = clWhite; LarguraBarraFina = 1; LarguraBarraGrossa = 3; AlturaBarra = 50; var X : integer; Col : integer; Lar : integer; CodigoAuxiliar : string; begin CodigoAuxiliar := Define2de5; Result := TImage.Create(nil); Result.Height := AlturaBarra; Result.Width := 0; For X := 1 to Length(CodigoAuxiliar) do case CodigoAuxiliar[X] of '0' : Result.Width := Result.Width + LarguraBarraFina; '1' : Result.Width := Result.Width + LarguraBarraGrossa; end; Col := 0; if CodigoAuxiliar <> 'Erro' then begin for X := 1 to length(CodigoAuxiliar) do begin {Desenha barra} with Result.Canvas do begin if Odd(X) then Pen.Color := CorBarra else Pen.Color := CorEspaco; if CodigoAuxiliar[X] = '0' then begin for Lar := 1 to LarguraBarraFina do begin MoveTo(Col,0); LineTo(Col,AlturaBarra); Col := Col + 1; end; end else begin for Lar := 1 to LarguraBarraGrossa do begin MoveTo(Col,0); LineTo(Col,AlturaBarra); Col := Col + 1; end; end; end; end; end else Result.Canvas.TextOut(0,0,'Erro'); end; {TEndereco} procedure TEndereco.Assign(AEndereco: TEndereco); begin Rua := AEndereco.Rua; Numero := AEndereco.Numero; Complemento := AEndereco.Complemento; Bairro := AEndereco.Bairro; Cidade := AEndereco.Cidade; Estado := AEndereco.Estado; CEP := AEndereco.CEP; EMail := AEndereco.EMail; end; {TPessoa} constructor TPessoa.Create; begin inherited Create; Endereco := TEndereco.Create; end; destructor TPessoa.Destroy; begin Endereco.Destroy; inherited Destroy; end; procedure TPessoa.Assign(APessoa: TPessoa); begin Nome := APessoa.Nome; Endereco.Assign(APessoa.Endereco); end; procedure TCedente.Assign(ACedente: TCedente); begin inherited Assign(ACedente); CNPJ := ACedente.CNPJ; SICAS_Completo := ACedente.SICAS_Completo; SICAS_Simples := ACedente.SICAS_Simples; CNAE := ACedente.CNAE; end; procedure TSacado.Assign(ASacado: TSacado); begin inherited Assign(ASacado); Contribuinte := ASacado.Contribuinte; Contribuinte_Mask := ASacado.Contribuinte_Mask; Capital_Social := ASacado.Capital_Social; end; {TValores} constructor TValores.Create; begin inherited Create; //Valores := TValores.Create; end; destructor TValores.Destroy; begin inherited Destroy; end; procedure TValores.Assign(AValores: TValores); begin Contribuicao := AValores.Contribuicao; Abatimento := AValores.Abatimento; Deducao := AValores.Deducao; Multa := AValores.Multa; Acrescimo := AValores.Acrescimo; end; {TGuias} constructor TGuias.Create(Owner: TComponent); begin inherited Create(Owner); // Initialize inherited parts fCedente := TCedente.Create; fSacado := TSacado.Create; fValores := TValores.Create; fMensagem := TStringList.Create; fEspecie := 'R$'; fVencimento := Date; end; destructor TGuias.Destroy; begin Cedente.Destroy; Sacado.Destroy; Valores.Destroy; Mensagem.Destroy; inherited Destroy; end; procedure TGuias.Assign(AGuia: TGuias); begin Exercicio := AGuia.Exercicio; Especie := AGuia.Especie; Tipo_Entidade := AGuia.Tipo_Entidade; Vencimento := AGuia.Vencimento; Cedente.Assign(AGuia.Cedente); Sacado.Assign(AGuia.Sacado); Mensagem.Assign(AGuia.Mensagem); end; procedure TGuias.SetMensagem(Texto: TStringList); begin fMensagem.Assign(Texto); end; {procedure TGuias.Visualizar; var ABoleto : TImp_GRCS; begin ABoleto := TImp_GRCS.Create(nil); TRY PrepararBoleto(ABoleto); ABoleto.Preview; ABoleto.Free; EXCEPT ABoleto.Free; Raise; END; end; procedure TGuias.Imprimir; var ABoleto : TImp_GRCS; begin ABoleto := TImp_GRCS.Create(nil); TRY PrepararBoleto(ABoleto); ABoleto.Print; ABoleto.Free; EXCEPT ABoleto.Free; Raise; END; end; } //////////////////////////////////////////////////////////// ////// termino da criação do componente //////////////////////////////////////////////////////////// function TGuias.GerarCodigoBarra : TCodigoBarra; var AValor_Total :Real; ACodigoBanco, ACodigoMoeda, ADigitoCodigoBarras, AFatorVencimento, AValorDocumento, ASICOB, AEntidade, ACNAE_P1, ATP_Entidade, ASITCS, AContribuinte, ACNAE_P2, ACodigoBarras: string; begin Result := TCodigoBarra.Create; With Valores do AValor_Total := Contribuicao - (Abatimento + Deducao) + (Multa + Acrescimo); {Primeira parte do código de barras} ACodigoBanco := '104'; ACodigoMoeda := '9'; AFatorVencimento := Formatar(CalcularFatorVencimento(Vencimento),4,false,'0'); AValorDocumento := FormatCurr('0000000000',AValor_Total*100); {Formata o valor com 10 dígitos, incluindo as casas decimais, mas não mostra o ponto decimal} ASICOB := '97'; AEntidade := Cedente.SICAS_Simples; ACNAE_P1 := Copy(Cedente.CNAE, 1, 1); ATP_Entidade := '1'; ASITCS := '77'; AContribuinte := Sacado.Contribuinte; ACNAE_P2 := Copy(Cedente.CNAE, 2, 2);; {Calcula o dígito e completa o código de barras} ACodigoBarras := ACodigoBanco + ACodigoMoeda + AFatorVencimento + AValorDocumento + ASICOB + AEntidade + ACNAE_P1 + ATP_Entidade + ASITCS + AContribuinte + ACNAE_P2; ADigitoCodigoBarras := Modulo11(ACodigoBarras,9); // ADigitoCodigoBarras := Calcula_QBarras(ACodigoBarras); // if ADigitoCodigoBarras = '0' then // ADigitoCodigoBarras := '1'; Result.Codigo := Copy(ACodigoBarras,1,4) + ADigitoCodigoBarras + Copy(ACodigoBarras,5,length(ACodigoBarras)-4); end; {procedure TGuias.PrepararBoleto(ABoleto: TImp_GRCS); var Agencia2, NossoNumero2, Especie, AAgenciaCodigoCedente, ANossoNumero, ACarteira, AEspecieDocumento, ACodigoBanco: string; AInstrucoes: TStringList; begin AInstrucoes := TStringList.Create; { if DataProtesto <> 0 then AInstrucoes.Add('Protestar em ' + FormatDateTime('dd/mm/yyyy',DataProtesto)); if ValorAbatimento <> 0 then if DataAbatimento <> 0 then AInstrucoes.Add('Conceder abatimento de ' + FormatCurr('R$ #,##0.00',ValorAbatimento) + ' para pagamento até ' + FormatDateTime('dd/mm/yyyy',DataAbatimento)) else AInstrucoes.Add('Conceder abatimento de ' + FormatCurr('R$ #,##0.00',ValorAbatimento) + ' para pagamento até ' + FormatDateTime('dd/mm/yyyy',DataVencimento)); if ValorDesconto <> 0 then if DataDesconto <> 0 then AInstrucoes.Add('Conceder desconto de ' + FormatCurr('R$ #,##0.00',ValorDesconto) + ' por dia de antecipação para pagamento até ' + FormatDateTime('dd/mm/yyyy',DataDesconto)) else AInstrucoes.Add('Conceder desconto de ' + FormatCurr('R$ #,##0.00',ValorDesconto) + ' por dia de antecipação'); if ValorMoraJuros <> 0 then if DataMoraJuros <> 0 then AInstrucoes.Add('Cobrar juros de ' + FormatCurr('R$ #,##0.00',ValorMoraJuros) + ' por dia de atraso para pagamento a partir de ' + FormatDateTime('dd/mm/yyyy',DataMoraJuros)) else AInstrucoes.Add('Cobrar juros de ' + FormatCurr('R$ #,##0.00',ValorMoraJuros) + ' por dia de atraso'); AInstrucoes.AddStrings(Instrucoes); } { with ABoleto do begin ReportTitle := 'Guia Sindical - ' + ' - Cedente: ' + Cedente.Nome + ' - Sacado: ' + Sacado.Nome; {Primeira via do boleto} { qrlEmpresa1.Caption := Cedente.Nome; txtValorDocumento.Caption := FormatCurr('#,##0.00',ValorDocumento); txtInstrucoes.Lines.Clear; txtInstrucoes.Lines.AddStrings(AInstrucoes); txtValorDescontoAbatimento.Caption := ''; txtValorDescontoAbatimentoB.Caption := ''; txtValorMoraMulta.Caption := ''; txtValorMoraMultaB.Caption := ''; txtValorCobrado.Caption := ''; txtSacadoNome.Caption := AnsiUpperCase(Sacado.Nome); case Sacado.TipoInscricao of tiPessoaFisica : txtSacadoCPFCGC.Caption := 'CPF: ' + FormatarComMascara('!000\.000\.000\-00;0; ',Sacado.NumeroCPFCGC); tiPessoaJuridica: txtSacadoCPFCGC.Caption := 'CNPJ: ' + FormatarComMascara('!00\.000\.000\/0000\-00;0; ',Sacado.NumeroCPFCGC); tiOutro : txtSacadoCPFCGC.Caption := Sacado.NumeroCPFCGC; end; txtSacadoRuaNumeroComplemento.Caption := AnsiUpperCase(Sacado.Endereco.Rua + ', ' + Sacado.Endereco.Numero + ' ' + Sacado.Endereco.Complemento); txtSacadoCEPBairroCidadeEstado.Caption := AnsiUpperCase(FormatarComMascara('00000-000;0; ',Sacado.Endereco.CEP) + ' ' + Sacado.Endereco.Bairro + ' ' + Sacado.Endereco.Cidade + ' ' + Sacado.Endereco.Estado); txtCodigoBaixa.Caption := NossoNumero2; } {Segunda via do boleto} { txtNomeBanco3.Caption := Cedente.ContaBancaria.Banco.Nome; txtCodigoBanco3.Caption := Cedente.ContaBancaria.Banco.Codigo + '-' + Cedente.ContaBancaria.Banco.Digito; txtLocalPagamento3.Caption := AnsiUpperCase(LocalPagamento); txtDataVencimento3.Caption := FormatDateTime('dd/mm/yyyy',DataVencimento); txtNomeCedente3.Caption := AnsiUpperCase(Cedente.Nome); txtAgenciaCodigoCedente3.Caption := Agencia2; txtDataDocumento3.Caption := FormatDateTime('dd/mm/yyyy',DataDocumento); txtNumeroDocumento3.Caption := NumeroDocumento; txtEspecieDocumento3.Caption := Especie; if AceiteDocumento = adSim then txtAceite3.Caption := 'S' else txtAceite3.Caption := 'N'; txtDataProcessamento3.Caption := FormatDateTime('dd/mm/yyyy',Now); txtNossoNumero3.Caption := NossoNumero2; txtUsoBanco3.Caption := ''; txtCarteira3.Caption := ACarteira; txtEspecieMoeda3.Caption := 'R$'; txtQuantidadeMoeda3.Caption := ''; txtValorMoeda3.Caption := ''; txtValorDocumento3.Caption := FormatCurr('#,##0.00',ValorDocumento); txtInstrucoes3.Lines.Clear; txtInstrucoes3.Lines.AddStrings(AInstrucoes); txtValorDescontoAbatimento3.Caption := ''; txtValorDescontoAbatimentoB3.Caption := ''; txtValorMoraMulta3.Caption := ''; txtValorMoraMultaB3.Caption := ''; txtValorCobrado3.Caption := ''; txtSacadoNome3.Caption := AnsiUpperCase(Sacado.Nome); case Sacado.TipoInscricao of tiPessoaFisica : txtSacadoCPFCGC3.Caption := 'CPF: ' + FormatarComMascara('!000\.000\.000\-00;0; ',Sacado.NumeroCPFCGC); tiPessoaJuridica: txtSacadoCPFCGC3.Caption := 'CNPJ: ' + FormatarComMascara('!00\.000\.000\/0000\-00;0; ',Sacado.NumeroCPFCGC); tiOutro : txtSacadoCPFCGC3.Caption := Sacado.NumeroCPFCGC; end; txtSacadoRuaNumeroComplemento3.Caption := AnsiUpperCase(Sacado.Endereco.Rua + ', ' + Sacado.Endereco.Numero + ' ' + Sacado.Endereco.Complemento); txtSacadoCEPBairroCidadeEstado3.Caption := AnsiUpperCase(FormatarComMascara('00000-000;0; ',Sacado.Endereco.CEP) + ' ' + Sacado.Endereco.Bairro + ' ' + Sacado.Endereco.Cidade + ' ' + Sacado.Endereco.Estado); txtCodigoBaixa3.Caption := NossoNumero2; txtLinhaDigitavel3.Caption := CodigoBarra.LinhaDigitavel; } // imgCodigoBarras.Picture.Assign(CodigoBarra.Imagem.Picture); //end; // AInstrucoes.Free; //end; procedure Register; begin RegisterComponents('GRCS', [TGuias]); end; end.
(* Objets stream étendues et optimisés pour l'accès aux données séquentiellement.@br Grace à un systeme de cache et de l'utilisation du "File Mapping" pour les fichiers. Contient TBZZLibStream un cllasse spécialisée pour la compression et decompression de flux avec ZLib ------------------------------------------------------------------------------------------------------------- @created(2017-06-11) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(11/06/2017 : Creation) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : Cette unité n'est pas 100% finalisé. Il manque quelques classes. ------------------------------------------------------------------------------------------------------------- @bold(Dependances) : BZSystem, BZUtils. + BZLogger si DEBUG est activé ------------------------------------------------------------------------------------------------------------- @bold(Credits :) @unorderedList( @item(J.Delauney (BeanzMaster)) ) ------------------------------------------------------------------------------------------------------------- @bold(LICENCE) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) Unit BZStreamClasses; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} //============================================================================== Interface Uses LCLType, LCLIntf, Classes, SysUtils, Math, ZBase //GZio, Dialogs // {$IFDEF WINDOWS} // Windows, // {$ENDIF} {$IFDEF LINUX} //BaseUnix, ,Unix //UnixType, UnixUtil {$ENDIF}; Const { cDefaultBufferedStreamBlockSize : par défaut tampon de 32Mo } cDefaultBufferedStreamBlockSize = 1024 * 1024 * 32; { cDefaultCharsDelims : Caractères de délimitation : Tabulation, retour à la ligne, espace } cDefaultCharsDelims = #8#9#10#13#32; Type { @abstract(TBZCustomBufferedStream : Classe d'aide à la lecture et ou ecriture de données dans un flux (TStream).@br L'acces se fait par le biais d'un tampon de taille définie.) L'acces aux données est un acces directe en mémoire et se fait de façon séquentielle. @br TBZCustomBufferedStream contient de nombreuse procedures et fonctions optimisées pour la lecture et l'écriture de valeurs de différents types. @br Disponibles en 2 versions "Little-Endian" et "Big-Endian". Cette classe ameliore surtout les performances d'accès aux données de fichiers physique. @br Ne pas employer directement TBZCustomBufferedStream. Utilsez la classe TBZBufferedStream et les autres classes descendantes. } TBZCustomBufferedStream = Class(TStream) Private Procedure LoadBuffer; Virtual;//(var Buf; BufSize: integer) : integer; virtual; Procedure WriteBuffer; Virtual; Protected Stream: TStream; // Les données que l'on veux exploiter StreamSize: Int64; // La taille des données du stream StreamPosition: Int64; // Position dans le stream AutoFreeStream: Boolean; //Indicateur si l'on doit libérer le stream ou pas StreamViewStart, StreamViewEnd, StreamViewLength: Int64; // position et longueur du tampon dans le stream //StreamViewStartPtr, FZStreamViewEndPtr : PByte; // pointe directement sur le debut ou la fin peut-être utile dans certain cas (lecture depuis la fin par ex) StreamBytesLeft: Int64; // Nombre d'octet qui reste à lire StreamBytesRead: Int64; // Nombre d'octet deja lu (égual à FZStreamPosition+1) Buffer: Pointer; //PByte; // Tampon mémoire pour l'acces au donnée par bloque BufferDefaultSize: Int64; // Taille du tampon par defaut BufferSize: Int64; // Taille réelle du tampon BufferPosition: Int64; // Position dans le tampon BufferBytesRead, BufferBytesWrite: Int64; // Nombre d'octet deja lu ou écrit dans le tampon BufferBytesLeft: Int64; // Nombre d'octet qui reste à lire dans le tampon FUseAlignedCache: Boolean; // On aligne la taille du tampon sur 32bit (accélère les échanges mémoire dans certain cas) StrideSize: Byte; //Taille en octet à ajouté à la fin du tampon pour l'alignement des données NeedStreamWrite : Boolean; BytesInBuf : Int64; BytesWritten: Int64; Procedure SetSize(Const NewSize: Int64); Override; Function GetStreamPosition: Int64; Public { Créer un nouveau flux en mémoire tampon avec une taille de bloc définie par le parmètre "aBlockSize" (64 Mo par défaut) } Constructor Create(Const aBlockSize: Integer = cDefaultBufferedStreamBlockSize); { Créer un nouveau flux mis en mémoire tampon à partir d'un objet TStream hérité avec une taille de bloc définie (64 Mo par défaut) } Constructor Create(AStream: TStream; Const aBlockSize: Integer = cDefaultBufferedStreamBlockSize); Overload; { Destruction de TBZCustomBufferedStream } Destructor Destroy; Override; { Assigne un tampon de données "aBuffer" de taille "aSize" en octet } Procedure AssignBuffer(aBuffer: Pointer; aSize:Int64); { Assign les données d'un objet TStream "aStream" } Procedure AssignStream(aStream: TStream); { Vide le tampon } Procedure Flush; { Lit des données du flux, de taille "Count" a partir de la position courante et retourne les données dans un tampon "aBuffer" } Function Read(Var aBuffer; Count: Longint):Longint; Override; { Ecrit les données du tampon de "aBuffer" de taille "Count" à la position courrante dans le flux } Function Write(Const aBuffer; Count: Longint): Longint; Override; { Se déplacer dans le tampon suivant "Offset" et en fonction du paramètre "Origin" } Function Seek(Const Offset: Int64; Origin: TSeekOrigin): Int64; Override; { Se déplacer dans le tampon vers l'avant de "Offset" } Function SeekForward(Offset : Int64):Int64; { Se déplacer dans le tampon en arrière de "Offset" } Function SeekBackward(Offset : Int64):Int64; { Lit une valeur "Byte" dans le tampon à la position actuelle et se déplace à la position suivante } Function ReadByte: Byte; virtual; { Ecrit une valeur "Byte" dans le tampon à la position actuelle et se déplace à la position suivante } procedure WriteByte(Const Value : Byte); virtual; { Se deplace de "aCount" Byte vers l'avant dans le flux depuis la position courrante } Procedure SkipNextByte(Const aCount: Integer = 1); virtual; { Se deplace de "aCount" Byte vers l'arrière dans le flux depuis la position courrante } Procedure GotoPreviousByte(Const aCount: Integer = 1); virtual; { Si les données sont du texte alors se déplace sur la ligne suivante } Procedure GotoNextStringLine; virtual; { Lit une valeur de type Word à la position courrante } Function ReadWord: Word; virtual; { Ecrit une valeur de type Word à la position courrante } procedure WriteWord(Const Value : Word); { Lit une valeur de type Integer à la position courrante } Function ReadInteger: Integer; virtual; { Ecrit une valeur de type Integer à la position courrante } procedure WriteInteger(Const Value : Integer); virtual; { Lit une valeur de type LongWord à la position courrante } Function ReadLongWord: Longword; virtual; { Ecrit une valeur de type LongWord à la position courrante } procedure WriteLongWord(Const Value : LongWord); virtual; { Lit une valeur de type Longint à la position courrante } Function ReadLongint: Longint; virtual; { Ecrit une valeur de type Longint à la position courrante } procedure WriteLongint(Const Value : Longint); virtual; { Lit une valeur de type Cardinal à la position courrante } Function ReadCardinal: Cardinal; virtual; { Ecrit une valeur de type Cardinal à la position courrante } procedure WriteCardinal(Const Value : Cardinal); { Lit une valeur de type Single à la position courrante } Function ReadSingle: Single; virtual; { Ecrit une valeur de type Single à la position courrante } procedure WriteSingle(Const Value : Single); virtual; { Lit une valeur de type Double à la position courrante } Function ReadDouble: Double; virtual; { Ecrit une valeur de type Double à la position courrante } procedure WriteDouble(Const Value : Double); virtual; { Lit une valeur de type Char à la position courrante } Function ReadChar: Char; virtual; { Ecrit une valeur de type Char à la position courrante } procedure WriteChar(Const Value : Char); virtual; { Lit une valeur de type Word à la position suivante, sans incrémenter la postion } Function ReadNextChar: Char; virtual; { Saute les caractères inclus dans CharsDelim. (Par defaut : Espace, tab, EOL) } Procedure SkipChar(Const CharsDelim: String = cDefaultCharsDelims); virtual; { Lit une ligne de texte délimiter par #0 ou #13 à la position courrante } Function ReadLnString: String; virtual; //procedure WriteLnString(Const Value : String); { Lit une ligne de texte de longueur indéfinie à la position courrante } Function ReadString: String; virtual; //procedure WriteString(Const Value : String); { Lit une ligne de texte de longueur "Len" à la position courrante } Function ReadString(len: Integer): String; Overload; { Lit une chaine de caractères délimiter par "CharsDelim" } Function ReadStrToken(Const CharsDelim: String = cDefaultCharsDelims): String; { Lit une valeur integer dans une chaine de caractères } Function ReadStrIntToken: Integer; { Efface les données } Procedure Clear; { Retourne le tampon de données } Function GetBuffer: Pointer; { Sauvegarde le tampon de données dans le flux} procedure Save; { Retourne le tampon de données sous forme de chaine de caractères. @br    @bold(Attention) : La taille maximal est celle définie à la création du TBZBufferdStream } Function GetBufferAsString: String; { Retourne @True si la fin du flux est atteinte} Function EOS: Boolean; { Retourne le flux } function GetStream : TStream; { Retourne la taille totale du flux } Property Size: Int64 read StreamSize; { Retourne la position dans le flux } Property position: Int64 read GetStreamPosition; { Retourne le nombre d'octets restant à parcourir } property BytesLeft : Int64 read BufferBytesLeft; End; { Descendant class type of TBZCustomBufferedStream } TBZCustomBufferedStreamClass = Class Of TBZCustomBufferedStream; //TBZFileMapStream = class(TStream) // //End; //TBZBufferFileMapStream = Class(TBZCustomBufferedStream) //private // hMapping : THandle; // Handle de l'objet file-mapping // //FMemory : ;// Adresse de base du mapping // FHandle : THandle; // Handle du fichier ouvert pour le mapping // FMapPosition, // FMapSize , // FMapMaxSize : Integer; //public // Constructor Create(AStream: TStream; Const aBlockSize: Integer = cDefaultBufferedStreamBlockSize); Overload; // // Entregistre les pages modifiées dans le fichier sur le disque // procedure Flush; // // Charge Count octet du flux dans Buffer // function Read(var Buffer; Count: Longint): Longint; override; // // Ecrit Count octet de Buffer dans le flux // function Write(const Buffer; Count: Longint): Longint; override; // // Déplace le cuseur de lectre/ecriure dans le flux // function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; // // Tableau d'octet pour un accés direct en mémoire // //property MapMemory: pByteArray read FMemory; // // Retoune la position ducurseu delecture/écriture dans le Flux // property MapPosition: Integer read FPosition; // // Taille du Flux // property MapSize : Integer read FMapSize; // // Taille Maximum du Flux // property MapMaxSize : Integer read FMapMaxSize; // // Handle du fichier // property MapHandle: TMapHandle read FHandle; // constructor Create(FileName: string; // MappingName: String ; // Mode: Word; // Rights: Cardinal; // Offset: Cardinal; // Count : Cardinal; // MaxSize: Cardinal; // WriteCopy: Boolean = true); // destructor Destroy; override; //published // { Published declarations } //End; { TBZBufferedStream : See @link(TBZCustomBufferedStream) for more informations } TBZBufferedStream = Class(TBZCustomBufferedStream); { : TBZBufferedFileStream Stream spécialisé dans l'acces aux données d'un fichier sur le disque, par tampon } (* TBZBufferedFileStream = class(TBZCustomBufferedStream) private procedure FlushCache; protected FHandle: THandle; FOwnsHandle: Boolean; FFileName: string; FFileSize: Int64; function CreateHandle(FlagsAndAttributes: DWORD): THandle; function GetFileSize: Int64; virtual; public constructor Create(const FileName: string); overload; constructor Create(const FileName: string; CacheSize: Integer); overload; constructor Create(const FileName: string; CacheSize: Integer; Handle: THandle); overload; virtual; destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; property FileName : String Read FFileName; end; *) { : TBZBufferedFileMapStream est spécialisé dans l'acces aux données d'un fichier mappé (File Mapping), par tampon } (* TBZBufferedFileMapStream = class(TBZCustomBufferedFileStream) private protected FMapHandle : THandle; FOwnsMapHandle: Boolean; function CreateHandle(FlagsAndAttributes: DWORD): THandle;override; function GetFileSize: Int64; virtual; public constructor Create(const AStream: TStream); overload; constructor Create(const FileName: string; CacheSize: Integer); overload; constructor Create(const FileName: string; CacheSize: Integer; Handle: THandle); overload; virtual; constructor Create(const FileName: string); overload; destructor Destroy; override; end; *) { : TBZStream "Super Classe" pour la gestion d'acces aux données via et en fonction d'autres stream. L'acces via les classes TStream de base (TStream, TCustomMemoryStream, ThandleStream,...) sont soit utilisé tel quel, soit pour le THandleStream utilise TBZBufferedFileStream ou TBZBufferedFileMapStream pour améliorer les performances. Les Stream de type inconnue sont convertit en TMemoryStream } (* TBZStream = class(TStream) private FAutoCacheFile : Boolean; FAutoFileMap : Boolean; FUseFileMapping : Boolean; FWrappedStream : TStream; BufferedStreamClass : TBZCustomBufferedStreamClass; protected public Constructor Create(AStream : TStream); overload; override; Constructor Create(AFileName : String; Mode:byte); overload; override; Destructor Destroy; procedure LoadFromStream( AStream : TStream); procedure LoadFromFile( AFileName : String); procedure SaveToStream( AStream : TStream); procedure SaveToFile( AFileName : String); // procedure clone(var aBZStreamClass; aBZStreamClassMode); property AutoCacheFile : Boolean Read FAutoCacheFile Write AutoCacheFile; property AutoFileMap : Boolean read FAutoFileMap Write FAutoFileMap; property UseFileMapping : Boolean Read FUseFileMapping Write FUseFileMapping; end; *) Type { TGZCompressionLevel : Enumeration des niveaux de compression } TGZCompressionLevel = ( clnone, //< Do not use compression, just copy data. clfastest, //< Use fast (but less) compression. cldefault, //< Use default compression clmax //< Use maximum compression ); { TGZOpenMode : Enumeration des modes d'acces aux fichiers compressés } TGZOpenMode = ( gzopenread, //< Open file for reading. gzopenwrite //< Open file for writing. ); { TBZZLibStream : Classe utile pour compresser et décompresser un flux avec ZLib. @br Version améliorée de la classe ZStream de FPC } TBZZLibStream = Class(TOwnerStream) Private Fonprogress: TNotifyEvent; FBuffer: pointer; FWriteMode: Boolean; Protected FZStream: z_stream; raw_written, compressed_written: Int64; raw_read, compressed_read: Int64; skipheader: Boolean; Procedure reset; Function GetPosition(): Int64; Override; Function GetAvailableInput: Integer; Function GetAvailableOutput: Integer; Procedure Progress(Sender: TObject); Public Constructor Create(stream: TStream); Constructor Create(Level: TGZCompressionLevel; Dest: TStream; Askipheader: Boolean = False); Overload; // Pour l'ecriture Constructor Create(ASource: TStream; Askipheader: Boolean = False); // Pour la lecture Destructor Destroy; Override; Function Write(Const buffer; Count: Longint): Longint; Override; Function Read(Var buffer; Count: Longint): Longint; Override; Function Seek(Const Offset: Int64; Origin: TSeekOrigin): Int64; Override; Procedure Flush; Function Get_CompressionReadRate: Single; Function Get_CompressionWriteRate: Single; Property AvailableInput: Integer read GetAvailableInput; Property AvailableOutput: Integer read GetAvailableOutput; Property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; End; { Exception levée par la bibliothèque ZLib } EZLibError = Class(EStreamError); { Exception levée par la bibliothèque ZLib en cas d'erreur pendant la compression } EGZCompressionError = Class(EZLibError); { Exception levée par la bibliothèque ZLib en cas d'erreur pendant la décompression } EGZDecompressionError = Class(EZLibError); { Exception levée si le fichier n'existe pas } EBZFileNotExist = Class(Exception); { Exception levée si le fichier ne peux pas être créé } EBZCantCreateFile = Class(Exception); { Creation d'un flux pour l'acces à un fichier en écriture et ou en lecture) } Function CreateFileStream(Const fileName: String; mode: Word = fmOpenRead + fmShareDenyNone): TStream; Implementation Uses Dialogs, zdeflate, zinflate, BZSystem, BZUtils //, BZCrossPlateFormTools {.$IFDEF DEBUG} ,BZLogger {.$ENDIF}; Const {Taille du tampon utilisé pour stocker temporairement les données du flux enfant.} cGZBufsize = 1024 * 64; Function CreateFileStream(Const fileName: String; mode: Word = fmOpenRead + fmShareDenyNone): TStream; var fn : String; Begin fn:=filename; FixPathDelimiter(fn); If ((mode And fmCreate) = fmCreate) Or FileExists(fn) Then Result := TFileStream.Create(fn, mode) //TBZFileMapping.Create(fileName,fmmOpenOrCreate) // Else Raise EBZFileNotExist.Create('Fichier non trouvé : "' + fn + '"'); End; {%region%=====[ TBZCustomBufferedStream ]=====================================} constructor TBZCustomBufferedStream.Create(const aBlockSize : Integer); Begin Inherited Create; Buffer := nil; BufferDefaultSize := aBlockSize; BufferSize := BufferDefaultSize; BufferBytesRead := 0; BufferBytesLeft := -1; BufferPosition := 0; Stream := nil; StreamSize := BufferSize; StreamPosition := 0; StreamViewStart := 0; StreamViewEnd := 0; StreamViewLength := 0; AutoFreeStream := False; StreamBytesLeft := 0; StreamBytesRead := 0; NeedStreamWrite := False; BytesInBuf := 0; End; constructor TBZCustomBufferedStream.Create(AStream : TStream; const aBlockSize : Integer); Begin Inherited Create; Buffer := nil; BufferDefaultSize := aBlockSize; BufferSize := BufferDefaultSize; BufferBytesRead := 0; BufferBytesLeft := -1; BufferPosition := 0; Stream := nil; StreamSize := BufferSize; NeedStreamWrite := False; BytesInBuf := 0; Stream := AStream; StreamSize := AStream.Size; StreamPosition := 0; StreamViewStart := 0; StreamViewEnd := 0; StreamViewLength := 0; AutoFreeStream := False; StreamBytesLeft := StreamSize; StreamBytesRead := 0; End; destructor TBZCustomBufferedStream.Destroy; Begin If AutoFreeStream Then FreeAndNil(Stream); //FreeAndNil(Buffer); memReAlloc(Buffer, 0); FreeMem(Buffer); Buffer := nil; Inherited Destroy; End; procedure TBZCustomBufferedStream.Flush; Begin //Clear; StreamViewStart := StreamViewStart + BufferPosition; //StreamViewEnd := // StreamViewLength :=StreamViewEnd - StreamViewStart + 1; StreamBytesLeft := StreamSize - BufferPosition; BufferSize := BufferDefaultSize; BufferBytesRead := 0; BufferBytesLeft := -1;//BufferSize; BufferPosition := 0; BytesInBuf := 0; NeedStreamWrite := False; End; procedure TBZCustomBufferedStream.LoadBuffer; Var SeekResult: Integer; RSize: Int64; Begin //GlobalLogger.LogNotice('Load Buffer from file'); // C'est la 1er fois ? on initialise le tampon If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); // Fin des données, plus rien à lire, on remet tout a zero et on s'en va If (StreamViewStart > StreamSize - 1) Or (StreamBytesLeft <= 0) Then Begin // BufferPosition:=0; BufferBytesRead := 0; BufferBytesLeft := 0; StreamViewLength := 0; StreamBytesLeft := 0; StreamViewStart := 0; StreamViewEnd := 0; //EndOFZStream := true; exit; End; // On se place sous la bonne fenètre SeekResult := Stream.Seek(StreamViewStart, soBeginning); If SeekResult = -1 Then Raise EStreamError.Create('TBZCustomBufferedStream.LoadBuffer: Erreur lors du positionnement dans le flux'); If (StreamBytesLeft < BufferDefaultSize) Then Rsize := StreamBytesLeft Else RSize := BufferDefaultSize; // On lit les données, et on transfert dans le tampon BufferSize := Stream.Read(Buffer^, RSize); If BufferSize <= 0 Then Raise EStreamError.Create('TBZCustomBufferedStream.LoadBuffer: Erreur lors de la Lecture du flux'); // On met à jour les marqueurs de la "fenêtre" de lecture du Stream pour le chargement StreamPosition := StreamViewStart; StreamViewLength := BufferSize; StreamViewEnd := StreamViewStart + StreamViewLength - 1; If StreamViewEnd >= StreamSize Then Raise EStreamError.Create('TBZCustomBufferedStream.LoadBuffer: Index StreamViewEnd hors limite'); Dec(StreamBytesLeft, BufferSize); Inc(StreamBytesRead, BufferSize); // On reinitialise les marqueurs du Buffer BufferPosition := 0; BufferBytesRead := 0; BufferBytesLeft := BufferSize; End; procedure TBZCustomBufferedStream.WriteBuffer; var SeekResult: Integer; begin {.$IFDEF DEBUG} GlobalLogger.LogNotice('Ecriture du fichier sur le disque'); {.$ENDIF} If Not (Assigned(Buffer)) Then Exit; // rien à écrire // if Not(NeedStreamWrite) or (BytesInBuf<=0) then exit; // On n'a pas demandé l'ecriture ou il n'y a rien à écrire SeekResult := Stream.Seek(StreamViewStart, soBeginning); if SeekResult = -1 then raise EStreamError.Create('TBZCustomBufferedStream.WriteBuffer: Erreur lors du positionnement dans le flux'); BytesWritten := Stream.Write(Buffer^, BytesInBuf); if BytesWritten <> BytesInBuf then raise EStreamError.Create('TBZCustomBufferedStream.LoadBuffer: Erreur lors de l''ecriture du flux'); Dec(BytesInBuf,BytesWritten); if BytesinBuf<>0 then ShowMessage('TBZCustomBufferedStream.LoadBuffer: Erreur probable lors de l''ecriture du flux'); NeedStreamWrite := False; End; procedure TBZCustomBufferedStream.SetSize(const NewSize : Int64); Begin memReAlloc(Buffer, NewSize); BufferSize := NewSize; BufferPosition := 0; BufferBytesRead := 0; BufferBytesWrite := 0; BufferBytesLeft := NewSize; End; function TBZCustomBufferedStream.GetStreamPosition : Int64; Begin Result := StreamViewStart + BufferPosition; //GlobalLogger.LogStatus(' - Stream View Start : '+Inttostr(StreamViewStart)); //GlobalLogger.LogStatus(' - Stream Position : '+Inttostr(result)); //GlobalLogger.LogStatus(' - Buffer Position : '+Inttostr(BufferPosition)); End; function TBZCustomBufferedStream.Read(var aBuffer; Count : Longint) : Longint; Var NumOfBytesToCopy, NumOfBytesLeft: Int64; //, NumOfBytesRead CachePtr, BufferPtr: PByte; Begin {$IFDEF DEBUG} {$IFDEF DEBUGLOG} GlobalLogger.LogNotice('Read Data in Buffer : '+Inttostr(Count)+' Octets'); GlobalLogger.LogStatus(' - Stream Position : '+Inttostr(Position)); GlobalLogger.LogStatus(' - Buffer Position : '+Inttostr(BufferPosition)); GlobalLogger.LogStatus(' - Buffer Bytes Left : '+Inttostr(BufferBytesLeft)); GlobalLogger.LogStatus(' - Stream Bytes Left : '+Inttostr(StreamBytesLeft)); GlobalLogger.LogStatus(' - Stream Size : '+Inttostr(StreamSize)); GlobalLogger.LogStatus(' - Buffer Size : '+Inttostr(BufferSize)); {$ENDIF} {$ENDIF} Result := 0; If (StreamBytesLeft > 0) then NumOfBytesLeft := Count else if (Count>BufferBytesLeft) then NumOfBytesLeft := BufferBytesLeft else NumOfBytesLeft := Count; BufferPtr := @aBuffer; While NumOfBytesLeft > 0 Do Begin If (BufferBytesLeft <= 0) Then Begin //StreamViewStart := StreamViewStart + BufferPosition; Flush; LoadBuffer; // On charge un nouveau tampon depuis le stream End; // On copie les données NumOfBytesToCopy := Min(BufferSize - BufferPosition, NumOfBytesLeft); CachePtr :=Self.Buffer; Inc(CachePtr, BufferPosition); Move(CachePtr^, BufferPtr^, NumOfBytesToCopy); Inc(Result, NumOfBytesToCopy); Inc(BufferPosition, NumOfBytesToCopy); Inc(BufferPtr, NumOfBytesToCopy); // On met à jour les marqueur de notre tampon Inc(BufferBytesRead, NumOfBytesToCopy); Dec(BufferBytesLeft, NumOfBytesToCopy); Dec(NumOfBytesLeft, NumOfBytesToCopy); End; {$IFDEF DEBUG} {$IFDEF DEBUGLOG} GlobalLogger.LogStatus(' - New Buffer Position : '+Inttostr(BufferPosition)); GlobalLogger.LogStatus(' - New Stream Position : '+Inttostr(Position)); {$ENDIF} {$ENDIF} End; function TBZCustomBufferedStream.Write(const aBuffer; Count : Longint) : Longint; Var NumOfBytesToCopy, NumOfBytesLeft, NumOfBytesWriteLeft: Longint; CachePtr, BufferPtr: PByte; // BytesWritten : Longint; Begin {.$IFDEF DEBUG} //{$IFDEF DEBUGLOG} //GlobalLogger.LogNotice('Write Data in Buffer : '+Inttostr(Count)+' Octets'); //GlobalLogger.LogStatus(' - Stream Position : '+Inttostr(Position)); //GlobalLogger.LogStatus(' - Buffer Position : '+Inttostr(BufferPosition)); //GlobalLogger.LogStatus(' - Bytes in buf : '+Inttostr(BytesInBuf)); //GlobalLogger.LogStatus(' - Stream Bytes Left : '+Inttostr(StreamBytesLeft)); //GlobalLogger.LogStatus(' - Stream Size : '+Inttostr(StreamSize)); //GlobalLogger.LogStatus(' - Buffer Size : '+Inttostr(BufferSize)); //{$ENDIF} {.$ENDIF} Result := 0; NumOfBytesLeft := Count; If (Assigned(Buffer)) and (BufferSize>0) and (BytesInBuf + NumOfBytesLeft > pred(BufferSize)) Then Save; If Not(Assigned(Buffer)) Then SetSize(BufferDefaultSize); BufferPtr := @aBuffer; // NumOfBytesToCopy := 0; While NumOfBytesLeft > 0 Do Begin NumOfBytesToCopy := 0; If (BufferPosition + NumOfBytesLeft) >= pred(BufferSize) Then NumOfBytesToCopy := Pred(BufferSize) - BufferPosition; NumOfBytesWriteLeft := NumOfBytesLeft-NumOfBytesToCopy; //if NumOfBytesWriteLeft < 0 then NumOfBytesWriteLeft:=0; //GlobalLogger.LogStatus(' - NumOfBytesToCopy : '+Inttostr(NumOfBytesToCopy)); //GlobalLogger.LogStatus(' - NumOfBytesWriteLeft : '+Inttostr(NumOfBytesWriteLeft)); if NumOfBytesToCopy>0 then begin //GlobalLogger.LogNotice('---> Ecriture du tampon'); CachePtr := Buffer; Inc(CachePtr, BufferPosition); Move(BufferPtr^,CachePtr^, NumOfBytesToCopy); //Inc(BufferPosition, NumOfBytesToCopy-1); Inc(BufferPtr, NumOfBytesToCopy); Inc(BytesInBuf, NumOfBytesToCopy); //BytesInBuf:=BufferSize; BufferPosition := BytesInBuf-1; //-1 car on commence à la position 0 NeedStreamWrite := True; WriteBuffer; Inc(Result, NumOfBytesToCopy); Dec(NumOfBytesLeft,NumOfBytesToCopy); Flush; end else begin //GlobalLogger.LogNotice('---> Ecriture des données dans le cache'); CachePtr := Buffer; Inc(CachePtr, BufferPosition); Move(BufferPtr^, CachePtr^, NumOfBytesWriteLeft); //Inc(BufferPosition,NumOfBytesWriteLeft); Inc(BytesInBuf,NumOfBytesWriteLeft); BufferPosition := BytesInBuf; Dec(NumOfBytesLeft,NumOfBytesWriteLeft); Inc(Result,NumOfBytesWriteLeft); End; end; end; function TBZCustomBufferedStream.Seek(const Offset : Int64; Origin : TSeekOrigin) : Int64; Var //NewBufStart, NewPos: Integer; Begin // Calcul de la nouvelle position Case Origin Of soBeginning: NewPos := Offset; soCurrent: NewPos := StreamViewStart + BufferPosition + Offset; soEnd: NewPos := pred(StreamSize) - Offset; Else Raise Exception.Create('TBZCustomBufferedStream.Seek: Origine Invalide'); End; Result :=NewPos; // if Offset = 0 then exit; // Calcul de la fenêtre du stream, alignement des données // NewBufStart := NewPos and not Pred(BufferSize); //NewBufStart := NewPos - (StreamViewStart mod BufferSize); (* if NewBufStart <> StreamViewStart then begin StreamViewStart := NewBufStart; StreamPosition := NewBufStart; BufferBytesLeft:=0; end else StreamPosition := NewPos; //- NewBufStart; *) if NeedStreamWrite then begin WriteBuffer; NeedStreamWrite := False; Flush; end; BufferPosition := NewPos; BufferBytesLeft := BufferSize - BufferPosition; Result := NewPos; {$IFDEF DEBUG} {$IFDEF DEBUGLOG} GlobalLogger.LogStatus(' - Seek New Buffer Position : '+Inttostr(BufferPosition)); GlobalLogger.LogStatus(' - Seek New Stream Position : '+Inttostr(Position)); {$ENDIF} {$ENDIF} End; function TBZCustomBufferedStream.SeekForward(Offset : Int64) : Int64; Begin result := Seek(Abs(Offset),soCurrent); //SkipNextByte(Abs(Offset)); //result := Position; End; function TBZCustomBufferedStream.SeekBackward(Offset : Int64) : Int64; Begin if Offset>0 then Offset := -Offset; result := Seek(Offset,soCurrent); ////Offset := Position - Offset; ////result := Seek(Offset,soBeginning); //GotoPreviousByte(Abs(Offset)); //result := Position; End; procedure TBZCustomBufferedStream.AssignBuffer(aBuffer : Pointer; aSize : Int64); Begin SetSize(aSize); Move(aBuffer^, Buffer, aSize); End; procedure TBZCustomBufferedStream.Save; begin if BytesInBuf>0 then begin NeedStreamWrite := True; WriteBuffer; Flush; End; End; procedure TBZCustomBufferedStream.AssignStream(aStream : TStream); Var ms: TMemoryStream; Begin If (aStream Is TCustomMemoryStream) Then Begin // AssignBuffer(TCustomMemoryStream(aStream).Memory,aStream.Size); Stream := TCustomMemoryStream(aStream); StreamSize := TCustomMemoryStream(aStream).Size; StreamPosition := 0; StreamViewStart := 0; StreamViewEnd := StreamSize - 1; StreamViewLength := StreamSize; StreamBytesLeft := StreamSize; StreamBytesRead := 0; AutoFreeStream := False; End Else Begin ms := TMemoryStream.Create; With ms Do Begin CopyFrom(aStream, 0); Position := 0; End; Stream := ms; StreamSize := ms.Size; StreamPosition := 0; StreamViewStart := 0; StreamViewEnd := StreamSize - 1; StreamViewLength := StreamSize; StreamBytesLeft := StreamSize; StreamBytesRead := 0; AutoFreeStream := True; End; End; function TBZCustomBufferedStream.ReadByte : Byte; Begin If (BufferBytesLeft < 1) Then Begin Flush; LoadBuffer; End; Result := PByte(Buffer + BufferPosition)^; Inc(BufferPosition); Inc(BufferBytesRead); Dec(BufferBytesLeft); End; procedure TBZCustomBufferedStream.WriteByte(const Value : Byte); Begin If (BufferSize>0) and (BytesInBuf+1 > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PByte(Buffer + BufferPosition)^ := value; Inc(BufferPosition); Inc(BytesInBuf); End; procedure TBZCustomBufferedStream.SkipNextByte(const aCount : Integer); Begin If (BufferBytesLeft < aCount) Then Begin Flush; LoadBuffer; End; Inc(BufferPosition, aCount); Inc(BufferBytesRead, aCount); Dec(BufferBytesLeft, aCount); End; procedure TBZCustomBufferedStream.GotoPreviousByte(const aCount : Integer); Begin { TODO 0 -oBZStreamClasses -cTBZCustomBufferedStream : GotoPreviousByte. Gérer le rechargement en arriere du buffer } Dec(BufferPosition,aCount); Dec(BufferBytesRead,aCount); Inc(BufferBytesLeft,aCount); End; function TBZCustomBufferedStream.ReadWord : Word; Begin If (BufferBytesLeft < 2) Then Begin flush; loadbuffer; End; Result := PWord(Buffer + BufferPosition)^; Inc(BufferPosition, 2); Inc(BufferBytesRead, 2); Dec(BufferBytesLeft, 2); End; procedure TBZCustomBufferedStream.WriteWord(const Value : Word); Begin If (BufferSize>0) and ((BytesInBuf+2) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PWord(Buffer + BufferPosition)^ := value; Inc(BufferPosition,2); Inc(BytesInBuf,2); End; function TBZCustomBufferedStream.ReadInteger : Integer; Begin If (BufferBytesLeft < 4) Then Begin flush; loadbuffer; End; Result := PInteger(Buffer + BufferPosition)^; Inc(BufferPosition, 4); Inc(BufferBytesRead, 4); Dec(BufferBytesLeft, 4); End; procedure TBZCustomBufferedStream.WriteInteger(const Value : Integer); Begin If (BufferSize>0) and ((BytesInBuf+4) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PInteger(Buffer + BufferPosition)^ := value; Inc(BufferPosition,4); Inc(BytesInBuf,4); End; function TBZCustomBufferedStream.ReadLongint : Longint; Begin If (BufferBytesLeft < 4) Then Begin flush; loadbuffer; End; Result := PLongint(Buffer + BufferPosition)^; Inc(BufferPosition, 4); Inc(BufferBytesRead, 4); Dec(BufferBytesLeft, 4); End; procedure TBZCustomBufferedStream.WriteLongint(const Value : Longint); Begin If (BufferSize>0) and ((BytesInBuf+4) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PLongint(Buffer + BufferPosition)^ := value; Inc(BufferPosition,4); Inc(BytesInBuf,4); End; function TBZCustomBufferedStream.ReadLongWord : Longword; Begin If (BufferBytesLeft < 4) Then Begin flush; loadbuffer; End; Result := PLongWord(Buffer + BufferPosition)^; Inc(BufferPosition, 4); Inc(BufferBytesRead, 4); Dec(BufferBytesLeft, 4); End; procedure TBZCustomBufferedStream.WriteLongWord(const Value : LongWord); Begin If (BufferSize>0) and ((BytesInBuf+4) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PLongWord(Buffer + BufferPosition)^ := value; Inc(BytesInBuf,4); BufferPosition := BytesInBuf; End; function TBZCustomBufferedStream.ReadCardinal : Cardinal; Begin If (BufferBytesLeft < 4) Then Begin flush; loadbuffer; End; Result := PCardinal(Buffer + BufferPosition)^; Inc(BufferPosition, 4); Inc(BufferBytesRead, 4); Dec(BufferBytesLeft, 4); End; procedure TBZCustomBufferedStream.WriteCardinal(const Value : Cardinal); Begin If (BufferSize>0) and ((BytesInBuf+4) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PCardinal(Buffer + BufferPosition)^ := value; Inc(BufferPosition,4); Inc(BytesInBuf,4); End; function TBZCustomBufferedStream.ReadSingle : Single; Var ts: Byte; Begin ts := SizeOf(Single); If (BufferBytesLeft < ts) Then Begin flush; loadbuffer; End; Result := PSingle(Buffer + BufferPosition)^; Inc(BufferPosition, ts); Inc(BufferBytesRead, ts); Dec(BufferBytesLeft, ts); End; procedure TBZCustomBufferedStream.WriteSingle(const Value : Single); Var ts: Byte; Begin ts := SizeOf(Single); If (BufferSize>0) and ((BytesInBuf+ts) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PSingle(Buffer + BufferPosition)^ := value; Inc(BufferPosition,ts); Inc(BytesInBuf,ts); End; function TBZCustomBufferedStream.ReadDouble : Double; Var ts: Byte; Begin If (BufferBytesLeft < 8) Then Begin flush; loadbuffer; End; Result := PDouble(Buffer + BufferPosition)^; ts := SizeOf(Double); Inc(BufferPosition, ts); Inc(BufferBytesRead, ts); Dec(BufferBytesLeft, ts); End; procedure TBZCustomBufferedStream.WriteDouble(const Value : Double); Var ts: Byte; Begin ts := SizeOf(Double); If (BufferSize>0) and ((BytesInBuf+ts) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PDouble(Buffer + BufferPosition)^ := value; Inc(BufferPosition,ts); Inc(BytesInBuf,ts); End; function TBZCustomBufferedStream.ReadChar : Char; Begin If (BufferBytesLeft < 1) Then Begin flush; loadbuffer; End; Result := PChar(Buffer + BufferPosition)^; Inc(BufferPosition); Inc(BufferBytesRead); Dec(BufferBytesLeft); End; procedure TBZCustomBufferedStream.WriteChar(const Value : Char); Begin If (BufferSize>0) and ((BytesInBuf+1) > pred(BufferSize)) Then Save; If Not (Assigned(Buffer)) Then SetSize(BufferDefaultSize); PChar(Buffer + BufferPosition)^ := value; Inc(BufferPosition); Inc(BytesInBuf); End; function TBZCustomBufferedStream.ReadNextChar : Char; Begin If (BufferBytesLeft < 1) Then Begin flush; loadbuffer; End; Result := PChar(Buffer + BufferPosition)^; End; procedure TBZCustomBufferedStream.GotoNextStringLine; Var c: Char; sLineEnding: String; Begin sLineEnding := #13#10; C := ReadChar; While ((BufferPosition < BufferSize) And Not (pos(C, sLineEnding) > 0)) Do Begin C := ReadChar; End; If (C = #13) Then ReadChar; //or (C=#10) End; function TBZCustomBufferedStream.ReadLnString : String; Var C1, C2: Char; Stop: Boolean; S: String; Begin If (BufferBytesLeft <= 0) Then Begin flush; loadbuffer; End; S := ''; Stop := False; While Not (Stop) And (BufferPosition <= BufferSize - 1) Do Begin C1 := ReadChar; If (C1 = #13) Or (C1 = #10) or (C1 = #0) Then Begin Stop := True; C2 := ReadChar; If (C2 In [#32..#255]) Then Begin Dec(BufferPosition); Dec(BufferBytesRead); Inc(BufferBytesLeft); End; // S:=S+C1; End Else Begin If (C1 = #9) Or (C1 = #32) Or (C1 In [#32..#255]) Then S := S + C1; End; End; Result := S; End; function TBZCustomBufferedStream.ReadString(len : Integer) : String; Var S: String; TmpBuffer: PByte; Begin //GlobalLogger.LogNotice('ReadString At : '+IntToStr(GetPosition)); If (BufferBytesLeft < Len) Then Begin flush; loadbuffer; End; Result := ''; S := ''; SetLength(S, Len); Move(PChar(Buffer + BufferPosition)^, S[1], Len); TmpBuffer := Pointer(S) + Len; TmpBuffer^ := 0; Result := S; Len:=Len-1; Inc(BufferPosition, Len); Inc(BufferBytesRead, Len); Dec(BufferBytesLeft, Len); End; function TBZCustomBufferedStream.ReadString : String; Var Len: Integer; TmpBuffer: PByte; Begin Len := ReadInteger; SetLength(Result, Len); Read(Pointer(Result), Len); TmpBuffer := Pointer(Result) + Len; TmpBuffer^ := 0; End; procedure TBZCustomBufferedStream.SkipChar(const CharsDelim : String); Var c: Char; Begin C := ReadChar; While ((BufferPosition < BufferSize) And (pos(C, CharsDelim) > 0)) Do Begin C := ReadChar; End; Dec(BufferPosition); Dec(BufferBytesRead); Inc(BufferBytesLeft); End; function TBZCustomBufferedStream.ReadStrToken(const CharsDelim : String) : String; Var LastC: Char; Begin Result := ''; SkipChar(CharsDelim); LastC := ReadChar; While ((BufferPosition < BufferSize) And Not (pos(LastC, CharsDelim) > 0)) Do Begin SetLength(Result, Length(Result) + 1); Result[Length(Result)] := LastC; LastC := ReadChar; End; End; function TBZCustomBufferedStream.ReadStrIntToken : Integer; Var LastC: Char; S: String; Begin Result := -1; S := ''; SkipChar(cDefaultCharsDelims); LastC := ReadChar; While ((BufferPosition < BufferSize) And (pos(LastC, '0123456789') > 0)) Do Begin SetLength(S, Length(S) + 1); S[Length(S)] := LastC; LastC := ReadChar; End; If s <> '' Then Begin Result := StrToInt(S); GotoPreviousByte; End; End; (*function TBZCustomBufferedStream.ReadBigEndianCardinal: Cardinal; // Reads the next four bytes from the memory pointed to by Run, converts this into a cardinal number (inclusive byte // order swapping) and advances Run. begin if BufferBytesLeft = 0 then begin flush; loadbuffer; end; Result := SwapLong(PCardinal(Buffer+BufferPosition)^); Inc(BufferPosition,Sizeof(Cardinal)); // Inc(PCardinal(Buffer)); //Inc(Buffer,Sizeof(Cardinal)); Dec(BufferBytesLeft,Sizeof(Cardinal)); end; function TBZCustomBufferedStream.ReadBigEndianDouble: Double; // Reads the next two bytes from the memory pointed to by Run, converts this into a word number (inclusive byte // order swapping) and advances Run. begin result:=-1; if BufferBytesLeft = 0 then begin flush; loadbuffer; end; SwapDouble(PDouble(Buffer+BufferPosition)^, Result); Inc(BufferPosition,Sizeof(Double)); // Inc(Buffer,Sizeof(Double)); Dec(BufferBytesLeft,Sizeof(Double)); end; function TBZCustomBufferedStream.ReadBigEndianInteger: Integer; // Reads the next four bytes from the memory pointed to by Run, converts this into a cardinal number (inclusive byte // order swapping) and advances Run. begin if BufferBytesLeft = 0 then begin flush; loadbuffer; end; Result := SwapLong(PInteger(Buffer+BufferPosition)^); Inc(BufferPosition,Sizeof(Integer)); // Inc(PInteger(Buffer)); Dec(BufferBytesLeft,Sizeof(Integer)); end; function TBZCustomBufferedStream.ReadBigEndianString(Len: Cardinal): WideString; // Reads the next Len bytes from the memory pointed to by Run, converts this into a Unicode string (inclusive byte // order swapping) and advances Run. // Run is not really a PChar type, but an untyped pointer using PChar for easier pointer maths. begin if BufferBytesLeft = 0 then begin flush; loadbuffer; end; SetString(Result, PWideChar(PAnsiChar(Buffer+BufferPosition)), Len); // Inc(PWideChar(PAnsiChar(Buffer+BufferPosition)), Len); Inc(BufferPosition,Len); Dec(BufferBytesLeft,Len); SwapShort(Pointer(Result), Len); end; function TBZCustomBufferedStream.ReadBigEndianString: WideString; // Same as ReadBigEndianString with length parameter. However the length must first be retrieved. var Len: Cardinal; begin Len := ReadBigEndianCardinal; Result := ReadBigEndianString(Len); end; function TBZCustomBufferedStream.ReadBigEndianWord: Word; // Reads the next two bytes from the memory pointed to by Run, converts this into a word number (inclusive byte // order swapping) and advances Run. begin Result := Swap(PWord(Buffer+BufferPosition)^); Inc(BufferPosition,Sizeof(Word)); // Inc(PWord(Buffer)); Dec(BufferBytesLeft,Sizeof(Word)); end; *) procedure TBZCustomBufferedStream.Clear; Begin FillByte(PByte(Buffer)^, BufferSize, 0); End; function TBZCustomBufferedStream.GetBuffer : Pointer; Var Buf : PByte; // S : Int64; Begin // S := StreamSize; Buf := nil; GetMem(Buf,StreamSize); Seek(0,soBeginning); Read(Buf^,StreamSize); Result := Pointer(Buf); End; function TBZCustomBufferedStream.GetBufferAsString : String; Var S: String; Begin If (BufferBytesLeft <= 0) Then Begin flush; loadbuffer; End; SetLength(S, BufferSize); Move(PChar(Buffer)^, S[1], BufferSize); Result := S; End; function TBZCustomBufferedStream.EOS : Boolean; Begin Result := False; If ((StreamBytesLeft <= 0) And (BufferBytesLeft <= 0)) Then Result := True; //if result then GlobalLogger.LogWarning('EOS'); //result:= GetStreamPosition>=StreamSize; End; function TBZCustomBufferedStream.GetStream : TStream; begin // Stream.Seek(0,soBeginning); Result := Stream; end; (* Search type TPatternArray = Array of byte; function TBZCustomBufferedStream.Search(Pattern: TPatternArray): Int64; var idx: Integer; begin Result := -1; for idx := FStream.Position to FStream.Size - Length(Pattern) do begin if CompareMem(FStream.Memory + Idx, @Pattern[0], Length(Pattern)) then exit(idx); FStream.LoadBuffer(); end; end; *) {%endregion%} {%region%=====[ TBZBufferMapStream ]==========================================} (*procedure TBZBufferMapStream.Flush; begin FlushViewOfFile(FMemory, 0); end; function TBZBufferMapStream.Read(var Buffer; Count: Integer): Integer; begin if FPosition + Count > FMaxSize then Count := FMaxSize - FPosition; move(FMemory[FPosition], Buffer, Count); Result := Count; end; function TBZBufferMapStream.Write(const Buffer; Count: Longint): Longint; begin if FPosition + Count > FMaxSize then Count := FMaxSize - FPosition; move(Buffer, FMemory[FPosition], Count); Result := Count; end; function TBZBufferMapStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Case Origin of // Seek from the beginning of the resource. The seek operation moves to a // specified position (offset), which must be greater than or equal to zero. soBeginning: if Offset < FMaxSize then FPosition := Offset else raise ERangeError.Create('Offset en dehors de la projection'); // Seek from the current position in the resource. The seek operation moves // to an offset from the current position (position + offset). The offset is // positive to move forward, negative to move backward. soCurrent : if FPosition + Offset < FMaxSize then FPosition := FPosition + Offset else raise ERangeError.Create('Offset en dehors de la projection'); // Seek from the end of the resource. The seek operation moves to an offset // from the end of the resource, where the offset is expressed as a negative // value because it is moving toward the beginning of the resource soEnd : soEnd : if FSize - Offset >= 0 then FPosition := FMaxSize - Offset else raise ERangeError.Create('Offset en dehors de la projection'); end; result := FPosition; end; constructor TBZBufferMapStream.Create(FileName: string; MappingName: String; Mode: Word; Rights: Cardinal; Offset: Cardinal; Count: Cardinal; MaxSize: Cardinal; WriteCopy: Boolean = true); var dwDA, dwSM, dwCD, flP, dwVA: DWORD; FileInfo: _BY_HANDLE_FILE_INFORMATION; pchName : pChar; begin // Initialise correctement les attributs de construction du mapping If Mode = fmOpenRead then begin dwDA := GENERIC_READ; dwCD := OPEN_EXISTING; dwVA := FILE_MAP_READ; flP := PAGE_READONLY; end Else begin dwDA := GENERIC_READ or GENERIC_WRITE; If WriteCopy then begin dwVA := FILE_MAP_COPY; flP := PAGE_WRITECOPY; end else begin dwVA := FILE_MAP_WRITE; flP := PAGE_READWRITE; end; Case Mode of fmCreate: dwCD := CREATE_ALWAYS; fmOpenWrite: dwCD := TRUNCATE_EXISTING; fmOpenReadWrite: dwCD := OPEN_EXISTING; end; end; case Rights of fmShareCompat or fmShareExclusive: dwSM := 0; fmShareDenyWrite: dwSM := FILE_SHARE_READ; fmShareDenyRead: dwSM := FILE_SHARE_WRITE; fmShareDenyNone: dwSM := FILE_SHARE_READ and FILE_SHARE_WRITE; end; // Verife si le mapping a créer est nomé. if MappingName <> '' then begin // Le cas échéant, essayons dans un premier temps d'ouvrir un mapping existant pchName := pChar(MappingName); hMapping := OpenFileMapping(dwDA, false, pchName); end else begin // Si non, RAZ de pchName et hMapping pchName := nil; hMapping := 0; end; inherited create; // Si le mapping n'est pas déjà ouvert If hMapping = 0 then begin // Ouvre le fichier FHandle := CreateFile(pChar(FileName), dwDA, dwSM, nil, dwCD, 0, 0); if FHandle = INVALID_HANDLE_VALUE then raise Exception.Create(SysErrorMessage(GetLastError)); if MaxSize = 0 then begin if not GetFileInformationByHandle(FHandle, FileInfo) then begin CloseHandle(FHandle); raise Exception.Create(SysErrorMessage(GetLastError)); end; FMapSize := FileInfo.nFileSizeLow; end else FMapSize := MaxSize; hMapping := CreateFileMapping(FHandle, nil, flP, 0, FSize, pchName); if (hMapping = INVALID_HANDLE_VALUE) or (hMapping = 0) then begin FileClose(FHandle); raise Exception.Create(SysErrorMessage(GetLastError)); end; end; FMemory := MapViewOfFile(hMapping, dwVA, 0, Offset, Count); if FMemory = nil then begin FileClose(FHandle); CloseHandle(hMapping); raise Exception.Create(SysErrorMessage(GetLastError)); end; end; destructor TBZBufferMapStream.Destroy; begin Flush; UnMapViewOfFile(FMemory); CloseHandle(hMapping); CloseHandle(FHandle); inherited destroy; end;*) {%endregion%} {%region%=====[ TBZBufferedFileMapStream ]====================================} {%endregion%} {%region%=====[ TBZStream ]===================================================} {%endregion%} {%region%=====[ TBZZLibStream ]===============================================} Constructor TBZZLibStream.Create(stream: Tstream); Begin assert(stream <> nil); Inherited Create(stream); FBuffer := nil; GetMem(FBuffer, cGZBufsize); End; Procedure TBZZLibStream.Progress(Sender: TObject); Begin If FOnProgress <> nil Then FOnProgress(Sender); End; Destructor TBZZLibStream.Destroy; Begin If FWriteMode Then inflateEnd(FZStream) Else Begin Try Flush; Finally deflateEnd(FZStream); End; End; FreeMem(FBuffer); FBuffer := nil; Inherited Destroy; End; {***************************************************************************} Constructor TBZZLibStream.Create(level: TGZCompressionLevel; Dest: TStream; Askipheader: Boolean = False); Var err, l: Smallint; Begin Inherited Create(dest); FZStream.next_out := Fbuffer; FZStream.avail_out := cGZBufsize; Case level Of clnone: l := Z_NO_COMPRESSION; clfastest: l := Z_BEST_SPEED; cldefault: l := Z_DEFAULT_COMPRESSION; clmax: l := Z_BEST_COMPRESSION; End; If Askipheader Then err := deflateInit2(FZStream, l, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, 0) Else err := deflateInit(FZStream, l); If err <> Z_OK Then Raise EGZCompressionError.Create(zerror(err)); FWriteMode := True; End; Function TBZZLibStream.GetAvailableInput: Integer; Begin Result := FZStream.avail_in; End; //---------------------------------------------------------------------------------------------------------------------- Function TBZZLibStream.GetAvailableOutput: Integer; Begin Result := FZStream.avail_out; End; Function TBZZLibStream.Write(Const buffer; Count: Longint): Longint; Var err: Smallint; lastavail, written: Longint; Begin FZStream.next_in := @buffer; FZStream.avail_in := Count; lastavail := Count; While FZStream.avail_in <> 0 Do Begin If FZStream.avail_out = 0 Then Begin { Flush the buffer to the stream and update progress } written := Source.Write(Fbuffer^, cGZBufsize); Inc(compressed_written, written); Inc(raw_written, lastavail - FZStream.avail_in); lastavail := FZStream.avail_in; progress(self); { reset output buffer } FZStream.next_out := Fbuffer; FZStream.avail_out := cGZBufsize; End; err := deflate(FZStream, Z_NO_FLUSH); If err <> Z_OK Then Raise EGZCompressionError.Create(zerror(err)); End; Inc(raw_written, lastavail - FZStream.avail_in); Write := Count; End; Function TBZZLibStream.Get_CompressionWriteRate: Single; Begin Result := 100 * compressed_written / raw_written; End; Procedure TBZZLibStream.Flush; Var err: Smallint; written: Longint; Begin {Compress remaining data still in internal zlib data buffers.} Repeat If FZStream.avail_out = 0 Then Begin { Flush the buffer to the stream and update progress } written := Source.Write(Fbuffer^, cGZBufsize); Inc(compressed_written, written); progress(self); { reset output buffer } FZStream.next_out := Fbuffer; FZStream.avail_out := cGZBufsize; End; err := deflate(FZStream, Z_FINISH); If err = Z_STREAM_END Then break; If (err <> Z_OK) Then Raise EGZCompressionError.Create(zerror(err)); Until False; If FZStream.avail_out < cGZBufsize Then Begin Source.writebuffer(FBuffer^, cGZBufsize - FZStream.avail_out); Inc(compressed_written, cGZBufsize - FZStream.avail_out); progress(self); End; End; {***************************************************************************} Constructor TBZZLibStream.Create(Asource: TStream; Askipheader: Boolean = False); Var err: Smallint; Begin Inherited Create(Asource); skipheader := Askipheader; If Askipheader Then err := inflateInit2(FZStream, -MAX_WBITS) Else err := inflateInit(FZStream); If err <> Z_OK Then Raise EGZCompressionError.Create(zerror(err)); FWriteMode := False; End; Function TBZZLibStream.Read(Var buffer; Count: Longint): Longint; Var err: Smallint; lastavail: Longint; Begin FZStream.next_out := @buffer; FZStream.avail_out := Count; lastavail := Count; While FZStream.avail_out <> 0 Do Begin If FZStream.avail_in = 0 Then Begin {Refill the buffer.} FZStream.next_in := Fbuffer; FZStream.avail_in := Source.Read(Fbuffer^, cGZBufsize); Inc(compressed_read, FZStream.avail_in); Inc(raw_read, lastavail - FZStream.avail_out); lastavail := FZStream.avail_out; progress(self); End; err := inflate(FZStream, Z_NO_FLUSH); If err = Z_STREAM_END Then break; If err <> Z_OK Then Raise EGZDecompressionError.Create(zerror(err)); End; If err = Z_STREAM_END Then Dec(compressed_read, FZStream.avail_in); Inc(raw_read, lastavail - FZStream.avail_out); Read := Count - FZStream.avail_out; End; Procedure TBZZLibStream.reset; Var err: Smallint; Begin Source.seek(-compressed_read, sofromcurrent); raw_read := 0; compressed_read := 0; inflateEnd(FZStream); If skipheader Then err := inflateInit2(FZStream, -MAX_WBITS) Else err := inflateInit(FZStream); If err <> Z_OK Then Raise EGZDecompressionError.Create(zerror(err)); End; Function TBZZLibStream.GetPosition(): Int64; Begin Result := raw_read; End; Function TBZZLibStream.Seek(Const Offset: Int64; Origin: TSeekOrigin): Int64; Var c, off: Int64; Begin off := Offset; If origin = soCurrent Then Inc(off, raw_read); If (origin = soEnd) Or (off < 0) Then Raise EGZDecompressionError.Create('Seek in deflate compressed stream failed.'); seek := off; If off < raw_read Then reset Else Dec(off, raw_read); While off > 0 Do Begin c := off; If c > cGZBufsize Then c := cGZBufsize; If Read(Fbuffer^, c) <> c Then Raise EGZDecompressionError.Create('Seek in deflate compressed stream failed.'); Dec(off, c); End; End; Function TBZZLibStream.Get_CompressionReadRate: Single; Begin Result := 100 * compressed_read / raw_read; End; {%endregion%} End.
unit uOptions; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Common; type TfrmOptions = class(TForm) radDifficulty: TRadioGroup; BitBtn1: TBitBtn; BitBtn2: TBitBtn; GroupBox1: TGroupBox; txtWidth: TEdit; Label2: TLabel; Label1: TLabel; txtHeight: TEdit; Label3: TLabel; GroupBox3: TGroupBox; txtCount: TEdit; Label4: TLabel; txtBoxSize: TEdit; Label5: TLabel; procedure radDifficultyClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure GameChanger(Sender: TObject); procedure txtBoxSizeChange(Sender: TObject); private FOptions: TOptions; public constructor Create(AOptions: TOptions); property Options: TOptions read FOptions; end; var frmOptions: TfrmOptions; implementation {$R *.dfm} uses uMain; constructor TfrmOptions.Create(AOptions: TOptions); begin inherited Create(nil); FOptions:= AOptions; txtWidth.Text:= IntToStr(AOptions.Width); txtHeight.Text:= IntToStr(AOptions.Height); txtCount.Text:= IntToStr(AOptions.Count); radDifficulty.ItemIndex:= Integer(AOptions.Difficulty); txtBoxSize.Text:= IntToStr(AOptions.BoxSize); FOptions.GameChanged:= False; FOptions.SizeChanged:= False; end; procedure TfrmOptions.BitBtn1Click(Sender: TObject); begin //Check if current game has any progress if MessageDlg('This will restart the game. Continue?', mtWarning, [mbYes,mbNo], 0) = mrYes then begin ModalResult:= mrOK; BitBtn1.ModalResult:= mrOK; FOptions.Difficulty:= TDifficulty(radDifficulty.ItemIndex); FOptions.Width:= StrToIntDef(txtWidth.Text, 15); FOptions.Height:= StrToIntDef(txtHeight.Text, 15); FOptions.Count:= StrToIntDef(txtCount.Text, 5); FOptions.BoxSize:= StrToIntDef(txtBoxSize.Text, 20); Close; end; end; procedure TfrmOptions.radDifficultyClick(Sender: TObject); begin //Changed difficulty case radDifficulty.ItemIndex of 0: begin txtWidth.Text:= IntToStr(EASY_WIDTH); txtHeight.Text:= IntToStr(EASY_HEIGHT); txtCount.Text:= IntToStr(EASY_COUNT); end; 1: begin txtWidth.Text:= IntToStr(MEDIUM_WIDTH); txtHeight.Text:= IntToStr(MEDIUM_HEIGHT); txtCount.Text:= IntToStr(MEDIUM_COUNT); end; 2: begin txtWidth.Text:= IntToStr(HARD_WIDTH); txtHeight.Text:= IntToStr(HARD_HEIGHT); txtCount.Text:= IntToStr(HARD_COUNT); end; 3: begin end; end; FOptions.GameChanged:= True; end; procedure TfrmOptions.txtBoxSizeChange(Sender: TObject); begin FOptions.SizeChanged:= True; end; procedure TfrmOptions.GameChanger(Sender: TObject); begin radDifficulty.ItemIndex:= 3; FOptions.GameChanged:= True; end; end.
unit uRabbitMQ.Utils; interface uses SysUtils, Windows, uRabbitMQ; procedure amqp_dump(const buffer:Pointer; len:size_t); function now_microseconds:UInt64; procedure microsleep(usec:Integer); procedure die(fmt: String; Args: array of const); procedure die_on_error(x: Integer; context: AnsiString); procedure die_on_amqp_error(x: amqp_rpc_reply_t; context: AnsiString); implementation function now_microseconds:UInt64; var ft:FILETIME; begin GetSystemTimeAsFileTime(&ft); Result:= ((UInt64(ft.dwHighDateTime) shl 32) or ft.dwLowDateTime) div 10; end; procedure microsleep(usec:Integer); begin Sleep(usec div 1000); end; procedure die(fmt: String; Args: array of const); begin WriteLn(Format(fmt, Args)); Halt(1); end; procedure die_on_error(x: Integer; context: AnsiString); begin if (x < 0) then begin WriteLn(Format('%s: %s\n', [context, amqp_error_string2(x)])); Halt(1); end; end; procedure die_on_amqp_error(x: amqp_rpc_reply_t; context: AnsiString); var m: pamqp_connection_close_t; begin case x.reply_type of AMQP_RESPONSE_NORMAL: Exit; AMQP_RESPONSE_NONE: WriteLn(Format('%s: missing RPC reply type!', [context])); AMQP_RESPONSE_LIBRARY_EXCEPTION: WriteLn(Format('%s: %s', [context, amqp_error_string2(x.library_error)])); AMQP_RESPONSE_SERVER_EXCEPTION: case (x.reply.id) of AMQP_CONNECTION_CLOSE_METHOD: begin m := pamqp_connection_close_t(x.reply.decoded); WriteLn(Format('%s: server connection error %d, message: %.*s', [context, m.reply_code, m.reply_text.len, PAnsiChar(m.reply_text.bytes)])); end; AMQP_CHANNEL_CLOSE_METHOD: begin m := pamqp_connection_close_t(x.reply.decoded); WriteLn(Format('%s: server channel error %d, message: %.*s', [context, m.reply_code, m.reply_text.len, PAnsiChar(m.reply_text.bytes)])); end; else WriteLn(Format('%s: unknown server error, method id 0x%08X', [context, x.reply.id])); end; end; Halt(1); end; function IsPrint(C:Char):Boolean; begin Result:= C in [' '..'~']; end; procedure dump_row(count:UInt32; numinrow:Integer; chs:PIntegerArray); var i:Integer; begin Write(Format('%08lX:', [count - numinrow])); if (numinrow > 0) then begin for i := 0 to numinrow-1 do begin if (i = 8) then Write(' :'); Write(Format(' %02X', [Char(chs[i])])); end; for i:= numinrow to 16-1 do begin if (i = 8) then Write(' :'); Write(' '); end; WriteLn(' '); for i := 0 to numinrow-1 do begin if (IsPrint(Char(chs[i]))) then Write(Char(chs[i])) else Write('.'); end; end; WriteLn; end; function rows_eq(a, b:PIntegerArray):Boolean; var i:Integer; begin for i:=0 to 16-1 do if (a[i] <> b[i]) then Exit(False); Result:=True; end; procedure amqp_dump(const buffer:Pointer; len:size_t); var buf:PAnsiChar; count:UInt32; numinrow :Integer; chs:array[0..16-1] of Integer; oldchs:array[0..16-1] of Integer; showed_dots:Boolean; i:size_t; ch:AnsiChar; j:Integer; begin buf := buffer; count := 0; numinrow := 0; showed_dots := False; for i := 0 to len-1 do begin ch := buf[i]; if (numinrow = 16) then begin if (rows_eq(@oldchs, @chs)) then begin if (not showed_dots) then begin showed_dots := True; WriteLn(' .. .. .. .. .. .. .. .. : .. .. .. .. .. .. .. ..'); end end else begin showed_dots := False; dump_row(count, numinrow, @chs); end; for j:=0 to 16-1 do oldchs[j] := chs[j]; numinrow := 0; end; Inc(count); chs[numinrow] := Ord(ch); Inc(numinrow); end; dump_row(count, numinrow, @chs); if (numinrow <> 0) then WriteLn(Format('%08lX:', [count])); end; end.
unit UQR; // Demo app for ZXing QRCode port to Delphi, by Debenu Pty Ltd (www.debenu.com) // Need a PDF SDK? Checkout Debenu Quick PDF Library: http://www.debenu.com/products/development/debenu-pdf-library/ interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DelphiZXingQRCode, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ExtDlgs, Vcl.ComCtrls; type TfrmQRGen = class(TForm) cmbEncoding: TComboBox; lblEncoding: TLabel; edtQuietZone: TEdit; lblPreview: TLabel; PaintBox1: TPaintBox; btnSave: TButton; pnlPreview: TPanel; pnlProperties: TPanel; pgcInput: TPageControl; tabText: TTabSheet; edtText: TEdit; btnTextGenerate: TButton; tabPhone: TTabSheet; edtContact: TEdit; btnGeneratePhone: TButton; tabEmail: TTabSheet; btnGenerateEmail: TButton; edtEmail: TEdit; tabSMS: TTabSheet; edtPhone: TEdit; lblQuietZone: TLabel; btnGenerateSMS: TButton; SavePictureDialog1: TSavePictureDialog; lblKCTech: TLabel; pnlMaster: TPanel; pnlQR: TPanel; edtSMS: TEdit; lblPhone_No: TLabel; lblMSG: TLabel; pnlTitle: TPanel; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure cmbEncodingChange(Sender: TObject); procedure edtQuietZoneChange(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnTextGenerateClick(Sender: TObject); procedure btnGeneratePhoneClick(Sender: TObject); procedure btnGenerateEmailClick(Sender: TObject); function IsValidEmail(const Value: string): boolean; procedure btnGenerateSMSClick(Sender: TObject); function QRGen(inputData: String): String; procedure edtContactKeyPress(Sender: TObject; var Key: Char); function keyPress(var data: Char): Char; private QRCodeBitmap: TBitmap; public end; var frmQRGen: TfrmQRGen; implementation {$R *.dfm} // For Validating Email Address function TfrmQRGen.IsValidEmail(const Value: string): boolean; function CheckAllowed(const s: string): boolean; var i: integer; begin Result := False; for i := 1 to Length(s) do begin // illegal char - no valid address if not(s[i] in ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '-', '.', '+']) then Exit; end; Result := True; end; var i: integer; namePart, serverPart: string; begin Result := False; i := Pos('@', Value); if (i = 0) then Exit; if (Pos('..', Value) > 0) or (Pos('@@', Value) > 0) or (Pos('.@', Value) > 0) then Exit; if (Pos('.', Value) = 1) or (Pos('@', Value) = 1) then Exit; namePart := Copy(Value, 1, i - 1); serverPart := Copy(Value, i + 1, Length(Value)); if (Length(namePart) = 0) or (Length(serverPart) < 5) then Exit; // too short i := Pos('.', serverPart); // must have dot and at least 3 places from end if (i = 0) or (i > (Length(serverPart) - 2)) then Exit; Result := CheckAllowed(namePart) and CheckAllowed(serverPart); end; // For Block Typing the alphabetes in a Phone tab function TfrmQRGen.keyPress(var data: Char): Char; begin if NOT(data in ['0' .. '9', '+', #8]) then data := #0; end; // For Creating QR function TfrmQRGen.QRGen(inputData: String): String; var QRCode: TDelphiZXingQRCode; Row, Column: integer; begin cmbEncoding.Enabled := True; QRCode := TDelphiZXingQRCode.Create; try QRCode.data := inputData; QRCode.Encoding := TQRCodeEncoding(cmbEncoding.ItemIndex); QRCode.QuietZone := StrToIntDef(edtQuietZone.Text, 4); QRCodeBitmap.SetSize(QRCode.Rows, QRCode.Columns); for Row := 0 to QRCode.Rows - 1 do begin for Column := 0 to QRCode.Columns - 1 do begin if (QRCode.IsBlack[Row, Column]) then begin QRCodeBitmap.Canvas.Pixels[Column, Row] := clBlack; end else begin QRCodeBitmap.Canvas.Pixels[Column, Row] := clWhite; end; end; end; finally FreeAndNil(QRCode); end; PaintBox1.Repaint; end; procedure TfrmQRGen.cmbEncodingChange(Sender: TObject); begin Update; end; procedure TfrmQRGen.edtQuietZoneChange(Sender: TObject); begin Update; end; procedure TfrmQRGen.edtContactKeyPress(Sender: TObject; var Key: Char); begin keyPress(Key); end; // To Generate OR for Phone procedure TfrmQRGen.btnGeneratePhoneClick(Sender: TObject); var phone_no: String; begin phone_no := edtContact.Text; QRGen(phone_no); end; //SMS procedure TfrmQRGen.btnGenerateSMSClick(Sender: TObject); var smsData: String; begin smsData := 'Phone.NO:' + edtPhone.Text + ' ' + 'Message:' + edtSMS.Text; QRGen(smsData); end; //Email procedure TfrmQRGen.btnGenerateEmailClick(Sender: TObject); var emailData: String; begin if IsValidEmail(edtEmail.Text) then begin emailData := edtEmail.Text; QRGen(emailData); end else ShowMessage('InValid Email Address'); end; //Text procedure TfrmQRGen.btnTextGenerateClick(Sender: TObject); var Qr: String; begin Qr := edtText.Text; QRGen(Qr) end; // To Save QR as Image procedure TfrmQRGen.btnSaveClick(Sender: TObject); begin if SavePictureDialog1.Execute then QRCodeBitmap.SaveToFile(SavePictureDialog1.FileName); end; // For Changing Colours procedure TfrmQRGen.FormCreate(Sender: TObject); begin edtText.StyleElements := [seBorder]; pnlProperties.StyleElements := [seBorder]; pgcInput.StyleElements := [seBorder]; lblPreview.StyleElements := [seBorder]; PaintBox1.StyleElements := [seBorder]; cmbEncoding.StyleElements := [seBorder]; edtQuietZone.StyleElements := [seBorder]; QRCodeBitmap := TBitmap.Create; pnlQR.StyleElements := [seBorder]; pnlPreview.StyleElements := [seBorder]; lblKCTech.StyleElements := [seBorder]; lblQuietZone.StyleElements := [seBorder]; lblEncoding.StyleElements := [seBorder]; edtContact.StyleElements := [seBorder]; edtEmail.StyleElements := [seBorder]; edtSMS.StyleElements := [seBorder]; pnlQR.Color := $008CFF; lblPhone_No.StyleElements := [seBorder]; edtText.Font.Color := clHotLight; cmbEncoding.Font.Color := clHotLight; edtQuietZone.Font.Color := clHotLight; lblMSG.StyleElements := [seBorder]; lblPreview.Font.Color := clHotLight; lblEncoding.Font.Color := clHotLight; lblQuietZone.Font.Color := clHotLight; lblPhone_No.Font.Color := clHotLight; lblMSG.Font.Color := clHotLight; edtSMS.StyleElements := [seBorder]; Update; end; procedure TfrmQRGen.FormDestroy(Sender: TObject); begin FreeAndNil(QRCodeBitmap); end; // for paint the QR procedure TfrmQRGen.PaintBox1Paint(Sender: TObject); var Scale: Double; begin PaintBox1.Canvas.Brush.Color := clWhite; PaintBox1.Canvas.FillRect(Rect(0, 0, PaintBox1.Width, PaintBox1.Height)); if ((QRCodeBitmap.Width > 0) and (QRCodeBitmap.Height > 0)) then begin if (PaintBox1.Width < PaintBox1.Height) then begin Scale := PaintBox1.Width / QRCodeBitmap.Width; end else begin Scale := PaintBox1.Height / QRCodeBitmap.Height; end; PaintBox1.Canvas.StretchDraw(Rect(0, 0, Trunc(Scale * QRCodeBitmap.Width), Trunc(Scale * QRCodeBitmap.Height)), QRCodeBitmap); end; end; end.
unit AddExitTime; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.DateTimeCtrls, FMX.Layouts, BusLine, BusLineController, Generics.Collections, BusExitController, BusExitTime; type TAddExitTimeForm = class(TForm) ToolBar1: TToolBar; ToolBar2: TToolBar; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; ComboBox1: TComboBox; Memo1: TMemo; Button1: TSpeedButton; Layout1: TLayout; rbQuarta: TRadioButton; rbSegunda: TRadioButton; rbTerca: TRadioButton; rbDomingo: TRadioButton; rbQuinta: TRadioButton; rbSexta: TRadioButton; rbSabado: TRadioButton; Label1: TLabel; TimeEdit1: TTimeEdit; StyleBook1: TStyleBook; procedure SpeedButton1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); private { Private declarations } FLineList: TList<TBusLine>; procedure CarregarHorariosLinhaSelecionada; function GetWeekDay: TWeekDay; public { Public declarations } end; var AddExitTimeForm: TAddExitTimeForm; implementation uses Utils; {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} procedure TAddExitTimeForm.Button1Click(Sender: TObject); begin Layout1.Enabled := True; end; procedure TAddExitTimeForm.CarregarHorariosLinhaSelecionada; var BusExitCtr: TBusExitController; BusExitList: TList<TBusExitTime>; BusExit: TBusExitTime; begin BusExitCtr := TBusExitController.create; try BusExitList := BusExitCtr.getTimes(FLineList[ComboBox1.ItemIndex]); if Assigned(BusExitList) and (BusExitList.Count > 0) then begin Memo1.Lines.Clear; for BusExit in BusExitList do begin Memo1.Lines.Add(Format('Horário: %s - Dia - %s', [BusExit.ExitTime, WeekDayToStr(BusExit.WeekDay)])) end; end; finally BusExitCtr.Free; end; end; procedure TAddExitTimeForm.ComboBox1Change(Sender: TObject); begin CarregarHorariosLinhaSelecionada; end; procedure TAddExitTimeForm.FormShow(Sender: TObject); var BLCtr: TBusLineController; BusLine: TBusLine; begin BLCtr := TBusLineController.Create; try FLineList := BLCtr.getAll; if Assigned(FLineList) and (FLineList.Count > 0) then begin for BusLine in FLineList do ComboBox1.Items.Add(BusLine.Description); end; finally BLCtr.Free; end; end; function TAddExitTimeForm.GetWeekDay: TWeekDay; begin if rbSegunda.IsChecked then Result := wdMonday; if rbTerca.IsChecked then Result := wdTuesday; if rbQuarta.IsChecked then Result := wdWednesday; if rbQuinta.IsChecked then Result := wdThursday; if rbSexta.IsChecked then Result := wdFriday; if rbSabado.IsChecked then Result := wdSaturday; if rbDomingo.IsChecked then Result := wdSunday; end; procedure TAddExitTimeForm.SpeedButton1Click(Sender: TObject); begin Close; end; procedure TAddExitTimeForm.SpeedButton2Click(Sender: TObject); var BusExitTime: TBusExitTime; Ctr: TBusExitController; begin BusExitTime := TBusExitTime.Create; BusExitTime.BusLine := FLineList[ComboBox1.ItemIndex]; BusExitTime.ExitTime := TimeEdit1.Text; BusExitTime.WeekDay := GetWeekDay; Ctr := TBusExitController.create; try Ctr.Save(BusExitTime); CarregarHorariosLinhaSelecionada; finally Ctr.Free; BusExitTime.Free; Layout1.Enabled := False; end; end; end.
unit uDCStatus; interface uses Graphics, CWindowThread; type TDCStatus = class private FProgressWin: TCWindowThread; public constructor Create; destructor Destroy; override; procedure ShowStatus(aStatus: string; aCanceled: Boolean = False; aPercent: Integer = -1); procedure HideStatus; property ProgressWin: TCWindowThread read FProgressWin; end; function DCStatus: TDCStatus; implementation uses SysUtils; var FDCStatus: TDCStatus; function DCStatus: TDCStatus; begin if not Assigned(FDCStatus) then FDCStatus := TDCStatus.Create; Result := FDCStatus; end; { TDCStatus } constructor TDCStatus.Create; begin FProgressWin := TCWindowThread.Create(nil); ProgressWin.Visible := False; ProgressWin.Width := 400; ProgressWin.Height := 70; ProgressWin.Percent := -1; ProgressWin.Enabled := False; ProgressWin.Interval := 500; ProgressWin.Color := 14935011; ProgressWin.CaptionColor := 14405055; ProgressWin.Font.Color := clWindowText; end; destructor TDCStatus.Destroy; begin ProgressWin.Free; inherited; end; procedure TDCStatus.HideStatus; begin ProgressWin.Visible := False; ProgressWin.Percent := -1; ProgressWin.Canceled := False; end; procedure TDCStatus.ShowStatus(aStatus: string; aCanceled: Boolean; aPercent: Integer); begin ProgressWin.Text := aStatus; ProgressWin.Enabled := aCanceled; ProgressWin.Percent := aPercent; if not ProgressWin.Visible then ProgressWin.Visible := True; end; initialization FDCStatus := nil; finalization FreeAndNil(FDCStatus); end.
unit MyFormat; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sysconst; Const feInvalidFormat = 1; feMissingArgument = 2; feInvalidArgIndex = 3; var MyDefaultFormatSettings : TFormatSettings = ( CurrencyFormat: 1; NegCurrFormat: 5; ThousandSeparator: ','; DecimalSeparator: '.'; CurrencyDecimals: 2; DateSeparator: '-'; TimeSeparator: ':'; ListSeparator: ','; CurrencyString: '$'; ShortDateFormat: 'd.m.y'; LongDateFormat: 'dd" "mm" "yyyy'; TimeAMString: 'AM'; TimePMString: 'PM'; ShortTimeFormat: 'hh:nn'; LongTimeFormat: 'hh:nn:ss'; ShortMonthNames: ('Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'); LongMonthNames: ('January','February','March','April','May','June', 'July','August','September','October','November','December'); ShortDayNames: ('Sun','Mon','Tue','Wed','Thu','Fri','Sat'); LongDayNames: ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); TwoDigitYearCenturyWindow: 50; ); function MyFormat (Const Fmt : AnsiString; const Args : Array of const; const FormatSettings: TFormatSettings) : AnsiString; function MyFormat (Const Fmt : AnsiString; const Args : Array of const) : AnsiString; procedure ReadInteger(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt); procedure ReadIndex(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt); procedure ReadLeft(const AFmt : AnsiString; var AChPos : SizeInt; var ALeft : Boolean); procedure ReadWidth(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt; var AWidth : LongInt); procedure ReadPrec(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt; var APrec : LongInt); function ReadFormat(const AFmt : AnsiString; const AArgs : Array of const; var AOldPos,AChPos,AArgpos,ALen,AIndex : SizeInt; var AWidth,APrec : LongInt; var ALeft : Boolean) : Char; function Checkarg (const AFmt : AnsiString; var ADoArg,AArgPos,AIndex : SizeInt; const AArgs : Array of const; AT : SizeInt; Err:boolean):boolean; procedure DoFormatError (ErrCode : Longint;const fmt:ansistring); implementation function MyFormat (Const Fmt : AnsiString; const Args : Array of const; const FormatSettings: TFormatSettings) : AnsiString; var ChPos,OldPos, ArgPos,DoArg, Len,Index : SizeInt; Hs,ToAdd : AnsiString; Width,Prec : Longint; Left : Boolean; Fchar : Char; Vq : QWord; begin Result := ''; Len := Length(Fmt); ChPos := 1; OldPos := 1; ArgPos := 0; While ChPos <= Len do begin // пробегаем до первого знака % While (ChPos <= Len) and (Fmt[ChPos] <> '%') do inc(ChPos); // копируем пройденный кусок в результат If ChPos > OldPos Then Result := Result + Copy(Fmt, OldPos, ChPos-OldPos); // не конец строки? If ChPos < Len then begin // читаем формат FChar := ReadFormat(Fmt,Args,OldPos,ChPos,ArgPos,Len,Index,Width,Prec,Left); case FChar of 'D' : begin //записываем числовое значение в строку if Checkarg(Fmt,DoArg,ArgPos,Index,Args,vtinteger,false) then Str(Args[DoArg].VInteger,ToAdd) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtInt64,false) then Str(Args[DoArg].VInt64^,ToAdd) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtQWord,true) then Str(int64(Args[DoArg].VQWord^),ToAdd); Width := Abs(Width); Index := Prec-Length(ToAdd); // вставляем знак If ToAdd[1] <> '-' then ToAdd := StringOfChar('0',Index) + ToAdd else Insert(StringOfChar('0',Index + 1),toadd,2);// + 1 to accomodate for - sign in length !! end; 'U' : begin if Checkarg(Fmt,DoArg,ArgPos,Index,Args,vtinteger,false) then Str(cardinal(Args[Doarg].VInteger),ToAdd) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtInt64,false) then Str(qword(Args[DoArg].VInt64^),toadd) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtQWord,true) then Str(Args[DoArg].VQWord^,toadd); Width := Abs(width); Index := Prec - Length(ToAdd); ToAdd := StringOfChar('0',Index) + ToAdd end; {$ifndef FPUNONE} 'E' : begin if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtCurrency,false) then ToAdd:=FloatToStrF(Args[doarg].VCurrency^,ffexponent,Prec,3,FormatSettings) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtExtended,true) then ToAdd:=FloatToStrF(Args[doarg].VExtended^,ffexponent,Prec,3,FormatSettings); end; 'F' : begin if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtCurrency,false) then ToAdd:=FloatToStrF(Args[doarg].VCurrency^,ffFixed,9999,Prec,FormatSettings) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtExtended,true) then ToAdd:=FloatToStrF(Args[doarg].VExtended^,ffFixed,9999,Prec,FormatSettings); end; 'G' : begin if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtCurrency,false) then ToAdd:=FloatToStrF(Args[doarg].VCurrency^,ffGeneral,Prec,3,FormatSettings) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtExtended,true) then ToAdd:=FloatToStrF(Args[doarg].VExtended^,ffGeneral,Prec,3,FormatSettings); end; 'N' : begin if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtCurrency,false) then ToAdd:=FloatToStrF(Args[doarg].VCurrency^,ffNumber,9999,Prec,FormatSettings) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtExtended,true) then ToAdd:=FloatToStrF(Args[doarg].VExtended^,ffNumber,9999,Prec,FormatSettings); end; 'M' : begin if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtExtended,false) then ToAdd:=FloatToStrF(Args[doarg].VExtended^,ffCurrency,9999,Prec,FormatSettings) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtCurrency,true) then ToAdd:=FloatToStrF(Args[doarg].VCurrency^,ffCurrency,9999,Prec,FormatSettings); end; {$else} 'E','F','G','N','M': RunError(207); {$endif} 'S' : begin if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtString,false) then hs := Args[doarg].VString^ else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtChar,false) then hs := Args[doarg].VChar else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtPChar,false) then hs := Args[doarg].VPChar else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtPWideChar,false) then hs := WideString(Args[doarg].VPWideChar) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtWideChar,false) then hs := WideString(Args[doarg].VWideChar) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtWidestring,false) then hs := WideString(Args[doarg].VWideString) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtAnsiString,false) then hs := ansistring(Args[doarg].VAnsiString) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtUnicodeString,false) then hs := UnicodeString(Args[doarg].VUnicodeString) else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtVariant,true) then hs := Args[doarg].VVariant^; Index := Length(hs); If (Prec <> -1) and (Index > Prec) then Index := Prec; ToAdd := Copy(hs,1,Index); end; 'P' : Begin CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtpointer,true); ToAdd := HexStr(PtrUInt(Args[DoArg].VPointer), SizeOf(Ptruint)*2); end; 'X' : begin if Checkarg(Fmt,DoArg,ArgPos,Index,Args,vtinteger,false) then begin Vq := Cardinal(Args[Doarg].VInteger); Index := 16; end else if CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtQWord, false) then begin Vq := Qword(Args[DoArg].VQWord^); Index := 31; end else begin CheckArg(Fmt,DoArg,ArgPos,Index,Args,vtInt64,true); Vq := Qword(Args[DoArg].VInt64^); Index := 31; end; If Prec > Index then ToAdd := HexStr(Int64(Vq),Index) else begin // determine minimum needed number of hex digits. Index := 1; While (QWord(1) shl (Index * 4) <= Vq) and (Index < 16) do Inc(Index); If Index > Prec then Prec := Index; ToAdd := HexStr(int64(Vq),Prec); end; end; '%': ToAdd:='%'; end; if Width <> -1 then if Length(ToAdd) < Width then if not Left then ToAdd := Space(Width - Length(ToAdd)) + ToAdd else ToAdd := ToAdd + Space(Width - Length(ToAdd)); Result := Result + ToAdd; end; Inc(ChPos); OldPos := ChPos; end; end; procedure ReadInteger(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt); var Code: Word; ArgN: SizeInt; begin If AValue <> -1 then Exit; // Was already read. AOldPos := AChPos; While (AChPos <= ALen) and (AFmt[AChPos] <= '9') and (AFmt[AChPos] >= '0') do inc(AChPos); If AChPos > ALen then DoFormatError(feInvalidFormat,AFmt); If AFmt[AChPos] = '*' then begin if AIndex = -1 then ArgN := AArgpos else begin ArgN := AIndex; Inc(AIndex); end; If (AChPos > AOldPos) or (ArgN > High(AArgs)) then DoFormatError(feInvalidFormat,AFmt); AArgPos := ArgN + 1; case AArgs[ArgN].Vtype of vtInteger : AValue := AArgs[ArgN].VInteger; vtInt64 : AValue := AArgs[ArgN].VInt64^; vtQWord : AValue := AArgs[ArgN].VQWord^; else DoFormatError(feInvalidFormat,AFmt); end; Inc(AChPos); end else begin If (AOldPos < AChPos) Then begin Val (Copy(AFmt,AOldPos,AChPos-AOldPos), AValue, Code); // This should never happen !! If Code > 0 then DoFormatError (feInvalidFormat,AFmt); end else AValue := -1; end; end; procedure ReadIndex(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt); begin If AFmt[AChPos] <> ':' then ReadInteger(AFmt,AArgs,AValue,AOldPos,AChPos,AArgpos,AIndex,ALen) else AValue := 0; // Delphi undocumented behaviour, assume 0, #11099 If AFmt[AChPos] = ':' then begin If AValue = -1 then DoFormatError(feMissingArgument,AFmt); AIndex := AValue; AValue := -1; Inc(AChPos); end; end; procedure ReadLeft(const AFmt : AnsiString; var AChPos : SizeInt; var ALeft : Boolean); begin If AFmt[AChPos]='-' then begin ALeft := True; Inc(AChPos); end else ALeft := False; end; procedure ReadWidth(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt; var AWidth : LongInt); begin ReadInteger(AFmt,AArgs,AValue,AOldPos,AChPos,AArgpos,AIndex,ALen); If AValue <> -1 then begin AWidth := AValue; AValue := -1; end; end; procedure ReadPrec(const AFmt : AnsiString; const AArgs : Array of const; var AValue : LongInt; var AOldPos,AChPos,AArgpos,AIndex,ALen : SizeInt; var APrec : LongInt); begin If AFmt[AChPos]='.' then begin Inc(AChPos); ReadInteger(AFmt,AArgs,AValue,AOldPos,AChPos,AArgpos,AIndex,ALen); If AValue = -1 then AValue := 0; APrec := AValue; end; end; function ReadFormat(const AFmt : AnsiString; const AArgs : Array of const; var AOldPos,AChPos,AArgpos,ALen,AIndex : SizeInt; var AWidth,APrec : LongInt; var ALeft : Boolean) : Char; var Value : longint; {$ifdef INWIDEFORMAT} var FormatChar : TFormatChar; {$endif INWIDEFORMAT} { ReadFormat reads the format string. It returns the type character in uppercase, and sets index, Width, Prec to their correct values, or -1 if not set. It sets Left to true if left alignment was requested. In case of an error, DoFormatError is called. } begin AIndex := -1; AWidth := -1; APrec := -1; Value := -1; Inc(AChPos); if AFmt[AChPos]='%' then begin Result:='%'; Exit; // VP fix end; ReadIndex(AFmt,AArgs,Value,AOldPos,AChPos,AArgpos,AIndex,ALen); ReadLeft(AFmt,AChPos,ALeft); ReadWidth(AFmt,AArgs,Value,AOldPos,AChPos,AArgpos,AIndex,ALen,AWidth); ReadPrec(AFmt,AArgs,Value,AOldPos,AChPos,AArgpos,AIndex,ALen,APrec); {$ifdef INWIDEFORMAT} FormatChar:=UpCase(UnicodeChar(Fmt[ChPos])); if word(FormatChar)>255 then Result:=#255 else Result:=FormatChar; {$else INWIDEFORMAT} Result := Upcase(AFmt[AChPos]); {$endif INWIDEFORMAT} end; function Checkarg (const AFmt : AnsiString; var ADoArg,AArgPos,AIndex : SizeInt; const AArgs : Array of const; AT : SizeInt; Err:boolean):boolean; { Check if argument INDEX is of correct type (AT) If Index=-1, ArgPos is used, and argpos is augmented with 1 DoArg is set to the argument that must be used. } begin Result := False; if AIndex = -1 then ADoArg := AArgPos else ADoArg := AIndex; AArgPos := ADoArg + 1; If (ADoArg > High(AArgs)) or (AArgs[ADoArg].Vtype<>AT) then begin if Err then DoFormatError(feInvalidArgindex,AFmt); Dec(AArgPos); Exit; end; Result := True; end; procedure DoFormatError (ErrCode : Longint; const Fmt : ansistring); var S : String; begin //!! must be changed to contain format string... S := Fmt; Case ErrCode of feInvalidFormat : raise EConvertError.Createfmt(SInvalidFormat,[s]); feMissingArgument : raise EConvertError.Createfmt(SArgumentMissing,[s]); feInvalidArgIndex : raise EConvertError.Createfmt(SInvalidArgIndex,[s]); end; end; Function MyFormat (Const Fmt : AnsiString; const Args : Array of const) : AnsiString; begin Result:=Format(Fmt,Args,MyDefaultFormatSettings); end; end.
// ------------------------------------------------------------------------------------------------- // This file contains class for HTML to PDF conversion using great components HTMLVIEW and SynPdf. // Thanks for authors of these components: HTMLVIEW - L. David Baldwin and SynPdf - Arnaud Bouchez. // The orignal class was written by Pawel Stroinski on 2010/07/07 and is public domain. // Revisioned by Muzio Valerio on 2019/07/01 and is public domain. // ------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------- // New implementation 2021/04/24 // TvmHtmlToPdfGDI // a class derived from TPdfDocumentGDI // is a public domain. // ------------------------------------------------------------------------------------------------- unit vmHtmlToPdf; interface uses System.Classes,System.SysUtils, Winapi.Windows, Vcl.Printers, Vcl.Forms, Vcl.Graphics, SynPdf, HTMLView; const CPointsPerInch = 72; CCentimetersPerInch = 2.54; type TPositionPrint = (ppTop, ppBottom); TvmHtmlToPdf = class(TPdfDocument) strict private // PDF Parameters FPrintOrientation: TPrinterOrientation; FPDFMarginTop: Double; FPDFMarginLeft: Double; FPDFMarginRight: Double; FPDFMarginBottom: Double; FScaleToFit: Boolean; // ---------------- // Source Viewer HtmlViewer FSrcViewer: THtmlViewer; // ------------------------ // Optional parameters for print Page Number FPrintPageNumber: Boolean; FTextPageNumber: string; FPageNumberPositionPrint: TPositionPrint; // ----------------------------------------- // Utility function function Points2Pixels(APoints: Single): Integer; function Centimeters2Points(ACentimeters: Double): Single; function DefinePointsHeight: Single; function DefinePointsWidth: Single; // ---------------- private procedure SetDefaultPaperSize(const Value: TPDFPaperSize); procedure SetPDFMarginTop(const Value: Double); procedure SetPDFMarginLeft(const Value: Double); procedure SetPDFMarginRight(const Value: Double); procedure SetPDFMarginBottom(const Value: Double); procedure SetScaleToFit(const Value: Boolean); procedure SetSrcViewer(const Value: THTMLViewer); function GetPrintOrientation: TPrinterOrientation; procedure SetPrintOrientation(const Value: TPrinterOrientation); procedure SetPrintPageNumber(const Value: Boolean); procedure SetTextPageNumber(const Value: string); procedure SetPageNumberPostionPrint(const Value: TPositionPrint); public property PDFMarginTop: Double write SetPDFMarginTop; property PDFMarginLeft: Double write SetPDFMarginLeft; property PDFMarginRight: Double write SetPDFMarginRight; property PDFMarginBottom: Double write SetPDFMarginBottom; property PDFScaleToFit: Boolean write SetScaleToFit; property PrintOrientation: TPrinterOrientation read GetPrintOrientation write SetPrintOrientation; property DefaultPaperSize: TPDFPaperSize write SetDefaultPaperSize; property SrcViewer: THTMLViewer write SetSrcViewer; property PrintPageNumber: Boolean write SetPrintPageNumber; property TextPageNumber: string write SetTextPageNumber; property PageNumberPositionPrint: TPositionPrint write SetPageNumberPostionPrint; procedure Execute; end; TvmHtmlToPdfGDI = class(TPdfDocumentGDI) strict private // PDF Parameters FPrintOrientation: TPrinterOrientation; FPDFMarginTop: Double; FPDFMarginLeft: Double; FPDFMarginRight: Double; FPDFMarginBottom: Double; FScaleToFit: Boolean; // ---------------- // Source Viewer HtmlViewer FSrcViewer: THtmlViewer; // ------------------------ // Optional parameters for print Page Number FPrintPageNumber: Boolean; FTextPageNumber: string; FPageNumberPositionPrint: TPositionPrint; // ----------------------------------------- // Utility function function Centimeters2Points(const aCentimeters: Double): Single; function DefinePointsWidth: Single; function Points2Pixels(const aPoints: Single): Integer; function DefinePointsHeight: Single; // ----------------- private function GetPrintOrientation: TPrinterOrientation; procedure SetDefaultPaperSize(const Value: TPDFPaperSize); procedure SetPageNumberPostionPrint(const Value: TPositionPrint); procedure SetPDFMarginBottom(const Value: Double); procedure SetPDFMarginLeft(const Value: Double); procedure SetPDFMarginRight(const Value: Double); procedure SetPDFMarginTop(const Value: Double); procedure SetPrintOrientation(const Value: TPrinterOrientation); procedure SetPrintPageNumber(const Value: Boolean); procedure SetScaleToFit(const Value: Boolean); procedure SetSrcViewer(const Value: THTMLViewer); procedure SetTextPageNumber(const Value: string); public property PDFMarginTop: Double write SetPDFMarginTop; property PDFMarginLeft: Double write SetPDFMarginLeft; property PDFMarginRight: Double write SetPDFMarginRight; property PDFMarginBottom: Double write SetPDFMarginBottom; property PDFScaleToFit: Boolean write SetScaleToFit; property PrintOrientation: TPrinterOrientation read GetPrintOrientation write SetPrintOrientation; property DefaultPaperSize: TPDFPaperSize write SetDefaultPaperSize; property SrcViewer: THTMLViewer write SetSrcViewer; property PrintPageNumber: Boolean write SetPrintPageNumber; property TextPageNumber: string write SetTextPageNumber; property PageNumberPositionPrint: TPositionPrint write SetPageNumberPostionPrint; procedure Execute; end; implementation { TvmHtmlToPdf } function TvmHtmlToPdf.Points2Pixels(APoints: Single): Integer; begin Result := Round(APoints / CPointsPerInch * Screen.PixelsPerInch); end; function TvmHtmlToPdf.Centimeters2Points(ACentimeters: Double): Single; begin Result := ACentimeters / CCentimetersPerInch * CPointsPerInch; end; function TvmHtmlToPdf.DefinePointsHeight: Single; begin Result := DefaultPageHeight - Centimeters2Points(FPDFMarginTop + FPDFMarginBottom); end; function TvmHtmlToPdf.DefinePointsWidth: Single; begin Result := DefaultPageWidth - Centimeters2Points(FPDFMarginLeft + FPDFMarginRight); end; procedure TvmHtmlToPdf.SetPrintOrientation(const Value: TPrinterOrientation); var lTmpWidth: Integer; begin if Value <> FPrintOrientation then begin lTmpWidth := DefaultPageWidth; DefaultPageWidth := DefaultPageHeight; DefaultPageHeight := lTmpWidth; end; end; procedure TvmHtmlToPdf.SetScaleToFit(const Value: Boolean); begin FScaleToFit := Value; end; procedure TvmHtmlToPdf.SetSrcViewer(const Value: THTMLViewer); begin FSrcViewer := Value; end; function TvmHtmlToPdf.GetPrintOrientation: TPrinterOrientation; begin Result := TPrinterOrientation(Ord(DefaultPageWidth > DefaultPageHeight)); end; procedure TvmHtmlToPdf.SetDefaultPaperSize(const Value: TPDFPaperSize); var lPrintOrientation: TPrinterOrientation; begin lPrintOrientation := FPrintOrientation; FDefaultPaperSize := Value; inherited; FPrintOrientation := lPrintOrientation; end; procedure TvmHtmlToPdf.SetPrintPageNumber(const Value: Boolean); begin FPrintPageNumber := Value; end; procedure TvmHtmlToPdf.SetTextPageNumber(const Value: string); begin FTextPageNumber := Value; end; procedure TvmHtmlToPdf.SetPageNumberPostionPrint(const Value: TPositionPrint); begin FPageNumberPositionPrint := Value; end; procedure TvmHtmlToPdf.SetPDFMarginBottom(const Value: Double); begin FPDFMarginBottom := Value; end; procedure TvmHtmlToPdf.SetPDFMarginLeft(const Value: Double); begin FPDFMarginLeft := Value; end; procedure TvmHtmlToPdf.SetPDFMarginRight(const Value: Double); begin FPDFMarginRight := Value; end; procedure TvmHtmlToPdf.SetPDFMarginTop(const Value: Double); begin FPDFMarginTop := Value; end; procedure TvmHtmlToPdf.Execute; function TextOutX(const aLeftValue, aPiontsWidth, aTextWidth: Single): Single; begin Result := aLeftValue + (aPiontsWidth - aTextWidth)/2; end; function TextOutY(const aValue: Single): Single; begin Result := aValue; end; const cFontSize: Single = 9; var lFormatWidth, lWidth, lHeight, I: Integer; lPages: TList; lPage: TMetafile; lScale: Single; lMarginL, lPointsWidth, lPointsHeight, lMarginBottom, lMarginTop: Single; lPageText: string; lTextOutX, lTextOutY: Single; begin lPointsWidth := DefinePointsWidth; lFormatWidth := Points2Pixels(lPointsWidth); lWidth := FSrcViewer.FullDisplaySize(lFormatWidth).cx; lScale := 1; if FScaleToFit and (lWidth > lFormatWidth) and (lFormatWidth > 0) then lScale := lFormatWidth / lWidth; lPointsHeight := DefinePointsHeight / lScale; lHeight := Points2Pixels(lPointsHeight); lPages := FSrcViewer.MakePagedMetaFiles(lWidth, lHeight); lMarginL := Centimeters2Points(FPDFMarginLeft); lMarginBottom := Centimeters2Points(FPDFMarginBottom); lMarginTop := Centimeters2Points(FPDFMarginTop); for I := 0 to lPages.Count - 1 do begin AddPage; lPage := TMetafile(lPages[I]); Canvas.GSave; Canvas.Rectangle(lMarginL, lMarginTop, lPointsWidth, lPointsHeight); Canvas.Clip; Canvas.RenderMetaFile(lPage, lScale, 0, lMarginL, lMarginBottom, tpExactTextCharacterPositining); Canvas.GRestore; if FPrintPageNumber then begin if FTextPageNumber = '' then lPageText := 'Page %d/%d' else lPageText := FTextPageNumber; lPageText := Format(lPageText,[I + 1, lPages.Count]); Canvas.SetFont('Segoe UI', cFontSize, []); Canvas.SetRGBStrokeColor(clBlack); case FPageNumberPositionPrint of ppTop: begin lTextOutX := TextOutX(lMarginL, lPointsWidth, Canvas.TextWidth(PDFString(lPageText))); lTextOutY := TextOutY(cFontSize*2); Canvas.TextOut(lTextOutX, lPointsHeight - lTextOutY, PDFString(lPageText)); end; ppBottom: begin lTextOutX := TextOutX(lMarginL, lPointsWidth, Canvas.TextWidth(PDFString(lPageText))); lTextOutY := TextOutY(lMarginBottom - (cFontSize*2)); Canvas.TextOut(lTextOutX, lTextOutY, PDFString(lPageText)); end; end; end; FreeAndNil(LPage); end; FreeAndNil(LPages); end; { TvmHtmlToPdfGDI } function TvmHtmlToPdfGDI.Centimeters2Points(const aCentimeters: Double): Single; begin Result := ACentimeters / CCentimetersPerInch * CPointsPerInch; end; function TvmHtmlToPdfGDI.DefinePointsHeight: Single; begin Result := (DefaultPageHeight - Centimeters2Points(FPDFMarginTop + FPDFMarginBottom)); end; function TvmHtmlToPdfGDI.DefinePointsWidth: Single; begin Result := DefaultPageWidth - Centimeters2Points(FPDFMarginLeft + FPDFMarginRight); end; procedure TvmHtmlToPdfGDI.Execute; var lFormatWidth, lWidth, lHeight, I: Integer; lMarginL, lMarginR, lPointsWidth, lPointsHeight, lMarginTop: Single; lPages: TList; lMFPage: TMetafile; lScale: Single; lPageText: string; begin try lPointsWidth := DefinePointsWidth; lFormatWidth := Points2Pixels(lPointsWidth); lWidth := FSrcViewer.FullDisplaySize(lFormatWidth).cx; lScale := 1; if FScaleToFit and (lWidth > lFormatWidth) and (lFormatWidth > 0) then lScale := lFormatWidth / lWidth; lPointsHeight := DefinePointsHeight / lScale; lHeight := Points2Pixels(lPointsHeight); lPages := FSrcViewer.MakePagedMetaFiles(lWidth, lHeight); lMarginL := Centimeters2Points(FPDFMarginLeft); lMarginR := Centimeters2Points(FPDFMarginRight); lMarginTop := Centimeters2Points(FPDFMarginTop); ScreenLogPixels := Screen.PixelsPerInch; for I := 0 to LPages.Count - 1 do begin lMFPage := TMetafile(lPages[I]); Self.AddPage; VCLCanvas.Draw(Trunc(lMarginL), Trunc(lMarginTop), LMFPage); if FPrintPageNumber then begin if FTextPageNumber = '' then lPageText := 'Page %d/%d' else lPageText := FTextPageNumber; lPageText := Format(lPageText, [I + 1, LPages.Count]); VCLCanvas.Font.Name := 'Segoe UI'; VCLCanvas.Font.Size := 10; VCLCanvas.Font.Color := clRed; case FPageNumberPositionPrint of ppTop: begin VCLCanvas.TextOut(Trunc(lMarginR + (lPointsWidth - VCLCanvas.TextWidth(lPageText))/2), Trunc(0 + VCLCanvas.Font.Size), lPageText); end; ppBottom: begin VCLCanvas.TextOut(Trunc(lMarginR + (lPointsWidth - VCLCanvas.TextWidth(lPageText))/2), lHeight + (VCLCanvas.Font.Size * 2), lPageText); end; end; end; FreeAndNil(LMFPage); end; finally FreeAndNil(lPages); end; end; function TvmHtmlToPdfGDI.GetPrintOrientation: TPrinterOrientation; begin Result := FPrintOrientation; end; function TvmHtmlToPdfGDI.Points2Pixels(const aPoints: Single): Integer; begin Result := Round(aPoints / CPointsPerInch * Screen.PixelsPerInch); end; procedure TvmHtmlToPdfGDI.SetDefaultPaperSize(const Value: TPDFPaperSize); var lPrintOrientation: TPrinterOrientation; begin lPrintOrientation := FPrintOrientation; FDefaultPaperSize := Value; inherited; FPrintOrientation := lPrintOrientation; end; procedure TvmHtmlToPdfGDI.SetPageNumberPostionPrint(const Value: TPositionPrint); begin FPageNumberPositionPrint := Value; end; procedure TvmHtmlToPdfGDI.SetPDFMarginBottom(const Value: Double); begin FPDFMarginBottom := Value; end; procedure TvmHtmlToPdfGDI.SetPDFMarginLeft(const Value: Double); begin FPDFMarginLeft := Value; end; procedure TvmHtmlToPdfGDI.SetPDFMarginRight(const Value: Double); begin FPDFMarginRight := Value; end; procedure TvmHtmlToPdfGDI.SetPDFMarginTop(const Value: Double); begin FPDFMarginTop := Value; end; procedure TvmHtmlToPdfGDI.SetPrintOrientation(const Value: TPrinterOrientation); begin FPrintOrientation := Value; end; procedure TvmHtmlToPdfGDI.SetPrintPageNumber(const Value: Boolean); begin FPrintPageNumber := Value; end; procedure TvmHtmlToPdfGDI.SetScaleToFit(const Value: Boolean); begin FScaleToFit := Value; end; procedure TvmHtmlToPdfGDI.SetSrcViewer(const Value: THTMLViewer); begin FSrcViewer := Value; end; procedure TvmHtmlToPdfGDI.SetTextPageNumber(const Value: string); begin FTextPageNumber := Value; end; end.
{******************************************************************************* 作者: dmzn@163.com 2012-02-03 描述: 业务常量定义 备注: *.所有In/Out数据,最好带有TBWDataBase基数据,且位于第一个元素. *******************************************************************************} unit UBusinessConst; interface uses UBusinessPacker; const {*channel type*} cBus_Channel_Connection = $0002; cBus_Channel_Business = $0005; {*worker action code*} cWorker_GetPackerName = $0010; cWorker_GetMITName = $0012; {*business command*} cBC_RemoteExecSQL = $0050; cBC_ReaderCardIn = $0052; cBC_MakeTruckIn = $0053; cBC_MakeTruckOut = $0055; cBC_MakeTruckCall = $0056; cBC_MakeTruckResponse = $0057; cBC_SaveTruckCard = $0060; cBC_LogoutBillCard = $0061; cBC_LoadQueueTrucks = $0062; type PWorkerBusinessCommand = ^TWorkerBusinessCommand; TWorkerBusinessCommand = record FBase : TBWDataBase; FCommand : Integer; //命令 FData : string; //数据 end; resourcestring {*common function*} sSys_SweetHeart = 'Sys_SweetHeart'; //心跳指令 sSys_BasePacker = 'Sys_BasePacker'; //基本封包器 {*business mit function name*} sBus_BusinessCommand = 'Bus_BusinessCommand'; //业务指令 {*client function name*} sCLI_BusinessCommand = 'CLI_BusinessCommand'; //业务指令 sCLI_RemoteQueue = 'CLI_RemoteQueue'; //业务指令 implementation end.
unit uThreadScanner; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil; type TFileScannerThread = class(TThread) private fPath: string; fFilter: string; fList: TStringList; protected procedure Execute; override; procedure FileFoundEvent(FileIterator: TFileIterator); public constructor Create; destructor Destroy; override; property Path: string read fPath write fPath; property Filter: string read fFilter write fFilter; property List: TStringList read fList; end; implementation { TFileScannerThread } constructor TFileScannerThread.Create; begin inherited Create(true); FreeOnTerminate:= false; fPath:= ''; fFilter:= '*.*'; fList:= TStringList.Create; end; destructor TFileScannerThread.Destroy; begin FreeAndNil(fList); inherited Destroy; end; procedure TFileScannerThread.Execute; var Searcher: TFileSearcher; begin fPath:= IncludeTrailingPathDelimiter(fPath); Searcher := TFileSearcher.Create; try Searcher.OnFileFound:= @FileFoundEvent; Searcher.DirectoryAttribute := faDirectory; Searcher.Search(fPath, fFilter, true); finally Searcher.Free; end; fList.Sort; end; procedure TFileScannerThread.FileFoundEvent(FileIterator: TFileIterator); var s: string; begin s:= Copy(FileIterator.FileName, Length(fPath) + 1, MaxInt); fList.Add(s); end; end.
unit VisibleDSA.MergeSortData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Generics.Collections; type ArrType = (Default, NearlyOrdered); TMergeSortData = class public L: integer; R: integer; MergeIndex: integer; Numbers: array of integer; constructor Create(n, randomBound: integer; dataType: ArrType = ArrType.Default); destructor Destroy; override; procedure Swap(i, j: integer); function Length: integer; function GetValue(index: integer): integer; end; implementation type TArrayHelper_int = specialize TArrayHelper<integer>; { TMergeSortData } constructor TMergeSortData.Create(n, randomBound: integer; dataType: ArrType); var i, swapTime, a, b: integer; begin L := -1; R := -1; MergeIndex := -1; Randomize; SetLength(Numbers, n); for i := 0 to n - 1 do Numbers[i] := Random(randomBound) + 1; if dataType = ArrType.NearlyOrdered then begin TArrayHelper_int.Sort(Numbers); swapTime := Trunc(0.02 * n); for i := 0 to swapTime - 1 do begin a := Random(n); b := Random(n); Swap(a, b); end; end; end; destructor TMergeSortData.Destroy; begin inherited Destroy; end; function TMergeSortData.Length: integer; begin Result := System.Length(Numbers); end; function TMergeSortData.GetValue(index: integer): integer; begin if (index < 0) or (index >= Length) then raise Exception.Create('Invalid index to access Sort Data.'); Result := Numbers[index]; end; procedure TMergeSortData.Swap(i, j: integer); var temp: integer; begin if (i < 0) or (i >= Self.Length) or (j < 0) or (j >= Self.Length) then raise Exception.Create('Invalid index to access Sort Data.'); temp := Numbers[j]; Numbers[j] := Numbers[i]; Numbers[i] := temp; end; end.
unit frmAAEditPrefsUnit; {$MODE Delphi} interface uses LCLIntf, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, LResources, SynEdit, synedittypes, betterControls; type { TfrmAAEditPrefs } TfrmAAEditPrefs = class(TForm) cbFontQuality: TComboBox; cbShowGutter: TCheckBox; cbShowLineNumbers: TCheckBox; cbSmartTab: TCheckBox; cbTabsToSpace: TCheckBox; edtTabWidth: TEdit; Label1: TLabel; Label2: TLabel; Panel2: TPanel; Button1: TButton; Button2: TButton; Panel1: TPanel; FontDialog1: TFontDialog; btnFont: TButton; Panel3: TPanel; Panel4: TPanel; procedure btnFontClick(Sender: TObject); procedure cbFontQualitySelect(Sender: TObject); procedure edtTabWidthChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cbShowLineNumbersClick(Sender: TObject); procedure cbShowGutterClick(Sender: TObject); procedure cbSmartTabClick(Sender: TObject); procedure cbTabsToSpaceClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Panel1Click(Sender: TObject); private { Private declarations } fSynEdit: TCustomSynEdit; oldsettings: record font: tfont; showlinenumbers: boolean; showgutter: boolean; options: TSynEditorOptions; tabwidth: integer; end; public { Public declarations } function execute(synedit: TCustomSynEdit): boolean; end; var frmAAEditPrefs: TfrmAAEditPrefs; implementation function TfrmAAEditPrefs.execute(synedit: TCustomSynEdit): boolean; begin fSynEdit:=synedit; FontDialog1.Font.Assign(fSynEdit.Font); cbFontQuality.ItemIndex:=integer(fSynEdit.Font.Quality); //save all parameters that could get changed oldsettings.font.Assign(fSynEdit.Font); oldsettings.showlinenumbers:=fSynEdit.Gutter.LineNumberPart.Visible; oldsettings.showgutter:=fSynEdit.Gutter.Visible; oldsettings.options:=fSynEdit.options; oldsettings.tabwidth:=fSynEdit.TabWidth; //setup GUI cbShowLineNumbers.Checked:=fSynEdit.Gutter.linenumberpart.visible; cbShowGutter.Checked:=fSynEdit.Gutter.Visible; cbSmartTab.Checked:=eoSmartTabs in fSynEdit.Options; cbTabsToSpace.Checked:=eoTabsToSpaces in fSynEdit.Options; edtTabWidth.Text:=inttostr(fSynEdit.TabWidth); btnFont.Caption:=fontdialog1.Font.Name+' '+inttostr(fontdialog1.Font.Size); //show form result:=showmodal=mrok; if not result then //undo all changes begin fsynedit.font.Assign(oldsettings.font); fsynedit.Gutter.linenumberpart.visible:=oldsettings.showlinenumbers; fsynedit.Gutter.visible:=oldsettings.showgutter; fsynedit.Options:=oldsettings.options; fSynEdit.TabWidth:=oldsettings.tabwidth; end; //else leave it and let the caller save to registry, ini, or whatever end; procedure TfrmAAEditPrefs.btnFontClick(Sender: TObject); begin if fontdialog1.Execute then begin fsynedit.font.name:=fontdialog1.Font.name; fsynedit.font.size:=fontdialog1.Font.size; btnFont.Caption:=fontdialog1.Font.Name+' '+inttostr(fontdialog1.Font.Size); end; end; procedure TfrmAAEditPrefs.cbFontQualitySelect(Sender: TObject); begin if cbFontQuality.itemindex<>-1 then fsynedit.font.Quality:=TFontQuality(cbFontQuality.ItemIndex); end; procedure TfrmAAEditPrefs.edtTabWidthChange(Sender: TObject); var i: integer; begin if TryStrToInt(edtTabWidth.text,i) then fSynEdit.TabWidth:=i; end; procedure TfrmAAEditPrefs.FormCreate(Sender: TObject); begin oldsettings.font:=tfont.Create; end; procedure TfrmAAEditPrefs.FormDestroy(Sender: TObject); begin if oldsettings.font<>nil then oldsettings.font.Free; end; procedure TfrmAAEditPrefs.cbShowLineNumbersClick(Sender: TObject); begin fSynEdit.Gutter.linenumberpart.visible:=cbShowLineNumbers.checked; end; procedure TfrmAAEditPrefs.cbShowGutterClick(Sender: TObject); begin fSynEdit.Gutter.Visible:=cbShowGutter.Checked; end; procedure TfrmAAEditPrefs.cbSmartTabClick(Sender: TObject); begin if cbSmartTab.Checked then fSynEdit.Options:=fSynEdit.Options+[eoSmartTabs, eoSmartTabDelete] else fSynEdit.Options:=fSynEdit.Options-[eoSmartTabs, eoSmartTabDelete]; end; procedure TfrmAAEditPrefs.cbTabsToSpaceClick(Sender: TObject); begin if cbTabsToSpace.Checked then fSynEdit.Options:=fSynEdit.Options+[eoTabsToSpaces] else fSynEdit.Options:=fSynEdit.Options-[eoTabsToSpaces]; end; procedure TfrmAAEditPrefs.FormShow(Sender: TObject); begin button1.AutoSize:=false; button2.autosize:=false; if button1.width<button2.width then button1.width:=button2.width else button2.width:=button1.width; end; procedure TfrmAAEditPrefs.Panel1Click(Sender: TObject); begin end; initialization {$i frmAAEditPrefsUnit.lrs} end.
{ ***************************************************************************** See the file COPYING.modifiedLGPL.txt, included in this distribution, for details about the license. ***************************************************************************** Copyright (C) <2005> <Andrew Haines> chmspecialparser.pas } unit ChmSpecialParser; {$mode objfpc}{$H+} interface uses Classes, Forms, SysUtils, Controls, ComCtrls, chmsitemap; type TContentTreeNode = class(TTreeNode) private FUrl: String; public property Url: String read FUrl write FUrl; end; TIndexItem = class(TListITem) private FUrl: String; public property Url: String read FUrl write FUrl; end; { TContentsFiller } { Fill TTreeView with TChmSiteMap items } TContentsFiller = class(TObject) private FTreeView: TTreeView; FSitemap: TChmSiteMap; FChm: TObject; FBranchCount: DWord; FStop: PBoolean; FLastNode: TTreeNode; procedure AddItem(AItem: TChmSiteMapItem; AParentNode: TTreeNode); public LocaleID: DWord; constructor Create(ATreeView: TTreeView; ASitemap: TChmSiteMap; StopBoolean: PBoolean; AChm: TObject); procedure DoFill(ParentNode: TTreeNode); end; implementation uses LConvEncoding, LazUTF8, HTMLDefs, lcid_conv; function ToUTF8(const AText: AnsiString): String; var encoding: String; begin encoding := GuessEncoding(AText); if (encoding <> EncodingUTF8) then Result := ConvertEncoding(AText, encoding, EncodingUTF8) else Result := AText; end; function FixEscapedHTML(const AText: string): string; var i, iPosAmpersand, iLenAText: Integer; bFoundClosureSemiColon: Boolean; ampStr: string; ws: widestring; entity: widechar; begin Result := ''; i := 1; iLenAText:= Length(AText); while i <= iLenAText do begin if AText[i] = '&' then begin iPosAmpersand := i; ampStr := ''; Inc(i); while (i <= iLenAText) and (AText[i] <> ';') do begin ampStr := ampStr + AText[i]; Inc(i); end; //is there a Char ';', closing a possible HTML entity like '&{#x}~~~{~~};'? bFoundClosureSemiColon := False; if (i > iLenAText) then begin if (AText[i-1] = ';') then bFoundClosureSemiColon := True; end else begin if (AText[i] = ';') then bFoundClosureSemiColon := True; end; if bFoundClosureSemiColon then begin //only if it's a possible HTML encoded character like "&xxx;" ... ws := UTF8Encode(ampStr); if ResolveHTMLEntityReference(ws, entity) then Result := Result + UnicodeToUTF8(cardinal(entity)) else Result := Result + '?'; end else begin //it's not an HTML entity; only an ampersand by itself Result := Result + RightStr(AText, iLenAText - (iPosAmpersand-1)); end; end else Result := Result + AText[i]; Inc(i); end; end; // Replace %20 with space, \ with / function FixURL(URL: String): String; var X: LongInt; begin X := Pos('%20', Url); while X > 0 do begin Delete(Url, X, 3); Insert(' ', Url, X); X := Pos('%20', Url); end; Result := StringReplace(Url, '\', '/', [rfReplaceAll]); end; { TContentsFiller } procedure TContentsFiller.AddItem(AItem: TChmSiteMapItem; AParentNode: TTreeNode); var NewNode: TContentTreeNode; X: Integer; txt: string; begin if FStop^ then Exit; txt := AItem.KeyWord; // Fallback: if txt = '' then txt := AItem.Text; //txt := FixEscapedHTML(ToUTF8(Trim(txt))); txt := ConvToUTF8FromLCID(LocaleID, Trim(txt)); txt := FixEscapedHTML(txt); if not Assigned(FLastNode) or (FLastNode.Text <> txt) then begin // Add new child node FLastNode := AParentNode; NewNode := TContentTreeNode(FTreeView.Items.AddChild(AParentNode, txt)); NewNode.Url := FixURL('/'+AItem.Local); NewNode.Data := FChm; if FTreeView.Images <> nil then begin NewNode.ImageIndex := 3; NewNode.SelectedIndex := 3; if (AParentNode.ImageIndex < 0) or (AParentNode.ImageIndex > 2) then begin AParentNode.ImageIndex := 1; AParentNode.SelectedIndex := 1; end; end; end else NewNode := TContentTreeNode(FLastNode); Inc(FBranchCount); if FBranchCount mod 200 = 0 then Application.ProcessMessages; for X := 0 to AItem.Children.Count-1 do AddItem(AItem.Children.Item[X], NewNode); end; constructor TContentsFiller.Create(ATreeView: TTreeView; ASitemap: TChmSiteMap; StopBoolean: PBoolean; AChm: TObject); begin inherited Create; FTreeView := ATreeView; FSitemap := ASitemap; FStop := StopBoolean; FChm := AChm; end; procedure TContentsFiller.DoFill(ParentNode: TTreeNode); var X: Integer; begin FTreeView.BeginUpdate(); for X := 0 to FSitemap.Items.Count-1 do AddItem(FSitemap.Items.Item[X], ParentNode); FTreeView.EndUpdate(); end; end.
unit uDBDataManager; interface uses System.SysUtils, System.Classes, uDADriverManager, uDAConnectionManager, uROComponent, uDAStreamableComponent, uDAClientSchema, uDASchema, uDAServerInterfaces, uDAInterfaces, SchoolLibrary_Intf, uDAEngine, uDASDACDriver; type TDBDataManager = class(TDataModule) ConnectionManager: TDAConnectionManager; DriverManager: TDADriverManager; Schema: TDASchema; SDACDriver: TDASDACDriver; private function GetConnection: IDAConnection; protected property Connection: IDAConnection read GetConnection; public { Public declarations } function GetPupils(out aList: roPupilsView): boolean; end; function DataManager: TDBDataManager; {$WRITEABLECONST ON} const __DataManager: TDBDataManager = nil; {$WRITEABLECONST OFF} implementation const CONNECTION_STRING = 'MSSQL'; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} function DataManager: TDBDataManager; begin if __DataManager = nil then __DataManager := TDBDataManager.Create(nil); Result := __DataManager; end; { TDBDataManager } function TDBDataManager.GetConnection: IDAConnection; begin Result := ConnectionManager.NewConnection(CONNECTION_STRING); end; function TDBDataManager.GetPupils(out aList: roPupilsView): boolean; var Dataset: IDADataset; begin Result := False; aList := nil; Dataset := Schema.NewDataset(Connection, 'PUPILS'); Dataset.Open; aList := roPupilsView.Create; while not Dataset.EOF do begin with aList.Add do begin AutoIndex := Dataset.FieldByName('AutoIndex').AsInteger; FirstName := Dataset.FieldByName('FirstName').AsString; LastName := Dataset.FieldByName('LastName').AsString; end; Dataset.Next; end; Result := True; end; initialization finalization if Assigned(__DataManager) then FreeAndNil(__DataManager); end.
{ GeoJSON/Feature Object Copyright (c) 2018 Gustavo Carreno <guscarreno@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit lazGeoJSON.Feature; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpjson, lazGeoJSON, lazGeoJSON.Utils, lazGeoJSON.Geometry.Point; type { Exceptions } EFeatureWrongObject = class(Exception); EFeatureWrongFormedObject = class(Exception); { TGeoJSONFeature } TGeoJSONFeature = class(TGeoJSON) private FID: String; FGeometry: TGeoJSON; FProperties: TJSONData; FHasProperties: Boolean; procedure DoLoadFromJSON(const aJSON: String); procedure DoLoadFromJSONData(const aJSONData: TJSONData); procedure DoLoadFromJSONObject(const aJSONObject: TJSONObject); procedure DoLoadFromStream(const aStream: TStream); function GetHasID: Boolean; function GetJSON: String; protected public constructor Create; constructor Create(const aJSON: String); constructor Create(const aJSONData: TJSONData); constructor Create(const aJSONObject: TJSONObject); constructor Create(const aStream: TStream); destructor Destroy; override; property ID: String read FID write FID; property HasID: Boolean read GetHasID; property Geometry: TGeoJSON read FGeometry; property Properties: TJSONData read FProperties; property HasProperties: Boolean read FHasProperties; property asJSON: String read GetJSON; end; implementation { TGeoJSONFeature } procedure TGeoJSONFeature.DoLoadFromJSON(const aJSON: String); var jData: TJSONData; begin jData:= GetJSONData(aJSON); try DoLoadFromJSONData(jData); finally jData.Free; end; end; procedure TGeoJSONFeature.DoLoadFromJSONData(const aJSONData: TJSONData); begin if aJSONData.JSONType <> jtObject then raise EFeatureWrongObject.Create('JSONData does not contain an Object.'); DoLoadFromJSONObject(aJSONData as TJSONObject); end; procedure TGeoJSONFeature.DoLoadFromJSONObject(const aJSONObject: TJSONObject); begin if aJSONObject.IndexOfName('type') = -1 then raise EFeatureWrongFormedObject.Create('Object does not contain member type'); if aJSONObject.Strings['type'] <> 'Feature' then raise EFeatureWrongFormedObject.Create('Member type is not Feature'); if aJSONObject.IndexOfName('geometry') = -1 then raise EFeatureWrongFormedObject.Create('Object does not contain member geometry'); if aJSONObject.IndexOfName('id') <> -1 then begin FID:= aJSONObject.Strings['id']; end; { Go through all the Geometries } { TODO -ogcarreno -cGeoJSON.Feature : Need a safer way to test for the Geometry type } if aJSONObject.Objects['geometry'].Strings['type'] = 'Point' then FGeometry:= TGeoJSONPoint.Create(aJSONObject.Objects['geometry']); //if aJSONObject.Objects['geometry'].Strings['type'] = 'MultiPoint' then // FGeometry:= TGeoJSONMultiPoint.Create(aJSONObject.Objects['geometry']); { END Goemetries } if aJSONObject.IndexOfName('properties') <> -1 then begin if aJSONObject.Items[aJSONObject.IndexOfName('properties')].JSONType = jtObject then begin FProperties:= aJSONObject.Items[aJSONObject.IndexOfName('properties')].Clone; FHasProperties:= True; end; end; end; procedure TGeoJSONFeature.DoLoadFromStream(const aStream: TStream); var jData: TJSONData; begin jData:= GetJSONData(aStream); DoLoadFromJSONData(jData); jData.Free; end; function TGeoJSONFeature.GetHasID: Boolean; begin Result:= FID <> ''; end; function TGeoJSONFeature.GetJSON: String; var jFeature: TJSONObject; begin Result:= ''; jFeature:= TJSONObject.Create; try jFeature.Add('type', TJSONString.Create('Feature')); if GetHasID then jFeature.Add('id', TJSONString.Create(FID)); if Assigned(FGeometry) then begin case FGeometry.GeoJSONType of gjtPoint: begin jFeature.Add('geometry', GetJSONData(TGeoJSONPoint(FGeometry).asJSON).Clone); end; //gjtMultiPoint: begin // Result+= ', "geometry": ' + TGeoJSONMultiPoint(FGeometry).asJSON; //end; end; end; if Assigned(FProperties) then jFeature.Add('properties', FProperties.Clone); Result:= jFeature.FormatJSON(AsCompressedJSON); finally jFeature.Free; end; end; constructor TGeoJSONFeature.Create; begin FGeoJSONType:= gjtFeature; FID:= ''; FGeometry:= nil; FProperties:= nil; FHasProperties:= False; end; constructor TGeoJSONFeature.Create(const aJSON: String); begin Create; DoLoadFromJSON(aJSON); end; constructor TGeoJSONFeature.Create(const aJSONData: TJSONData); begin Create; DoLoadFromJSONData(aJSONData); end; constructor TGeoJSONFeature.Create(const aJSONObject: TJSONObject); begin Create; DoLoadFromJSONObject(aJSONObject); end; constructor TGeoJSONFeature.Create(const aStream: TStream); begin Create; DoLoadFromStream(aStream); end; destructor TGeoJSONFeature.Destroy; begin if Assigned(FGeometry) then case FGeometry.GeoJSONType of gjtPoint: TGeoJSONPoint(FGeometry).Free; //gjtMultiPoint: TGeoJSONMultiPoint(FGeometry).Free; end; if Assigned(FProperties) then FProperties.Free; inherited Destroy; end; end.
{ UNIVERSIDAD DE ORIENTE NUCLEO NUEVA ESPARTA ESCUELA DE INGENIERIA Y CIENCIAS APLICADAS LICENCIATURA EN INFORMATICA LENGUAJES DE PROGRAMACION PROYECTO 4: Las 8 Torres. REALIZADO POR: Eduardo Manuel Rodriguez Lara C.I.: 26.082.457 } program proyecto; { A continuacion la seccion de tipos, en donde se crean los tipos de variables para las matrices utilizadas en el programa. } type matrizCoord = array[0..7,0..1] of integer; {Tipo: matrizCoord(Matriz de coordenadas)} tipomatriz = array[0..7,0..7] of integer; {Tipo: tipomatriz(Matriz asociada al tablero)} { A continuacion la seccion de variables, donde se establecen las variables globales utilizadas en el programa. } var difFil,difCol:boolean; { Banderas que indican si las torres estan o no ubicadas en diferentes filas y en diferentes columnas. } matriz: tipomatriz; {La matriz que representa el tablero} coords: matrizCoord; {La matriz que representa las posiciones de las torres} { A continuacion la seccion de declaracion de funciones y procedimientos. } procedure inicializar; { Procedimiento que inicializa toda la matriz con ceros. } var i,j:integer; begin for i:=0 to 7 do begin for j:=0 to 7 do begin matriz[i,j] := 0; end; end; end; procedure posicionRandomInicial; { Procedimiento que se encarga de asignar las torres a posiciones aleatorias a lo largo del tablero. } var torre,i,j:integer; asignado:boolean; begin for torre:=1 to 8 do begin asignado:=false; while (asignado = false) do begin i:=random(7); j:=random(7); if (matriz[i,j]=0) then begin matriz[i,j]:=torre; coords[torre-1,0]:= i; coords[torre-1,1]:= j; asignado:=true; end; end; end; end; procedure mostrarMatriz; { Procedimiento que se encarga de mostrar la matriz. } var i,j:integer; begin for i:=0 to 7 do begin for j:=0 to 7 do begin if(matriz[i,j]=0)then begin write('__'); end else begin write('T',matriz[i,j]); end; write(' '); end; writeln; end; writeln; end; { De aqui en adelante estan los metodos que me son utilizados por el proceso ubicarPorFilas. } function sePuedeArriba(idTorre: integer): boolean; { Funcion que se encarga de decir si una torre dada puede moverse para arriba. } begin if (coords[idTorre-1,0]=0) then begin sePuedeArriba:= false; end else begin if (matriz[coords[idTorre-1,0]-1,coords[idTorre-1,1]] <> 0) then begin sePuedeArriba:= false; end else begin sePuedeArriba:= true; end end end; function sePuedeAbajo(idTorre: integer): boolean; { Funcion que se encarga de decir si una torre dada puede moverse hacia abajo. } begin if (coords[idTorre-1,0]=7) then begin sePuedeAbajo:= false; end else begin if (matriz[coords[idTorre-1,0]+1,coords[idTorre-1,1]] <> 0) then begin sePuedeAbajo:= false; end else begin sePuedeAbajo:= true; end end end; function isCleanAbove(idTorre: integer):boolean; { Funcion que se encarga de decir si la fila que esta arriba no tiene ninguna torre. } var i,filaSup: integer; isClean:boolean; begin filaSup:=coords[idTorre-1,0] - 1; isClean:=true; i:=0; while (isClean and (i<=7)) do begin if(coords[i,0]=filaSup)then isClean:=false; i:=i+1; end; isCleanAbove:=isClean; end; function isCleanUnder(idTorre: integer):boolean; { Funcion que se encarga de decir si la fila que esta abajo no tiene ninguna torre. } var i,filaInf: integer; isClean:boolean; begin filaInf:=coords[idTorre-1,0] + 1; isClean:=true; i:=0; while (isClean and (i<=7)) do begin if(coords[i,0]=filaInf)then isClean:=false; i:=i+1; end; isCleanUnder:=isClean; end; procedure difFilas(coords:matrizCoord); { Procedimiento que se encarga de verificar si todas las torres estan en diferentes filas. Actua sobre la bandera global difFil. } var i,j:integer; diferentes:boolean; begin i:=0; diferentes:=true; while(i<=6)do begin j:=i+1; while(diferentes and (j<=7))do begin if(coords[i,0]=coords[j,0])then begin diferentes:=False; end; j:=j+1; end; i:=i+1; end; difFil:=diferentes; end; { De aqui en adelante estan los metodos que me son utilizados por el proceso ubicarPorColumnas. } function sePuedeDerecha(idTorre: integer): boolean; { Funcion que se encarga de decir si una torre dada puede moverse hacia la derecha. } begin if (coords[idTorre-1,1]=7) then begin sePuedeDerecha:= false; end else begin if (matriz[coords[idTorre-1,0],coords[idTorre-1,1]+1] <> 0) then begin sePuedeDerecha:= false; end else begin sePuedeDerecha:= true; end end end; function sePuedeIzq(idTorre: integer): boolean; { Funcion que se encarga de decir si una torre dada puede moverse hacia la izquierda. } begin if (coords[idTorre-1,1]=0) then begin sePuedeIzq:= false; end else begin if (matriz[coords[idTorre-1,0],coords[idTorre-1,1]-1] <> 0) then begin sePuedeIzq:= false; end else begin sePuedeIzq:= true; end end end; function isCleanRigth(idTorre: integer):boolean; { Funcion que se encarga de decir si la fila que esta a la derecha no tiene ninguna torre. } var i,colDer: integer; isClean:boolean; begin colDer:=coords[idTorre-1,1] + 1; isClean:=true; i:=0; while (isClean and (i<=7)) do begin if(coords[i,1]=colDer)then isClean:=false; i:=i+1; end; isCleanRigth:=isClean; end; function isCleanLeft(idTorre: integer):boolean; { Funcion que se encarga de decir si la fila que esta a la izquierda no tiene ninguna torre. } var i,colIzq: integer; isClean:boolean; begin colIzq:=coords[idTorre-1,1] - 1; isClean:=true; i:=0; while (isClean and (i<=7)) do begin if(coords[i,1]=colIzq)then isClean:=false; i:=i+1; end; isCleanLeft:=isClean; end; procedure difColumnas(coords:matrizCoord); { Procedimiento que se encarga de verificar si todas las torres estan en diferentes columnas. Actua sobre la bandera global difCol. } var i,j:integer; diferentes:boolean; begin i:=0; diferentes:=true; while(i<=6)do begin j:=i+1; while(diferentes and (j<=7))do begin if(coords[i,1]=coords[j,1])then begin diferentes:=False; end; j:=j+1; end; i:=i+1; end; difCol:=diferentes; end; { A continuacion la declaracion del monitor. El monitor en esta oportunidad me esta controlando el tablero. Existen dos procesos que pueden tomar el tablero: -ubicarPorFilas -ubicarPorColumnas Por lo tanto, el monitor posee dos procedimientos que son usados por esos procesos: -tomarControl -liberarControl Ambos procesos estan programados para que al inicio, deseen tomar el control, y al final, cuando hayan terminado de realizar su tarea, procedan a liberar el control sobre el tablero. Es necesaria una variable booleana que indique si el tablero esta o no tomado por algun proceso. } monitor tablero; export tomarControl; export liberarControl; var tableroTomado:boolean; ocupado:condition; procedure tomarControl; { Procedimiento que consulta si el tablero esta tomado, y si lo esta entonces decide enviar a la cola al proceso que esta queriendo tomar el control. Si el tablero NO esta tomado, entonces simplemente se cambia el valor de tableroTomado a verdadero(true). } begin if (tableroTomado) then delay(ocupado); tableroTomado:=true; end; procedure liberarControl; { Procedimiento que se encarga de cambiar la bandera tableroTomado a falso y de desencolar al proceso que estuvo esperando a que el tablero estuviera disponible. } begin tableroTomado:=false; resume(ocupado); end; end; { Fin de la declaracion del monitor } { A continuacion, la declaracion de los procesos que se encargan de ubicar todas las torres en filas y columnas diferentes. } process ubicarPorFilas(var coords:matrizCoord); { Proceso que se encarga de ubicar las torres en filas diferentes. Tal y como se menciona anteriormente, el proceso intenta tomar el control del tablero justo al inicio, y al finalizar libera el control. La logica del proceso consiste en que cada una de las torres busca una fila vacia a donde moverse. Si la encuentra, se mueve. El proceso continua hasta que ya todas esten en diferentes filas. Por cada una de las torres, se pregunta primero si se puede mover hacia arriba y si tambien la fila de arriba esta vacia,y si estas dos cosas resultan ciertas entonces se procede a mover la torre hacia la fila de arriba. Tambien se preguntan las mismas cosas para la fila de abajo (Si el movimiento es valido y si la fila esta vacia). Solo se mueve una torre si el movimiento la lleva a una fila vacia. } var idTorre: integer; begin tablero.tomarControl; difFilas(coords); while(not(difFil))do begin for idTorre:=1 to 8 do begin if (sePuedeArriba(idTorre) and isCleanAbove(idTorre)) then begin matriz[coords[idTorre-1,0],coords[idTorre-1,1]]:=0; matriz[coords[idTorre-1,0]-1,coords[idTorre-1,1]]:=idTorre; coords[idTorre-1,0]:=coords[idTorre-1,0]-1; writeln('Movimiento hacia arriba de T',idTorre,'!:'); mostrarMatriz; end else begin if (sePuedeAbajo(idTorre) and isCleanUnder(idTorre)) then begin matriz[coords[idTorre-1,0],coords[idTorre-1,1]]:=0; matriz[coords[idTorre-1,0]+1,coords[idTorre-1,1]]:=idTorre; coords[idTorre-1,0]:=coords[idTorre-1,0]+1; writeln('Movimiento hacia abajo de T',idTorre,'!:'); mostrarMatriz; end; end; end; difFilas(coords); end; tablero.liberarControl; end; process ubicarPorColumnas(var coords:matrizCoord); { Proceso que se encarga de ubicar las torres en columnas diferentes. Tal y como se menciona anteriormente, el proceso intenta tomar el control del tablero justo al inicio, y al finalizar libera el control. La logica del proceso consiste en que cada una de las torres busca una columna vacia a donde moverse. Si la encuentra, se mueve. El proceso continua hasta que ya todas esten en diferentes columnas. Por cada una de las torres, se pregunta primero si se puede mover hacia la derecha y si tambien la columna de la derecha esta vacia,y si estas dos cosas resultan ciertas entonces se procede a mover la torre hacia la columna de la derecha. Tambien se preguntan las mismas cosas para la columna de la izquierda (Si el movimiento es valido y si la columna esta vacia). Solo se mueve una torre si el movimiento la lleva a una columna vacia. } var idTorre: integer; begin tablero.tomarControl; difColumnas(coords); while(not(difCol))do begin for idTorre:=1 to 8 do begin if (sePuedeDerecha(idTorre) and isCleanRigth(idTorre)) then begin matriz[coords[idTorre-1,0],coords[idTorre-1,1]]:=0; matriz[coords[idTorre-1,0],coords[idTorre-1,1]+1]:=idTorre; coords[idTorre-1,1]:=coords[idTorre-1,1]+1; writeln('Movimiento hacia la derecha de T',idTorre,'!:'); mostrarMatriz; end else begin if (sePuedeIzq(idTorre) and isCleanLeft(idTorre)) then begin matriz[coords[idTorre-1,0],coords[idTorre-1,1]]:=0; matriz[coords[idTorre-1,0],coords[idTorre-1,1]-1]:=idTorre; coords[idTorre-1,1]:=coords[idTorre-1,1]-1; writeln('Movimiento hacia la izquierda de T',idTorre,'!:'); mostrarMatriz; end; end; end; difColumnas(coords); end; tablero.liberarControl; end; { Inicio del algoritmo principal. } begin inicializar; {Se inicializa la matriz} posicionRandomInicial; {Se ubican las torres en posiciones aleatorias} writeln('Matriz Inicial: '); mostrarMatriz; { Inicio de la seccion para los procesos de forma concurrente. } cobegin ubicarPorFilas(coords); ubicarPorColumnas(coords); coend; { Fin de la seccion para los procesos de forma concurrente. } writeln('Solucion:'); mostrarMatriz; end.
unit ServerContainerUnit; interface uses System.SysUtils, System.Classes, Vcl.Dialogs, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSClientMetadata, Datasnap.DSHTTPServiceProxyDispatcher, Datasnap.DSProxyJavaAndroid, Datasnap.DSProxyJavaBlackBerry, Datasnap.DSProxyObjectiveCiOS, Datasnap.DSProxyCsharpSilverlight, Datasnap.DSProxyFreePascal_iOS, Datasnap.DSAuth, Datasnap.DSNames, uServerDSProvider; type TServerContainer = class(TDataModule) DSServer: TDSServer; DSServerClass: TDSServerClass; procedure DataModuleCreate(Sender: TObject); procedure DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); private { Private declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RegisterServerClasses; end; function DSServer: TDSServer; implementation {$R *.dfm} uses Winapi.Windows, uDSUtils, ServerMethodsUnit, uServerClasses; var FModule: TComponent; FDSServer: TDSServer; function DSServer: TDSServer; begin Result := FDSServer; end; constructor TServerContainer.Create(AOwner: TComponent); begin inherited; FDSServer := DSServer; end; procedure TServerContainer.DataModuleCreate(Sender: TObject); begin RegisterServerClasses; end; destructor TServerContainer.Destroy; begin inherited; FDSServer := nil; end; procedure TServerContainer.DSServerClassGetClass( DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := ServerMethodsUnit.TServerMethods; end; procedure TServerContainer.RegisterServerClasses; begin Assert(DSServer.Started = false, 'Server Active.' + #13 + 'Can''t add class to Active Server.'); TCustServerClass.Create(Self, DSServer, TUser, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrud, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TDSProvider, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TDSReport, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDMR, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDPNLReport, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDPNLSetting, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDEconomicSetting, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDEconomicReport, DSServerClass.LifeCycle); //custom class here : // TCustServerClass.Create(Self, DSServer, TSuggestionOrder, DSServerClass.LifeCycle); // TCustServerClass.Create(Self, DSServer, TCrudSupplier, DSServerClass.LifeCycle); // TCustServerClass.Create(Self, DSServer, TCrudPO, DSServerClass.LifeCycle); // TCustServerClass.Create(Self, DSServer, TCrudDO, DSServerClass.LifeCycle); end; initialization FModule := TServerContainer.Create(nil); finalization FModule.Free; end.
unit FHIRValueSetChecker; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, AdvObjects, AdvStringObjectMatches, FHIRTypes, FHIRResources, FHIRUtilities, FHIRBase, TerminologyServices, TerminologyServerStore; Type TValueSetChecker = class (TAdvObject) private FStore : TTerminologyServerStore; FOthers : TAdvStringObjectMatch; // checkers or code system providers fvs : TFHIRValueSet; FId: String; FProfile : TFhirExpansionProfile; function check(system, version, code : String; abstractOk : boolean; displays : TStringList; var message : String) : boolean; overload; function findCode(cs : TFhirCodeSystem; code: String; list : TFhirCodeSystemConceptList; displays : TStringList; out isabstract : boolean): boolean; function checkConceptSet(cs: TCodeSystemProvider; cset : TFhirValueSetComposeInclude; code : String; abstractOk : boolean; displays : TStringList; var message : String) : boolean; // function rule(op : TFhirOperationOutcome; severity : TFhirIssueSeverityEnum; test : boolean; code : TFhirIssueTypeEnum; msg : string):boolean; function getName: String; procedure prepareConceptSet(desc: string; cc: TFhirValueSetComposeInclude; var cs: TCodeSystemProvider); public constructor Create(store : TTerminologyServerStore; id : String); overload; destructor Destroy; override; property id : String read FId; property name : String read getName; procedure prepare(vs : TFHIRValueSet; profile : TFhirExpansionProfile); function check(system, version, code : String; abstractOk : boolean) : boolean; overload; function check(coding : TFhirCoding; abstractOk : boolean): TFhirParameters; overload; function check(code: TFhirCodeableConcept; abstractOk : boolean) : TFhirParameters; overload; end; implementation { TValueSetChecker } constructor TValueSetChecker.create(store : TTerminologyServerStore; id : string); begin Create; FStore := store; FId := id; FOthers := TAdvStringObjectMatch.create; FOthers.PreventDuplicates; end; destructor TValueSetChecker.destroy; begin FVs.Free; FOthers.Free; FStore.Free; Fprofile.Free; inherited; end; procedure TValueSetChecker.prepare(vs: TFHIRValueSet; profile : TFhirExpansionProfile); var cs : TCodeSystemProvider; cc : TFhirValueSetComposeInclude; {$IFDEF FHIR2} i, j : integer; other : TFHIRValueSet; checker : TValueSetChecker; {$ENDIF} begin FProfile := profile.Link; vs.checkNoImplicitRules('ValueSetChecker.prepare', 'ValueSet'); vs.checkNoModifiers('ValueSetChecker.prepare', 'ValueSet'); if (vs = nil) then else begin FVs := vs.link; {$IFDEF FHIR2} if fvs.codeSystem <> nil then begin fvs.codeSystem.checkNoModifiers('ValueSetChecker.prepare', 'CodeSystem'); FOthers.Add(fvs.codeSystem.system, TFhirCodeSystemProvider.create(FVs.Link)); end; {$ENDIF} if (fvs.compose <> nil) then begin fvs.compose.checkNoModifiers('ValueSetChecker.prepare', 'compose', []); {$IFDEF FHIR2} for i := 0 to fvs.compose.importList.Count - 1 do begin other := FStore.getValueSetByUrl(fvs.compose.importList[i].value); try if other = nil then raise ETerminologyError.create('Unable to find value set '+fvs.compose.importList[i].value); checker := TValueSetChecker.create(Fstore.link, other.url); try checker.prepare(other, profile); FOthers.Add(fvs.compose.importList[i].value, checker.Link); finally checker.free; end; finally other.free; end; end; {$ENDIF} for cc in fvs.compose.includeList do prepareConceptSet('include', cc, cs); for cc in fvs.compose.excludeList do prepareConceptSet('exclude', cc, cs); end; end; end; procedure TValueSetChecker.prepareConceptSet(desc: string; cc: TFhirValueSetComposeInclude; var cs: TCodeSystemProvider); var {$IFNDEF FHIR2} ivs: TFhirUri; other: TFhirValueSet; {$ENDIF} checker: TValueSetChecker; ccf: TFhirValueSetComposeIncludeFilter; begin cc.checkNoModifiers('ValueSetChecker.prepare', desc, []); {$IFNDEF FHIR2} for ivs in cc.valueSetList do begin other := FStore.getValueSetByUrl(ivs.value); try if other = nil then raise ETerminologyError.create('Unable to find value set ' + ivs.value); checker := TValueSetChecker.create(Fstore.link, other.url); try checker.prepare(other, FProfile); FOthers.Add(ivs.value, checker.Link); finally checker.free; end; finally other.free; end; end; {$ENDIF} if not FOthers.ExistsByKey(cc.system) then FOthers.Add(cc.system, FStore.getProvider(cc.system, cc.version, Fprofile)); cs := TCodeSystemProvider(FOthers.matches[cc.system]); for ccf in cc.filterList do begin ccf.checkNoModifiers('ValueSetChecker.prepare', desc + '.filter', []); if not (('concept' = ccf.property_) and (ccf.Op = FilterOperatorIsA)) then if not cs.doesFilter(ccf.property_, ccf.Op, ccf.value) then raise ETerminologyError.create('The filter "' + ccf.property_ + ' ' + CODES_TFhirFilterOperatorEnum[ccf.Op] + ' ' + ccf.value + '" was not understood in the context of ' + cs.system(nil)); end; end; function TValueSetChecker.findCode(cs : TFhirCodeSystem; code: String; list : TFhirCodeSystemConceptList; displays : TStringList; out isabstract : boolean): boolean; var i : integer; begin result := false; for i := 0 to list.count - 1 do begin if (code = list[i].code) then begin result := true; {$IFNDEF FHIR2} isabstract := cs.isAbstract(list[i]); {$ELSE} isabstract := list[i].abstract; {$ENDIF} displays.Add(list[i].display); exit; end; if findCode(cs, code, list[i].conceptList, displays, isabstract) then begin result := true; exit; end; end; end; function TValueSetChecker.getName: String; begin if (fvs <> nil) then result := fvs.name else result := '??'; end; function TValueSetChecker.check(system, version, code: String; abstractOk : boolean): boolean; var list : TStringList; msg : string; begin list := TStringList.Create; try list.Duplicates := dupIgnore; list.CaseSensitive := false; result := check(system, version, code, abstractOk, list, msg); finally list.Free; end; end; function TValueSetChecker.check(system, version, code : String; abstractOk : boolean; displays : TStringList; var message : String) : boolean; var // checker : TValueSetChecker; cs : TCodeSystemProvider; ctxt : TCodeSystemProviderContext; cc : TFhirValueSetComposeInclude; // uri : TFhirUri; excluded : boolean; {$IFDEF FHIR2} i : integer; isabstract : boolean; {$ENDIF} checker : TValueSetChecker; uri : TFhirUri; begin result := false; {special case:} if (fvs.url = ANY_CODE_VS) then begin cs := FStore.getProvider(system, version, FProfile, true); try if cs = nil then result := false else begin ctxt := cs.locate(code); if (ctxt = nil) then result := false else try result := (abstractOk or not cs.IsAbstract(ctxt)) and ((FProfile = nil) or not FProfile.activeOnly or not cs.isInactive(ctxt)); cs.Displays(ctxt, displays, Fprofile.displayLanguage); finally cs.Close(ctxt); end; end; finally cs.Free; end; end else begin {$IFDEF FHIR2} if (fvs.codeSystem <> nil) and ((system = fvs.codeSystem.system) or (system = SYSTEM_NOT_APPLICABLE)) then begin result := FindCode(fvs, code, fvs.codeSystem.conceptList, displays, isabstract); if result then begin result := abstractOk or not isabstract; exit; end; end; {$ENDIF} if (fvs.compose <> nil) then begin result := false; {$IFDEF FHIR2} for i := 0 to fvs.compose.importList.Count - 1 do begin if not result then begin checker := TValueSetChecker(FOthers.matches[fvs.compose.importList[i].value]); result := checker.check(system, version, code, abstractOk, displays, message); end; end; {$ENDIF} for cc in fvs.compose.includeList do begin if cc.system = '' then result := true else begin cs := TCodeSystemProvider(FOthers.matches[cc.system]); result := ((system = SYSTEM_NOT_APPLICABLE) or (cs.system(nil) = system)) and checkConceptSet(cs, cc, code, abstractOk, displays, message); end; {$IFNDEF FHIR2} for uri in cc.valueSetList do begin checker := TValueSetChecker(FOthers.matches[uri.value]); result := result and checker.check(system, version, code, abstractOk, displays, message); end; {$ENDIF} if result then break; end; if result then for cc in fvs.compose.excludeList do begin if cc.system = '' then excluded := true else begin cs := TCodeSystemProvider(FOthers.matches[cc.system]); excluded := ((system = SYSTEM_NOT_APPLICABLE) or (cs.system(nil) = system)) and checkConceptSet(cs, cc, code, abstractOk, displays, message); end; {$IFDEF FHIR3} for uri in cc.valueSetList do begin checker := TValueSetChecker(FOthers.matches[uri.value]); excluded := excluded and checker.check(system, version, code, abstractOk, displays, message); end; {$ENDIF} if excluded then exit(false); end; end; end; end; function TValueSetChecker.check(coding: TFhirCoding; abstractOk : boolean) : TFhirParameters; var list : TStringList; message : String; begin result := TFhirParameters.create; try list := TStringList.Create; try list.Duplicates := dupIgnore; list.CaseSensitive := false; if check(coding.system, coding.version, coding.code, abstractOk, list, message) then begin result.AddParameter('result', TFhirBoolean.Create(true)); if (coding.display <> '') and (list.IndexOf(coding.display) < 0) then result.AddParameter('message', 'The display "'+coding.display+'" is not a valid display for the code '+coding.code); if list.Count > 0 then result.AddParameter('display', list[0]); end else begin result.AddParameter('result', TFhirBoolean.Create(false)); result.AddParameter('message', 'The system/code "'+coding.system+'"/"'+coding.code+'" is not in the value set '+fvs.name); if (message <> '') then result.AddParameter('message', message); end; finally list.Free; end; result.Link; finally result.free; end; end; function hasMessage(params : TFhirParameters; msg : String) : boolean; var p : TFhirParametersParameter; begin result := false; for p in params.parameterList do if (p.name = 'message') and (p.value is TFHIRString) and (TFHIRString(p.value).value = msg) then exit(true); end; function TValueSetChecker.check(code: TFhirCodeableConcept; abstractOk : boolean) : TFhirParameters; function Summary(code: TFhirCodeableConcept) : String; begin if (code.codingList.Count = 1) then result := 'The code provided ('+summarise(code)+') is not ' else result := 'None of the codes provided ('+summarise(code)+') are '; end; var list : TStringList; i : integer; v : boolean; ok : TFhirBoolean; cc, codelist, message : String; prov : TCodeSystemProvider; ctxt : TCodeSystemProviderContext; begin if FVs = nil then raise Exception.Create('Error: cannot validate a CodeableConcept without a nominated valueset'); result := TFhirParameters.Create; try list := TStringList.Create; try list.Duplicates := dupIgnore; list.CaseSensitive := false; ok := TFhirBoolean.Create(false); result.AddParameter('result', ok); codelist := ''; for i := 0 to code.codingList.Count - 1 do begin list.Clear; cc := ',{'+code.codingList[i].system+'}'+code.codingList[i].code; codelist := codelist + cc; v := check(code.codingList[i].system, code.codingList[i].version, code.codingList[i].code, abstractOk, list, message); if not v and (message <> '') then result.AddParameter('message', message); ok.value := ok.value or v; if (v) then begin message := ''; if (code.codingList[i].display <> '') and (list.IndexOf(code.codingList[i].display) < 0) then result.AddParameter('message', 'The display "'+code.codingList[i].display+'" is not a valid display for the code '+cc.substring(1)); if list.Count > 0 then result.AddParameter('display', list[0]); end else begin prov := FStore.getProvider(code.codingList[i].system, code.codingList[i].version, FProfile, true); try if (prov = nil) then begin result.AddParameter('message', 'The system "'+code.codingList[i].system+'" is not known'); result.AddParameter('cause', 'unknown'); end else begin ctxt := prov.locate(code.codingList[i].code, message); try if ctxt = nil then begin result.AddParameter('message', 'The code "'+code.codingList[i].code+'" is not valid in the system '+code.codingList[i].system); result.AddParameter('cause', 'invalid'); if (message <> '') and not hasMessage(result, message) then result.AddParameter('message', message); end else begin prov.Displays(ctxt, list, ''); if (code.codingList[i].display <> '') and (list.IndexOf(code.codingList[i].display) = -1) then result.AddParameter('message', 'The display "'+code.codingList[i].display+'" is not a valid display for the code '+cc) end; finally prov.Close(ctxt); end; end; finally prov.Free; end; end; end; if (not ok.value) then if fvs.name = '' then result.AddParameter('message', Summary(code) +' valid') else result.AddParameter('message', Summary(code) +' valid in the value set '+fvs.name); finally list.Free; end; result.Link; finally result.free; end; end; Function FreeAsBoolean(cs : TCodeSystemProvider; ctxt : TCodeSystemProviderContext) : boolean; overload; begin result := ctxt <> nil; if result then cs.Close(ctxt); end; Function FreeAsBoolean(cs : TCodeSystemProvider; ctxt : TCodeSystemProviderFilterContext) : boolean; overload; begin result := ctxt <> nil; if result then cs.Close(ctxt); end; function TValueSetChecker.checkConceptSet(cs: TCodeSystemProvider; cset : TFhirValueSetComposeInclude; code: String; abstractOk : boolean; displays : TStringList; var message : String): boolean; var i : integer; fc : TFhirValueSetComposeIncludeFilter; ctxt : TCodeSystemProviderFilterContext; loc : TCodeSystemProviderContext; prep : TCodeSystemProviderFilterPreparationContext; filters : Array of TCodeSystemProviderFilterContext; msg : String; begin result := false; if (cset.conceptList.count = 0) and (cset.filterList.count = 0) then begin loc := cs.locate(code, message); try result := (loc <> nil) and (abstractOk or not cs.IsAbstract(loc)); if result then begin cs.displays(loc, displays, FProfile.displayLanguage); exit; end else finally cs.Close(loc); end; end; for i := 0 to cset.conceptList.count - 1 do if (code = cset.conceptList[i].code) then begin loc := cs.locate(code); if Loc <> nil then begin cs.close(loc); cs.displays(code, displays, ''); result := (abstractOk or not cs.IsAbstract(loc)); exit; end; end; if cset.filterList.count > 0 then begin SetLength(filters, cset.filterList.count); prep := cs.getPrepContext; try for i := 0 to cset.filterList.count - 1 do begin fc := cset.filterList[i]; // gg - why? if ('concept' = fc.property_) and (fc.Op = FilterOperatorIsA) then filters[i] := cs.filter(fc.property_, fc.Op, fc.value, prep); end; if cs.prepare(prep) then // all are together, just query the first filter begin ctxt := filters[0]; loc := cs.filterLocate(ctxt, code); try result := (loc <> nil) and (abstractOk or not cs.IsAbstract(loc)); if result then cs.displays(loc, displays, FProfile.displayLanguage); finally cs.Close(loc); end; end else begin result := true; for i := 0 to cset.filterList.count - 1 do begin fc := cset.filterList[i]; if ('concept' = fc.property_) and (fc.Op = FilterOperatorIsA) then begin loc := cs.locateIsA(code, fc.value); try result := (loc <> nil) and (abstractOk or not cs.IsAbstract(loc)); if loc <> nil then cs.displays(loc, displays, FProfile.displayLanguage); finally cs.Close(loc); end; end else begin ctxt := filters[i]; loc := cs.filterLocate(ctxt, code, msg); try if (loc = nil) and (message = '') then message := msg; result := (loc <> nil) and (abstractOk or not cs.IsAbstract(loc)); if loc <> nil then cs.displays(loc, displays, FProfile.displayLanguage); finally cs.Close(loc); end; end; if not result then break; end; end; finally for i := 0 to cset.filterList.count - 1 do cs.Close(filters[i]); cs.Close(prep); end; end; end; end.
unit Domain.ValuesObject.CPF; interface uses EF.Core.Types, SysUtils; type TCPF = class private FValue: TString; procedure SetValue(const Value: TString); public property Value: TString read FValue write SetValue; end; THelperCPF = class helper For TCPF private function isCPF(CPF: string): boolean; public procedure validarCPF; end; implementation function THelperCPF.isCPF(CPF: string): boolean; var dig10, dig11: string; s, i, r, peso: integer; begin // length - retorna o tamanho da string (CPF é um número formado por 11 dígitos) if ((CPF = '00000000000') or (CPF = '11111111111') or (CPF = '22222222222') or (CPF = '33333333333') or (CPF = '44444444444') or (CPF = '55555555555') or (CPF = '66666666666') or (CPF = '77777777777') or (CPF = '88888888888') or (CPF = '99999999999') or (length(CPF) <> 11)) then begin isCPF := false; exit; end; // try - protege o código para eventuais erros de conversão de tipo na função StrToInt try { *-- Cálculo do 1o. Digito Verificador --* } s := 0; peso := 10; for i := 1 to 9 do begin // StrToInt converte o i-ésimo caractere do CPF em um número s := s + (StrToInt(CPF[i]) * peso); peso := peso - 1; end; r := 11 - (s mod 11); if ((r = 10) or (r = 11)) then dig10 := '0' else str(r:1, dig10); // converte um número no respectivo caractere numérico { *-- Cálculo do 2o. Digito Verificador --* } s := 0; peso := 11; for i := 1 to 10 do begin s := s + (StrToInt(CPF[i]) * peso); peso := peso - 1; end; r := 11 - (s mod 11); if ((r = 10) or (r = 11)) then dig11 := '0' else str(r:1, dig11); { Verifica se os digitos calculados conferem com os digitos informados. } if ((dig10 = CPF[10]) and (dig11 = CPF[11])) then isCPF := true else isCPF := false; except isCPF := false end; end; procedure THelperCPF.validarCPF; begin if (FValue.Value <>'') and (not isCPF(FValue.Value)) then begin raise Exception.Create('CPF "'+FValue.Value+'" inválido!'); end; end; { TCPF } procedure TCPF.SetValue(const Value: TString); begin FValue:= Value; end; end.
unit VisibleDSA.AlgoVisualizer; interface uses System.SysUtils, System.Types, FMX.Graphics, FMX.Forms, VisibleDSA.AlgoVisHelper, VisibleDSA.SelectionSortData; type TAlgoVisualizer = class(TObject) private _width: integer; _height: integer; _data: TSelectionSortData; _form: TForm; public constructor Create(form: TForm; sceneWidth, sceneHeight, n: integer); destructor Destroy; override; procedure Paint(canvas: TCanvas); procedure Run; end; implementation uses VisibleDSA.AlgoForm; { TAlgoVisualizer } constructor TAlgoVisualizer.Create(form: TForm; sceneWidth, sceneHeight, n: integer); begin _form := form; _width := form.ClientWidth; _height := form.ClientHeight; _data := TSelectionSortData.Create(n, _height); _form.Caption := 'Selection Sort Visualization'; end; destructor TAlgoVisualizer.Destroy; begin FreeAndNil(_data); inherited Destroy; end; procedure TAlgoVisualizer.Paint(canvas: TCanvas); var w: integer; i: integer; begin w := _width div _data.Length; TAlgoVisHelper.SetFill(CL_LIGHTBLUE); for i := 0 to _data.Length - 1 do begin TAlgoVisHelper.FillRectangle(canvas, i * w, _height - _data.GetValue(i), w - 1, _data.GetValue(i)); end; end; procedure TAlgoVisualizer.Run; var i, j, minIndex: integer; begin for i := 0 to _data.Length - 1 do begin minIndex := i; for j := i + 1 to _data.Length - 1 do begin if _data.GetValue(j) < _data.GetValue(minIndex) then minIndex := j; end; _data.swap(i, minIndex); TAlgoVisHelper.Pause(100); AlgoForm.PaintBox.Repaint; end; end; end.
{** * Author: TRan Quang Loc (darkkcyan) * Problem: https://wcipeg.com/problem/coi09p3 * Idea: to calculate the branch, at each node, we have to match the descendants at every level. * So for each node we have to maintain 2 list: the left most and the right most node at each level * or in my code, I just store the left most and the right most side for simplicity. * If we have 2 children, we just need to match the min(left child height, right child height) nodes * and then we also merge the lists in the same amount of time, so we end up with complixity O(nlogn). * If it is not really clear, the idea is similar to DSU on tree. * Please also note for the case we the left most can also be at the right branch and vice versa. * See the test case in the end of this file for more intuition. * I will not explain how to handle the case here, so please see the code. *} {$mode objfpc} uses classes, sysutils, math; const maxn = 300101; type chain = record val: int64; lazy: int64; next: ^chain; end; type PChain = ^chain; function createChain(val: int64= 0): PChain; begin result := new(pchain); result^.val := val; result^.lazy := 0; result^.next := nil; end; procedure deleteChain(chain: PChain); begin if chain = nil then exit; deleteChain(chain^.next); dispose(chain); end; procedure update(var chain: PChain); begin if chain = nil then exit; inc(chain^.val, chain^.lazy); if chain^.next <> nil then inc(chain^.next^.lazy, chain^.lazy); chain^.lazy := 0; end; type node = record frameLeft, frameRight: int64; branch: int64; lchild, rchild: int64; lchain, rchain: Pchain; end; var n: longint; var nodes: array [0..maxn] of node; function createNode(nameLength: longint): node; begin inc(nameLength, 2); result.frameRight := nameLength div 2; result.frameLeft := nameLength - result.frameRight - 1; result.branch := 0; result.lchild := 0; result.rchild := 0; result.lchain := createChain(result.frameLeft); result.rchain := createChain(result.frameRight); end; procedure addChild(parent: longint; childId: longint); begin if nodes[parent].lchild = 0 then nodes[parent].lchild := childId else nodes[parent].rchild := childId; end; function calMaxSum(left: Pchain; right: Pchain): int64; var ans: int64; begin ans := 0; while (left <> nil) and (right <> nil) do begin update(left); update(right); ans := max(ans, (left^.val + right^.val)); left := left^.next; right := right^.next; end; exit(ans); end; procedure shorterTail(var u, v: PChain); begin while (u^.next <> nil) and (v^.next <> nil) do begin update(u); update(v); u := u^.next; v := v^.next; end; update(u); update(v); end; procedure process; var u, l, r: longint; var lc, rc: PChain; begin for u := n downto 1 do begin l := nodes[u].lchild; r := nodes[u].rchild; if r = 0 then begin if l <> 0 then begin nodes[u].lchain^.next := nodes[l].lchain; nodes[u].rchain^.next := nodes[l].rchain; end; continue; end; nodes[u].branch := (calMaxSum(nodes[l].rchain, nodes[r].lchain) + 2) div 2; lc := nodes[l].lchain; rc := nodes[r].lchain; shorterTail(lc, rc); if rc^.next <> nil then begin lc^.next := rc^.next; rc^.next := nil; dec(lc^.next^.lazy, 2 * nodes[u].branch); end; lc := nodes[l].rchain; rc := nodes[r].rchain; shorterTail(lc, rc); if lc^.next <> nil then begin rc^.next := lc^.next; lc^.next := nil; dec(rc^.next^.lazy, 2 * nodes[u].branch); end; nodes[u].lchain^.next := nodes[l].lchain; nodes[u].rchain^.next := nodes[r].rchain; inc(nodes[l].lchain^.lazy, nodes[u].branch); inc(nodes[r].rchain^.lazy, nodes[u].branch); end; end; function costOf(const n: node): int64; var res: int64 = 0; begin inc(res, 3 * (n.frameLeft + n.frameRight + 1)); if n.lchild <> 0 then inc(res, 2 + n.branch * 2 + byte(n.lchild <> 0) + byte(n.rchild <> 0)); exit(res); end; var s: string; var i: longint; var ans: int64; var par: longint; var line: TStringList; begin readln(n); readln(s); nodes[1] := createNode(length(s)); for i := 2 to n do begin readln(s); line := TStringList.create; line.delimiter := ' '; line.delimitedText := s; par := strToInt(line[1]); nodes[i] := createNode(length(line[0])); addChild(par, i); line.Free; end; process; ans := 0; for i := 1 to n do inc(ans, costOf(nodes[i])); writeln(ans); end. { 8 a b 1 c 1 d 1 e 1 f 4 g 3 abcdefghijklmnopqrst f }
unit uEditController; interface uses Aurelius.Engine.ObjectManager; type IEditController = interface procedure Save; procedure Load(Id: Variant); end; TEditController<T: class, constructor> = class(TInterfacedObject, IEditController) private FManager: TObjectManager; FEntity: T; procedure SetEntity(const Value: T); procedure DestroyEntity; public constructor Create; destructor Destroy; override; procedure Save; procedure Load(Id: Variant); property Entity: T read FEntity write SetEntity; property Manager: TObjectManager read FManager; end; implementation uses dConnection; { TEditController<T> } constructor TEditController<T>.Create; begin FManager := dmConnection.CreateManager; FEntity := T.Create; end; destructor TEditController<T>.Destroy; begin DestroyEntity; FManager.Free; inherited; end; procedure TEditController<T>.DestroyEntity; begin if not FManager.IsAttached(FEntity) then FEntity.Free; end; procedure TEditController<T>.Load(Id: Variant); begin DestroyEntity; FEntity := FManager.Find<T>(Id); end; procedure TEditController<T>.Save; begin if not FManager.IsAttached(FEntity) then FManager.SaveOrUpdate(FEntity); FManager.Flush; end; procedure TEditController<T>.SetEntity(const Value: T); begin FEntity := Value; end; end.
unit AddressBookResources; {$mode objfpc}{$H+} {$define USE_SQLITE3_SLIM} interface uses Classes, SysUtils, LuiRESTServer, LuiRESTSqldb, sqldb, HTTPDefs, {$ifdef USE_SQLITE3_SLIM} sqlite3slimconn {$else} sqlite3conn {$endif}; type { TServiceInfoResource } TServiceInfoResource = class(TRESTResource) public procedure HandleGet(ARequest: TRequest; AResponse: TResponse); override; end; { TCategoriesResource } TCategoriesResource = class(TSqldbCollectionResource) protected class function GetItemParam: String; override; public constructor Create; override; end; { TContactsResource } TContactsResource = class(TSqldbCollectionResource) protected class function GetItemParam: String; override; procedure PrepareItem(ItemResource: TSqldbResource); override; public constructor Create; override; end; { TContactPhonesResource } TContactPhonesResource = class(TSqldbCollectionResource) protected class function GetItemParam: String; override; procedure PrepareItem(ItemResource: TSqldbResource); override; public constructor Create; override; end; implementation { TContactPhonesResource } class function TContactPhonesResource.GetItemParam: String; begin Result := 'phoneid'; end; procedure TContactPhonesResource.PrepareItem(ItemResource: TSqldbResource); begin inherited PrepareItem(ItemResource); ItemResource.InputFields := '["number"]'; end; constructor TContactPhonesResource.Create; begin inherited Create; SelectSQL := 'Select Id, ContactId, Number from Phones'; ConditionsSQL := 'where ContactId = :contactid'; OutputFields := '["id", "number"]'; InputFields := '["number", "contactid"]'; end; { TCategoriesResource } class function TCategoriesResource.GetItemParam: String; begin Result := 'categoryid'; end; constructor TCategoriesResource.Create; begin inherited Create; SelectSQL := 'Select Id, Name from Categories'; end; { TContactsResource } class function TContactsResource.GetItemParam: String; begin Result := 'contactid'; end; procedure TContactsResource.PrepareItem(ItemResource: TSqldbResource); begin inherited PrepareItem(ItemResource); ItemResource.RegisterSubPath('phones', TContactPhonesResource, 0); end; constructor TContactsResource.Create; begin inherited Create; SelectSQL := 'Select Id, CategoryId, Name from contacts'; end; { TServiceInfoResource } procedure TServiceInfoResource.HandleGet(ARequest: TRequest; AResponse: TResponse); begin AResponse.Contents.Add('{"version":"0.1"}'); end; end.
unit HrdUtils; interface uses SysUtils, StrUtils, DateUtils, Math; function StrReplace(const S, OldPattern, NewPattern: string; IgnoreCase: boolean = false): string; function StrRemove(S: String; const AStrRemove: array of string; ignoreCase: Boolean = false): String; function StrGrab(S, AStart, AEnd: string; iIndex: Integer = 1; ignorecase : boolean = true): string; function DeleteDoubleSpace(const OldText: string): string; function StrCount(const Substring, Text: string): integer; function IsNumber(const S: String): Boolean; function IsCurrency(const S: String): Boolean; function IsModuleName(const S: String): Boolean; function IfThenStr(AValue: Boolean; const ATrue: string; AFalse: string = ''): string; function IfThenInt(AValue: Boolean; const ATrue: integer; AFalse: integer = 0) : integer; function IfBlankStr(ATrue, AFalse: string): String; function RemoveHTMLTag(S: string): string; function RemoveHTMLcomment(S: string): string; function FillStrLeft(S : String; aLength : Integer; c : Char = ' ') : string; function FillStrRight(S : String; aLength : Integer; c : Char = ' ') : string; function SaveToLog(const aData, aFileKeyName : string) : boolean; implementation function StrReplace(const S, OldPattern, NewPattern: string; IgnoreCase: boolean = false): string; var OldPat,Srch: string; // Srch and Oldp can contain uppercase versions of S,OldPattern PatLength,NewPatLength,P,i,PatCount,PrevP: Integer; c,d: pchar; Flags: TReplaceFlags; begin if IgnoreCase then Flags := [rfIgnoreCase, rfReplaceAll] else Flags := [rfReplaceAll]; PatLength := Length(OldPattern); if PatLength = 0 then begin Result := S; exit; end; if rfIgnoreCase in Flags then begin Srch := AnsiUpperCase(S); OldPat := AnsiUpperCase(OldPattern); end else begin Srch := S; OldPat := OldPattern; end; PatLength := Length(OldPat); if Length(NewPattern) = PatLength then begin //Result length will not change Result := S; P := 1; repeat P := PosEx(OldPat, Srch, P); if P > 0 then begin for i := 1 to PatLength do Result[P+i-1] := NewPattern[i]; if not (rfReplaceAll in Flags) then exit; inc(P, PatLength); end; until p = 0; end else begin //Different pattern length -> Result length will change //To avoid creating a lot of temporary strings, we count how many //replacements we're going to make. P := 1; PatCount := 0; repeat P := PosEx(OldPat, Srch, P); if P > 0 then begin inc(P, PatLength); inc(PatCount); if not (rfReplaceAll in Flags) then break; end; until p=0; if PatCount = 0 then begin Result := S; exit; end; NewPatLength := Length(NewPattern); SetLength(Result,Length(S)+PatCount*(NewPatLength-PatLength)); P:=1; PrevP:=0; c := pchar(Result); d := pchar(S); repeat P := PosEx(OldPat, Srch, P); if P > 0 then begin for i := PrevP+1 to P-1 do begin c^ := d^; inc(c); inc(d); end; for i := 1 to NewPatLength do begin c^ := NewPattern[i]; inc(c); end; if not (rfReplaceAll in Flags) then exit; inc(P, PatLength); inc(d, PatLength); PrevP := P-1; end else begin for i := PrevP+1 to Length(S) do begin c^ := d^; inc(c); inc(d); end; end; until p = 0; end; end; function StrRemove(S: String; const AStrRemove: array of string; ignoreCase: Boolean = false): String; var i : integer; begin for i := 0 to High(aStrRemove) do begin S := StrReplace(S, AStrRemove[i], '', ignoreCase); end; Result := S; end; function StrGrab(S, AStart, AEnd: string; iIndex : Integer = 1; ignorecase : boolean = true): string; var Srch : string; Count, indexStart, indexEnd : Integer; LenAStart : Integer; begin Result := ''; if iIndex < 1 then exit; // AStart and AEnd Blank if (Length(AStart) = 0) and (Length(AEnd) = 0) then if iIndex = 1 then Result := S else Exit; // Check Lower Case Condition if not ignorecase then begin Srch := AnsiUpperCase(S); AStart := AnsiUpperCase(AStart); AEnd := AnsiUpperCase(AEnd); end else begin Srch := S; end; // Find index of AStart LenAStart := Length(AStart); indexStart := 1; if LenAStart > 0 then begin Count := 0; while Count < iIndex do begin indexStart := PosEx(AStart, Srch, indexStart) + LenAStart; if indexStart > LenAStart then begin Inc(Count); end else exit; end; if Count < iIndex then exit; end; // Find index of AEnd if Length(AEnd) > 0 then begin indexEnd := PosEx(AEnd, Srch, indexStart); if indexEnd <= 1 then Exit; end else indexEnd := Length(S) + 1; Result := Copy(S, indexStart, indexEnd - indexStart); end; function DeleteDoubleSpace(const OldText: string): string; var i : integer; s : string; begin if length(OldText) > 0 then s := OldText[1] else s := ''; for i:=1 to length(OldText) do begin if OldText[i] = ' ' then begin if not (OldText[i - 1] = ' ') then s := s + ' '; end else begin s := s + OldText[i]; end; end; DeleteDoubleSpace := s; end; function StrCount(const Substring, Text: string): integer; var offset: integer; begin result := 0; offset := PosEx(Substring, Text, 1); while offset <> 0 do begin inc(result); offset := PosEx(Substring, Text, offset + length(Substring)); end; end; function IsNumber(const S: String): Boolean; var P: PChar; begin Result := False; P := PChar(S); while P^ <> #0 do begin if not (P^ in ['0'..'9']) then Exit; Inc(P); end; Result := True; end; function IsCurrency(const S: String): Boolean; var P : PChar; begin Result := False; P := PChar(S); if p^ = '-' then inc(p); // First Char Can be - sign if StrCount('.', S) > 1 then Exit; // accept only one . while P^ <> #0 do begin if not (P^ in ['0'..'9', '.']) then Exit; Inc(P); end; Result := True; end; function IsModuleName(const S: String): Boolean; begin Result := false; if Length(S) <> 11 then exit; if Copy(S, 1, 4) <> 'PROJ' then exit; if not IsNumber(Copy(S, 5, 7)) then exit; Result := True; end; function IfThenStr(AValue: Boolean; const ATrue: string; AFalse: string = ''): string; begin Result := IfThen(AValue, ATrue, AFalse); end; function IfThenInt(AValue: Boolean; const ATrue: integer; AFalse: integer = 0) : integer; begin Result := IfThen(AValue, ATrue, AFalse); end; function IfBlankStr(ATrue, AFalse: string): String; begin if ATrue <> '' then Result := ATrue else result := AFalse; end; function RemoveHTMLcomment(S: string): string; var TagBegin, TagEnd, TagLength: integer; begin TagBegin := PosEx('<!--', S, 1); while (TagBegin > 0) do begin TagEnd := PosEx('-->', S, TagBegin + 1); TagLength := TagEnd - TagBegin + 1; Delete(S, TagBegin, TagLength + 2); TagBegin := PosEx( '<!--', S, TagBegin - 1); end; Result := S; end; function RemoveHTMLTag(S: string): string; var TagBegin, TagEnd, TagLength: integer; begin S := RemoveHTMLcomment(S); TagBegin := PosEx('<', S, 1); while (TagBegin > 0) do begin TagEnd := PosEx('>', S, TagBegin + 1); TagLength := TagEnd - TagBegin + 1; Delete(S, TagBegin, TagLength); TagBegin := PosEx( '<', S, TagBegin - 1); end; Result := S; end; function FillStrLeft(S : String; aLength : Integer; C : Char = ' ') : string; var i : Integer; begin aLength := aLength - Length(S); for i := 1 to aLength do Insert(C, S, 1); Result := S; end; function FillStrRight(S : String; aLength : Integer; C : Char = ' ') : string; var i : Integer; begin aLength := aLength - Length(S); for i := 1 to aLength do S := S + C; Result := S; end; function SaveToLog(const aData, aFileKeyName : string) : boolean; var FileName : String; myFile : TextFile; Path : String; begin Result := False; Path := 'D:\workspace_hrd\plugins\log'; if not DirectoryExists(Path) then CreateDir(Path); FileName := Path + '\' + ChangeFileExt(ExtractFileName(ParamStr(0)), ''); FileName := FileName + '_' + aFileKeyName + '_' + FormatDateTime('YYYYMMDD_HHNNSS_ZZZ', Now) + '.txt'; AssignFile(myFile, FileName); Rewrite(myFile); Writeln(myFile, aData); CloseFile(myFile); Result := True; end; end.
{ WARNING: This code is old, and some data structures have changed out from * under it. The source code is here to preserve it, but it is currently not * being built. } { All the routines to implement a dumb linear list aggregate object. } module type1_list; define type1_list_class_make; %include 'ray_type1_2.ins.pas'; type obj_block_p_t = {pointer to a child object list entry block} ^obj_block_t; obj_block_t = record {template for child object list entry block} list_p: obj_block_p_t; {pointer to list of remaining child blocks} obj: ray_object_t; {handle to child object} end; object_data_t = record {data record pointed to by object block} shader: ray_shader_t; {pointer to shader entry point} liparm_p: type1_liparm_p_t; {pointer to light source parameters block} visprop_p: type1_visprop_p_t; {pointer to visual properties block} n_obj: sys_int_machine_t; {current number of child objects} list_p: obj_block_p_t; {pointer to first child object block in list} end; object_data_p_t = {pointer to object data block} ^object_data_t; procedure type1_list_create ( {create new primitive with custom data} out object: ray_object_t; {newly filled in object block} in data: type1_list_user_data_t; {parameters from user} out stat: sys_err_t); {completion status code} val_param; forward; function type1_list_intersect_check ( {check for ray/object intersection} in out ray: type1_ray_t; {ray descriptor} in object: ray_object_t; {object to intersect ray with} in uparms: type1_object_parms_t; {run-time parameters passed from above} out hit_info: ray_hit_info_t; {all returned information} out shader: ray_shader_t) {pointer to shader to resolve color} :boolean; {TRUE if ray does hit object} val_param; forward; procedure type1_list_intersect_geom ( {return detailed geometry of intersection} in hit_info: ray_hit_info_t; {data saved by INTERSECT_CHECK} in flags: ray_geom_flags_t; {bit mask list of what is being requested} out geom_info: ray_geom_info_t); {filled in geometric info} val_param; forward; procedure type1_list_intersect_box ( {find object/box intersection status} in box: ray_box_t; {descriptor for a paralellpiped volume} in object: ray_object_t; {object to intersect with the box} out here: boolean; {TRUE if ISECT_CHECK could be true in box} out enclosed: boolean); {TRUE if solid obj, and completely encloses box} val_param; forward; procedure type1_list_add_child ( {Add child to this object} in aggr_obj: ray_object_t; {the object to add child to} var object: ray_object_t); {the object to add} val_param; forward; procedure type1_list_version ( {return version information about object} out version: ray_object_version_t); {returned version information} val_param; forward; { **************************************************************************** * * Local subroutine TYPE1_LIST_CREATE (OBJECT, DATA, STAT) * * Fill in the new object in OBJECT. DATA is the user data parameters for * this object. STATUS is the standard system error return code. } procedure type1_list_create ( {create new primitive with custom data} out object: ray_object_t; {newly filled in object block} in data: type1_list_user_data_t; {parameters from user} out stat: sys_err_t); {completion status code} val_param; var data_p: object_data_p_t; {pointer to internal object data} begin sys_error_none (stat); {init to no error} util_mem_grab ( {allocate data block for new object} sizeof(data_p^), ray_mem_p^, false, data_p); object.data_p := ray_obj_data_p_t(data_p); {set pointer to object data block} data_p^.shader := data.shader; {copy pointer to shader to use} data_p^.liparm_p := data.liparm_p; {copy pointer to light source block} data_p^.visprop_p := data.visprop_p; {copy pointer to visual properties block} data_p^.n_obj := 0; {init number of child objects} data_p^.list_p := nil; {init pointer to linked list of children} end; { **************************************************************************** * * Local subroutine TYPE1_LIST_VERSION (VERSION) * * Return version information obout this class of objects. } procedure type1_list_version ( {return version information about object} out version: ray_object_version_t); {returned version information} val_param; begin version.year := 1987; version.month := 10; version.day := 25; version.hour := 19; version.minute := 32; version.second := 0; version.version := 0; version.name := string_v('LIST'); version.aggregate := true; end; { **************************************************************************** * * Local function TYPE1_LIST_INTERSECT_CHECK ( * RAY, OBJECT, UPARMS, HIT_INFO, SHADER) * * Check ray and object for an intersection. If so, return TRUE, and save * any partial results in HIT_INFO. These partial results may be used later * to get detailed information about the intersection geometry. } function type1_list_intersect_check ( {check for ray/object intersection} in out ray: type1_ray_t; {ray descriptor} in object: ray_object_t; {object to intersect ray with} in uparms: type1_object_parms_t; {run-time parameters passed from above} out hit_info: ray_hit_info_t; {all returned information} out shader: ray_shader_t) {pointer to shader to resolve color} :boolean; {TRUE if ray does hit object} val_param; var dp: object_data_p_t; {pointer to object unique data block} hit: boolean; {TRUE if found hit so far} old_mem: sys_int_adr_t; {MEM index before any hits} new_mem: sys_int_adr_t; {MEM index after best hit so far} child_p: obj_block_p_t; {pointer to children list entry} parms: type1_object_parms_t; {parms for child intersect checks} begin dp := object_data_p_t(object.data_p); {make local pointer to object data} if dp^.shader = nil {resolve shader pointer inheritance} then parms.shader := uparms.shader else parms.shader := dp^.shader; if dp^.liparm_p = nil {resolve LIPARM pointer inheritance} then parms.liparm_p := uparms.liparm_p else parms.liparm_p := dp^.liparm_p; if dp^.visprop_p = nil {resolve VISPROP pointer inheritance} then parms.visprop_p := uparms.visprop_p else parms.visprop_p := dp^.visprop_p; hit := false; {init to no object hit so far} child_p := dp^.list_p; {init pointer to first child block} old_mem := next_mem; {save MEM index before any hits} while child_p <> nil do begin {once for each child object in our list} if child_p^.obj.routines_p^.intersect_check^ ( {run child intersect check routine} ray, {ray descriptor} child_p^.obj, {object to insertect ray with} parms, {run time parameters} hit_info, {data about the hit} shader) {shader entry point to use for this hit} then begin {do this block if ray hit child object} hit := true; {remember that the ray hit something} new_mem := next_mem; {save MEM index after this hit data} next_mem := old_mem; {restore mem index to before hit data} end; {done handling if ray hit child} child_p := child_p^.list_p; {point to next child block in our list} end; {back and try next child} type1_list_intersect_check := hit; {indicate whether there was a hit at all} if hit then begin {there was a hit} next_mem := new_mem; {set next mem after hit data for this hit} end; end; { **************************************************************************** * * Local subroutine TYPE1_LIST_INTERSECT_GEOM (HIT_INFO, FLAGS, GEOM_INFO) * * Return specific geometric information about a ray/object intersection * in GEOM_INFO. In HIT_INFO are any useful results left by the ray/object * intersection check calculation. FLAGS identifies what specific geometric * information is being requested. } procedure type1_list_intersect_geom ( {return detailed geometry of intersection} in hit_info: ray_hit_info_t; {data saved by INTERSECT_CHECK} in flags: ray_geom_flags_t; {bit mask list of what is being requested} out geom_info: ray_geom_info_t); {filled in geometric info} val_param; begin writeln ('Intersect geom entry point to LIST object called.'); sys_bomb; {save traceback info and bomb out} end; { *************************************************************************************** * * Local subroutine TYPE1_LIST_INTERSECT_BOX (BOX, OBJECT, HERE, ENCLOSED) * * Find the intersection status between this object and a paralellpiped. * HERE is returned as TRUE if the intersect check routine for this object could * ever return TRUE for ray within the box volume. ENCLOSED is returned as true * if the object completely encloses the box. } procedure type1_list_intersect_box ( {find object/box intersection status} in box: ray_box_t; {descriptor for a paralellpiped volume} in object: ray_object_t; {object to intersect with the box} out here: boolean; {TRUE if ISECT_CHECK could be true in box} out enclosed: boolean); {TRUE if solid obj, and completely encloses box} val_param; var obj_here: boolean; {HERE flag for subordinate object} obj_enclosed: boolean; {ENCLOSED flag for subordinate object} obj_block_p: obj_block_p_t; {pointer to linked object descriptor} data_p: object_data_p_t; {pointer to specific data for this object} label obj_loop; begin here := false; {init returned intersect status flags} enclosed := false; data_p := object_data_p_t(object.data_p); {get pointer to our data block} obj_block_p := data_p^.list_p; {get pointer to first child object block} obj_loop: {back here each new child pointer} if obj_block_p = nil then return; {no more child objects left to check ?} obj_block_p^.obj.routines_p^.intersect_box^ ( {call child's box intersector} box, {the box to intersect object with} obj_block_p^.obj, {object to intersect box with} obj_here, {HERE flag for child object} obj_enclosed); {ENCLOSED flag for child object} here := here or obj_here; {merge in child's here status} enclosed := enclosed or obj_enclosed; {merge in child's enclosed status} if here and enclosed then return; {can't change from this state anyway} obj_block_p := obj_block_p^.list_p; {advance pointer to next child descriptor} goto obj_loop; {back and process new child} end; { **************************************************************************** * * Local subroutine TYPE1_LIST_ADD_CHILD (AGGR_OBJ, OBJECT) } procedure type1_list_add_child ( {Add child to this object} in aggr_obj: ray_object_t; {the object to add child to} var object: ray_object_t); {the object to add} val_param; var obj_p: obj_block_p_t; {pointer to new child block} data_p: object_data_p_t; {pointer to internal object data} begin data_p := object_data_p_t(aggr_obj.data_p); {make local pointer to our data} util_mem_grab ( {allocate storage for new list entry} sizeof(obj_p^), ray_mem_p^, false, obj_p); obj_p^.obj := object; {copy object handle into list entry} obj_p^.list_p := data_p^.list_p; {make new entry point to rest of list} data_p^.list_p := obj_p; {set start of list pointer to new entry} data_p^.n_obj := data_p^.n_obj; {count one more object in list} end; { ******************************************************************************** * * Subroutine TYPE1_LIST_CLASS_MAKE (CLASS) * * Fill in the routines block for this class of objects. } procedure type1_list_class_make ( {fill in object class descriptor} out class: ray_object_class_t); {block to fill in} val_param; begin class.create := addr(type1_list_create); class.intersect_check := addr(type1_list_intersect_check); class.hit_geom := addr(type1_list_intersect_geom); class.intersect_box := addr(type1_list_intersect_box); class.add_child := addr(type1_list_add_child); end;
unit uMap; interface uses SysUtils, Variants, uGeoTools, ActiveX, uModule, uOSMCommon, uInterfaces; type TAbstractMap = class(TOSManObject, IMap) protected fStorage: Variant; function getMultiObjects(const ObjType:AnsiString;objIdArray:Variant):OleVariant; public function get_storage: OleVariant; virtual; procedure set_storage(const newStorage: OleVariant); virtual; function get_onPutFilter: OleVariant; virtual; abstract; procedure set_onPutFilter(const aFilter: OleVariant); virtual; abstract; published //create epmty node function createNode(): IDispatch; virtual; //create epmty way function createWay(): IDispatch; virtual; //create epmty relation function createRelation(): IDispatch; virtual; //store Node into Storage procedure putNode(const aNode: OleVariant); virtual; abstract; //store Way into Storage procedure putWay(const aWay: OleVariant); virtual; abstract; //store Relation into Storage procedure putRelation(const aRelation: OleVariant); virtual; abstract; //store MapObject (Node,Way or Relation) into Store procedure putObject(const aObj: OleVariant); virtual; //delete Node and its tags from Storage procedure deleteNode(const nodeId: int64); virtual; abstract; //delete Way, its tags and node-list from Storage procedure deleteWay(const wayId: int64); virtual; abstract; //delete Relation, its tags and ref-list from Storage procedure deleteRelation(const relationId: int64); virtual; abstract; //get node by ID. If no node found returns false function getNode(const id: int64): OleVariant; virtual; abstract; //get way by ID. If no way found returns false function getWay(const id: int64): OleVariant; virtual; abstract; //get relation by ID. If no relation found returns false function getRelation(const id: int64): OleVariant; virtual; abstract; //get nodes with Ids in nodeIdArray. If at least one object not found <false> returned (see OSM API wiki) function getNodes(const nodeIdArray: OleVariant): OleVariant;virtual; //get ways with Ids in wayIdArray. If at least one object not found <false> returned (see OSM API wiki) function getWays(const wayIdArray: OleVariant): OleVariant;virtual; //get relations with Ids in relationIdArray. If at least one object not found <false> returned (see OSM API wiki) function getRelations(const relationIdArray: OleVariant): OleVariant;virtual; //get filtered object set function getObjects(const filterOptions: OleVariant): OleVariant; virtual; abstract; //IMapOnPutFilter property onPutFilter: OleVariant read get_onPutFilter write set_onPutFilter; //initialize new storage - drop and create tables procedure initStorage(); virtual; abstract; //set storage. Suppoted storage interface see in descendants. To free // system resource set storage to unassigned. property storage: OleVariant read get_storage write set_storage; end; implementation const mapClassGuid: TGuid = '{7B3FBE69-1232-4C22-AAF5-C649EFB89981}'; type TMapObject = class(TOSManObject, IMapObject) protected //IKeyList fTags: TWideStringArray; fId, fChangeset, fTimeStamp: int64; fVersion, fUserId: integer; fUserName: WideString; public function get_tags: OleVariant; procedure set_tags(const newTags: OleVariant); function get_id: int64; procedure set_id(const newId: int64); function get_version: integer; procedure set_version(const newVersion: integer); function get_userId: integer; procedure set_userId(const newUserId: integer); function get_userName: WideString; procedure set_userName(const newUserName: WideString); function get_changeset: int64; procedure set_changeset(const newChangeset: int64); function get_timestamp: WideString; procedure set_timestamp(const newTimeStamp: WideString); published //tags, associated with object. Supports IKeyList property tags: OleVariant read get_tags write set_tags; //OSM object ID. property id: int64 read get_id write set_id; //OSM object version property version: integer read get_version write set_version; //OSM object userID property userId: integer read get_userId write set_userId; //OSM object userName property userName: WideString read get_userName write set_userName; //OSM object changeset property changeset: int64 read get_changeset write set_changeset; //OSM object timestamp. Format "yyyy-mm-ddThh:nn:ssZ" like in OSM files property timestamp: WideString read get_timestamp write set_timestamp; end; TTags = class(TOSManObject, IKeyList) protected fMapObj: TMapObject; public function get_count: integer; destructor destroy;override; published //delete item by key. If no such key, no actions performed procedure deleteByKey(const key: WideString); //delete item by index in list. If index out of bounds then exception raised procedure deleteById(const id: integer); //get all keys in list. Result is SafeArray of string variants. //Keys and Values interlived - [0]=key[0],[1]=value[0]...[10]=key[5],[11]=value[5],... function getAll: OleVariant; //add items to list. On key conflict replaces old value with new one. //kvArray interlived as in getAll() method procedure setAll(const kvArray: OleVariant); //returns true if key exists in list. function hasKey(const key: WideString): WordBool; //returns value assiciated with key. If no such key empty string('') returned function getByKey(const key: WideString): WideString; //add or replace key-value pair procedure setByKey(const key: WideString; const value: WideString); //returns value by index. If index out of bounds [0..count-1] exception raised function getValue(const id: integer): WideString; //sets value by index. If index out of bounds [0..count-1] exception raised procedure setValue(const id: integer; const value: WideString); //returns key by index. If index out of bounds [0..count-1] exception raised function getKey(const id: integer): WideString; //sets key by index. If index out of bounds [0..count-1] exception raised procedure setKey(const id: integer; const key: WideString); //returns number of pairs in list property count: integer read get_count; end; TNode = class(TMapObject, INode) protected fLat, fLon: integer; public function get_lat: double; procedure set_lat(const value: double); function get_lon: double; procedure set_lon(const value: double); published //node latitude. If out of bounds [-91...+91] exception raised property lat: double read get_lat write set_lat; //node longitude. If out of bounds [-181...181] exception raised property lon: double read get_lon write set_lon; end; TWay = class(TMapObject, IWay) protected fNodes: array of int64; public function get_nodes: OleVariant; procedure set_nodes(const newNodes: OleVariant); published //array of node OSM IDs. SafeArray of Int64 variants property nodes: OleVariant read get_nodes write set_nodes; end; TRelation = class(TMapObject, IRelation) protected fMembers: OleVariant; public function get_members: OleVariant; procedure set_members(const newMembers: OleVariant); constructor create(); override; published //list of relation members. Supports IRefList property members: OleVariant read get_members write set_members; end; TMap = class(TAbstractMap) protected fQryPutNode, fQryPutWay, fQryPutWayNode, fQryPutRelation, fQryPutRelationMember, fQryPutObjTag, fQryDeleteNode, fQryDeleteWay, fQryDeleteRelation, fQryGetNode, fQryGetWay, fQryGetWayNodes, fQryGetRelation, fQryGetRelationMembers: OleVariant; fOnPutFilter: TPutFilterAdaptor; procedure putTags(const objId: int64; const objType: byte {0-node,1-way,2-relation}; const tagNamesValuesInterlived: OleVariant); function doOnPutNode(const aNode: OleVariant): boolean; function doOnPutWay(const aWay: OleVariant): boolean; function doOnPutRelation(const aRelation: OleVariant): boolean; public procedure set_storage(const newStorage: OleVariant); override; function get_onPutFilter: OleVariant; override; procedure set_onPutFilter(const aFilter: OleVariant); override; destructor destroy; override; published //store Node into Storage procedure putNode(const aNode: OleVariant); override; //store Way into Storage procedure putWay(const aWay: OleVariant); override; //store Relation into Storage procedure putRelation(const aRelation: OleVariant); override; //delete Node and its tags from Storage procedure deleteNode(const nodeId: int64); override; //delete Way, its tags and node-list from Storage procedure deleteWay(const wayId: int64); override; //delete Relation, its tags and ref-list from Storage procedure deleteRelation(const relationId: int64); override; //get node by ID. If no node found returns false function getNode(const id: int64): OleVariant; override; //get way by ID. If no way found returns false function getWay(const id: int64): OleVariant; override; //get relation by ID. If no relation found returns false function getRelation(const id: int64): OleVariant; override; //get filtered object set function getObjects(const filterOptions: OleVariant): OleVariant; override; //IMapOnPutFilter property onPutFilter: OleVariant read get_onPutFilter write set_onPutFilter; //set SQL-storage (IStorage). To free system resource set storage to unassigned //property storage:OleVariant read get_storage write set_storage; end; TMapObjectStream = class(TOSManObject, IInputStream) protected fMap: TMap; fStorage, fQry: Variant; fBPolies: array of OleVariant; fCustomFilters: array of TPutFilterAdaptor; fNodeList, fWayList, fRelList, fToDoRelList: OleVariant; fNodeSelectCondition: WideString; fOutMode: TRefType; fEOS: boolean; fClipIncompleteWays: boolean; //read one object function read1: OleVariant; procedure set_eos(const aEOS: boolean); public procedure initialize(const aMap: TMap; const aStorage, aFilter: OleVariant); constructor create(); override; destructor destroy(); override; published //maxBufSize: read buffer size //Readed data in zero-based one dimensional SafeArray of MapObjects function read(const maxBufSize: integer): OleVariant; function get_eos(): WordBool; //"true" if end of stream reached, "false" otherwise property eos: WordBool read get_eos; end; { TMap } procedure TMap.deleteNode(const nodeId: int64); begin if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.deleteNode: storage not assigned'); if VarIsEmpty(fQryDeleteNode) then begin fQryDeleteNode := fStorage.sqlPrepare( 'DELETE FROM nodes WHERE id=:id'); end; fStorage.sqlExec(fQryDeleteNode, ':id', nodeId); end; procedure TMap.deleteRelation(const relationId: int64); begin if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.deleteRelation: storage not assigned'); if VarIsEmpty(fQryDeleteRelation) then begin fQryDeleteRelation := fStorage.sqlPrepare( 'DELETE FROM relations WHERE id=:id'); end; fStorage.sqlExec(fQryDeleteRelation, ':id', relationId); end; procedure TMap.deleteWay(const wayId: int64); begin if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.deleteWay: storage not assigned'); if VarIsEmpty(fQryDeleteWay) then begin fQryDeleteWay := fStorage.sqlPrepare( 'DELETE FROM ways WHERE id=:id'); end; fStorage.sqlExec(fQryDeleteWay, ':id', wayId); end; destructor TMap.destroy; begin FreeAndNil(fOnPutFilter); inherited; end; function TMap.doOnPutNode(const aNode: OleVariant): boolean; begin if assigned(fOnPutFilter) then result := fOnPutFilter.onPutNode(aNode) else result := true; end; function TMap.doOnPutRelation(const aRelation: OleVariant): boolean; begin if assigned(fOnPutFilter) then result := fOnPutFilter.onPutRelation(aRelation) else result := true; end; function TMap.doOnPutWay(const aWay: OleVariant): boolean; begin if assigned(fOnPutFilter) then result := fOnPutFilter.onPutWay(aWay) else result := true; end; function TMap.getNode(const id: int64): OleVariant; const sQry = 'SELECT nodes.id AS id,' + 'nodes.version AS version,' + 'nodes.userId as userId,' + 'nodes.name as userName,' + 'nodes.changeset AS changeset,' + 'nodes.timestamp as timestamp,' + 'nodes.lat as lat,' + 'nodes.lon as lon,' + 'tags.tagname as k,' + 'tags.tagvalue as v ' + 'FROM (SELECT * FROM nodes,users WHERE nodes.id=:id AND nodes.userId=users.id)AS nodes ' + 'LEFT JOIN objtags ON nodes.id*4=objtags.objid ' + 'LEFT JOIN tags ON objtags.tagid=tags.id ' + 'ORDER BY tags.tagname '; var //IQueryResult qr, row, t: OleVariant; ws:WideString; begin if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.getNode: storage not assigned'); if VarIsEmpty(fQryGetNode) then begin fQryGetNode := fStorage.sqlPrepare(sQry); end; qr := fStorage.sqlExec(fQryGetNode, ':id', id); result := false; if qr.eos then exit; row := qr.read(1); result := createNode(); result.id := row[0]; result.version := row[1]; result.userId := row[2]; result.userName := row[3]; result.changeset := row[4]; t:=row[5]; if VarIsType(t,varOleStr)then begin ws:=t; if (length(ws)<>length('20001010230023'))then result.timestamp := ws else result.timestamp := timeStampToWideString(WideStrToInt64(ws)); end else result.timestamp:=timeStampToWideString(t); result.lat := intToDeg(row[6]); result.lon := intToDeg(row[7]); if VarIsNull(row[8]) then //no tags exit; t := result.tags; t.setByKey(row[8], row[9]); while not qr.eos do begin row := qr.read(1); if VarIsArray(row) then t.setByKey(row[8], row[9]); end; end; function TMap.getObjects(const filterOptions: OleVariant): OleVariant; var os: TMapObjectStream; begin os := TMapObjectStream.create(); os.initialize(self, fStorage, varFromJsObject(filterOptions)); result := os as IDispatch; end; function TMap.getRelation(const id: int64): OleVariant; const sQry = 'SELECT relations.id AS id, ' + 'relations.version AS version, ' + 'relations.userId as userId, ' + 'relations.name as userName, ' + 'relations.changeset AS changeset, ' + 'relations.timestamp as timestamp, ' + 'tags.tagname as k, ' + 'tags.tagvalue as v ' + 'FROM (SELECT * FROM relations,users WHERE relations.id=:id AND relations.userId=users.id)AS relations ' + 'LEFT JOIN objtags ON relations.id*4+2=objtags.objid ' + 'LEFT JOIN tags ON objtags.tagid=tags.id ' + 'ORDER BY tags.tagname'; sQryMembers = 'SELECT membertype as membertype, ' + 'memberid as memberid, ' + 'memberrole as memberrole ' + 'FROM strrelationmembers ' + 'WHERE relationid=:id ' + 'ORDER BY memberidx'; var //IQueryResult qr, row, t: OleVariant; ws: WideString; begin if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.getRelation: storage not assigned'); if VarIsEmpty(fQryGetRelation) then begin fQryGetRelation := fStorage.sqlPrepare(sQry); end; qr := fStorage.sqlExec(fQryGetRelation, ':id', id); result := false; if qr.eos then exit; row := qr.read(1); result := createRelation; result.id := row[0]; result.version := row[1]; result.userId := row[2]; result.userName := row[3]; result.changeset := row[4]; t:=row[5]; if VarIsType(t,varOleStr)then begin ws:=t; if (length(ws)<>length('20001010230023'))then result.timestamp := ws else result.timestamp := timeStampToWideString(WideStrToInt64(ws)); end else result.timestamp:=timeStampToWideString(t); if not VarIsNull(row[6]) then begin //relation has tags t := result.tags; t.setByKey(row[6], row[7]); while not qr.eos do begin row := qr.read(1); if VarIsArray(row) then t.setByKey(row[6], row[7]); end; end; if VarIsEmpty(fQryGetRelationMembers) then begin fQryGetRelationMembers := fStorage.sqlPrepare(sQryMembers); end; qr := fStorage.sqlExec(fQryGetRelationMembers, ':id', id); if not qr.eos then begin //relation has members t := result.members; while not qr.eos do begin row := qr.read(1); t.insertBefore(MaxInt, row[0], row[1], row[2]); end; end; end; function TMap.getWay(const id: int64): OleVariant; const sQry = 'SELECT ways.id AS id, ' + 'ways.version AS version, ' + 'ways.userId as userId, ' + 'ways.name as userName, ' + 'ways.changeset AS changeset, ' + 'ways.timestamp as timestamp, ' + 'tags.tagname as k, ' + 'tags.tagvalue as v ' + 'FROM (SELECT * FROM ways,users WHERE ways.id=:id AND ways.userId=users.id)AS ways ' + 'LEFT JOIN objtags ON ways.id*4+1=objtags.objid ' + 'LEFT JOIN tags ON objtags.tagid=tags.id ' + 'ORDER BY tags.tagname'; sQryNodes = 'SELECT nodeid AS nodeid ' + 'FROM waynodes ' + 'WHERE wayid=:id ORDER BY nodeidx'; var ndList: array of int64; ndCount: integer; procedure grow(); begin if length(ndList) <= ndCount then setLength(ndList, ndCount * 2); end; var //IQueryResult qr, row, t: OleVariant; pv: PVarData; pi64: PInt64; ws:WideString; begin if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.getWay: storage not assigned'); if VarIsEmpty(fQryGetWay) then begin fQryGetWay := fStorage.sqlPrepare(sQry); end; qr := fStorage.sqlExec(fQryGetWay, ':id', id); result := false; if qr.eos then exit; row := qr.read(1); result := createWay; result.id := row[0]; result.version := row[1]; result.userId := row[2]; result.userName := row[3]; result.changeset := row[4]; t:=row[5]; if VarIsType(t,varOleStr)then begin ws:=t; if (length(ws)<>length('20001010230023'))then result.timestamp := ws else result.timestamp := timeStampToWideString(WideStrToInt64(ws)); end else result.timestamp:=timeStampToWideString(t); if not VarIsNull(row[6]) then begin //way has tags t := result.tags; t.setByKey(row[6], row[7]); while not qr.eos do begin row := qr.read(1); if VarIsArray(row) then t.setByKey(row[6], row[7]); end; end; if VarIsEmpty(fQryGetWayNodes) then begin fQryGetWayNodes := fStorage.sqlPrepare(sQryNodes); end; qr := fStorage.sqlExec(fQryGetWayNodes, ':id', id); if not qr.eos then begin //way has nodes ndCount := 0; setLength(ndList, 4); while not qr.eos do begin row := qr.read(1); inc(ndCount); grow(); ndList[ndCount - 1] := row[0]; end; t := VarArrayCreate([0, ndCount - 1], varVariant); if ndCount > 0 then begin pi64 := @ndList[0]; pv := VarArrayLock(t); try while ndCount > 0 do begin pv^.VType := varInt64; pv^.VInt64 := pi64^; inc(pv); inc(pi64); dec(ndCount); end; finally VarArrayUnlock(t); end; result.nodes := t; end; end; end; function TMap.get_onPutFilter: OleVariant; begin if assigned(fOnPutFilter) then result := fOnPutFilter.getFilter() else result := unassigned; end; procedure TMap.putNode(const aNode: OleVariant); var id: int64; k: OleVariant; begin if not doOnPutNode(aNode) then exit; if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.putNode: storage not assigned'); id := aNode.id; if VarIsEmpty(fQryPutNode) then begin fQryPutNode := fStorage.sqlPrepare( 'INSERT INTO strnodes' + '(id, lat, lon , version , timestamp , userId , userName, changeset ) VALUES ' + '(:id, :lat, :lon, :version, :timestamp, :userId, :userName, :changeset);' ); end; fStorage.sqlExec(fQryPutNode, VarArrayOf([':id', ':lat', ':lon', ':version', ':timestamp', ':userId', ':userName', ':changeset']), VarArrayOf([id, degToInt(aNode.lat), degToInt(aNode.lon), aNode.version, wideStringToTimeStamp(aNode.timestamp), aNode.userId, aNode.userName, aNode.changeset])); k := aNode.tags; putTags(id, 0, k.getAll); end; procedure TMap.putRelation(const aRelation: OleVariant); var id, memberid: int64; t, r: WideString; n, i: integer; k: OleVariant; pv: PVariant; begin if not doOnPutRelation(aRelation) then exit; if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.putRelation: storage not assigned'); id := aRelation.id; if VarIsEmpty(fQryPutRelation) then begin fQryPutRelation := fStorage.sqlPrepare( 'INSERT INTO strrelations' + '(id, version , timestamp , userId , userName, changeset ) VALUES ' + '(:id, :version, :timestamp, :userId, :userName, :changeset);' ); end; fStorage.sqlExec(fQryPutRelation, VarArrayOf([':id', ':version', ':timestamp', ':userId', ':userName', ':changeset']), VarArrayOf([id, aRelation.version, wideStringToTimeStamp(aRelation.timestamp), aRelation.userId, aRelation.userName, aRelation.changeset])); k := aRelation.tags; putTags(id, 2, k.getAll); k := aRelation.members.getAll; if (VarArrayDimCount(k) <> 1) or ((VarType(k) and varTypeMask) <> varVariant) then raise EInOutError.create(toString() + '.putRelation: illegal members set'); n := (VarArrayHighBound(k, 1) - VarArrayLowBound(k, 1) + 1) div 3; if n <= 0 then exit; if VarIsEmpty(fQryPutRelationMember) then begin fQryPutRelationMember := fStorage.sqlPrepare( 'INSERT INTO strrelationmembers' + '(relationid, memberidx, membertype, memberid, memberrole) VALUES ' + '(:relationid,:memberidx,:membertype,:memberid,:memberrole)'); end; i := 0; pv := VarArrayLock(k); try while i < n do begin t := pv^; inc(pv); memberid := pv^; inc(pv); r := pv^; inc(pv); fStorage.sqlExec(fQryPutRelationMember, VarArrayOf([':relationid', ':memberidx', ':membertype', ':memberid', ':memberrole']), VarArrayOf([id, i, t, memberid, r])); inc(i); end; finally VarArrayUnlock(k); end; end; procedure TMap.putTags(const objId: int64; const objType: byte; const tagNamesValuesInterlived: OleVariant); var objIdType: int64; i, nTags: integer; pnvi, pqp: PVariant; vQryParams: OleVariant; begin nTags := (VarArrayHighBound(tagNamesValuesInterlived, 1) - VarArrayLowBound(tagNamesValuesInterlived, 1) + 1) div 2; if nTags <= 0 then exit; if VarIsEmpty(fQryPutObjTag) then begin fQryPutObjTag := fStorage.sqlPrepare( 'INSERT OR IGNORE INTO strobjtags (objid,tagname,tagvalue) ' + 'VALUES(:objid, :tagname, :tagvalue)' ); end; vQryParams := VarArrayCreate([0, nTags * 3 - 1], varVariant); pnvi := VarArrayLock(tagNamesValuesInterlived); pqp := VarArrayLock(vQryParams); objIdType := objId * 4 + objType; try for i := 0 to nTags - 1 do begin //prepare parameters pqp^ := objIdType; inc(pqp); pqp^ := pnvi^; //copy name inc(pqp); inc(pnvi); pqp^ := pnvi^; //copy value inc(pqp); inc(pnvi); end; finally VarArrayUnlock(vQryParams); VarArrayUnlock(tagNamesValuesInterlived); end; fStorage.sqlExec(fQryPutObjTag, VarArrayOf([':objid', ':tagname', ':tagvalue']), vQryParams); end; procedure TMap.putWay(const aWay: OleVariant); var id: int64; k, vQryParams: OleVariant; pv, pp: PVariant; i, n: integer; begin if not doOnPutWay(aWay) then exit; if not varIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.putWay: storage not assigned'); id := aWay.id; if VarIsEmpty(fQryPutWay) then begin fQryPutWay := fStorage.sqlPrepare( 'INSERT INTO strways' + '(id, version , timestamp , userId , userName, changeset ) VALUES ' + '(:id, :version, :timestamp, :userId, :userName, :changeset);' ); end; fStorage.sqlExec(fQryPutWay, VarArrayOf([':id', ':version', ':timestamp', ':userId', ':userName', ':changeset']), VarArrayOf([id, aWay.version, wideStringToTimeStamp(aWay.timestamp), aWay.userId, aWay.userName, aWay.changeset])); k := aWay.tags; putTags(id, 1, k.getAll); k := aWay.nodes; if (VarArrayDimCount(k) <> 1) or ((VarType(k) and varTypeMask) <> varVariant) then raise EInOutError(toString() + '.putWay: illegal nodes set'); n := varArrayLength(k); if n <= 0 then exit; if VarIsEmpty(fQryPutWayNode) then begin fQryPutWayNode := fStorage.sqlPrepare( 'INSERT INTO waynodes' + '(wayid, nodeidx, nodeid) VALUES ' + '(:wayid,:nodeidx,:nodeid)'); end; vQryParams := VarArrayCreate([0, n * 3 - 1], varVariant); pv := VarArrayLock(k); pp := VarArrayLock(vQryParams); try for i := 0 to n - 1 do begin //prepare parameters pp^ := id; //wayid inc(pp); pp^ := i; //nodeidx inc(pp); pp^ := pv^; //nodeid inc(pp); inc(pv); end; finally VarArrayUnlock(vQryParams); VarArrayUnlock(k); end; fStorage.sqlExec(fQryPutWayNode, VarArrayOf([':wayid', ':nodeidx', ':nodeid']), vQryParams); end; procedure TMap.set_onPutFilter(const aFilter: OleVariant); begin FreeAndNil(fOnPutFilter); fOnPutFilter := TPutFilterAdaptor.create(aFilter); end; procedure TMap.set_storage(const newStorage: OleVariant); begin fQryPutNode := unassigned; fQryPutWay := unassigned; fQryPutWayNode := unassigned; fQryPutRelation := unassigned; fQryPutRelationMember := unassigned; fQryPutObjTag := unassigned; fQryDeleteNode := unassigned; fQryDeleteWay := unassigned; fQryDeleteRelation := unassigned; fQryGetNode := unassigned; fQryGetWay := unassigned; fQryGetWayNodes := unassigned; fQryGetRelation := unassigned; fQryGetRelationMembers := unassigned; inherited set_storage(newStorage); end; { TMapObject } function TMapObject.get_changeset: int64; begin result := fChangeset; end; function TMapObject.get_id: int64; begin result := fId; end; function TMapObject.get_tags: OleVariant; var tg:TTags; begin tg:=TTags.create(); tg.fMapObj:=self; _AddRef(); result := tg as IDispatch; end; function TMapObject.get_timestamp: WideString; begin result := timeStampToWideString(fTimeStamp); end; function TMapObject.get_userId: integer; begin result := fUserId; end; function TMapObject.get_userName: WideString; begin result := fUserName; end; function TMapObject.get_version: integer; begin result := fVersion; end; procedure TMapObject.set_changeset(const newChangeset: int64); begin fChangeset := newChangeset; end; procedure TMapObject.set_id(const newId: int64); begin fId := newId; end; procedure TMapObject.set_tags(const newTags: OleVariant); var nt:OleVariant; i:integer; begin nt:=varFromJsObject(newTags.getAll()); if(VarIsArray(nt)) then begin i:=varArrayLength(nt); if(odd(i)) then i:=0;//should be even length setLength(fTags,i); while(i>0)do begin dec(i); fTags[i]:=nt[i]; end; end; end; procedure TMapObject.set_timestamp(const newTimeStamp: WideString); begin assert(length(newTimeStamp)=length('2005-07-05T07:18:37Z'),'TMapObject.set_timestamp:Invalid timestamp '+newTimeStamp); fTimeStamp := wideStringToTimeStamp(newTimeStamp); end; procedure TMapObject.set_userId(const newUserId: integer); begin fUserId := newUserId; end; procedure TMapObject.set_userName(const newUserName: WideString); begin fUserName := newUserName; end; procedure TMapObject.set_version(const newVersion: integer); begin fVersion := newVersion; end; { TTags } procedure TTags.deleteByKey(const key: WideString); var i: integer; fTags: TWideStringArray; begin fTags:=fMapObj.fTags; for i := 0 to count - 1 do if fTags[i*2] = key then begin deleteById(i); break; end; end; procedure TTags.deleteById(const id: integer); var i: integer; fTags: TWideStringArray; begin fTags:=fMapObj.fTags; if (id < 0) or (id >= count) then raise ERangeError.create(toString() + '.deteteById: id out of bounds'); for i := id*2 to high(fTags)-2 do begin fTags[i] := fTags[i + 2]; end; setLength(fMapObj.fTags,length(fTags)-2); end; function TTags.get_count: integer; begin result := length(fMapObj.fTags) div 2; end; function TTags.getAll: OleVariant; var pk: PVariant; i: integer; fTags: TWideStringArray; begin fTags:=fMapObj.fTags; result := VarArrayCreate([0, count * 2 - 1], varVariant); pk := VarArrayLock(result); try for i := 0 to high(fTags) do begin pk^ := fTags[i]; inc(pk); end; finally VarArrayUnlock(result); end; end; function TTags.getByKey(const key: WideString): WideString; var i: integer; fTags: TWideStringArray; begin fTags:=fMapObj.fTags; result := ''; for i := 0 to count-1 do begin if key = fTags[i*2] then begin result := fTags[i*2+1]; break; end; end; end; function TTags.getKey(const id: integer): WideString; begin if (id >= count) or (id < 0) then raise ERangeError.create(toString() + '.getKey: index out of range'); result := fMapObj.fTags[id*2]; end; function TTags.getValue(const id: integer): WideString; begin if (id >= count) or (id < 0) then raise ERangeError.create(toString() + '.getValue: index out of range'); result := fMapObj.fTags[id*2+1]; end; function TTags.hasKey(const key: WideString): WordBool; var i: integer; fTags: TWideStringArray; begin fTags:=fMapObj.fTags; result := false; for i := 0 to count-1 do if key = fTags[i*2] then begin result := true; break; end; end; procedure TTags.setAll(const kvArray: OleVariant); var i, l: integer; a: OleVariant; pv1: POleVariant; fTags: TWideStringArray; begin a := varFromJsObject(kvArray); if (VarArrayDimCount(a) <> 1) or odd(varArrayLength(a)) then raise ERangeError.create(toString() + '.setAll: need even-length array'); l := varArrayLength(a); setLength(fMapObj.fTags,l); fTags:=fMapObj.fTags; pv1 := VarArrayLock(a); try for i := 0 to l - 1 do begin fTags[i]:=pv1^; inc(pv1); end; finally VarArrayUnlock(a); end; end; procedure TTags.setByKey(const key, value: WideString); var i: integer; fTags: TWideStringArray; begin fTags:=fMapObj.fTags; for i := 0 to count - 1 do begin if key = fTags[i*2] then begin fTags[i*2+1] := value; exit; end; end; setLength(fMapObj.fTags,length(fTags)+2); fTags:=fMapObj.fTags; fTags[high(fTags) - 1] := key; fTags[high(fTags)] := value; end; procedure TTags.setKey(const id: integer; const key: WideString); begin if (id >= count) or (id < 0) then raise ERangeError.create(toString() + '.setKey: index out of range'); fMapObj.fTags[id*2] := key; end; procedure TTags.setValue(const id: integer; const value: WideString); begin if (id >= count) or (id < 0) then raise ERangeError.create(toString() + '.setValue: index out of range'); fMapObj.fTags[id*2+1] := value; end; destructor TTags.destroy; begin if assigned(fMapObj) then begin fMapObj._release(); fMapObj:=nil; end; inherited; end; { TNode } function TNode.get_lat: double; begin result := intToDeg(fLat); end; function TNode.get_lon: double; begin result := intToDeg(fLon); end; procedure TNode.set_lat(const value: double); begin if (value > 91) or (value < -91) then raise ERangeError.create(toString() + '.set_lat: lat out of range'); fLat := degToInt(value); end; procedure TNode.set_lon(const value: double); begin if (value > 181) or (value < -181) then raise ERangeError.create(toString() + '.set_lon: lon out of range'); fLon := degToInt(value); end; { TWay } function TWay.get_nodes: OleVariant; var i: integer; pv: PVarData; pi: PInt64; begin i := length(fNodes); result := VarArrayCreate([0, i - 1], varVariant); if i > 0 then begin pi := @fNodes[0]; pv := VarArrayLock(result); try while i > 0 do begin pv^.VType := varInt64; pv^.VInt64 := pi^; inc(pi); inc(pv); dec(i); end; finally VarArrayUnlock(result); end; end; end; procedure TWay.set_nodes(const newNodes: OleVariant); var i: integer; pv: PVarData; pi: PInt64; v: OleVariant; begin v := varFromJsObject(newNodes); if (VarArrayDimCount(v) <> 1) or ((VarType(v) and varTypeMask) <> varVariant) then raise EConvertError.create(toString() + '.set_nodes: array of variants expected'); i := VarArrayHighBound(v, 1) - VarArrayLowBound(v, 1) + 1; setLength(fNodes, i); if i > 0 then begin pi := @fNodes[0]; pv := VarArrayLock(v); try while i > 0 do begin pi^ := PVariant(pv)^; inc(pi); inc(pv); dec(i); end; finally VarArrayUnlock(v); end; end; end; { TRelation } constructor TRelation.create; begin inherited; fMembers := unassigned; end; function TRelation.get_members: OleVariant; begin if VarIsEmpty(fMembers) then fMembers := TRefList.create() as IDispatch; result := fMembers; end; procedure TRelation.set_members(const newMembers: OleVariant); begin fMembers := newMembers; end; { TMapObjectStream } constructor TMapObjectStream.create; begin inherited; fOutMode := rtNode; end; destructor TMapObjectStream.destroy; begin set_eos(true); inherited; end; function TMapObjectStream.get_eos: WordBool; begin result := fEOS; end; procedure TMapObjectStream.initialize(const aMap: TMap; const aStorage, aFilter: OleVariant); procedure parseBox(var pv: POleVariant; var idx: integer; cnt: integer); const bboxextra = 2E-7; var n, e, s, w: double; begin if ((idx + 4) >= cnt) then exit; //set pv to north inc(pv); inc(idx); n := pv^ + bboxextra; inc(pv); inc(idx); e := pv^ + bboxextra; inc(pv); inc(idx); s := pv^ - bboxextra; inc(pv); inc(idx); w := pv^ - bboxextra; if fNodeSelectCondition <> '' then fNodeSelectCondition := fNodeSelectCondition + ' OR ' else fNodeSelectCondition := ' WHERE '; fNodeSelectCondition := fNodeSelectCondition + '( (lat BETWEEN ' + intToStr(degToInt(s)) + ' AND ' + intToStr(degToInt(n)) + ') AND ' + '(lon BETWEEN ' + intToStr(degToInt(w)) + ' AND ' + intToStr(degToInt(e)) + ') )'; end; procedure parsePoly(var pv: POleVariant; var idx: integer; cnt: integer); var l: integer; begin if (idx + 1) >= cnt then exit; inc(pv); inc(idx); if varIsType(pv^, varDispatch) and isDispNameExists(pv^, 'isIn') then begin l := length(fBPolies); setLength(fBPolies, l + 1); fBPolies[l] := pv^; end; end; procedure parseClipIncompleteWays(var pv: POleVariant; var idx: integer; cnt: integer); begin fClipIncompleteWays := true; end; procedure parseCustomFilter(var pv: POleVariant; var idx: integer; cnt: integer); var l: integer; begin if (idx + 1) >= cnt then exit; inc(pv); inc(idx); if varIsType(pv^, varDispatch) then begin l := length(fCustomFilters); setLength(fCustomFilters, l + 1); fCustomFilters[l] := TPutFilterAdaptor.create(pv^); end; end; var pv: POleVariant; ws: WideString; i, n: integer; begin if assigned(fMap) then fMap._Release(); fMap := aMap; if assigned(fMap) then fMap._AddRef(); varCopyNoInd(fStorage, aStorage); fClipIncompleteWays := false; //parse filter options if (VarArrayDimCount(aFilter) <> 1) then //no multi-dim or scalar options support exit; n := VarArrayHighBound(aFilter, 1) - VarArrayLowBound(aFilter, 1) + 1; i := 0; pv := VarArrayLock(aFilter); try while (i < n) do begin if varIsType(pv^, varOleStr) then begin ws := pv^; if (ws <> '') and (ws[1] = ':') then begin if (ws = ':bbox') then begin //parse bbox n,e,s,w parameters parseBox(pv, i, n); end else if (ws = ':bpoly') then begin parsePoly(pv, i, n); end else if (ws = ':clipIncompleteWays') then begin parseClipIncompleteWays(pv, i, n); end else if (ws = ':customFilter') then begin parseCustomFilter(pv, i, n); end; end; end; inc(pv); inc(i); end; finally VarArrayUnlock(aFilter) end; end; function TMapObjectStream.read(const maxBufSize: integer): OleVariant; var i: integer; pv: PVariant; begin if (maxBufSize <= 0) or eos then result := unassigned else if maxBufSize = 1 then result := read1 else begin result := VarArrayCreate([0, maxBufSize - 1], varVariant); pv := VarArrayLock(result); i := 0; try while (i < maxBufSize) and not eos do begin pv^ := read1; if varIsType(pv^, varDispatch) then begin inc(pv); inc(i); end; end; finally VarArrayUnlock(result); end; if i < maxBufSize then VarArrayRedim(result, i - 1); end; end; function TMapObjectStream.read1: OleVariant; procedure addNodeToList(const nodeId: int64); begin fNodeList.add(nodeId); end; procedure addWayToList(const wayId: int64); begin fWayList.add(wayId); end; procedure addRelToList(const relId: int64); begin fRelList.add(relId); end; procedure addToDoList(const memArray: OleVariant); var pv: POleVariant; n: integer; id: int64; begin n := varArrayLength(memArray) div 3; pv := VarArrayLock(memArray); try while (n > 0) do begin dec(n); if pv^ <> 'relation' then begin inc(pv, 3); continue; end; inc(pv); id := pv^; inc(pv, 2); fToDoRelList.add(id); end; finally VarArrayUnlock(memArray); end; end; function checkNodeFilter(aNode: OleVariant): boolean; var i, l: integer; v: OleVariant; begin l := length(fBPolies); result := l = 0; //check bpolies (OR short eval) for i := 0 to l - 1 do begin if fBPolies[i].isIn(aNode) then begin if (i > 0) then begin v := fBPolies[i]; fBPolies[i] := fBPolies[i - 1]; fBPolies[i - 1] := v; end; result := true; break; end; end; if not result then exit; //check custom filters (AND short eval) l := length(fCustomFilters); for i := 0 to l - 1 do begin if not fCustomFilters[i].onPutNode(aNode) then begin result := false; break; end; end; end; function checkWayFilter(const aWay: Variant): boolean; //returns true if length(node-list)>=2 function clipWay(const aWay: Variant): boolean; var nodes: Variant; pvs, pvt: PVariant; n, i, cnt: integer; nid: int64; begin nodes := aWay.nodes; n := varArrayLength(nodes); cnt := 0; i := n; pvs := VarArrayLock(nodes); pvt := pvs; try while i > 0 do begin nid := pvs^; if fNodeList.isIn(nid) then begin if pvt <> pvs then pvt^ := pvs^; inc(pvt); inc(cnt); end; inc(pvs); dec(i); end; finally VarArrayUnlock(nodes); end; if n <> cnt then begin VarArrayRedim(nodes, cnt - 1); aWay.nodes := nodes; end; result := cnt >= 2; end; var i: integer; begin if fClipIncompleteWays then result := clipWay(aWay) else result := true; if not result then exit; for i := 0 to high(fCustomFilters) do begin if not fCustomFilters[i].onPutWay(aWay) then begin result := false; break; end; end; end; function checkRelationFilter(aRelation: OleVariant): boolean; var i, l: integer; begin result := true; //check custom filters (AND short eval) l := length(fCustomFilters); for i := 0 to l - 1 do begin if not fCustomFilters[i].onPutRelation(aRelation) then begin result := false; break; end; end; end; var id: int64; resultValid: boolean; begin result := unassigned; resultValid := false; if VarIsEmpty(fNodeList) then fNodeList := fStorage.createIdList(); if VarIsEmpty(fWayList) then fWayList := fStorage.createIdList(); if VarIsEmpty(fRelList) then fRelList := fStorage.createIdList(); if VarIsEmpty(fToDoRelList) then fToDoRelList := fStorage.createIdList(); repeat case fOutMode of rtNode: begin if VarIsEmpty(fQry) then begin fQry := fStorage.sqlPrepare('SELECT id AS id FROM nodes ' + fNodeSelectCondition); fQry := fStorage.sqlExec(fQry, 0, 0); end; if not fQry.eos then begin id := fQry.read(1)[0]; result := fMap.getNode(id); if checkNodeFilter(result) then begin addNodeToList(id); resultValid := true; end; end else begin fQry := fStorage.sqlPrepare( 'INSERT OR IGNORE INTO ' + fToDoRelList.tableName + '(id) ' + 'SELECT relationid FROM relationmembers ' + 'WHERE memberid IN (SELECT id FROM ' + fNodeList.tableName + ') AND ' + '(memberidxtype & 3)=0' ); fStorage.sqlExec(fQry, 0, 0); fQry := unassigned; fOutMode := rtWay; end; end; rtWay: begin if VarIsEmpty(fQry) then begin fQry := fStorage.sqlPrepare('SELECT DISTINCT(wayid) AS id FROM waynodes ' + 'WHERE waynodes.nodeid IN (' + 'SELECT id FROM ' + fNodeList.tableName + ')'); fQry := fStorage.sqlExec(fQry, 0, 0); end; if not fQry.eos then begin id := fQry.read(1)[0]; result := fMap.getWay(id); if checkWayFilter(result) then begin addWayToList(id); resultValid := true; end; end else begin fQry := fStorage.sqlPrepare( 'INSERT OR IGNORE INTO ' + fToDoRelList.tableName + '(id) ' + 'SELECT relationid FROM relationmembers ' + 'WHERE memberid IN (SELECT id FROM ' + fWayList.tableName + ') AND ' + '(memberidxtype & 3)=1' ); fStorage.sqlExec(fQry, 0, 0); fQry := unassigned; fOutMode := rtRelation; end; end; rtRelation: begin if VarIsEmpty(fQry) then begin fQry := fStorage.sqlPrepare('SELECT id FROM ' + fToDoRelList.tableName + ' '); fQry := fStorage.sqlExec(fQry, 0, 0); end; if not fQry.eos then begin id := fQry.read(1)[0]; result := fMap.getRelation(id); addRelToList(id); if varIsType(result, varDispatch) and checkRelationFilter(result) then begin addToDoList(result.members.getAll()); resultValid := true; end; if fQry.eos then begin fQry := fStorage.sqlPrepare( 'INSERT OR IGNORE INTO ' + fToDoRelList.tableName + '(id) ' + 'SELECT relationid FROM relationmembers ' + 'WHERE memberid IN (SELECT id FROM ' + fRelList.tableName + ') AND ' + '(memberidxtype & 3)=2' ); fStorage.sqlExec(fQry, 0, 0); fQry := fStorage.sqlPrepare('DELETE FROM ' + fToDoRelList.tableName + ' WHERE id IN (SELECT id FROM ' + fRelList.tableName + ')'); fStorage.sqlExec(fQry, 0, 0); fQry := unassigned; end; end else begin fOutMode := rtNode; set_eos(true); resultValid := true; end; end; else raise EInOutError.create(toString() + '.read1: unknown output mode'); end; until resultValid; end; procedure TMapObjectStream.set_eos(const aEOS: boolean); var i: integer; begin if aEOS and not fEOS then begin fNodeList := unassigned; fWayList := unassigned; fRelList := unassigned; fToDoRelList := unassigned; for i := 0 to high(fCustomFilters) do FreeAndNil(fCustomFilters[i]); setLength(fCustomFilters, 0); setLength(fBPolies, 0); fQry := unassigned; fStorage := unassigned; if assigned(fMap) then fMap._Release(); fMap := nil; end; fEOS := fEOS or aEOS; end; { TAbstractMap } function TAbstractMap.createNode: IDispatch; begin result := TNode.create(); end; function TAbstractMap.createRelation: IDispatch; begin result := TRelation.create(); end; function TAbstractMap.createWay: IDispatch; begin result := TWay.create(); end; function TAbstractMap.getMultiObjects(const ObjType: AnsiString; objIdArray: Variant): OleVariant; type TObjGetter=function (const id: int64): OleVariant of object; var i:integer; pv,pv2:PVariant; narr:Variant; getter:TObjGetter; begin if ObjType='Node' then getter:=getNode else if ObjType='Way' then getter:=getWay else if ObjType='Relation' then getter:=getRelation else raise ERangeError.Create(toString()+'.getMultiObjects: invalid object type '+ObjType); if not VarIsType(fStorage, varDispatch) then raise EInOutError.create(toString() + '.get'+ObjType+'s: storage not assigned'); narr := varFromJsObject(objIdArray); if (VarArrayDimCount(narr) <> 1) then raise EInOutError.create(toString() + '.get'+ObjType+'s: one dimension array expected'); i:=varArrayLength(narr); result:=varArrayCreate([0,i-1],varVariant); pv2:=varArrayLock(narr); pv:=varArrayLock(result); try while i > 0 do begin dec(i); varCopyNoInd(pv^,getter(pv2^)); if not varIsType(pv^,varDispatch) then i:=-1; inc(pv); inc(pv2); end; finally varArrayUnlock(result); varArrayUnlock(narr); end; if(i=-1) then result:=varArrayOf([]); end; function TAbstractMap.getNodes(const nodeIdArray: OleVariant): OleVariant; begin result:=getMultiObjects('Node',nodeIdArray); end; function TAbstractMap.getRelations( const relationIdArray: OleVariant): OleVariant; begin result:=getMultiObjects('Relation',relationIdArray); end; function TAbstractMap.getWays(const wayIdArray: OleVariant): OleVariant; begin result:=getMultiObjects('Way',wayIdArray); end; function TAbstractMap.get_storage: OleVariant; begin result := fStorage; end; procedure TAbstractMap.putObject(const aObj: OleVariant); var s: WideString; begin s := aObj.getClassName(); if s = 'Node' then putNode(aObj) else if s = 'Way' then putWay(aObj) else if s = 'Relation' then putRelation(aObj) else raise EConvertError.create(toString() + '.putObject: unknown class "' + s + '"'); end; procedure TAbstractMap.set_storage(const newStorage: OleVariant); begin varCopyNoInd(fStorage, newStorage); end; initialization uModule.OSManRegister(TMap, mapClassGuid); end.
{----------------------------------------------------------------------------- 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvAnimTitle.PAS, released on 2001-02-28. The Initial Developer of the Original Code is Sébastien Buysse [sbuysse att buypin dott com] Portions created by Sébastien Buysse are Copyright (C) 2001 Sébastien Buysse. All Rights Reserved. Contributor(s): Michael Beck [mbeck att bigfoot dott com]. You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvAnimTitle.pas 13104 2011-09-07 06:50:43Z obones $ unit JvAnimTitle; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} Classes, Controls, ExtCtrls, Forms, JvComponentBase; type {$IFDEF RTL230_UP} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32)] {$ENDIF RTL230_UP} TJvAnimTitle = class(TJvComponent) private FTimer: TTimer; FEnabled: Boolean; FTitle: string; FCurrentTitle: string; FDelay: Integer; FSens: Boolean; FForm: TCustomForm; FBlink: Integer; FBlinked: Integer; FBlinking: Boolean; procedure SetTitle(const NewTitle: string); procedure SetEnabled(NewEnable: Boolean); procedure SetDelay(NewDelay: Integer); procedure AnimateTitle(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Title: string read FTitle write SetTitle; property Enabled: Boolean read FEnabled write SetEnabled default False; property Delay: Integer read FDelay write SetDelay default 50; property Blink: Integer read FBlink write FBlink default 5; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvAnimTitle.pas $'; Revision: '$Revision: 13104 $'; Date: '$Date: 2011-09-07 08:50:43 +0200 (mer. 07 sept. 2011) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation constructor TJvAnimTitle.Create(AOwner: TComponent); begin inherited Create(AOwner); FEnabled := False; FDelay := 50; FBlink := 5; FForm := GetParentForm(TControl(AOwner)); FTitle := FForm.Caption; FSens := True; FBlinking := False; FBlinked := 0; FTimer := TTimer.Create(Self); FTimer.Enabled := FEnabled; FTimer.Interval := FDelay; FTimer.OnTimer := AnimateTitle; end; destructor TJvAnimTitle.Destroy; begin FTimer.Free; if not (csDestroying in FForm.ComponentState) then FForm.Caption := FTitle; inherited Destroy; end; procedure TJvAnimTitle.AnimateTitle(Sender: TObject); begin if FBlinking then begin // (rom) this is a bad implementation better try to manipulate // (rom) the WM_GETTEXT and WM_SETTEXT to the Form window if FForm.Caption = Title then FForm.Caption := '' else begin FForm.Caption := Title; Inc(FBlinked); if FBlinked >= Blink then begin FBlinking := False; FBlinked := 0; end; end; end else begin if FSens then begin if Length(FCurrentTitle) = Length(Title) then begin FSens := False; if Blink > 0 then FBlinking := True; end else FCurrentTitle := FCurrentTitle + Title[Length(FCurrentTitle) + 1]; end else if FCurrentTitle = '' then FSens := True else SetLength(FCurrentTitle, Length(FCurrentTitle) - 1); {$IFDEF UNIX} if FCurrentTitle = '' then FForm.Caption := ' ' // else caption becomes <1> else {$ENDIF UNIX} FForm.Caption := FCurrentTitle; end; end; procedure TJvAnimTitle.SetTitle(const NewTitle: string); begin FTitle := NewTitle; FCurrentTitle := ''; FSens := True; end; procedure TJvAnimTitle.SetEnabled(NewEnable: Boolean); begin FEnabled := NewEnable; FTimer.Enabled := FEnabled; end; procedure TJvAnimTitle.SetDelay(NewDelay: Integer); begin FDelay := NewDelay; FTimer.Interval := FDelay; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls; type TSpyForm = class(TForm) sbSelectColor: TSpeedButton; sbAbout: TSpeedButton; ColorView: TShape; labColor: TLabel; eColor: TEdit; labRed: TLabel; bev1: TBevel; labGreen: TLabel; labBlue: TLabel; eRed: TEdit; eGreen: TEdit; eBlue: TEdit; ColorDialog: TColorDialog; procedure sbAboutClick(Sender: TObject); procedure sbSelectColorClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var SpyForm: TSpyForm; implementation {$R *.dfm} uses About; procedure TSpyForm.sbAboutClick(Sender: TObject); begin AboutForm.ShowModal; end; procedure TSpyForm.sbSelectColorClick(Sender: TObject); var col : TColor; ec : Word; r, g, b : Byte; begin if ColorDialog.Execute then begin col := ColorDialog.Color; r := Round(GetRValue(col) / 255 * $1F); g := Round(GetGValue(col) / 255 * $3F); b := Round(GetBValue(col) / 255 * $1F); ec := b or (g shl 5) or (r shl 11); eColor.Text := '$' + IntToHex(ec, 4); eRed.Text := '$' + IntToHex(r, 2); eGreen.Text := '$' + IntToHex(g, 2); eBlue.Text := '$' + IntToHex(b, 2); ColorView.Brush.Color := col; end; end; end.
unit BaseForm; interface uses Forms, Controls, StdCtrls, Classes, Windows; type TBaseForm = class (TForm) protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Loaded; override; end; implementation { TBaseForm } procedure TBaseForm.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin if not ((ActiveControl is TComboBox) and TComboBox(ActiveControl).DroppedDown) then begin ModalResult := mrCancel; end; end; inherited; end; procedure TBaseForm.Loaded; begin inherited; KeyPreview := True; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { RdeEM LongInt } { 大數單元 } { ver 1.21 } { } { Copyright(c) 2018-2019 Reniasty de El Magnifico } { 天道玄虛 出品 } { All rights reserved } { 保留所有權利 } { } {*******************************************************} unit RdeEM.LongInt; interface uses System.Classes, System.SysUtils, System.UITypes, System.Generics.Collections, System.Math; type EZeroError = class(Exception); EPowerError = class(Exception); TLongInt = record private FSymb: Boolean; // True-正數,False-負數; FNumL: TArray<Boolean>; // function IsZero: Boolean; function AbstractValue: TLongInt; // 基本四則運算 class function OriAdd(LongIntA, LongIntB: TLongInt): TLongInt; static; // 符號由A定 class function OriSubtract(LongIntA, LongIntB: TLongInt): TLongInt; static; // 限絕對值A大於B,符號由A定 class function OriMultiply(LongIntA, LongIntB: TLongInt): TLongInt; static; public // 比較運算 class operator Equal(LongIntA, LongIntB: TLongInt): Boolean; class operator NotEqual(LongIntA, LongIntB: TLongInt): Boolean; class operator LessThan(LongIntA, LongIntB: TLongInt): Boolean; class operator GreaterThan(LongIntA, LongIntB: TLongInt): Boolean; class operator LessThanOrEqual(LongIntA, LongIntB: TLongInt): Boolean; class operator GreaterThanOrEqual(LongIntA, LongIntB: TLongInt): Boolean; // 移位運算 class operator LeftShift(LongIntA: TLongInt; IntB: Integer): TLongInt; class operator RightShift(LongIntA: TLongInt; IntB: Integer): TLongInt; // 按位運算,運算結果均取正值 class operator LogicalNot(LongIntA: TLongInt): TLongInt; class operator LogicalAnd(LongIntA, LongIntB: TLongInt): TLongInt; class operator LogicalOr(LongIntA, LongIntB: TLongInt): TLongInt; class operator LogicalXor(LongIntA, LongIntB: TLongInt): TLongInt; // 正負運算 class operator Negative(LongIntA: TLongInt): TLongInt; class operator Positive(LongIntA: TLongInt): TLongInt; // 四則運算 class operator Add(LongIntA, LongIntB: TLongInt): TLongInt; class operator Subtract(LongIntA, LongIntB: TLongInt): TLongInt; class operator Multiply(LongIntA, LongIntB: TLongInt): TLongInt; // 其餘方法 class function Create: TLongInt; static; end; implementation { TLongInt } class operator TLongInt.LogicalAnd(LongIntA, LongIntB: TLongInt): TLongInt; var l, m, n, i: Integer; a, b: Boolean; begin m := Length(LongIntA.FNumL); n := Length(LongIntB.FNumL); if n < m then begin l := m; end else begin l := n; end; with Result do if l = 0 then begin FSymb := True; SetLength(FNumL, 1); FNumL[0] := False; end else begin FSymb := True; SetLength(FNumL, l); for i := 0 to l - 1 do begin if i >= m then begin a := False; end else begin a := LongIntA.FNumL[i]; end; if i >= n then begin b := False; end else begin b := LongIntB.FNumL[i]; end; FNumL[i] := a and b; end; end; end; class operator TLongInt.LogicalNot(LongIntA: TLongInt): TLongInt; var i, l: Integer; begin l := Length(LongIntA.FNumL); with Result do if l = 0 then begin FSymb := True; SetLength(FNumL, 1); FNumL[0] := False; end else begin FSymb := True; SetLength(FNumL, l); for i := 0 to l - 1 do begin FNumL[i] := not FNumL[i]; end; end; end; class operator TLongInt.LogicalOr(LongIntA, LongIntB: TLongInt): TLongInt; var l, m, n, i: Integer; a, b: Boolean; begin m := Length(LongIntA.FNumL); n := Length(LongIntB.FNumL); if n < m then begin l := m; end else begin l := n; end; with Result do if l = 0 then begin FSymb := True; SetLength(FNumL, 1); FNumL[0] := False; end else begin FSymb := True; SetLength(FNumL, l); for i := 0 to l - 1 do begin if i >= m then begin a := False; end else begin a := LongIntA.FNumL[i]; end; if i >= n then begin b := False; end else begin b := LongIntB.FNumL[i]; end; FNumL[i] := a or b; end; end; end; class operator TLongInt.LogicalXor(LongIntA, LongIntB: TLongInt): TLongInt; var l, m, n, i: Integer; a, b: Boolean; begin m := Length(LongIntA.FNumL); n := Length(LongIntB.FNumL); if n < m then begin l := m; end else begin l := n; end; with Result do if l = 0 then begin FSymb := True; SetLength(FNumL, 1); FNumL[0] := False; end else begin FSymb := True; SetLength(FNumL, l); for i := 0 to l - 1 do begin if i >= m then begin a := False; end else begin a := LongIntA.FNumL[i]; end; if i >= n then begin b := False; end else begin b := LongIntB.FNumL[i]; end; FNumL[i] := a xor b; end; end; end; class operator TLongInt.Multiply(LongIntA, LongIntB: TLongInt): TLongInt; var ALI, BLI, CLI, DLI, XLI, YLI, ZLI: TLongInt; i, n: Integer; S: Boolean; begin if LongIntA.IsZero or LongIntB.IsZero then begin Exit(TLongInt.Create); end; S := not (LongIntA.FSymb xor LongIntB.FSymb); if Length(LongIntA.FNumL) > Length(LongIntB.FNumL) then begin n := (Length(LongIntA.FNumL) + 1) div 2; end else begin n := (Length(LongIntB.FNumL) + 1) div 2; end; SetLength(ALI.FNumL, n); SetLength(BLI.FNumL, n); SetLength(CLI.FNumL, n); SetLength(DLI.FNumL, n); for i := 0 to n - 1 do begin if i < Length(LongIntA.FNumL) then begin BLI.FNumL[i] := LongIntA.FNumL[i]; end else begin BLI.FNumL[i] := False; end; if i < Length(LongIntB.FNumL) then begin DLI.FNumL[i] := LongIntB.FNumL[i]; end else begin DLI.FNumL[i] := False; end; end; for i := n to 2 * n - 1 do begin if i < Length(LongIntA.FNumL) then begin ALI.FNumL[i] := LongIntA.FNumL[i]; end else begin ALI.FNumL[i] := False; end; if i < Length(LongIntB.FNumL) then begin CLI.FNumL[i] := LongIntB.FNumL[i]; end else begin CLI.FNumL[i] := False; end; end; XLI := OriMultiply(ALI, CLI); YLI := OriMultiply(BLI, DLI); ZLI := OriMultiply(ALI - BLI, DLI - CLI) + XLI + YLI; YLI := YLI + (XLI shl n) + (ZLI shl (2 * n)); YLI.FSymb := S; Exit(YLI); end; class operator TLongInt.Negative(LongIntA: TLongInt): TLongInt; begin with Result do begin FSymb := not LongIntA.FSymb; FNumL := Copy(LongIntA.FNumL, 0, Length(LongIntA.FNumL)); end; end; class operator TLongInt.NotEqual(LongIntA, LongIntB: TLongInt): Boolean; begin Exit(not (LongIntA = LongIntB)); end; class function TLongInt.OriAdd(LongIntA, LongIntB: TLongInt): TLongInt; var Car, X, Y: TLongInt; // 分別記録無進位和及僅進位和 begin Result := LongIntA xor LongIntB; Car := (LongIntA and LongIntB) shl 1; while not Car.IsZero do begin X := Result; Y := Car; Result := X xor Y; Car := (X and Y) shl 1; end; Result.FSymb := LongIntA.FSymb; end; class function TLongInt.OriMultiply(LongIntA, LongIntB: TLongInt): TLongInt; var i, n: Integer; A: TLongInt; S: Boolean; begin S := not (LongIntA.FSymb xor LongIntB.FSymb); A := LongIntA.AbstractValue; n := 0; for i := 0 to Length(LongIntB.FNumL) - 1 do if LongIntB.FNumL[i] then begin Result := Result + A shl (i - n); n := i; end; Result.FSymb := S; end; class function TLongInt.OriSubtract(LongIntA, LongIntB: TLongInt): TLongInt; var Car, X, Y: TLongInt; // 分別記録無進位差及僅借位差 begin if LongIntA <= LongIntB then begin Result := TLongInt.Create; end else begin Result := LongIntA xor LongIntB; Car := (not LongIntA and LongIntB) shl 1; while not Car.IsZero do begin X := Result; Y := Car; Result := X xor Y; Car := (not X and Y) shl 1; end; Result.FSymb := LongIntA.FSymb; end; end; class operator TLongInt.Positive(LongIntA: TLongInt): TLongInt; begin with Result do begin FSymb := LongIntA.FSymb; FNumL := Copy(LongIntA.FNumL, 0, Length(LongIntA.FNumL)); end; end; function TLongInt.AbstractValue: TLongInt; begin Result.FSymb := True; Result.FNumL := Copy(FNumL, 0, Length(FNumL)); end; class operator TLongInt.Add(LongIntA, LongIntB: TLongInt): TLongInt; begin if LongIntA.IsZero then begin Exit(+ LongIntB); end; if LongIntB.IsZero then begin Exit(+ LongIntA); end; if LongIntA.FSymb xor LongIntB.FSymb then begin Exit(LongIntA - (- LongIntB)); end else begin Exit(OriAdd(LongIntA, LongIntB)); end; end; class function TLongInt.Create: TLongInt; begin with Result do begin FSymb := True; SetLength(FNumL, 1); FNumL[0] := False; end; end; class operator TLongInt.Equal(LongIntA, LongIntB: TLongInt): Boolean; var l, n, m, i: Integer; a, b: Boolean; begin if LongIntA.IsZero and LongIntB.IsZero then begin Exit(True); end; if LongIntA.FSymb xor LongIntB.FSymb then begin Exit(False); end; m := Length(LongIntA.FNumL); n := Length(LongIntB.FNumL); if m < n then begin l := n; end else begin l := m; end; for i := 0 to l - 1 do begin if i >= m then begin a := False; end else begin a := LongIntA.FNumL[i]; end; if i >= n then begin b := False; end else begin b := LongIntB.FNumL[i]; end; if a xor b then begin Exit(False); end; end; Exit(True); end; class operator TLongInt.GreaterThan(LongIntA, LongIntB: TLongInt): Boolean; var l, n, m, i: Integer; a, b: Boolean; begin if LongIntA.IsZero and LongIntB.IsZero then begin Exit(False); end; if LongIntA.IsZero then begin Exit(not LongIntB.FSymb); end; if LongIntB.IsZero then begin Exit(LongIntA.FSymb); end; if LongIntA.FSymb xor LongIntB.FSymb then begin Exit(LongIntA.FSymb); end; m := Length(LongIntA.FNumL); n := Length(LongIntB.FNumL); if m < n then begin l := n; end else begin l := m; end; for i := l - 1 downto 0 do begin if i >= m then begin a := False; end else begin a := LongIntA.FNumL[i]; end; if i >= n then begin b := False; end else begin b := LongIntB.FNumL[i]; end; if a xor b then begin Exit(a); end; end; Exit(False); end; class operator TLongInt.GreaterThanOrEqual(LongIntA, LongIntB: TLongInt): Boolean; begin Exit(not (LongIntA < LongIntB)); end; function TLongInt.IsZero: Boolean; var i: Integer; begin if Length(FNumL) = 0 then begin Exit(True); end; for i := 0 to Length(FNumL) - 1 do if FNumL[i] = True then begin Exit(False); end; Exit(True); end; class operator TLongInt.LeftShift(LongIntA: TLongInt; IntB: Integer): TLongInt; var i: Integer; begin with Result do begin SetLength(FNumL, Length(LongIntA.FNumL) + IntB); FSymb := LongIntA.FSymb; for i := 0 to IntB - 1 do begin FNumL[i] := False; end; for i := 0 to Length(LongIntA.FNumL) - 1 do begin FNumL[i + IntB] := LongIntA.FNumL[i]; end; end; end; class operator TLongInt.LessThan(LongIntA, LongIntB: TLongInt): Boolean; var l, n, m, i: Integer; a, b: Boolean; begin if LongIntA.IsZero and LongIntB.IsZero then begin Exit(False); end; if LongIntA.IsZero then begin Exit(LongIntB.FSymb); end; if LongIntB.IsZero then begin Exit(not LongIntA.FSymb); end; if LongIntA.FSymb xor LongIntB.FSymb then begin Exit(LongIntB.FSymb); end; m := Length(LongIntA.FNumL); n := Length(LongIntB.FNumL); if m < n then begin l := n; end else begin l := m; end; for i := l - 1 downto 0 do begin if i >= m then begin a := False; end else begin a := LongIntA.FNumL[i]; end; if i >= n then begin b := False; end else begin b := LongIntB.FNumL[i]; end; if a xor b then begin Exit(b); end; end; Exit(False); end; class operator TLongInt.LessThanOrEqual(LongIntA, LongIntB: TLongInt): Boolean; begin Exit(not (LongIntA > LongIntB)); end; class operator TLongInt.RightShift(LongIntA: TLongInt; IntB: Integer): TLongInt; var i: Integer; begin with Result do if Length(LongIntA.FNumL) <= IntB then begin FSymb := True; SetLength(FNumL, 1); FNumL[0] := False; end else begin SetLength(FNumL, Length(LongIntA.FNumL) - IntB); FSymb := LongIntA.FSymb; for i := IntB to Length(LongIntA.FNumL) - 1 do begin FNumL[i - IntB] := LongIntA.FNumL[i]; end; end; end; class operator TLongInt.Subtract(LongIntA, LongIntB: TLongInt): TLongInt; begin if LongIntA.IsZero then begin Exit(- LongIntB); end; if LongIntB.IsZero then begin Exit(+ LongIntA); end; if LongIntA = LongIntB then begin Exit(TLongInt.Create); end; if LongIntA.FSymb xor LongIntB.FSymb then begin Exit(LongIntA + (- LongIntB)); end; if LongIntA.FSymb then begin if LongIntA > LongIntB then begin Exit(OriSubtract(LongIntA, LongIntB)); end else begin Exit(- OriSubtract(LongIntB, LongIntA)); end; end else begin if LongIntA > LongIntB then begin Exit(OriSubtract(- LongIntB, - LongIntA)); end else begin Exit(- OriSubtract(LongIntA, LongIntB)); end; end; end; end.
unit u7zip; interface uses windows,classes,sysutils,variants,activex, Dokan,DokanWin, sevenzip_ ; function _FindFiles(FileName: LPCWSTR; FillFindData: TDokanFillFindData; // function pointer var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; function _GetFileInformation( FileName: LPCWSTR; var HandleFileInformation: BY_HANDLE_FILE_INFORMATION; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; function _CreateFile(FileName: LPCWSTR; var SecurityContext: DOKAN_IO_SECURITY_CONTEXT; DesiredAccess: ACCESS_MASK; FileAttributes: ULONG; ShareAccess: ULONG; CreateDisposition: ULONG; CreateOptions: ULONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; function _WriteFile(FileName: LPCWSTR; const Buffer; NumberOfBytesToWrite: DWORD; var NumberOfBytesWritten: DWORD; Offset: LONGLONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; function _ReadFile(FileName: LPCWSTR; var Buffer; BufferLength: DWORD; var ReadLength: DWORD; Offset: LONGLONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; function _Mount(param:pwidechar):boolean; stdcall; function _unMount:NTSTATUS; stdcall; implementation var arch:i7zInArchive; guid:tguid; archive:string; debug:boolean=false; procedure log(msg:string;level:byte=0); begin if (level=0) and (debug=false) then exit; {$i-}writeln(msg);{$i+} end; procedure DbgPrint(format: string; const args: array of const); overload; begin //dummy end; procedure DbgPrint(fmt: string); overload; begin //dummy end; function VarToInt(const AVariant: Variant): integer; begin Result := StrToIntDef(Trim(VarToStr(AVariant)), 0); end; function VarToInt64(const AVariant: Variant): int64; begin Result := StrToInt64Def(Trim(VarToStr(AVariant)), 0); end; { ExtractFileDir('C:\Path\Path2') gives 'C:\Path' ExtractFileDir('C:\Path\Path2\') gives 'C:\Path\Path2' ExtractFileDir(ExcludeTrailingBackslash('C:\Path\Path2')) gives 'C:\Path' ExtractFileDir(ExcludeTrailingBackslash('C:\Path\Path2\')) gives 'C:\Path' } //https://stackoverflow.com/questions/10314757/delphi-converting-array-variant-to-string //VT_FILETIME = 64 function _FindFiles(FileName: LPCWSTR; FillFindData: TDokanFillFindData; // function pointer var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; var i:integer; // s:tstream; instream: IInStream; v:OleVariant; findData: WIN32_FIND_DATAW; i64:int64; temp:string; widetemp:widestring; pv:TPropVariant; begin //writeln('findfiles: full path '+FileName); try //the below should/could take place in the _open function if arch=nil then arch:=CreateInArchive(guid,{ExtractFilePath (Application.ExeName )+} '7z-win32.dll' ); with arch do begin OpenFile(Archive); //SetProgressCallback(nil, ProgressCallback); //optional for i := 0 to NumberOfItems - 1 do begin //if (string(filename)<>'\') then if 1=0 then begin // folder\filename if {(pos('\',Itempath[i])>0) and} (filename=extractfiledir('\'+Itempath[i])) then begin // if not ItemIsFolder[i] then findData.dwFileAttributes := FILE_ATTRIBUTE_NORMAL else findData.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY; // widetemp:=extractfilename(Itempath[i]); Move(widetemp[1], findData.cFileName,Length(widetemp)*Sizeof(Widechar)); // inArchive.GetProperty(i,kpidSize,v); if vartype(v)=21 then begin findData.nFileSizeHigh :=LARGE_INTEGER(VarToInt64(v)).HighPart; findData.nFileSizeLow :=LARGE_INTEGER(VarToInt64(v)).LowPart; end;//if vartype(v)=21 then // inArchive.GetProperty(i,kpidCreationTime,v); if vartype(v)=64 then findData.ftCreationTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); inArchive.GetProperty(i,kpidLastAccessTime,v); if vartype(v)=64 then findData.ftLastAccessTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); inArchive.GetProperty(i,kpidLastWriteTime,v); if vartype(v)=64 then findData.ftLastWriteTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); // FillFindData(findData, DokanFileInfo); end;//if (pos('\',Itempath[i])>0) and (filename=extractfiledir('\'+Itempath[i])) then end;//if (string(filename)<>'\') then //if string(filename)='\' then if 1=1 then begin if {(pos('\',Itempath[i])=0) and} (filename=extractfiledir('\'+Itempath[i])) then begin FillChar (findData ,sizeof(findData ),0); // if not ItemIsFolder[i] then findData.dwFileAttributes := FILE_ATTRIBUTE_NORMAL else findData.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY; // widetemp:=extractfilename(Itempath[i]); Move(widetemp[1], findData.cFileName,Length(widetemp)*Sizeof(Widechar)); //Move(Itempath[i][1], findData.cFileName,Length(Itempath[i])*Sizeof(Widechar)); //Move(Itemname[i][1], findData.cFileName,Length(Itemname[i])*Sizeof(Widechar)); // inArchive.GetProperty(i,kpidSize,v); if vartype(v)=21 then begin findData.nFileSizeHigh :=LARGE_INTEGER(VarToInt64(v)).HighPart; findData.nFileSizeLow :=LARGE_INTEGER(VarToInt64(v)).LowPart; end;//if vartype(v)=21 then // try inArchive.GetProperty(i,kpidCreationTime,olevariant(pv)); findData.ftCreationTime:=pv.filetime; //if vartype(v)=64 then findData.ftCreationTime :=_filetime(TvarData( V ).VInt64 ); //WriteFiletime(TvarData( V ).VInt64); inArchive.GetProperty(i,kpidLastAccessTime,olevariant(pv)); findData.ftLastAccessTime:=pv.filetime; //if vartype(v)=64 then findData.ftLastAccessTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); inArchive.GetProperty(i,kpidLastWriteTime,olevariant(pv)); findData.ftLastWriteTime :=pv.filetime; //if vartype(v)=64 then findData.ftLastWriteTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); except on e:exception do log('_FindFiles:'+e.message,1); end; //check varcast //i64:=varastype(v,64); // FillFindData(findData, DokanFileInfo); end;// if (pos('\',Itempath[i])=0) then end;//if string(filename)='\' then end;//for i := 0 to NumberOfItems - 1 do end;//with arch do Result := STATUS_SUCCESS; except on e:exception do log(e.Message,1 ); end; end; function filename_to_index(filename:string):integer; var i:integer; begin result:=-1; // try for i := 0 to arch.NumberOfItems - 1 do begin if '\'+ arch.ItemPath [i]=filename then begin result:=i; break; end; //if arch.ItemPath [i]=filename then end; //for i := 0 to arch.NumberOfItems - 1 do except on e:exception do log(e.message,1); end; end; function _ReadFile(FileName: LPCWSTR; var Buffer; BufferLength: DWORD; var ReadLength: DWORD; Offset: LONGLONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; var stream:tmemorystream; //tstream does not have a seek function i:integer; begin if WideCharToString(filename)='\' then exit; log('_ReadFile:'+FileName+' '+inttostr(BufferLength)+'@'+inttostr(Offset)); //writeln(DokanFileInfo.context); //later ... if arch=nil then exit; i:=filename_to_index(filename); if i=-1 then exit; try stream := tmemorystream.create( ); //stream.SetSize(BufferLength); //the whole file will be read by extractitem ... :( arch.ExtractItem(i,stream,false); stream.Position :=offset; //we could read junks by junks to emulate a seek ReadLength:=stream.read(buffer,BufferLength); stream.free; Result := STATUS_SUCCESS; except on e:exception do log('_ReadFile:'+e.message,1); end; end; function _WriteFile(FileName: LPCWSTR; const Buffer; NumberOfBytesToWrite: DWORD; var NumberOfBytesWritten: DWORD; Offset: LONGLONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; var dummy:string; begin //writeln('WriteFile: '+ FileName+' '+inttostr(NumberOfBytesToWrite)+'@'+inttostr(Offset) ); Result := STATUS_SUCCESS; end; function _GetFileInformation( FileName: LPCWSTR; var HandleFileInformation: BY_HANDLE_FILE_INFORMATION; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; var error: DWORD; find: WIN32_FIND_DATAW; // path:string; systime_:systemtime; filetime_:filetime; i:integer; v:olevariant; pv:TPropVariant; begin result:=STATUS_NO_SUCH_FILE; //writeln('_GetFileInformation:'+FileName); path := WideCharToString(filename); //root folder need to a success result + directory attribute... if path='\' then begin HandleFileInformation.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY; Result := STATUS_SUCCESS; exit; end; if arch=nil then exit; i:=filename_to_index(WideCharToString(filename)); if i=-1 then begin log('_GetFileInformation:'+filename+ ' no such file',1); exit; end; try fillchar(HandleFileInformation,sizeof(HandleFileInformation),0); // if not arch.ItemIsFolder[i] then HandleFileInformation.dwFileAttributes := FILE_ATTRIBUTE_NORMAL else HandleFileInformation.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY; // arch.inArchive.GetProperty(i,kpidSize,v); if vartype(v)=21 then begin HandleFileInformation.nFileSizeHigh :=LARGE_INTEGER(VarToInt64(v)).HighPart; HandleFileInformation.nFileSizeLow :=LARGE_INTEGER(VarToInt64(v)).LowPart; end;//if vartype(v)=21 then //writeln('kpidSize:'+inttostr(VarToInt64(v) )); // arch.inArchive.GetProperty(i,kpidCreationTime,olevariant(pv)); HandleFileInformation.ftCreationTime:=pv.filetime; //if vartype(v)=64 then findData.ftCreationTime :=_filetime(TvarData( V ).VInt64 ); //WriteFiletime(TvarData( V ).VInt64); arch.inArchive.GetProperty(i,kpidLastAccessTime,olevariant(pv)); HandleFileInformation.ftLastAccessTime:=pv.filetime; //if vartype(v)=64 then findData.ftLastAccessTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); arch.inArchive.GetProperty(i,kpidLastWriteTime,olevariant(pv)); HandleFileInformation.ftLastWriteTime :=pv.filetime; //if vartype(v)=64 then findData.ftLastWriteTime :=_filetime(TvarData( V ).VInt64); //WriteFiletime(TvarData( V ).VInt64); Result := STATUS_SUCCESS; except on e:exception do log(e.message,1); end; end; function _CreateFile(FileName: LPCWSTR; var SecurityContext: DOKAN_IO_SECURITY_CONTEXT; DesiredAccess: ACCESS_MASK; FileAttributes: ULONG; ShareAccess: ULONG; CreateDisposition: ULONG; CreateOptions: ULONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall; var creationDisposition: DWORD; fileAttributesAndFlags: DWORD; genericDesiredAccess: ACCESS_MASK; path:string; i:integer; begin Result := STATUS_SUCCESS; path := WideCharToString(filename); //writeln('CreateFile:'+path); if path='\' then exit; if arch=nil then exit; DokanMapKernelToUserCreateFileFlags( DesiredAccess, FileAttributes, CreateOptions, CreateDisposition, @genericDesiredAccess, @fileAttributesAndFlags, @creationDisposition); i:=filename_to_index(path); if i=-1 then begin log('_CreateFile:'+filename+ ' no such file',1); //this is needed so that files can execute if creationDisposition = CREATE_NEW then result := STATUS_SUCCESS else result:=STATUS_NO_SUCH_FILE; exit; end; //we could re use it in the readfile //and eventually in the close if we want to keep stream opened DokanFileInfo.Context :=i; if not arch.ItemIsFolder[i] then DokanFileInfo.IsDirectory := false else DokanFileInfo.IsDirectory := True; //manage creationdisposition DokanMapKernelToUserCreateFileFlags( DesiredAccess, FileAttributes, CreateOptions, CreateDisposition, @genericDesiredAccess, @fileAttributesAndFlags, @creationDisposition); if (creationDisposition = CREATE_NEW) then begin DbgPrint('\tCREATE_NEW\n'); end else if (creationDisposition = OPEN_ALWAYS) then begin DbgPrint('\tOPEN_ALWAYS\n'); end else if (creationDisposition = CREATE_ALWAYS) then begin DbgPrint('\tCREATE_ALWAYS\n'); end else if (creationDisposition = OPEN_EXISTING) then begin DbgPrint('\tOPEN_EXISTING\n'); end else if (creationDisposition = TRUNCATE_EXISTING) then begin DbgPrint('\tTRUNCATE_EXISTING\n'); end else begin DbgPrint('\tUNKNOWN creationDisposition!\n'); end; end; function _unMount:NTSTATUS; stdcall; begin result:=STATUS_UNSUCCESSFUL; try arch.Close ; result:=STATUS_SUCCESS; except end; //temp hack to avoid badvarianttype error... end; function _Mount(param:pwidechar):boolean; stdcall; var ext:string; begin result:=false; // log('******** proxy loaded ********',1); log('rootdirectory:'+string(widechartostring(param)),1); // guid:=StringToGUID ('{00000000-0000-0000-0000-000000000000}'); ext:=ExtractFileExt(string(widechartostring(param))); if lowercase(ext)='.iso' then guid:=CLSID_CFormatiso; if lowercase(ext)='.wim' then guid:=CLSID_CFormatWim; // guid:=CLSID_CFormatUdf; if lowercase(ext)='.zip' then guid:=CLSID_CFormatzip; if lowercase(ext)='.7z' then guid:=CLSID_CFormat7z; if lowercase(ext)='.cab' then guid:=CLSID_CFormatCab ; //if lowercase(ext)='.vhd' then guid:=CLSID_CFormatvhd; if lowercase(ext)='.wim' then guid:=CLSID_CFormatwim; //if lowercase(ext)='.img' then guid:=CLSID_CFormatmbr; // guid:=CLSID_CFormatNtfs; guid:=CLSID_CFormatFat; if lowercase(ext)='.squashfs' then guid:=CLSID_CFormatsquashfs; if lowercase(ext)='.bz2' then guid:=CLSID_CFormatBZ2; if lowercase(ext)='.rar' then guid:=CLSID_CFormatRar; if lowercase(ext)='.arj' then guid:=CLSID_CFormatArj; if lowercase(ext)='.z' then guid:=CLSID_CFormatZ; if lowercase(ext)='.lzh' then guid:=CLSID_CFormatLzh; if lowercase(ext)='.bkf' then guid:=CLSID_CFormatbkf; if lowercase(ext)='.gz' then guid:=CLSID_CFormatgzip; if lowercase(ext)='.split' then guid:=CLSID_CFormatsplit; if lowercase(ext)='.tar' then guid:=CLSID_CFormattar; if lowercase(ext)='.dmg' then guid:=CLSID_CFormatDmg; if lowercase(ext)='.tar' then guid:=CLSID_CFormatTar; if lowercase(ext)='.cab' then guid:=CLSID_CFormatcab; if lowercase(ext)='.xz' then guid:=CLSID_CFormatxz; if GUIDToString(guid)='{00000000-0000-0000-0000-000000000000}' then begin log('unknown archive',1); exit; end; archive:=string(widechartostring(param)); result:=true; end; end.
{$mode TP} {$codepage UTF-8} {$R+,B+,X-} program T_16_44(input, output); uses heaptrc; type TE = integer; list = ^node; node = record elem: TE; next: list end; Queue = record head: list; tail: list end; var n, t2, t3, t5, min1, min2: integer; Q2, Q3, Q5: Queue; procedure ClearQueue(var Q: Queue); begin Q.head := nil; Q.tail := nil; end; function EmptyQueue(Q: Queue): boolean; begin EmptyQueue := Q.head = nil; end; procedure AddToQueue(var Q: Queue; X: TE); var p: list; begin new(p); p^.elem := X; p^.next := nil; if Q.head = nil then Q.head := p else Q.tail^.next := p; Q.tail := p; end; procedure RemoveFromQueue(var Q: Queue; var X: TE); var p: list; begin P := Q.head; X := p^.elem; Q.head := p^.next; dispose(p); if Q.head = nil then Q.tail := nil; end; procedure Destroy(var Q: Queue); var t: TE; begin while not EmptyQueue(Q) do RemoveFromQueue(Q, t); end; begin writeln('Zyanchurin Igor, 110 group, 17-5v'); write('n = '); readln(n); if n < 1 then writeln else if n = 1 then writeln(2) else if n = 2 then writeln(2, ' ', 3) else begin t2 := 2; t3 := 3; t5 := 5; min1 := 1; ClearQueue(Q2); ClearQueue(Q3); ClearQueue(Q5); while n > 0 do begin if (t2 <= t3) and (t2 <= t5) then begin min2 := t2; AddToQueue(Q2, min2 * 2); AddToQueue(Q3, min2 * 3); AddToQueue(Q5, min2 * 5); RemoveFromQueue(Q2, t2); end else if (t3 <= t2) and (t3 <= t5) then begin min2 := t3; AddToQueue(Q2, min2 * 2); AddToQueue(Q3, min2 * 3); AddToQueue(Q5, min2 * 5); RemoveFromQueue(Q3, t3); end else begin min2 := t5; AddToQueue(Q2, min2 * 2); AddToQueue(Q3, min2 * 3); AddToQueue(Q5, min2 * 5); RemoveFromQueue(Q5, t5); end; if min2 <> min1 then begin write(min2, ' '); min1 := min2; n := n - 1; end; end; destroy(Q2); destroy(Q3); destroy(Q5); writeln end; end.
unit fib.DmMain; interface uses System.SysUtils, System.Classes, FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBQueryVk, Data.DB, FIBDataSet, pFIBDataSet, pFIBDataSetVk, datevk, pFIBDatabaseVk, pFIBProps, vkvariable, Variants, SettingsStorage, Forms, u_xmlinit; type PUserInfo = ^RUserInfo; RUserInfo = Record idgroup :LargeInt; iduser :LargeInt; idmenu :LargeInt; username :string; userpassword :string; g_username :string; g_rolename :string; end; TOnRequest = reference to procedure(AQuery: TpFIBQuery ); TMainDm = class(TDataModule) pFIBDatabaseMain: TpFIBDatabaseVk; pFIBDataSetVk1: TpFIBDataSetVk; pFIBQueryVkSelect: TpFIBQueryVk; pFIBTransactionReadOnly: TpFIBTransaction; pFIBTransactionUpdate: TpFIBTransaction; procedure DataModuleCreate(Sender: TObject); private { Private declarations } FCurrentUser: RUserInfo; FStorage: TSettingsStorage; FXmlIni : TXmlIni; FUsersAccessType: TVkVariableCollection; FUsersAccessValues: TVkVariableCollection; function CheckValidPassword(const aPassword: String): boolean; function CheckRequiredPassword(const aUserName:String):Boolean; function ValidUser(const AUserName, APassword:String):Boolean; procedure DoAfterLogin; procedure InitConstsList(var AVarList: TVkVariableCollection;const ATableName,AIdName:String); procedure InternalPrepareQuery(AUIBQuery:TpFIBQuery;const ASql:String;const AParams: array of variant ); public { Public declarations } function GetRootKey(bCurrentUser:Boolean = true):String; procedure LinkWithDataSet(fib_ds: TpFIBDataSetVk; TrRead, TrUpdate: TpFIBTransaction; aTableName:String; aKeyFields:String; aGenName:String); procedure LinkWithQuery(fib_qr: TpFIBQueryVk; aTr: TpFIBTransaction); function QueryValue(const ASql:String;const AParams: array of variant; ATransaction:TpFIBTransaction = nil):Variant; procedure QueryValues(AVkVariableList: TVkVariableCollection;const ASql:String;const AParams: array of variant; ATransaction:TpFIBTransaction = nil); function login(const userName, password:String):Boolean; function getAliasesList: TVkVariableCollection; function selectAlias: boolean; function GenId(const AID: String): Int64; function GetTypeGroup( AId: LargeInt):LargeInt; procedure DoRequest(const ASql:String;const AParams: array of variant; ATransaction:TpFIBTransaction = nil; AOnRequest: TOnRequest = nil); property XmlInit:TXmlIni read FXmlIni; property CurrentUser:RUserInfo read FCurrentUser; property UsersAccessType: TVkVariableCollection read FUsersAccessType; property UsersAccessValues: TVkVariableCollection read FUsersAccessValues; end; var MainDm: TMainDm; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses FmSelectDbAlias; {$R *.dfm} procedure TMainDm.DataModuleCreate(Sender: TObject); begin pFIBDatabaseMain.SetTransactionReadOnly(pFIBTransactionReadOnly); //pFIBDatabaseMain.SetTransactionConcurency(pFIBTransactionUpdate ); LinkWithQuery(pFIBQueryVkSelect, pFIBTransactionReadOnly); FStorage := TSettingsStorage.Create(ChangeFileExt(Application.ExeName,'.ini')); FStorage.Read; with pFIBDataBaseMain do begin ConnectParams.UserName := 'task'; ConnectParams.Password := 'vksoft123'; ConnectParams.CharSet := 'UTF8'; ConnectParams.RoleName := 'RHOPE'; end; FXmlIni := TXmlIni.Create(self,ChangeFileExt(Application.ExeName,'.xml')); end; procedure TMainDm.DoAfterLogin; begin InitConstsList(FUsersAccessType,'USERSACCESSTYPE','IDUATYPE'); InitConstsList(FUsersAccessValues,'USERSACCESSVALUES','IDUAVALUE'); end; procedure TMainDm.DoRequest(const ASql: String; const AParams: array of variant; ATransaction: TpFIBTransaction; AOnRequest: TOnRequest); var bTransactionOwner: Boolean; begin if not Assigned(AOnRequest) then Raise Exception.Create('ON Request not defined!'); // Assert(AOnRequest,'ON Request not defined!'); with pFIBQueryVkSelect do begin Close(); if Assigned(ATransaction) then Transaction := ATransaction else Transaction := pFIBTRansactionReadOnly; InternalPrepareQuery(pFIBQueryVkSelect,ASql,AParams); // SQL.Clear; // SQL.Text := ASql; bTransactionOwner := not Transaction.InTransaction; if bTransactionOwner then Transaction.StartTransaction; try ExecQuery; { if not Eof then Result := Fields.AsVariant[0] else Result := null;} AOnRequest(pFIBQueryVkSelect); finally if bTransactionOwner then Transaction.Commit; end; end; end; function TMainDm.GenId(const AID: String): Int64; begin Result := CoalEsce(QueryValue(Format('SELECT Gen_Id(%s,1) AS ID FROM RDB$DATABASE',[AId]),[]),0); end; function TMainDm.getAliasesList: TVkVariableCollection; var section: TSettingsStorageItem; begin section := FStorage.GetSection('aliases'); if Assigned(section) then Result := Section.Items else Result := nil; end; function TMainDm.GetRootKey(bCurrentUser: Boolean): String; begin Result := Format('\Software\VK Soft\%s\%d',[Application.ExeName,FCurrentUser.iduser]); end; function TMainDm.GetTypeGroup(AId: LargeInt): LargeInt; var id : LargeInt; begin id := -1; Result := -1; pFIBQueryVkSelect.Close; pFIBQueryVkSelect.SQL.Clear; pFIBQueryVkSelect.SQL.Add('SELECT idgroup, idobject FROM objects WHERE idobject=:idobject'); pFIBQueryVkSelect.ParamByName('idobject').AsInt64 := AId; while id<>0 do begin pFIBQueryVkSelect.ExecQuery; if not pFIBQueryVkSelect.IsEmpty then begin id := pFIBQueryVkSelect.FieldByName('idgroup').AsInt64; if id = 0 then begin Result := pFIBQueryVkSelect.FieldByName('idobject').AsInt64; Break; end else begin pFIBQueryVkSelect.Close; pFIBQueryVkSelect.ParamByName('idobject').AsInt64 := Id; end; end else raise Exception.Create('Error group'); end; pFIBQueryVkSelect.Close; end; procedure TMainDm.InitConstsList(var AVarList: TVkVariableCollection; const ATableName, AIdName: String); begin if Assigned(AVarList) then AVarList.Clear else AVarList := TVkVariableCollection.Create(self); with pFIBQueryVkSelect do begin Close; SQL.Clear; SQL.Add('SELECT * FROM '+ATableName); ExecQuery; try while not Eof do begin AVarList.CreateVkVariable(FieldByName('CONSTNAME').AsString,FieldByName(AIdName).Value); Next; end; finally Close; end; end; end; procedure TMainDm.InternalPrepareQuery(AUIBQuery: TpFIBQuery; const ASql: String; const AParams: array of variant); var i: Integer; begin with AUIBQuery do begin SQL.Clear; SQL.Text := ASql; Prepare(); for I := 0 to ParamCount-1 do Params[i].Value := AParams[i]; end; end; //============================================================= // Основная процедура установки коннекта //============================================================= procedure TMainDm.LinkWithDataSet(fib_ds: TpFIBDataSetVk; TrRead, TrUpdate: TpFIBTransaction; aTableName:String; aKeyFields:String; aGenName:String); begin with fib_ds do begin Database := pFIBDatabaseMain; if Assigned(TrRead) then begin if not Assigned(TrRead.DefaultDatabase) then TrRead.DefaultDatabase := pFIBDatabaseMain; Transaction := TrRead; end else Transaction := pFIBDatabaseMain.GetNewTransactionReadOnly(fib_ds.Owner); if Assigned(TrUpdate) then begin if not Assigned(TrUpdate.DefaultDatabase) then TrUpdate.DefaultDatabase := pFIBDatabaseMain; UpdateTransaction := TrUpdate; end else UpdateTransaction := pFIBDatabaseMain.DefaultUpdateTransaction; AutoUpdateOptions.AutoReWriteSqls := True; AutoUpdateOptions.CanChangeSQLs := True; AutoUpdateOptions.UpdateOnlyModifiedFields := True; if aTableName<>'' then begin AutoUpdateOptions.UpdateTableName := UpperCase(aTableName); AutoUpdateOptions.KeyFields := UpperCase(aKeyFields); if aGenName<> '' then begin AutoUpdateOptions.GeneratorName := UpperCase(aGenName); AutoUpdateOptions.WhenGetGenID := wgBeforePost; end; end; end; end; procedure TMainDm.LinkWithQuery(fib_qr: TpFIBQueryVk; aTr: TpFIBTransaction); begin with fib_qr do begin Database := pFIBDatabaseMain; if Assigned(aTr) then begin if not Assigned(aTr.DefaultDatabase) then aTr.DefaultDatabase := pFIBDatabaseMain; Transaction := aTr; end else Transaction := pFIBDatabaseMain.DefaultTransaction; end; end; function TMainDm.login(const userName, password: String):boolean; begin // if not SelectAlias then // Raise Exception.Create('Не указан путь к базе!'); pFIBDatabaseMain.Connected := true; if not ValidUser(userName, password) then pFIBDatabaseMain.Connected := false; Result := pFIBDatabaseMain.Connected; DoAfterLogin; end; function TMainDm.QueryValue(const ASql: String; const AParams: array of variant; ATransaction: TpFIBTransaction): Variant; var I: Integer; bTransactionOwner: Boolean; begin with pFIBQueryVkSelect do begin Close; if Assigned(ATransaction) then Transaction := ATransaction else Transaction := pFIBDatabaseMain.DefaultTransaction; SQL.Clear; SQL.Add(ASql); for I := 0 to Params.Count-1 do try params[i].Value := AParams[i]; except raise Exception.CreateFmt('Error set param qr2 [%d]',[i]); end; bTransactionOwner := not Transaction.Active; if (bTransactionOwner) then Transaction.StartTransaction; try ExecQuery; if not(Eof or Bof) then Result := Fields[0].Value else Result := null; finally if (bTransactionOwner) then Transaction.Commit; end; end; end; procedure TMainDm.QueryValues(AVkVariableList: TVkVariableCollection; const ASql: String; const AParams: array of variant; ATransaction: TpFIBTransaction); var I: Integer; bTransactionOwner: Boolean; _v: TVkVariable; begin with pFIBQueryVkSelect do begin Close; if Assigned(ATransaction) then Transaction := ATransaction else Transaction := pFIBDatabaseMain.DefaultTransaction; SQL.Clear; SQL.Add(ASql); for I := 0 to Params.Count-1 do try params[i].Value := AParams[i]; except raise Exception.CreateFmt('Error set param qr2 [%d]',[i]); end; bTransactionOwner := not Transaction.Active; if (bTransactionOwner) then Transaction.StartTransaction; try ExecQuery; for I := 0 to FieldCount-1 do begin _v := TVkVariable.Create(AVkvariableList); _v.Name := Fields[i].name; if not(Eof or Bof) then _v.Value := Fields[i].Value else _v.Value := null; end; finally if (bTransactionOwner) then Transaction.Commit; end; end; end; function TMainDm.selectAlias: boolean; const ALIASES = 'aliases'; DBPATH = 'dbpath'; LIBPATH = 'libpath'; var _List: TSettingsStorageItem; _idx: Integer; begin _List := FStorage.GetSection(ALIASES); try //FStorage.ReadSection(DBALIASES,_List); case _List.Items.Count of 0:begin Result := False; end; 1: begin pFIBDatabaseMain.DBName := FStorage.GetVariable(_List.Items.Items[0].name,DBPATH,'').AsString; pFIBDatabaseMain.LibraryName := FStorage.GetVariable(_List.Items.Items[0].Name,LIBPATH,'').AsString; Result := True; end; else begin if ParamCount=3 then begin for _idx := 0 to _List.Items.Count-1 do begin if _List.Items.Items[_idx].name.Equals(ParamStr(3)) then begin break; end; end; end else _idx := TSelectDbAliasFm.SelectAliasIndex(_List.getItemValues); if _Idx>-1 then begin pFIBDatabaseMain.DBName := FStorage.GetVariable(_List.Items.Items[_Idx].name,DBPATH,'').AsString; pFIBDatabaseMain.LibraryName:= FStorage.GetVariable(_List.Items.Items[_Idx].Name,LIBPATH,'').AsString; Result := True; end else Result := False; end; end; finally // _List.Free; end; end; function TMainDm.ValidUser(const AUserName, APassword: String): Boolean; begin Result := False; if Trim(AUserName)='' then begin Raise Exception.Create('Не определенный пользователь!'); Exit; end; try with pFIBQueryVkSelect do begin Close; SQL.Clear; SQL.Add('SELECT ul.*,ug.idmenu FROM userslist ul '); SQL.Add(' INNER JOIN usersgroup ug ON ug.idgroup= ul.idgroup '); SQL.Add(' WHERE UPPER(ul.username)=:username '); ParamByName('username').AsString := UpperCase(AUserName); Transaction.Active := true; try ExecQuery; if not Eof then begin FCurrentUser.idgroup := FieldByName('idgroup').AsInt64; FCurrentUser.iduser := FieldByName('iduser').AsInt64; FCurrentUser.username := FieldByName('username').AsString; FCurrentUser.userpassword := FieldByName('userpassword').AsString; FCurrentUser.idmenu := FieldByName('idmenu').AsInt64; Result := CheckValidPassword(APassword); end; if (FCurrentUser.iduser>0) and Result then begin Close; SQL.Clear; SQL.Add(' SELECT rdb$set_context(:nmsp,:varname,:varval) FROM rdb$database'); ParamByName('nmsp').AsString := 'USER_SESSION'; ParamByName('varname').AsString := 'iduser'; ParamByName('varval').AsString := IntToStr(FCurrentUser.iduser); ExecQuery; Close; end; finally Transaction.Commit; end; end; finally if not Result then Raise Exception.Create('Неверное имя пользователя или пароль.'); end; end; function TMainDm.CheckRequiredPassword(const aUserName: String): Boolean; begin with pFIBQueryVkSelect do begin Close; try Transaction.StartTransaction; SQL.Clear; SQL.Add('SELECT * FROM userslist WHERE UPPER(username)=:username'); ParamByName('username').AsString := AnsiUpperCase(aUserName); ExecQuery; Result := not Eof and (FieldByName('requiredpassword').AsBoolean); finally Close; end; end; end; function TMainDm.CheckValidPassword(const aPassword: String): boolean; var sHashPassword: String; begin sHashPassword := QueryValue(' SELECT CAST(HASH(CAST('''+IntToStr(FCurrentUser.iduser )+aPassword+''' as CHAR(20))) as CHAR(20)) as pwd FROM rdb$database',[]); Result := sHashPassword.trim()= FCurrentUser.userpassword.trim(); end; end.
{ This file is part of the FastPlaz package. (c) Luri Darmawan <luri@fastplaz.com> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. } unit currencyibacor_integration; {$mode objfpc}{$H+} { [x] USAGE with TCurrencyIbacorIntegration.Create do begin Token := 'yourtoken; Result := Converter( 'USD', 'IDR', 1)); Free; end; } interface uses common, http_lib, fpjson, logutil_lib, Classes, SysUtils; type { TCurrencyIbacorIntegration } TCurrencyIbacorIntegration = class private FDebug: boolean; FToken: string; jsonData: TJSONData; public constructor Create; destructor Destroy; override; property Token: string read FToken write FToken; function Converter(FromCurrency, ToCurrency: string; Value: integer): string; published property Debug: boolean read FDebug write FDebug; end; implementation const CURRENCY_IBACOR_URL = 'http://ibacor.com/api/currency-converter?k=%s&view=convert&from=%s&to=%s&amount=%d'; var Response: IHTTPResponse; { TCurrencyIbacorIntegration } constructor TCurrencyIbacorIntegration.Create; begin FDebug := False; end; destructor TCurrencyIbacorIntegration.Destroy; begin if Assigned(jsonData) then jsonData.Free; inherited Destroy; end; function TCurrencyIbacorIntegration.Converter(FromCurrency, ToCurrency: string; Value: integer): string; var _url: string; _http: THTTPLib; _nominalFloat: double; begin Result := ''; if FToken = '' then Exit; _url := Format(CURRENCY_IBACOR_URL, [FToken, FromCurrency, ToCurrency, Value]); _http := THTTPLib.Create(_url); Response := _http.Get; _http.Free; if Response.ResultCode <> 200 then begin LogUtil.Add(Response.ResultText, 'IBACOR'); Result := ''; Exit; end; try jsonData := GetJSON( Response.ResultText); if jsonGetData(jsonData, 'status') = 'success' then begin Result := UpperCase(FromCurrency) + ' ' + i2s(Value) + ' = ' + UpperCase(ToCurrency) + ' '; _nominalFloat:= s2f( jsonGetData(jsonData, 'data/to/amount')); DefaultFormatSettings.ThousandSeparator := '.'; Result := Result + FormatFloat('###,#0', _nominalFloat); end; except on E: Exception do begin Result := ''; if FDebug then begin LogUtil.Add(E.Message, 'IBACOR'); LogUtil.Add(Response.ResultText, 'IBACOR'); end; end; end; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Creation: January 17, 1998 Version: 7.00 Description: This sample program show how to get a document from a webserver and store it to a file. Also display some progress info. EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1997-2010 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Updates: Feb 4, 2011 V7.00 Angus added bandwidth throttling using TCustomThrottledWSocket Demo shows file download duration and speed * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsHttpGet1; {$I OverbyteIcsDefs.inc} {$IFNDEF DELPHI7_UP} Bomb('This sample requires Delphi 7 or later'); {$ENDIF} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OverbyteIcsHttpProt, StdCtrls, OverbyteIcsIniFiles, OverbyteIcsWndControl, OverByteIcsFtpSrvT; type THttpGetForm = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; URLEdit: TEdit; ProxyHostEdit: TEdit; ProxyPortEdit: TEdit; FileNameEdit: TEdit; Label5: TLabel; GetButton: TButton; AbortButton: TButton; InfoLabel: TLabel; HttpCli1: THttpCli; Label10: TLabel; BandwidthLimitEdit: TEdit; procedure GetButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure HttpCli1DocData(Sender: TObject; Buffer: Pointer; Len: Integer); procedure HttpCli1HeaderData(Sender: TObject); procedure AbortButtonClick(Sender: TObject); private { Déclarations privées } FInitialized : Boolean; FIniFileName : String; public { Déclarations publiques } end; var HttpGetForm: THttpGetForm; implementation {$R *.DFM} const SectionData = 'Data'; KeyURL = 'URL'; KeyProxyHost = 'ProxyHost'; KeyProxyPort = 'ProxyPort'; KeyFileName = 'FileName'; SectionWindow = 'Window'; KeyTop = 'Top'; KeyLeft = 'Left'; KeyWidth = 'Width'; KeyHeight = 'Height'; KeyBandwidthLimit = 'BandwidthLimit'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.FormCreate(Sender: TObject); begin FIniFileName := GetIcsIniFileName; InfoLabel.Caption := ''; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.FormShow(Sender: TObject); var IniFile : TIcsIniFile; begin if not FInitialized then begin FInitialized := TRUE; IniFile := TIcsIniFile.Create(FIniFileName); try URLEdit.Text := IniFile.ReadString(SectionData, KeyURL, 'http://www.rtfm.be/fpiette/images/overbyte.gif'); ProxyHostEdit.Text := IniFile.ReadString(SectionData, KeyProxyHost, ''); ProxyPortEdit.Text := IniFile.ReadString(SectionData, KeyProxyPort, '80'); FileNameEdit.Text := IniFile.ReadString(SectionData, KeyFileName, 'test.tmp'); Top := IniFile.ReadInteger(SectionWindow, KeyTop, Top); Left := IniFile.ReadInteger(SectionWindow, KeyLeft, Left); Width := IniFile.ReadInteger(SectionWindow, KeyWidth, Width); Height := IniFile.ReadInteger(SectionWindow, KeyHeight, Height); BandwidthLimitEdit.Text := IniFile.ReadString(SectionData, KeyBandwidthLimit, '1000000'); finally IniFile.Free; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.FormClose(Sender: TObject; var Action: TCloseAction); var IniFile : TIcsIniFile; begin IniFile := TIcsIniFile.Create(FIniFileName); try IniFile.WriteString(SectionData, KeyURL, URLEdit.Text); IniFile.WriteString(SectionData, KeyProxyHost, ProxyHostEdit.Text); IniFile.WriteString(SectionData, KeyProxyPort, ProxyPortEdit.Text); IniFile.WriteString(SectionData, KeyFileName, FileNameEdit.Text); IniFile.WriteInteger(SectionWindow, KeyTop, Top); IniFile.WriteInteger(SectionWindow, KeyLeft, Left); IniFile.WriteInteger(SectionWindow, KeyWidth, Width); IniFile.WriteInteger(SectionWindow, KeyHeight, Height); IniFile.WriteString(SectionData, KeyBandwidthLimit, BandwidthLimitEdit.Text); IniFile.UpdateFile; finally IniFile.Free; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.GetButtonClick(Sender: TObject); var StartTime: Longword; Duration, BytesSec, ByteCount: integer; Temp: string; begin HttpCli1.URL := URLEdit.Text; HttpCli1.Proxy := ProxyHostEdit.Text; HttpCli1.ProxyPort := ProxyPortEdit.Text; HttpCli1.RcvdStream := TFileStream.Create(FileNameEdit.Text, fmCreate); {$IFDEF BUILTIN_THROTTLE} HttpCli1.BandwidthLimit := StrToIntDef(BandwidthLimitEdit.Text, 1000000); if HttpCli1.BandwidthLimit > 0 then HttpCli1.Options := HttpCli1.Options + [httpoBandwidthControl]; {$ENDIF} GetButton.Enabled := FALSE; AbortButton.Enabled := TRUE; InfoLabel.Caption := 'Loading'; try try StartTime := GetTickCount; HttpCli1.Get; Duration := GetTickCount - StartTime; ByteCount := HttpCli1.RcvdStream.Size; Temp := 'Received ' + IntToStr(ByteCount) + ' bytes, '; if Duration < 5000 then Temp := Temp + IntToStr(Duration) + ' milliseconds' else Temp := Temp + IntToStr(Duration div 1000) + ' seconds'; if ByteCount > 32767 then BytesSec := 1000 * (ByteCount div Duration) else BytesSec := (1000 * ByteCount) div Duration; Temp := Temp + ' (' + IntToKByte(BytesSec) + 'bytes/sec)'; InfoLabel.Caption := Temp except on E: EHttpException do begin InfoLabel.Caption := 'Failed : ' + IntToStr(HttpCli1.StatusCode) + ' ' + HttpCli1.ReasonPhrase;; end else raise; end; finally GetButton.Enabled := TRUE; AbortButton.Enabled := FALSE; HttpCli1.RcvdStream.Destroy; HttpCli1.RcvdStream := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.HttpCli1DocData(Sender: TObject; Buffer: Pointer; Len: Integer); begin InfoLabel.Caption := IntToStr(HttpCli1.RcvdCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.HttpCli1HeaderData(Sender: TObject); begin InfoLabel.Caption := InfoLabel.Caption + '.'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THttpGetForm.AbortButtonClick(Sender: TObject); begin HttpCli1.Abort; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit MXmlBuilder; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses SysUtils, Classes, StringSupport, EncodeSupport, TextUtilities, AdvStreams, AdvVCLStreams, AdvObjects, AdvGenerics, MXML, XmlBuilder, ParserSupport; Type TMXmlBuilder = class (TXmlBuilder) private FExternal : Boolean; FStack : TAdvList<TMXmlElement>; FDoc : TMXmlDocument; FAttributes : TAdvMap<TMXmlAttribute>; FSourceLocation : TSourceLocation; Function Pad(offset : integer = 0) : String; function ReadTextLength(s : string):String; function ReadTextLengthWithEscapes(pfx, s, sfx : string):String; Public Constructor Create; Override; Destructor Destroy; override; Procedure Start(oNode : TMXmlElement); overload; Procedure Start(); overload; override; Procedure StartFragment; override; Procedure Finish; override; Procedure Build(oStream: TStream); Overload; override; Procedure Build(oStream: TAdvStream); Overload; override; Function Build : String; Overload; override; Function SourceLocation : TSourceLocation; override; Procedure Comment(Const sContent : String); override; Procedure AddAttribute(Const sName, sValue : String); override; Procedure AddAttributeNS(Const sNamespace, sName, sValue : String); override; function Tag(Const sName : String) : TSourceLocation; override; function Open(Const sName : String) : TSourceLocation; override; Procedure Close(Const sName : String); override; function Text(Const sValue : String) : TSourceLocation; override; function Entity(Const sValue : String) : TSourceLocation; override; function TagText(Const sName, sValue : String) : TSourceLocation; override; Procedure WriteXml(iElement : TMXmlElement); override; procedure ProcessingInstruction(sName, sText : String); override; procedure DocType(sText : String); override; procedure inject(const bytes : TBytes); override; End; Implementation { TMXmlBuilder } function TMXmlBuilder.SourceLocation: TSourceLocation; begin result.line := 0; result.col := 0; end; procedure TMXmlBuilder.Start(oNode : TMXmlElement); begin if oNode = nil Then Begin FDoc := TMXmlDocument.create; if CharEncoding <> '' Then FDoc.addChild(TMXmlElement.createProcessingInstruction(CharEncoding), true); FStack.Add(FDoc.Link); End else FStack.Add(oNode.Link); FSourceLocation.line := 0; FSourceLocation.col := 0; end; procedure TMXmlBuilder.Build(oStream: TAdvStream); var oVCL : TVCLStream; Begin oVCL := TVCLStream.Create; Try oVCL.Stream := oStream.Link; Build(oVCL); Finally oVCL.Free; End; End; procedure TMXmlBuilder.Finish; Begin if FStack.Count > 1 Then RaiseError('Close', 'Document is not finished'); FDoc.Free; End; procedure TMXmlBuilder.inject(const bytes: TBytes); begin raise Exception.Create('Inject is not supported on the MXml Builder'); end; procedure TMXmlBuilder.Build(oStream: TStream); Var b : TBytes; begin assert(FAttributes = nil); assert(not FExternal); b := TEncoding.UTF8.GetBytes(FStack[0].ToXml(true)); oStream.Write(b[0], length(b)); end; {function HasElements(oElem : IXMLDOMElement) : Boolean; var oChild : IXMLDOMNode; Begin Result := False; oChild := oElem.firstChild; While Not result and (oChild <> nil) Do Begin result := oChild.nodeType = NODE_ELEMENT; oChild := oChild.nextSibling; End; End; } function TMXmlBuilder.Open(const sName: String) : TSourceLocation; var oElem : TMXmlElement; oParent : TMXmlElement; iLoop : integer; len : integer; begin oElem := nil; try if CurrentNamespaces.DefaultNS <> '' Then begin oElem := TMXmlElement.Create(ntElement, sName, CurrentNamespaces.DefaultNS); len := length(sName)+3 end Else begin oElem := TMXmlElement.Create(ntElement, sName); len := length(sName); end; oParent := FStack.Last; if IsPretty and (oParent.NodeType = ntElement) Then oParent.addChild(TMXmlElement.createText(ReadTextLength(#13#10+pad)), true); oParent.addChild(oElem, true); inc(FSourceLocation.col, len+2); for iLoop := 0 to FAttributes.Count - 1 Do oElem.attributes.addAll(FAttributes); FAttributes.Clear; FStack.Add(oElem.Link); result.line := FSourceLocation.line; result.col := FSourceLocation.col; finally oElem.Free; end; end; procedure TMXmlBuilder.Close(const sName: String); begin if IsPretty Then Begin If FStack.Last.HasChildren Then FStack.Last.addChild(TMXmlElement.createText(readTextLength(#13#10+pad(-1))), true); End; FStack.Delete(FStack.Count - 1) end; procedure TMXmlBuilder.AddAttribute(const sName, sValue: String); begin FAttributes.AddOrSetValue(sName, TMXmlAttribute.Create(sName, sValue)); ReadTextLengthWithEscapes(sName+'="', sValue, '"'); end; function TMXmlBuilder.Text(const sValue: String) : TSourceLocation; begin FStack.Last.addChild(TMXmlElement.createText(ReadTextLengthWithEscapes('', sValue, '')), true); result.line := FSourceLocation.line; result.col := FSourceLocation.col; end; procedure TMXmlBuilder.WriteXml(iElement: TMXmlElement); begin raise Exception.Create('TMXmlBuilder.WriteXml not Done Yet'); end; function TMXmlBuilder.Entity(const sValue: String) : TSourceLocation; begin FStack.Last.addChild(TMXmlElement.createText('&'+sValue+';'), true); inc(FSourceLocation.col, length(sValue)+2); result.line := FSourceLocation.line; result.col := FSourceLocation.col; end; function TMXmlBuilder.Tag(const sName: String) : TSourceLocation; begin Open(sName); Close(sName); result.line := FSourceLocation.line; result.col := FSourceLocation.col; end; function TMXmlBuilder.TagText(const sName, sValue: String) : TSourceLocation; begin result := Open(sName); if (sValue <> '') Then Text(sValue); Close(sName); end; function TMXmlBuilder.Pad(offset : integer = 0): String; var iLoop : integer; begin Setlength(result, ((FStack.Count - 1) + offset) * 2); For iLoop := 1 to Length(Result) Do result[iLoop] := ' '; end; procedure TMXmlBuilder.ProcessingInstruction(sName, sText: String); begin raise Exception.Create('Not supported yet'); end; function TMXmlBuilder.ReadTextLength(s: string): String; var i : integer; begin i := 1; while i <= length(s) do begin if CharInSet(s[i], [#10, #13]) then begin inc(FSourceLocation.line); FSourceLocation.col := 0; if (i < length(s)) and (s[i+1] <> s[i]) and CharInSet(s[i+1], [#10, #13]) then inc(i); end else inc(FSourceLocation.col); inc(i); end; end; function TMXmlBuilder.ReadTextLengthWithEscapes(pfx, s, sfx: string): String; begin ReadTextLength(pfx); ReadTextLength(EncodeXml(s, xmlText)); ReadTextLength(sfx); end; Procedure TMXmlBuilder.Comment(Const sContent : String); begin if IsPretty and (FStack.Last.nodeType = ntElement) Then FStack.Last.addChild(TMXmlElement.createText(ReadTextLength(#13#10+pad)), true); FStack.Last.addChild(TMXmlElement.createComment(sContent), true); ReadTextLength('<!-- '+sContent+' -->'); End; function TMXmlBuilder.Build: String; var oStream : TStringStream; begin oStream := TStringStream.Create(''); Try Build(oStream); Result := oStream.DataString; Finally oStream.Free; End; end; constructor TMXmlBuilder.Create; begin inherited; CurrentNamespaces.DefaultNS := 'urn:hl7-org:v3'; CharEncoding := 'UTF-8'; FStack := TAdvList<TMXmlElement>.Create; FAttributes := TAdvMap<TMXmlAttribute>.Create; end; destructor TMXmlBuilder.Destroy; begin FStack.Free; FStack := nil; FAttributes.Free; FAttributes := nil; inherited; end; procedure TMXmlBuilder.DocType(sText: String); begin raise Exception.Create('Not supported yet'); end; procedure TMXmlBuilder.AddAttributeNS(const sNamespace, sName, sValue: String); var attr : TMXmlAttribute; begin attr := TMXmlAttribute.Create(sName, sValue); try attr.NamespaceURI := sNamespace; attr.LocalName := sName; FAttributes.AddOrSetValue(sName, attr.link); finally attr.free; end; ReadTextLengthWithEscapes(sName+'="', sValue, '"'); end; procedure TMXmlBuilder.Start; begin Start(nil); end; procedure TMXmlBuilder.StartFragment; begin Start(nil); end; End.
{ Copy changed data from overrides into the master records or previous overrides. If overrides reference new records, then inject and copy them into the master first. Don't select anything (just click OK) in plugin's selection window to always merge into the master records only. } unit MergeOverridesIntoMaster; var sFiles: string; //================================================================================== // Merge changes from record e into m procedure MergeInto(e, m: IInterface); var slElems: TStringList; e1, e2: IInterface; i, c: integer; s: string; begin if not IsEditable(m) then Exit; slElems := TStringList.Create; // iterate over all elements in override for i := 0 to Pred(ElementCount(e)) do begin e2 := ElementByIndex(e, i); s := Name(e2); // build a list of all elements in override slElems.Add(s); // special treatment for record header if s = 'Record Header' then begin // copy flags SetElementNativeValues(m, 'Record Header\Record Flags', GetElementNativeValues(e, 'Record Header\Record Flags')); Continue; end; // get the same element from master e1 := ElementByName(m, s); // element exists in override but not in master, add and copy it if not Assigned(e1) then begin if Pos(' - ', s) = 5 then s := Copy(s, 1, 4); // leave only subrecord's signature if present e1 := Add(m, s, True); ElementAssign(e1, LowInteger, e2, False); Continue; end; // element exists in both master and override, detect conflict c := ConflictAllForElements(e1, e2, False, IsInjected(m)); // copy it into master if data is different if c >= caConflictBenign then ElementAssign(e1, LowInteger, e2, False); end; // remove elements from master that don't exist in override for i := Pred(ElementCount(m)) downto 0 do begin e1 := ElementByIndex(m, i); if slElems.IndexOf(Name(e1)) = -1 then Remove(e1); end; slElems.Free; end; //================================================================================== function Process(e: IInterface): integer; var frm: TForm; clb: TCheckListBox; m, ovr: IInterface; i: integer; begin m := Master(e); // this is not an override, skip if not Assigned(m) then Exit; // plugins selection window if files are not selected yet if sFiles = '' then begin frm := frmFileSelect; try frm.Caption := 'Select plugin(s) to merge into'; frm.Width := 420; clb := TCheckListBox(frm.FindComponent('CheckListBox1')); // add files loaded before the current plugin i := 1; while not SameText(GetFileName(e), GetFileName(FileByIndex(i))) do begin clb.Items.Add(GetFileName(FileByIndex(i))); Inc(i); end; // create list of checked files in a string if frm.ShowModal = mrOk then for i := 0 to Pred(clb.Items.Count) do if clb.Checked[i] then sFiles := sFiles + '[' + clb.Items[i] + ']'; // if nothing is checked, use * to signal for merging into master records only if sFiles = '' then sFiles := '*'; finally frm.Free; end; end; if sFiles = '*' then // nothing selected - merge into master only MergeInto(e, m) else // merge into selected files for i := -1 to Pred(OverrideCount(m)) do begin if i = -1 then ovr := m else ovr := OverrideByIndex(m, i); if Pos(GetFileName(ovr), sFiles) > 0 then MergeInto(e, ovr); end; end; end.
unit uFrmPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Graphics, Vcl.Controls, Vcl.Forms, System.Classes, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections; type TFrmPrincipal = class(TForm) txtValor: TEdit; btnAdicionar: TButton; boxLista: TListBox; btnListar: TButton; btnLimpar: TButton; edtHipotese: TEdit; edtSignificancia: TEdit; lblHipotese: TLabel; lblSignificancia: TLabel; lblDados: TLabel; btnCalcular: TButton; lblMensagem: TLabel; procedure FormCreate(Sender: TObject); procedure btnAdicionarClick(Sender: TObject); procedure btnListarClick(Sender: TObject); procedure btnCalcularClick(Sender: TObject); private { Private declarations } public Dados: TList<double>; end; var FrmPrincipal: TFrmPrincipal; implementation {$R *.dfm} uses uFramework; procedure TFrmPrincipal.btnAdicionarClick(Sender: TObject); begin Dados.Add(StrToFloat(txtValor.Text)); txtValor.Clear(); end; procedure TFrmPrincipal.btnCalcularClick(Sender: TObject); var TesteHipotese: TTesteHipotese; Hipotese : double; Significancia : integer; begin if (Dados <> nil) then begin TesteHipotese := TTesteHipotese.Create(); TesteHipotese.Dados := Dados; TesteHipotese.NumeroDados := Dados.Count(); TesteHipotese.Hipotese := StrToFloat(edtHipotese.Text); TesteHipotese.Campo := '0,' + StrToFloat(edtSignificancia.Text)/2 + ',' + Dados.Count(); end else raise Exception.Create('Nenhum dado inserido. Informe alguns dados para realizar o cálculo'); end; procedure TFrmPrincipal.btnListarClick(Sender: TObject); var n: double; begin for n in Dados do boxLista.Items.Add(n.ToString()); end; procedure TFrmPrincipal.FormCreate(Sender: TObject); begin Dados := TList<double>.Create(); end; end.
unit uCalculator; interface type TCalculator = class function Add(x, y: integer): integer; end; implementation { TCalculator } function TCalculator.Add(x, y: integer): integer; begin Result := x + y; end; end.
unit UTagPage; interface uses UPageSuper, UTypeDef; type TTagPage = class (TPageContainer) public class function PageType (): TPageType; override; function ChildShowInTree (ptChild: TPageType): boolean; override; function CanAddChild (ptChild: TPageType): boolean; override; function CanOwnChild (ptChild: TPageType): boolean; override; class function DefChildType (): TPageType; override; end; implementation uses UxlFunctions, UPageFactory, Resource; class function TTagPage.PageType (): TPageType; begin result := ptTag; end; function TTagPage.CanAddChild (ptChild: TPageType): boolean; begin result := ptChild in [ptGroup, ptNote, ptCalc, ptMemo, ptDict, ptLink, ptContact, ptTemplate, ptFastLink, ptSheet, ptTag]; end; function TTagPage.CanOwnChild (ptChild: TPageType): boolean; begin result := ptChild = ptTag; end; class function TTagPage.DefChildType (): TPageType; begin result := ptTag; end; function TTagPage.ChildShowInTree (ptChild: TPageType): boolean; begin result := ptChild = ptTag; end; //------------------------- initialization PageFactory.RegisterClass (TTagPage); PageImageList.AddImageWithOverlay (ptTag, m_tag); PageNameMan.RegisterDefName (ptTag, sr_deftagname); finalization end.
unit fSearchOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, JvBaseDlg, JvSelectDirectory, uBigFastSearchDfm; type TSearchLocation = (slProjectFiles, slOpenFiles, slDirectory); TFrmBigSearchOptions = class(TForm) cmbTextToFind: TComboBox; lblTextToFind: TLabel; gbxWhere: TGroupBox; rbSearchAllFilesInProject: TRadioButton; rbSearchAllOpenFiles: TRadioButton; rbSearchInDirectories: TRadioButton; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; gbxSearchDirectoryOptions: TGroupBox; cmbFileMask: TComboBox; btnBrowse: TButton; lblFileMask: TLabel; chbSearchRecursive: TCheckBox; dslSearchDirectory: TJvSelectDirectory; gbxOptions: TGroupBox; chbWildCardSearch: TCheckBox; chbSmartSpaces: TCheckBox; chbStartingWith: TCheckBox; mmoHelp: TMemo; chbStringlistAsOne: TCheckBox; procedure btnHelpClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnBrowseClick(Sender: TObject); procedure cmbFileMaskChange(Sender: TObject); private function GetSearchString: string; procedure LoadSettings; virtual; procedure SaveSettings; virtual; function GetSearchFileMask: string; function GetSearchLocation: TSearchLocation; function GetSearchRecursive: Boolean; function GetSearchOptions: TSearchOptions; public property SearchString: string read GetSearchString; property SearchLocation: TSearchLocation read GetSearchLocation; property SearchOptions: TSearchOptions read GetSearchOptions; property SearchFileMask: string read GetSearchFileMask; property SearchRecursive: Boolean read GetSearchRecursive; end; implementation uses Registry; {$R *.dfm} procedure TFrmBigSearchOptions.btnHelpClick(Sender: TObject); begin MessageDlg(mmoHelp.Text, mtInformation, [mbOk], 0); end; function TFrmBigSearchOptions.GetSearchString: string; begin Result := cmbTextToFind.Text; end; procedure TFrmBigSearchOptions.FormShow(Sender: TObject); begin LoadSettings; end; procedure TFrmBigSearchOptions.btnOKClick(Sender: TObject); begin SaveSettings; end; procedure TFrmBigSearchOptions.LoadSettings; var sl: TStringList; i: Integer; begin sl := TStringList.Create; try with TRegistry.Create do try if OpenKeyReadOnly('\Software\GolezTrol\Big DFM Search\1.0\') then begin if ValueExists('LastFolder') then // Legacy cmbFileMask.Text := ReadString('LastFolder'); if ValueExists('Where') then case TSearchLocation(ReadInteger('Where')) of slProjectFiles: rbSearchAllFilesInProject.Checked := True; slDirectory: rbSearchInDirectories.Checked := True; else rbSearchAllOpenFiles.Checked := True; end; if ValueExists('Recursive') then chbSearchRecursive.Checked := ReadBool('Recursive'); if ValueExists('WildcardSearch') then chbWildCardSearch.Checked := ReadBool('WildcardSearch'); if ValueExists('SmartSpaces') then chbSmartSpaces.Checked := ReadBool('SmartSpaces'); if ValueExists('StartingWith') then chbStartingWith.Checked := ReadBool('StartingWith'); if ValueExists('StringlistAsOne') then chbStringlistAsOne.Checked := ReadBool('StringlistAsOne'); if OpenKeyReadOnly('\Software\GolezTrol\Big DFM Search\1.0\SearchHistory\') then begin GetValueNames(sl); sl.Sort; cmbTextToFind.Clear; for i := 0 to sl.Count - 1 do begin cmbTextToFind.Items.Add(ReadString(sl[i])); end; if cmbTextToFind.Items.Count > 0 then cmbTextToFind.ItemIndex := 0; end; if OpenKeyReadOnly('\Software\GolezTrol\Big DFM Search\1.0\FileMaskHistory\') then begin GetValueNames(sl); sl.Sort; cmbFileMask.Clear; for i := 0 to sl.Count - 1 do begin cmbFileMask.Items.Add(ReadString(sl[i])); end; if cmbFileMask.Items.Count > 0 then cmbFileMask.ItemIndex := 0; end; end; finally Free; end; finally sl.Free; end; end; procedure TFrmBigSearchOptions.SaveSettings; var sl: TStringList; i: Integer; begin sl := TStringList.Create; sl.Duplicates := dupIgnore; try with TRegistry.Create do try if OpenKey('\Software\GolezTrol\Big DFM Search\1.0\', True) then begin WriteInteger('Where', Integer(GetSearchLocation)); WriteBool('Recursive', chbSearchRecursive.Checked); WriteBool('WildcardSearch', chbWildCardSearch.Checked); WriteBool('SmartSpaces', chbSmartSpaces.Checked); WriteBool('StartingWith', chbStartingWith.Checked); WriteBool('StringlistAsOne', chbStringlistAsOne.Checked); end; if OpenKey('\Software\GolezTrol\Big DFM Search\1.0\SearchHistory\', True) then begin sl.Assign(cmbTextToFind.Items); i := sl.IndexOf(cmbTextToFind.Text); if i > -1 then sl.Move(i, 0) else sl.Insert(0, cmbTextToFind.Text); while sl.Count > 26 do sl.Delete(26); for i := 0 to sl.Count - 1 do WriteString(chr(65 + i), sl[i]); end; if OpenKey('\Software\GolezTrol\Big DFM Search\1.0\FileMaskHistory\', True) then begin sl.Assign(cmbFileMask.Items); i := sl.IndexOf(cmbFileMask.Text); if i > -1 then sl.Move(i, 0) else sl.Insert(0, cmbFileMask.Text); while sl.Count > 26 do sl.Delete(26); for i := 0 to sl.Count - 1 do WriteString(chr(65 + i), sl[i]); end; finally Free; end; finally sl.Free; end; end; procedure TFrmBigSearchOptions.btnBrowseClick(Sender: TObject); begin dslSearchDirectory.InitialDir := cmbFileMask.Text; if dslSearchDirectory.Execute then begin cmbFileMask.Text := dslSearchDirectory.Directory; end; end; function TFrmBigSearchOptions.GetSearchFileMask: string; begin Result := cmbFileMask.Text; end; function TFrmBigSearchOptions.GetSearchLocation: TSearchLocation; begin if rbSearchAllFilesInProject.Checked then Result := slProjectFiles else if rbSearchInDirectories.Checked then Result := slDirectory else Result := slOpenFiles; end; function TFrmBigSearchOptions.GetSearchOptions: TSearchOptions; begin Result := []; // Only add wildcard flag if search string contains wildcard. If not, // wildcard flag is omitted. This will result in faster searching for // files _containing_ the search string if chbWildCardSearch.Checked and ((Pos('*', cmbTextToFind.Text) > 0) or (Pos('?', cmbTextToFind.Text) > 0)) then Include(Result, soWildcard); if chbSmartSpaces.Checked then Include(Result, soSmartSpace); if chbStartingWith.Checked then Include(Result, soStartingWith); if not chbStringlistAsOne.Checked then Include(Result, soStringsItemsAsSeparateStrings); end; function TFrmBigSearchOptions.GetSearchRecursive: Boolean; begin Result := chbSearchRecursive.Checked; end; procedure TFrmBigSearchOptions.cmbFileMaskChange(Sender: TObject); begin rbSearchInDirectories.Checked := True; end; end.
PROGRAM BuildIndex1(INPUT, OUTPUT); USES Lexer, SortedCollection; PROCEDURE ReadFileToCollection(VAR F: TEXT); VAR Lexem: LexemType; BEGIN{ReadFileToCollection} RESET(F); WHILE NOT EOF(F) DO BEGIN WHILE NOT EOLN(F) DO BEGIN Lexem := ReadLexem(F); IF Lexem <> '' THEN Insert(Lexem); END; READLN(F) END; END;{ReadFileToCollection} VAR F: TEXT; BEGIN {BuildIndex1} ASSIGN(F, 'F1.TXT'); ReadFileToCollection(F); PrintCollection(); END. {BuildIndex1}
unit qsendmail; interface {$I 'qdac.inc'} { 发送邮件实现单元,方便发送邮件,您可以免费使用本单元,但请保留版权信息 (C)2016,swish,chinawsb@sina.com 本单元实现参考了 BCCSafe 的实现,详情参考: http://www.bccsafe.com/delphi%E7%AC%94%E8%AE%B0/2015/05/12/IndySendMail/?utm_source=tuicool&utm_medium=referral } uses classes, sysutils,qstring; type PQMailAttachment = ^TQMailAttachment; TQMailAttachment = record ContentType: QStringW; ContentId: QStringW; ContentFile: QStringW; ContentStream: TStream; end; IMailAttachments = interface procedure AddFile(const AFileName: QStringW; const AContentId: QStringW = ''); procedure AddStream(AData: TStream; const AContentType: QStringW; const AContentId: QStringW = ''); function GetCount: Integer; function GetItems(AIndex: Integer): PQMailAttachment; property Count: Integer read GetCount; property Items[AIndex: Integer]: PQMailAttachment read GetItems; end; TQMailSender = record public SMTPServer: QStringW; // 服务器地址 SMTPPort: Integer; // 服务器端口 UserName: QStringW; // 用户名 Password: QStringW; // 密码 CCList: QStringW; // 抄送地址列表 BCCList: QStringW; // 暗抄送地址列表 Attachements: IMailAttachments; // 附件 SenderName: QStringW; // 发送者姓名 SenderMail: QStringW; // 发送者邮箱 RecipientMail: QStringW; // 收件人邮箱 Subject: QStringW; // 邮件主题 Body: QStringW; // 邮件内容 LastError: QStringW; UseSASL: Boolean; private public class function Create(AServer, AUserName, APassword: QStringW) : TQMailSender; overload; static; class function Create: TQMailSender; overload; static; function Send: Boolean; function SendBySSL: Boolean; end; TGraphicFormat = (gfUnknown, gfBitmap, gfJpeg, gfPng, gfGif, gfMetafile, gfTga, gfPcx, gfTiff, gfIcon, gfCursor, gfIff, gfAni); function DetectImageFormat(AStream: TStream): TGraphicFormat; overload; function DetectImageFormat(AFileName: String): TGraphicFormat; overload; function EncodeMailImage(AStream: TStream; AId: QStringW = ''; AWidth: QStringW = ''; AHeight: QStringW = '') : QStringW; overload; function EncodeMailImage(AFileName: QStringW; AId: QStringW = ''; AWidth: QStringW = ''; AHeight: QStringW = '') : QStringW; overload; function EncodeMailImage(AImage: IStreamPersist; AId: QStringW = ''; AWidth: QStringW = ''; AHeight: QStringW = '') : QStringW; overload; var DefaultSMTPServer: String; DefaultSMTPUserName: String; DefaultSMTPPassword: String; implementation uses IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessage, IdMessageClient, IdMessageBuilder, IdSMTPBase, IdBaseComponent, IdIOHandler, IdSmtp, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdSASLLogin, IdSASL_CRAM_SHA1, IdSASL, IdSASLUserPass, IdSASL_CRAMBase, IdSASL_CRAM_MD5, IdSASLSKey, IdSASLPlain, IdSASLOTP, IdSASLExternal, IdSASLDigest, IdSASLAnonymous, IdUserPassProvider, EncdDecd{$IF RTLVersion>27}, NetEncoding{$IFEND}{$IFDEF UNICODE}, Generics.Collections{$ENDIF}; resourcestring SUnsupportImageFormat = '不支持的图片格式,HTML中图片只支持JPG/PNG/GIF/BMP'; type {$IF RTLVersion>=21} TAttachmentList = TList<PQMailAttachment>; {$ELSE} TAttachmentList = TList; {$IFEND} TQMailAttachments = class(TInterfacedObject, IMailAttachments) protected FItems: TAttachmentList; procedure AddFile(const AFileName: QStringW; const AContentId: QStringW = ''); procedure AddStream(AData: TStream; const AContentType: QStringW; const AContentId: QStringW = ''); function GetCount: Integer; function GetItems(AIndex: Integer): PQMailAttachment; procedure DoInitializeISO(var VHeaderEncoding: Char; var VCharSet: string); public constructor Create; overload; destructor Destroy; override; end; { TQMailSender } class function TQMailSender.Create(AServer, AUserName, APassword: QStringW) : TQMailSender; var AHost: QStringW; begin AHost := DecodeTokenW(AServer, ':', #0, true, true); Result.SMTPServer := AHost; if not TryStrToInt(AServer, Result.SMTPPort) then Result.SMTPPort := 25; Result.UserName := AUserName; Result.Password := APassword; Result.Attachements := TQMailAttachments.Create; Result.UseSASL := true; end; procedure BuildHtmlMessage(const AData: TQMailSender; AMsg: TIdMessage); var I: Integer; ABuilder: TIdMessageBuilderHtml; begin ABuilder := TIdMessageBuilderHtml.Create; try ABuilder.HtmlCharSet := 'UTF-8'; if StartWithW(PWideChar(AData.Body), '<', False) then ABuilder.Html.Text := AData.Body else ABuilder.PlainText.Text := AData.Body; for I := 0 to AData.Attachements.Count - 1 do begin with AData.Attachements.Items[I]^ do begin if Length(ContentFile) > 0 then ABuilder.Attachments.Add(ContentFile, ContentId) else if Assigned(ContentStream) then ABuilder.Attachments.Add(ContentStream, ContentType, ContentId) end; end; ABuilder.FillMessage(AMsg); finally FreeAndNil(ABuilder); end; AMsg.CharSet := 'UTF-8'; AMsg.Body.Text := AData.Body; AMsg.Sender.Text := AData.SenderMail; AMsg.From.Address := AData.SenderMail; AMsg.From.Name := AData.SenderName; AMsg.ReplyTo.EMailAddresses := AData.SenderMail; AMsg.Recipients.EMailAddresses := AData.RecipientMail; AMsg.Subject := AData.Subject; AMsg.CCList.EMailAddresses := AData.CCList; AMsg.ReceiptRecipient.Text := ''; AMsg.BCCList.EMailAddresses := AData.BCCList; end; procedure InitSASL(ASmtp: TIdSmtp; AUserName, APassword: String); var IdUserPassProvider: TIdUserPassProvider; IdSASLCRAMMD5: TIdSASLCRAMMD5; IdSASLCRAMSHA1: TIdSASLCRAMSHA1; IdSASLPlain: TIdSASLPlain; IdSASLLogin: TIdSASLLogin; IdSASLSKey: TIdSASLSKey; IdSASLOTP: TIdSASLOTP; IdSASLAnonymous: TIdSASLAnonymous; IdSASLExternal: TIdSASLExternal; begin IdUserPassProvider := TIdUserPassProvider.Create(ASmtp); IdUserPassProvider.UserName := AUserName; IdUserPassProvider.Password := APassword; IdSASLCRAMSHA1 := TIdSASLCRAMSHA1.Create(ASmtp); IdSASLCRAMSHA1.UserPassProvider := IdUserPassProvider; IdSASLCRAMMD5 := TIdSASLCRAMMD5.Create(ASmtp); IdSASLCRAMMD5.UserPassProvider := IdUserPassProvider; IdSASLSKey := TIdSASLSKey.Create(ASmtp); IdSASLSKey.UserPassProvider := IdUserPassProvider; IdSASLOTP := TIdSASLOTP.Create(ASmtp); IdSASLOTP.UserPassProvider := IdUserPassProvider; IdSASLAnonymous := TIdSASLAnonymous.Create(ASmtp); IdSASLExternal := TIdSASLExternal.Create(ASmtp); IdSASLLogin := TIdSASLLogin.Create(ASmtp); IdSASLLogin.UserPassProvider := IdUserPassProvider; IdSASLPlain := TIdSASLPlain.Create(ASmtp); IdSASLPlain.UserPassProvider := IdUserPassProvider; ASmtp.SASLMechanisms.Add.SASL := IdSASLCRAMSHA1; ASmtp.SASLMechanisms.Add.SASL := IdSASLCRAMMD5; ASmtp.SASLMechanisms.Add.SASL := IdSASLSKey; ASmtp.SASLMechanisms.Add.SASL := IdSASLOTP; ASmtp.SASLMechanisms.Add.SASL := IdSASLAnonymous; ASmtp.SASLMechanisms.Add.SASL := IdSASLExternal; ASmtp.SASLMechanisms.Add.SASL := IdSASLLogin; ASmtp.SASLMechanisms.Add.SASL := IdSASLPlain; end; procedure AddSSLSupport(ASmtp: TIdSmtp); var SSLHandler: TIdSSLIOHandlerSocketOpenSSL; begin SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(ASmtp); // SSL/TLS handshake determines the highest available SSL/TLS version dynamically SSLHandler.SSLOptions.Method := sslvSSLv23; SSLHandler.SSLOptions.Mode := sslmClient; SSLHandler.SSLOptions.VerifyMode := []; SSLHandler.SSLOptions.VerifyDepth := 0; ASmtp.IOHandler := SSLHandler; end; procedure SendMailEx(const AData: TQMailSender; AUseSSL, AUseSASL: Boolean); var AMsg: TIdMessage; ASmtp: TIdSmtp; begin AMsg := TIdMessage.Create; ASmtp := TIdSmtp.Create; try AMsg.OnInitializeISO := (AData.Attachements as TQMailAttachments) .DoInitializeISO; BuildHtmlMessage(AData, AMsg); if AUseSSL then begin AddSSLSupport(ASmtp); if AData.SMTPPort = 587 then ASmtp.UseTLS := utUseExplicitTLS else ASmtp.UseTLS := utUseImplicitTLS; end; if (Length(AData.UserName) > 0) or (Length(AData.Password) > 0) then begin if AUseSASL then begin ASmtp.AuthType := satSASL; InitSASL(ASmtp, AData.UserName, AData.Password); end else begin ASmtp.UserName := AData.UserName; ASmtp.Password := AData.Password; end; end else begin ASmtp.AuthType := satNone; end; ASmtp.Host := AData.SMTPServer; ASmtp.Port := AData.SMTPPort; ASmtp.ConnectTimeout := 30000; ASmtp.UseEHLO := true; ASmtp.Connect; try ASmtp.Send(AMsg); finally ASmtp.Disconnect; end; finally FreeAndNil(ASmtp); FreeAndNil(AMsg); end; end; class function TQMailSender.Create: TQMailSender; begin Result := Create(DefaultSMTPServer, DefaultSMTPUserName, DefaultSMTPPassword); end; function TQMailSender.Send: Boolean; begin try Result := true; SendMailEx(Self, False, UseSASL); except on E: Exception do begin LastError := E.Message; Result := False; end; end; end; function TQMailSender.SendBySSL: Boolean; begin try Result := true; SendMailEx(Self, true, UseSASL); except on E: Exception do begin LastError := E.Message; Result := False; end; end; end; { TQMailAttachments } procedure TQMailAttachments.AddFile(const AFileName, AContentId: QStringW); var AItem: PQMailAttachment; begin New(AItem); AItem.ContentFile := AFileName; AItem.ContentId := AContentId; FItems.Add(AItem); end; procedure TQMailAttachments.AddStream(AData: TStream; const AContentType, AContentId: QStringW); var AItem: PQMailAttachment; begin New(AItem); AItem.ContentStream := AData; AItem.ContentType := AContentType; AItem.ContentId := AContentId; FItems.Add(AItem); end; constructor TQMailAttachments.Create; begin FItems := TAttachmentList.Create; end; destructor TQMailAttachments.Destroy; var I: Integer; begin for I := 0 to FItems.Count - 1 do Dispose(PQMailAttachment(FItems[I])); FreeAndNil(FItems); inherited; end; procedure TQMailAttachments.DoInitializeISO(var VHeaderEncoding: Char; var VCharSet: string); begin VCharSet := 'UTF-8'; VHeaderEncoding := 'B'; end; function TQMailAttachments.GetCount: Integer; begin Result := FItems.Count; end; function TQMailAttachments.GetItems(AIndex: Integer): PQMailAttachment; begin Result := FItems[AIndex]; end; /// <summary>检测图片格式</summary> /// <params> /// <param name="AStream">要检测的图片数据流</param> /// </params> /// <returns>返回可以识别的图片格式代码</returns> function DetectImageFormat(AStream: TStream): TGraphicFormat; overload; var ABuf: array [0 .. 7] of Byte; AReaded: Integer; APos:Int64; begin FillChar(ABuf, 8, 0); APos:=AStream.Position; AReaded := AStream.Read(ABuf[0], 8); AStream.Position:=APos;// 回到原始位置 if (ABuf[0] = $FF) and (ABuf[1] = $D8) then // JPEG文件头标识 (2 bytes): $ff, $d8 (SOI) (JPEG 文件标识) Result := gfJpeg else if (ABuf[0] = $89) and (ABuf[1] = $50) and (ABuf[2] = $4E) and (ABuf[3] = $47) and (ABuf[4] = $0D) and (ABuf[5] = $0A) and (ABuf[6] = $1A) and (ABuf[7] = $0A) then Result := gfPng // 3.PNG文件头标识 (8 bytes) 89 50 4E 47 0D 0A 1A 0A else if (ABuf[0] = $42) and (ABuf[1] = $4D) then Result := gfBitmap else if (ABuf[0] = $47) and (ABuf[1] = $49) and (ABuf[2] = $46) and (ABuf[3] = $38) and (ABuf[4] in [$37, $39]) and (ABuf[5] = $61) then Result := gfGif // GIF- 文件头标识 (6 bytes) 47 49 46 38 39(37) 61 G I F 8 9 (7) a else if (ABuf[0] = $01) and (ABuf[1] = $00) and (ABuf[2] = $00) and (ABuf[3] = $00) then Result := gfMetafile // EMF 01 00 00 00 else if (ABuf[0] = $01) and (ABuf[1] = $00) and (ABuf[2] = $09) and (ABuf[3] = $00) and (ABuf[4] = $00) and (ABuf[5] = $03) then Result := gfMetafile // WMF 01 00 09 00 00 03 else if (ABuf[0] = $00) and (ABuf[1] = $00) and ((ABuf[2] = $02) or (ABuf[2] = $10)) and (ABuf[3] = $00) and (ABuf[4] = $00) then Result := gfTga // TGA- 未压缩的前5字节 00 00 02 00 00,RLE压缩的前5字节 00 00 10 00 00 else if (ABuf[0] = $0A) then Result := gfPcx // PCX - 文件头标识 (1 bytes) 0A else if ((ABuf[0] = $4D) and (ABuf[1] = $4D)) or ((ABuf[0] = $49) and (ABuf[1] = $49)) then Result := gfTiff // TIFF - 文件头标识 (2 bytes) 4D 4D 或 49 49 else if (ABuf[0] = $00) and (ABuf[1] = $00) and (ABuf[2] = $01) and (ABuf[3] = $00) and (ABuf[4] = $01) and (ABuf[5] = $00) and (ABuf[6] = $20) and (ABuf[7] = $20) then Result := gfIcon // ICO - 文件头标识 (8 bytes) 00 00 01 00 01 00 20 20 else if (ABuf[0] = $00) and (ABuf[1] = $00) and (ABuf[2] = $02) and (ABuf[3] = $00) and (ABuf[4] = $01) and (ABuf[5] = $00) and (ABuf[6] = $20) and (ABuf[7] = $20) then Result := gfCursor // CUR - 文件头标识 (8 bytes) 00 00 02 00 01 00 20 20 else if (ABuf[0] = $46) and (ABuf[1] = $4F) and (ABuf[2] = $52) and (ABuf[3] = $4D) then Result := gfIff // IFF - 文件头标识 (4 bytes) 46 4F 52 4D(FORM) else if (ABuf[0] = $52) and (ABuf[1] = $49) and (ABuf[2] = $46) and (ABuf[3] = $46) then Result := gfAni // 11.ANI- 文件头标识 (4 bytes) 52 49 46 46(RIFF) else Result := gfUnknown; end; /// <summary>检测图片格式</summary> /// <params> /// <param name="AFileName">要检测的图片文件名</param> /// </params> /// <returns>返回可以识别的图片格式代码</returns> function DetectImageFormat(AFileName: String): TGraphicFormat; overload; var AStream: TStream; begin AStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try Result := DetectImageFormat(AStream); finally FreeAndNil(AStream); end; end; function EncodeImageHeader(AStream: TStream; AId, AWidth, AHeight: String) : QStringW; begin if Length(AId) > 0 then Result := '<img id=' + QuotedStrW(AId, '"') else Result := '<img'; if Length(AWidth) > 0 then Result := Result + ' width=' + QuotedStrW(AWidth, '"'); if Length(AHeight) > 0 then Result := Result + ' height=' + QuotedStrW(AHeight, '"'); Result := Result + ' src="data:image/'; case DetectImageFormat(AStream) of gfBitmap: Result := Result + 'bmp;base64,'; gfJpeg: Result := Result + 'jpeg;base64,'; gfPng: Result := Result + 'png;base64,'; gfGif: Result := Result + 'gif;base64,'; else // 其它格式就不支持了,想支持的自己参考处理 raise Exception.Create(SUnsupportImageFormat); end; end; function EncodeMailImage(AStream: TStream; AId, AWidth, AHeight: QStringW) : QStringW; var ATemp: TCustomMemoryStream; begin if AStream is TCustomMemoryStream then begin ATemp := AStream as TCustomMemoryStream; Result := EncodeImageHeader(ATemp, '', '', '') + EncodeBase64(PByte(IntPtr(ATemp.Memory) + ATemp.Position), ATemp.Size - ATemp.Position) + '">'; end else begin ATemp := TMemoryStream.Create; try ATemp.CopyFrom(AStream, AStream.Size - AStream.Position); Result := EncodeImageHeader(ATemp, '', '', '') + EncodeBase64(ATemp.Memory, ATemp.Size) + '">'; finally FreeAndNil(ATemp); end; end; end; function EncodeMailImage(AFileName: QStringW; AId, AWidth, AHeight: QStringW): QStringW; var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try AStream.LoadFromFile(AFileName); AStream.Position := 0; Result := EncodeImageHeader(AStream, '', '', '') + EncodeBase64(AStream.Memory, AStream.Size) + '">'; finally FreeAndNil(AStream); end; end; function EncodeMailImage(AImage: IStreamPersist; AId: QStringW = ''; AWidth: QStringW = ''; AHeight: QStringW = ''): QStringW; var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try AImage.SaveToStream(AStream); AStream.Position := 0; Result := EncodeMailImage(AStream, AId, AWidth, AHeight); finally FreeAndNil(AStream); end; end; end.
unit uSearch; interface uses uISearch, uEventManager, Classes; type TSearch = class(TInterfacedObject, ISearch) private type TEventManager = class BeforeSearch: TEvents; AfterSearch: TEvents; BeforeFillResult: TEvents; AfterFillResult: TEvents; BeforeShow: TEvents; AfterShow: TEvents; BeforeClose: TEvents; AfterClose: TEvents; constructor Create; destructor Destroy; override; end; private procedure DoEvent(Event: TNotifyEvent); public Events: TEventManager; OnSearch: TNotifyEvent; OnFillResult: TNotifyEvent; OnShow: TNotifyEvent; OnClose: TNotifyEvent; /// <summary> /// Выполненить поиск (источник - определяется вами) /// </summary> procedure Search; virtual; /// <summary> /// Заполнить объект представления резльтатами поиска /// </summary> procedure FillResult; virtual; /// <summary> /// Открыть окно поиска /// </summary> procedure Show; virtual; /// <summary> /// Закрыть окно поиска /// </summary> procedure Close; virtual; constructor Create; destructor Destroy; override; end; implementation uses SysUtils; { TSearch } procedure TSearch.Close; begin Events.BeforeClose.DoEvents; DoEvent(OnClose); Events.AfterClose.DoEvents; end; constructor TSearch.Create; begin Events := TEventManager.Create; end; destructor TSearch.Destroy; begin FreeAndNil(Events); inherited; end; procedure TSearch.DoEvent(Event: TNotifyEvent); begin if Assigned(Event) then Event(Self) end; procedure TSearch.FillResult; begin Events.BeforeFillResult.DoEvents; DoEvent(OnFillResult); Events.AfterFillResult.DoEvents; end; procedure TSearch.Search; begin Events.BeforeSearch.DoEvents; DoEvent(OnSearch); Events.AfterSearch.DoEvents; end; procedure TSearch.Show; begin Events.BeforeShow.DoEvents; DoEvent(OnShow); Events.AfterShow.DoEvents; end; { TSearch.TEventManager } constructor TSearch.TEventManager.Create; begin BeforeSearch := TEvents.Create; AfterSearch := TEvents.Create; BeforeFillResult := TEvents.Create; AfterFillResult := TEvents.Create; BeforeShow := TEvents.Create; AfterShow := TEvents.Create; BeforeClose := TEvents.Create; AfterClose := TEvents.Create; end; destructor TSearch.TEventManager.Destroy; begin FreeAndNil(BeforeSearch); FreeAndNil(AfterSearch); FreeAndNil(BeforeFillResult); FreeAndNil(AfterFillResult); FreeAndNil(BeforeShow); FreeAndNil(AfterShow); FreeAndNil(BeforeClose); FreeAndNil(AfterClose); inherited; end; end.
unit Thread.ProcessaFechamento; interface uses System.Classes, Model.ExtratosExpressas, DAO.ExtratosExpressas, Model.FechamentoExpressas, Model.FechamentoLancamento, Model.FechamentoRestricao, DAO.FechamentoLancamento, DAO.FechamentoRestricao, DAO.FechamentosExpressas, Model.ParcelamentoRestricao, DAO.ParcelamentoRestricao, Model.ExtraviosMultas, DAO.ExtraviosMultas, clRestricoes, Generics.Collections, clLancamentos, Model.DebitosExtravios, DAO.DebitosExtravios, Model.TotalEntregas, DAO.TotalizaEntregas, Forms, Windows, Model.Entregadores, DAO.Entregadores, clAgentes, clGruposVerba, Dialogs, clEntregador; type Thread_ProcessaFechamento = class(TThread) private { Private declarations } FdPos: Double; extratos : TObjectList<TExtratosExpressas>; fechamentos : TObjectList<TFechamentoExpressas>; fechalancamentos : TObjectList<TFechamentoLancamento>; fecharestricoes : TObjectList<TFechamentoRestricao>; parcelas: TObjectList<TParcelamentoRestricao>; extravios : TObjectList<TExtraviosMultas>; extravioDAO : TExtraviosMultasDAO; entregas : TObjectList<TTotalEntregas>; debitosextravios: TObjectList<TDebitosExtravios>; extrato : TExtratosExpressas; entrega : TTotalEntregas; fechamento : TFechamentoExpressas; fechalancamento : TFechamentoLancamento; fecharestricao : TFechamentoRestricao; parcela: TParcelamentoRestricao; extravio : TExtraviosMultas; lancamento : TLancamentos; restricao : TRestricoes; extratoDAO : TExtratosExpressasDAO; entregaDAO: TTotalizaEntregasDAO; fechamentoDAO : TFechamentoExpressasDAO; fechalancamentoDAO : TFechamentoLancamentoDAO; fecharestricaoDAO : TFechamentoRestricaoDAO; parcelaDAO: TParcelamentoRestricaoDAO; entregadores : TObjectList<TEntregadores>; entregador : TEntregadores; entregadorDAO : TEntregadoresDAO; agente : TAgente; verba : TGruposVerba; iCodigoExpressa : Integer; iTipo: Integer; sMensagem: String; bFlag: Boolean; cadastro : TEntregador; public dtInicio: TDate; dtFinal: TDate; bRestricao : Boolean; bLancamentos: Boolean; bSLA : Boolean; protected procedure ProcessaExtrato; procedure IniciaProcesso; procedure AtualizaProcesso; procedure TerminaProcesso; procedure ProcessaFechamentos; procedure ProcessaVerba; procedure ProcessaLancamentos; procedure ProcessaRestricao; procedure ProcessaExtravios; procedure TotalizaExtrato; procedure PopulaFechamento; procedure Execute; override; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_TotalizaEntregas.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { Thread_TotalizaEntregas } uses System.SysUtils, FireDAC.Comp.Client, Data.DB, View.FechamentoExpressas, udm, uGlobais, Global.Parametros, Common.Utils; procedure Thread_ProcessaFechamento.AtualizaProcesso; begin view_FechamentoExpressas.sbFechamento.Panels[0].Text := sMensagem; view_FechamentoExpressas.sbFechamento.Refresh; view_FechamentoExpressas.pbFechamento.Position := FdPos; view_FechamentoExpressas.pbFechamento.Properties.Text := FormatFloat('0.00%',FdPos); view_FechamentoExpressas.pbFechamento.Refresh; end; procedure Thread_ProcessaFechamento.Execute; var aParam: array of Variant; begin { Place thread code here } Synchronize(IniciaProcesso); fechamentos := TObjectList<TFechamentoExpressas>.Create; fechamentoDAO := TFechamentoExpressasDAO.Create; SetLength(aParam,2); aParam[0] := dtInicio; aParam[1] := dtFinal; fechamentos := fechamentoDAO.FindFechamento('DATAS', aParam) ; Finalize(aParam); fechamentoDAO.Free; bFlag := False; if fechamentos.Count > 0 then begin if fechamentos[0].Fechado = 1 then bFlag := True; end; if fechamentos.Count = 0 then begin Synchronize(ProcessaExtrato); Synchronize(ProcessaVerba); if bLancamentos then Synchronize(ProcessaLancamentos); if bRestricao then Synchronize(ProcessaRestricao); Synchronize(ProcessaExtravios); Synchronize(TotalizaExtrato); Synchronize(ProcessaFechamentos); end; Synchronize(PopulaFechamento); Synchronize(TerminaProcesso); end; procedure Thread_ProcessaFechamento.IniciaProcesso; begin view_FechamentoExpressas.actProcessar.Enabled := False; view_FechamentoExpressas.actCancelar.Enabled := False; view_FechamentoExpressas.actEncerrar.Enabled := False; view_FechamentoExpressas.dsFechamento.Enabled := False; view_FechamentoExpressas.sbFechamento.Panels[0].Text := ''; view_FechamentoExpressas.pbFechamento.Visible := True; view_FechamentoExpressas.pbFechamento.Position := 0; view_FechamentoExpressas.pbFechamento.Refresh; view_FechamentoExpressas.sbFechamento.Refresh; view_FechamentoExpressas.dxActivityIndicator1.Active := True; end; procedure Thread_ProcessaFechamento.ProcessaFechamentos; var aParam: array of Variant; fechamentoTMP : TFechamentoExpressas; extratoTMP: TExtratosExpressas; iPos: Integer; iTotal : Integer; dRestricao: Double; sExtratos: String; begin try agente := TAgente.Create; restricao := TRestricoes.Create; fechamentos := TObjectList<TFechamentoExpressas>.Create; fechamentoDAO := TFechamentoExpressasDAO.Create; entregadores := TObjectList<TEntregadores>.Create; entregadorDAO := TEntregadoresDAO.Create; extratos := TObjectList<TExtratosExpressas>.Create; extratoDAO := TExtratosExpressasDAO.Create; FdPos := 0; iPos := 0; iTotal := 0; sMensagem := 'PROCESSANDO O FECHAMENTO. Aguarde ...'; Synchronize(AtualizaProcesso); SetLength(aParam,3); aParam[0] := dtInicio; aParam[1] := dtFinal; aParam[2] := 0; extratos := extratoDAO.FindExtrato('PERIODO', aParam); Finalize(aParam); iTotal := extratos.Count; for extratoTMP in extratos do begin iCodigoExpressa := 0; iTipo := 0; if agente.getObject(extratoTMP.Agente.ToString,'CODIGO') then begin if agente.Forma <> 'NENHUMA' then begin iCodigoExpressa := agente.Codigo.ToInteger(); iTipo := 1; end; end; if iCodigoExpressa = 0 then begin iCodigoExpressa := extratoTMP.Entregador; iTipo := 2; end; if iCodigoExpressa = 0 then begin iCodigoExpressa := 1; iTipo := 1; end; dRestricao := 0; if iTipo = 1 then dRestricao := restricao.RetornaTotal(iCodigoExpressa); if iTipo = 2 then dRestricao := restricao.RetornaDebito(iCodigoExpressa); SetLength(aParam,4); aParam[0] := dtInicio; aParam[1] := dtFinal; aParam[2] := iTipo; aParam[3] := iCodigoExpressa; fechamentos := fechamentoDAO.FindFechamento('EXTRATO', aParam); Finalize(aParam); if fechamentos.Count = 0 then begin fechamento := TFechamentoExpressas.Create; fechamento.Id := 0; fechamento.Tipo := iTipo; fechamento.DataInicio := dtInicio; fechamento.DataFinal := dtFinal; fechamento.Codigo := iCodigoExpressa; fechamento.ValorProducao := extratoTMP.ValorProducao; fechamento.VerbaEntregador := extratoTMP.Verba; fechamento.TotalVerbaFranquia := extratoTMP.TotalVerbaFranquia; fechamento.SaldoRestricao := dRestricao; fechamento.ValorResticao := extratoTMP.ValorRestricao; fechamento.ValorExtravios := extratoTMP.ValorExtravio; fechamento.ValorCreditos := extratoTMP.ValorCreditos; fechamento.ValorDebitos := extratoTMP.ValorDebitos; fechamento.ValorFinanciado := 0; fechamento.TotalDebitos := extratoTMP.ValorTotalDebitos; fechamento.TotalCreditos := extratoTMP.ValorCreditos; fechamento.TotalGeral := extratoTMP.ValorTotalGeral; fechamento.Fechado := 0; fechamento.Extratos := extratoTMP.Id.ToString; fechamento.TotalEntregas := extratoTMP.Entregas; fechamento.PFP := extratoTMP.PFP; fechamento.Log := FormatDateTime('yyyy/mm/dd ', Now()) + ' processado por ' + uGlobais.sUsuario; if not fechamentoDAO.Insert(fechamento) then begin Application.MessageBox(PChar('Erro ao criar o fechamento do agente/entregador ' + iCodigoExpressa.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; fechamento.Free; end else begin for fechamentoTMP in fechamentos do begin sExtratos:= ''; fechamentoTMP.ValorProducao := fechamentoTMP.ValorProducao + extratoTMP.ValorProducao; if fechamentotmp.VerbaEntregador < extratoTMP.Verba then fechamentoTMP.VerbaEntregador := extratoTMP.Verba; fechamentoTMP.TotalVerbaFranquia := fechamentoTMP.TotalVerbaFranquia + extratoTMP.TotalVerbaFranquia; fechamentoTMP.SaldoRestricao := dRestricao; fechamentoTMP.ValorResticao := fechamentoTMP.ValorResticao + extratoTMP.ValorRestricao; fechamentoTMP.ValorExtravios := fechamentoTMP.ValorExtravios + extratoTMP.ValorExtravio; fechamentoTMP.ValorCreditos := fechamentoTMP.ValorCreditos + extratoTMP.ValorCreditos; fechamentoTMP.ValorDebitos := fechamentoTMP.ValorDebitos + extratoTMP.ValorDebitos; fechamentoTMP.TotalDebitos := fechamentoTMP.TotalDebitos + extratoTMP.ValorTotalDebitos; fechamentoTMP.TotalCreditos := fechamentoTMP.TotalCreditos + extratoTMP.ValorTotalCreditos; fechamentoTMP.TotalGeral := fechamentoTMP.TotalGeral + extratoTMP.ValorTotalGeral; sExtratos := fechamentoTMP.Extratos; if sExtratos.IsEmpty then begin sExtratos := extratoTMP.Id.ToString; end else begin sExtratos := sExtratos + ',' + extratoTMP.Id.ToString; end; fechamentoTMP.Extratos := sExtratos; fechamentoTMP.TotalEntregas := fechamentoTMP.TotalEntregas + extratoTMP.Entregas; fechamentoTMP.PFP := fechamentoTMP.PFP + extratoTMP.PFP; if not fechamentoDAO.Update(fechamentoTMP) then begin Application.MessageBox(PChar('Erro ao atualizar o fechamento do agente/entregador ' + iCodigoExpressa.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; end; end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally agente.Free; restricao.Free; fechamentoDAO.Free; entregadorDAO.Free; extratoDAO.Free; end; end; procedure Thread_ProcessaFechamento.PopulaFechamento; var aParam: array of Variant; fechamentoTMP: TFechamentoExpressas; sNome: String; iPos: Integer; iCadastro: Integer; begin try fechamentos := TObjectList<TFechamentoExpressas>.Create; fechamentoDAO := TFechamentoExpressasDAO.Create; cadastro := TEntregador.Create; SetLength(aParam,2); aParam[0] := dtInicio; aParam[1] := dtFinal; fechamentos := fechamentoDAO.FindFechamento('DATAS', aParam); Finalize(aParam); agente := TAgente.Create; entregadores := TObjectList<TEntregadores>.Create; entregadorDAO := TEntregadoresDAO.Create; FdPos := 0; iPos := 0; sMensagem := 'POPULANDO O FECHAMENTO. Aguarde ...'; Synchronize(AtualizaProcesso); iTotal := fechamentos.Count; view_FechamentoExpressas.mtbFechamento.IsLoading := True; view_FechamentoExpressas.mtbFechamento.Close; view_FechamentoExpressas.mtbFechamento.Open; iCadastro := 0; for fechamentoTMP in fechamentos do begin view_FechamentoExpressas.mtbFechamento.Insert; view_FechamentoExpressas.mtbFechamentoID_FECHAMENTO.AsInteger := fechamentoTMP.Id; view_FechamentoExpressas.mtbFechamentoDAT_INICIO.AsDateTime :=fechamentoTMP.DataInicio; view_FechamentoExpressas.mtbFechamentoDAT_FINAL.AsDateTime := fechamentoTMP.DataFinal; view_FechamentoExpressas.mtbFechamentoCOD_TIPO.AsInteger := fechamentoTMP.Tipo; view_FechamentoExpressas.mtbFechamentoCOD_EXPRESSA.AsInteger := fechamentoTMP.Codigo; view_FechamentoExpressas.mtbFechamentoVAL_SALDO_RESTRICAO.AsFloat := fechamentoTMP.SaldoRestricao; view_FechamentoExpressas.mtbFechamentoVAL_RESTRICAO.AsFloat := fechamentoTMP.ValorResticao; view_FechamentoExpressas.mtbFechamentoVAL_VERBA_ENTREGADOR.AsFloat := fechamentoTMP.VerbaEntregador; view_FechamentoExpressas.mtbFechamentoTOT_VERBA_FRANQUIA.AsFloat := fechamentoTMP.TotalVerbaFranquia; view_FechamentoExpressas.mtbFechamentoVAL_EXTRAVIOS.AsFloat := fechamentoTMP.ValorExtravios; view_FechamentoExpressas.mtbFechamentoVAL_CREDITOS.AsFloat := fechamentoTMP.ValorCreditos; view_FechamentoExpressas.mtbFechamentoVAL_DEBITOS.AsFloat := fechamentoTMP.ValorDebitos; view_FechamentoExpressas.mtbFechamentoVAL_FINANCIADO.AsFloat := fechamentoTMP.ValorFinanciado; view_FechamentoExpressas.mtbFechamentoVAL_TOTAL_DEBITOS.AsFloat := fechamentoTMP.ValorResticao + fechamentoTMP.ValorExtravios + fechamentoTMP.ValorDebitos; view_FechamentoExpressas.mtbFechamentoVAL_TOTAL_CREDITOS.AsFloat := fechamentoTMP.ValorProducao + fechamentoTMP.ValorCreditos; view_FechamentoExpressas.mtbFechamentoVAL_TOTAL_GERAL.AsFloat := fechamentoTMP.ValorProducao + fechamentoTMP.ValorCreditos + fechamentoTMP.ValorResticao + fechamentoTMP.ValorExtravios + fechamentoTMP.ValorDebitos; view_FechamentoExpressas.mtbFechamentoDES_LOG.AsString := fechamentoTMP.Log; view_FechamentoExpressas.mtbFechamentoDES_EXTRATOS.AsString := fechamentoTMP.Extratos; view_FechamentoExpressas.mtbFechamentoVAL_PRODUCAO.AsFloat := fechamentoTMP.ValorProducao; view_FechamentoExpressas.mtbFechamentoQTD_PFP.AsInteger := fechamentoTMP.PFP; view_FechamentoExpressas.mtbFechamentoNOM_FAVORECIDO.asString := fechamentoTMP.Favorecido; view_FechamentoExpressas.mtbFechamentoNUM_CPF_CNPJ.AsString := fechamentoTMP.CPFCNPJ; view_FechamentoExpressas.mtbFechamentoCOD_BANCO.AsInteger := fechamentoTMP.Banco; view_FechamentoExpressas.mtbFechamentoCOD_AGENCIA.AsString := fechamentoTMP.Agencia; view_FechamentoExpressas.mtbFechamentoDES_TIPO_CONTA.AsString := fechamentoTMP.TipoConta; view_FechamentoExpressas.mtbFechamentoNUM_CONTA.AsString := fechamentoTMP.Conta; if fechamentoTMP.Tipo = 1 then begin if agente.getObject(fechamentoTMP.Codigo.ToString,'CODIGO') then begin view_FechamentoExpressas.mtbFechamentoNOM_EXPRESSA.AsString := agente.Fantasia; if view_FechamentoExpressas.mtbFechamentoNUM_CONTA.AsString.IsEmpty then begin view_FechamentoExpressas.mtbFechamentoNOM_FAVORECIDO.asString := agente.Favorecido; view_FechamentoExpressas.mtbFechamentoNUM_CPF_CNPJ.AsString := agente.CpfCnpjFavorecido; view_FechamentoExpressas.mtbFechamentoCOD_BANCO.AsInteger := StrToIntDef(Agente.Banco, 0); view_FechamentoExpressas.mtbFechamentoCOD_AGENCIA.AsString := agente.Agencia; view_FechamentoExpressas.mtbFechamentoDES_TIPO_CONTA.AsString := agente.TipoConta; view_FechamentoExpressas.mtbFechamentoNUM_CONTA.AsString := agente.NumeroConta; end; end; end else begin SetLength(aParam,1); aParam[0] := fechamentoTMP.Codigo; entregadores := entregadorDAO.FindEntregador('ENTREGADOR', aParam); Finalize(aParam); if entregadores.Count > 0 then begin view_FechamentoExpressas.mtbFechamentoNOM_EXPRESSA.AsString := entregadores[0].Fantasia; iCadastro := entregadores[0].Cadastro; end else begin view_FechamentoExpressas.mtbFechamentoNOM_EXPRESSA.AsString := 'NONE'; iCadastro := 0; end; if view_FechamentoExpressas.mtbFechamentoNUM_CONTA.AsString.IsEmpty then begin if iCadastro > 0 then begin if cadastro.getObject(iCadastro.ToString, 'CADASTRO') then begin view_FechamentoExpressas.mtbFechamentoNOM_FAVORECIDO.asString := cadastro.Favorecido; view_FechamentoExpressas.mtbFechamentoNUM_CPF_CNPJ.AsString := cadastro.CpfCnpjFavorecido; view_FechamentoExpressas.mtbFechamentoCOD_BANCO.AsInteger := StrToIntDef(cadastro.Banco, 0); view_FechamentoExpressas.mtbFechamentoCOD_AGENCIA.AsString := cadastro.Agencia; view_FechamentoExpressas.mtbFechamentoDES_TIPO_CONTA.AsString := cadastro.TipoConta; view_FechamentoExpressas.mtbFechamentoNUM_CONTA.AsString := cadastro.NumeroConta; end; end; end; end; view_FechamentoExpressas.mtbFechamentoTOT_ENTREGAS.AsInteger := fechamentoTMP.TotalEntregas; view_FechamentoExpressas.mtbFechamento.Post; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally view_FechamentoExpressas.mtbFechamento.IsLoading := False; entregadorDAO.Free; agente.Free; fechamentoDAO.Free; cadastro.Free; end; end; procedure Thread_ProcessaFechamento.ProcessaExtrato; var aParam: array of Variant; entregaTMP : TTotalEntregas; iPos : Integer; iTotal : Integer; begin try entregas := TObjectList<TTotalEntregas>.Create; entrega := TTotalEntregas.Create; entregaDAO := TTotalizaEntregasDAO.Create; extratoDAO := TExtratosExpressasDAO.Create; extrato := TExtratosExpressas.Create; SetLength(aParam,4); aParam[0] := 'S'; aParam[1] := dtInicio; aparam[2] := dtFinal; aparam[3] := 'S'; entregas := entregaDAO.Totaliza(aParam); Finalize(aParam); FdPos := 0; iPos := 0; sMensagem := 'PROCESSANDO AS ENTREGAS. Aguarde ...'; Synchronize(AtualizaProcesso); iTotal := entregas.Count; for entregaTMP in entregas do begin extrato.Id := 0; extrato.Agente := entregaTMP.Agente; extrato.Entregador := entregaTMP.Entregador; extrato.DataInicio := dtInicio; extrato.DataFinal := dtFinal; extrato.DataPagamento := 0; extrato.Volumes := entregaTMP.Volumes; extrato.Entregas := entregaTMP.Entregas; extrato.Atrasos := entregaTMP.Atraso; extrato.VolumesExtra := 0; extrato.SLA := entregaTMP.SLA; extrato.Verba := 0; extrato.ValorEntregas := 0; extrato.ValorVolumesExtra := 0; extrato.ValorProducao := 0; extrato.ValorCreditos := 0; extrato.ValorDebitos := 0; extrato.ValorTotalCreditos := 0; extrato.ValorTotalDebitos := 0; extrato.ValorTotalGeral := 0; extrato.TotalVerbaFranquia := entregaTMP.TotalVerbaFranquia; extrato.PFP := entregaTMP.PFP; extrato.Log := FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' processado por ' + uGlobais.sUsuario; if not extratoDAO.Insert(extrato) then begin Application.MessageBox(PChar('Erro ao salvar os totais de entregas no extrato do entregador ' + extrato.Entregador.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally entrega.Free; entregaDAO.Free; view_FechamentoExpressas.pbFechamento.Position := 0; view_FechamentoExpressas.pbFechamento.Refresh; end; end; procedure Thread_ProcessaFechamento.ProcessaExtravios; var extravioTMP : TExtraviosMultas; extratoTMP : TExtratosExpressas; iPos: Integer; aParam: array of Variant; dtDataBase : TDate; dValor : Double; begin try dtDataBase := Now(); dValor := 0; extravios := TObjectList<TExtraviosMultas>.Create; extravioDAO := TExtraviosMultasDAO.Create; extratos := TObjectList<TExtratosExpressas>.Create; extratoDAO := TExtratosExpressasDAO.Create; SetLength(aParam,1); aParam[0] := 'WHERE DOM_RESTRICAO = ' + QuotedStr('S') + ' AND VAL_PERCENTUAL_PAGO < 100'; extravios := extravioDAO.FindExtravio('FILTRO', aParam); Finalize(aParam); iTotal := extravios.Count; FdPos := 0; iPos := 0; sMensagem := 'PROCESSANDO OS EXTRAVIOS. Aguarde ...'; Synchronize(AtualizaProcesso); for extravioTMP in extravios do begin SetLength(aParam,3); aParam[0] := dtInicio; aParam[1] := dtFinal; aParam[2] := extravioTMP.Entregador; extratos := extratoDAO.FindExtrato('REFERENCIA',aParam); if extratos.Count > 0 then begin for extratoTMP in extratos do begin dValor := extratoTMP.ValorExtravio; if dValor > 0 then dValor := 0 - extratoTMP.ValorExtravio; extratoTMP.ValorExtravio := dValor + (0 - extravioTMP.Total); extratoTMP.Log := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now()) + ' processado por ' + Global.Parametros.pUser_Name; if not extratoDAO.Update(extratoTMP) then begin Application.MessageBox(PChar('Erro ao salvar os extravios no extrato do entregador ' + extratoTMP.Entregador.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; extravioTMP.IDExtrato := extratoTMP.ID; if not extravioDAO.Update(extravioTMP) then begin Application.MessageBox(PChar('Erro ao atualizar o extravio do entregador ' + extravioTMP.Entregador.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; end; end else begin extrato := TExtratosExpressas.Create; extrato.Id := 0; extrato.Agente := extravioTMP.Agente; extrato.Entregador := extravioTMP.Entregador; extrato.DataInicio := dtInicio; extrato.DataFinal := dtFinal; extrato.DataPagamento := 0; extrato.Volumes := 0; extrato.Entregas := 0; extrato.Atrasos := 0; extrato.VolumesExtra := 0; extrato.SLA := 0; extrato.Verba := 0; extrato.ValorEntregas := 0; extrato.ValorVolumesExtra := 0; extrato.ValorProducao := 0; extrato.ValorCreditos := 0; extrato.ValorExtravio := 0 - extravioTMP.Total; extrato.ValorDebitos := 0; extrato.ValorRestricao := 0; extrato.ValorTotalCreditos := 0; extrato.ValorTotalDebitos := 0; extrato.ValorTotalGeral := 0; extrato.Fechado := 0; extrato.TotalVerbaFranquia := 0; extrato.Log := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now()) + ' processado por ' + Global.Parametros.pUser_Name; if not extratoDAO.Insert(extrato) then begin Application.MessageBox(PChar('Erro ao criar o extrato com extravios do entregador ' + extravioTMP.Entregador.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; extravioTMP.IDExtrato := extrato.ID; extrato.Free; end; if not extravioDAO.Update(extravioTMP) then begin Application.MessageBox(PChar('Erro ao atualizar o extravio do entregador ' + extravioTMP.Entregador.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally extravioDAO.Free; extratoDAO.Free; end; end; procedure Thread_ProcessaFechamento.ProcessaLancamentos; var extratoTMP: TExtratosExpressas; aParam: array of Variant; iAgente : Integer; iEntregador: Integer; dValor : Double; iPos: Integer; iTotal: integer; begin try entregadores := TObjectList<TEntregadores>.Create; extratos := TObjectList<TExtratosExpressas>.Create; fechalancamentos := TObjectList<TFechamentoLancamento>.Create; entregadorDAO := TEntregadoresDAO.Create; extratoDAO := TExtratosExpressasDAO.Create; extrato := TExtratosExpressas.Create; lancamento := TLancamentos.Create; agente := TAgente.Create; FdPos := 0; iPos := 0; iTotal := 0; sMensagem := 'PROCESSANDO OS LANÇMENTOS DE CRÉDITOS E DÉBITOS. Aguarde ...'; Synchronize(AtualizaProcesso); if lancamento.getObject(DateToStr(dtFinal), 'PERIODO') then begin iTotal := dm.QryGetObject.RecordCount; while not dm.QryGetObject.Eof do begin if dm.qryGetObject.FieldByName('DOM_DESCONTO').AsString <> 'S' then begin dValor := 0; iAgente := 0; iEntregador := 0; SetLength(aParam,1); aParam[0] := dm.QryGetObject.FieldByName('COD_ENTREGADOR').AsInteger; entregadores := entregadorDAO.FindEntregador('CADASTRO', aParam); Finalize(aParam); if entregadores.Count > 0 then begin iAgente := entregadores[0].Agente; iEntregador := entregadores[0].Entregador; end; SetLength(aParam,3); aParam[0] := dtInicio; aParam[1] := dtFinal; aParam[2] := iEntregador; extratos := extratoDAO.FindExtrato('REFERENCIA', aParam); Finalize(aParam); if extratos.Count > 0 then begin for extratoTMP in extratos do begin if dm.QryGetObject.FieldByName('DES_TIPO').AsString = 'DEBITO' then begin dValor := 0 - dm.QryGetObject.FieldByName('VAL_LANCAMENTO').AsFloat; end else begin dValor := dm.QryGetObject.FieldByName('VAL_LANCAMENTO').AsFloat; end; if dValor < 0 then begin extratoTMP.ValorDebitos := extratoTMP.ValorDebitos + dValor; end else begin extratoTMP.ValorCreditos := extratoTMP.ValorCreditos + dValor; end; if not extratoDAO.Update(extratoTMP) then begin Application.MessageBox(PChar('Erro ao atualizar o extrato do entregador ' + extratoTMP.Entregador.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; // if lancamento.getObject(dm.qryPesquisa.FieldByName('COD_LANCAMENTO').AsString, 'CODIGO') then // begin // if not lancamento.Update() then // begin // Application.MessageBox(PChar('Erro ao atualizar o lancamento do entregador ' + extratoTMP.Entregador.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); // end; // end; dm.QryGetObject.Edit; dm.QryGetObject.FieldByName('NUM_EXTRATO').AsString := extratoTMP.Id.ToString; dm.ZConn.PingServer; dm.QryGetObject.Post; end; end else begin dValor := 0; if dm.QryGetObject.FieldByName('DES_TIPO').AsString = 'DEBITO' then begin dValor := 0 - dm.QryGetObject.FieldByName('VAL_LANCAMENTO').AsFloat; end else begin dValor := dm.QryGetObject.FieldByName('VAL_LANCAMENTO').AsFloat; end; extrato := TExtratosExpressas.Create; extrato.Id := 0; extrato.Agente := iAgente; extrato.Entregador := iEntregador; extrato.DataInicio := dtInicio; extrato.DataFinal := dtFinal; extrato.DataPagamento := 0; extrato.Volumes := 0; extrato.Entregas := 0; extrato.Atrasos := 0; extrato.VolumesExtra := 0; extrato.SLA := 0; extrato.Verba := 0; extrato.ValorEntregas := 0; extrato.ValorVolumesExtra := 0; extrato.ValorProducao := 0; if dValor < 0 then begin extrato.ValorDebitos := dValor; end else begin extrato.ValorCreditos := dValor; end; extrato.ValorTotalCreditos := 0; extrato.ValorTotalDebitos := 0; extrato.ValorTotalGeral := 0; if not extratoDAO.Insert(extrato) then begin Application.MessageBox(PChar('Erro ao salvar os totais de entregas no extrato do entregador ' + extrato.Entregador.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; // if lancamento.getObject(dm.qryPesquisa.FieldByName('COD_LANCAMENTO').AsString, 'CODIGO') then // begin // lancamento.Extrato := extratoTMP.Id.ToString; // if not lancamento.Update() then // begin // Application.MessageBox(PChar('Erro ao atualizar o lancamento do entregador ' + extratoTMP.Entregador.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); // end; // end; dm.QryGetObject.Edit; dm.QryGetObject.FieldByName('NUM_EXTRATO').AsString := extrato.Id.ToString; dm.ZConn.PingServer; dm.QryGetObject.Post; end; end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); dm.QryGetObject.Next; end; end; finally dm.QryGetObject.Close; extratoTMP.Free; entregadorDAO.Free; extratoDAO.Free; lancamento.Free; agente.Free; end; end; procedure Thread_ProcessaFechamento.ProcessaRestricao; var parcelaTMP : TParcelamentoRestricao; extratoTMP: TExtratosExpressas; dtDataBase: TDate; sFiltro: String; aParam: array of Variant; dValor: Double; iExtrato : Integer; iPos : Integer; begin try restricao := TRestricoes.Create; parcelas := TObjectList<TParcelamentoRestricao>.Create; parcela := TParcelamentoRestricao.Create; parcelaDAO :=TParcelamentoRestricaoDAO.Create; extratoDAO := TExtratosExpressasDAO.Create; extrato := TExtratosExpressas.Create; dtDataBase := Now(); dValor := 0; FdPos := 0; iPos := 0; sMensagem := 'PROCESSANDO AS RESTRICÕES. Aguarde ...'; Synchronize(AtualizaProcesso); if restricao.getObject('0','VALOR') then begin while not dm.QryGetObject.Eof do begin iTotal := dm.QryGetObject.RecordCount; dm.QryGetObject.First; sFiltro := 'WHERE COD_RESTRICAO = ' + restricao.Codigo.ToString + ' AND DAT_DEBITO <= ' + FormatDateTime('yyyy-mm-dd', dtDataBase) + ' AND DOM_DEBITADO = 0'; SetLength(aParam,1); aParam[0] := sFiltro; parcelas := parcelaDAO.FindParcelamentos('FILTRO', aParam); Finalize(aParam); if parcelas.Count > 0 then begin for parcelaTMP in parcelas do begin SetLength(aParam,1); aParam[0] := restricao.Entregador; extratos := extratoDAO.FindExtrato('ENTREGADOR', aParam); Finalize(aParam); iExtrato := 0; if extratos.Count > 0 then begin for extratoTMP in extratos do begin dValor := extratotmP.ValorRestricao; dValor := dValor + parcelaTMP.Valor; iExtrato := extratoTMP.Id; extratoTMP.ValorRestricao := (0 - dValor); if not extratoDAO.Update(extratoTMP) then begin Application.MessageBox(PChar('Erro ao salvar a restrição no extrato do entregador ' + extratoTMP.Entregador.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; if parcelaTMP.Extrato <> iExtrato then begin parcelaTMP.Extrato := iExtrato; if not parcelaDAO.Update(parcelaTMP) then begin Application.MessageBox(PChar('Erro ao salvar o número do extrato da restrição nº. ' + parcelaTMP.Restricao.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; end; end; end else begin dValor := 0; extrato.Id := 0; extrato.Agente := restricao.Agente; extrato.Entregador := restricao.Entregador; extrato.DataInicio := dtInicio; extrato.DataFinal := dtFinal; extrato.DataPagamento := 0; extrato.Volumes := 0; extrato.Entregas := 0; extrato.Atrasos := 0; extrato.VolumesExtra := 0; extrato.SLA := 0; extrato.Verba := 0; extrato.ValorEntregas := 0; extrato.ValorVolumesExtra := 0; extrato.ValorProducao := 0; extrato.ValorCreditos := 0; extrato.ValorExtravio := 0; extrato.ValorDebitos := 0; dValor := extratotmP.ValorRestricao; dValor := dValor + parcelaTMP.Valor; extrato.ValorRestricao := (0 - dValor); extrato.ValorTotalCreditos := 0; extrato.ValorTotalDebitos := 0; extrato.ValorTotalGeral := 0; extrato.Fechado := 0; extrato.Log := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now()) + ' processado por ' + Global.Parametros.pUser_Name; if not extratoDAO.Insert(extrato) then begin Application.MessageBox(PChar('Erro ao criar o extrato da restrição nº. ' + parcelaTMP.Restricao.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; iExtrato := extrato.Id; end; parcelaTMP.Extrato := iExtrato; if not parcelaDAO.Update(parcelaTMP) then begin Application.MessageBox(PChar('Erro ao salvar o número do extrato da restrição nº. ' + parcelaTMP.Restricao.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; end; end else begin parcela.Restricao := restricao.Codigo; parcela.Parcela := 1; parcela.TotalParcelas := 1; parcela.Debitado := 0; parcela.Extrato := 0; parcela.Valor := restricao.Debitar; parcela.Data := Now(); SetLength(aParam,1); aParam[0] := restricao.Entregador; extratos := extratoDAO.FindExtrato('ENTREGADOR', aParam); Finalize(aParam); if extratos.Count > 0 then begin for extratoTMP in extratos do begin dValor := extratotmP.ValorRestricao; dValor := dValor + parcela.Valor; iExtrato := extratoTMP.Id; extratoTMP.ValorRestricao := (0 - dValor); if not extratoDAO.Update(extratoTMP) then begin Application.MessageBox(PChar('Erro ao salvar a restrição no extrato do entregador ' + extratoTMP.Entregador.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; end; end else begin dValor := 0; extrato.Id := 0; extrato.Agente := restricao.Agente; extrato.Entregador := restricao.Entregador; extrato.DataInicio := dtInicio; extrato.DataFinal := dtFinal; extrato.DataPagamento := 0; extrato.Volumes := 0; extrato.Entregas := 0; extrato.Atrasos := 0; extrato.VolumesExtra := 0; extrato.SLA := 0; extrato.Verba := 0; extrato.ValorEntregas := 0; extrato.ValorVolumesExtra := 0; extrato.ValorProducao := 0; extrato.ValorCreditos := 0; extrato.ValorExtravio := 0; extrato.ValorDebitos := 0; dValor := extratotmP.ValorRestricao; dValor := dValor + parcelaTMP.Valor; extrato.ValorRestricao := (0 - dValor); extrato.ValorTotalCreditos := 0; extrato.ValorTotalDebitos := 0; extrato.ValorTotalGeral := 0; extrato.Fechado := 0; extrato.Log := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now()) + ' processado por ' + Global.Parametros.pUser_Name; if not extratoDAO.Insert(extrato) then begin Application.MessageBox(PChar('Erro ao criar o extrato da restrição nº. ' + parcelaTMP.Restricao.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; iExtrato := extrato.Id; end; parcela.Extrato := iExtrato; if not parcelaDAO.Insert(parcela) then begin Application.MessageBox(PChar('Erro ao gravar a parcela única da restrição ' + parcelaTMP.Restricao.ToString + '!'), 'Atenção', MB_OK + MB_ICONERROR); end; end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); dm.QryGetObject.Next; end; end; finally restricao.Free; extratoTMP.Free; extrato.Free; parcela.Free; parcelaTMP.Free; parcelaDAO.Free; extratoDAO.Free; end; end; procedure Thread_ProcessaFechamento.ProcessaVerba; var dVerba : Double; dPercentual : Double; dPercentualMin: Double; dPercentualMax: Double; aParam: array of Variant; extratoTMP: TExtratosExpressas; iPos: Integer; iTotal : Integer; iGrupo : Integer; begin try dVerba := 0; dPercentual := 0; dPercentualMin := 0; dPercentualMax := 0; iGrupo := 0; agente := Tagente.Create; verba := TGruposVerba.Create; entregadores := TObjectList<TEntregadores>.Create; entregadorDAO := TEntregadoresDAO.Create; extratos := TObjectList<TExtratosExpressas>.Create; extratoDAO := TExtratosExpressasDAO.Create; SetLength(aParam,3); aParam[0] := dtInicio; aParam[1] := dtFinal; aParam[2] := 0; extratos := extratoDAO.FindExtrato('PERIODO',aParam); Finalize(aParam); FdPos := 0; iPos := 0; sMensagem := 'PROCESSANDO AS VERBAS DE ENTREGA. Aguarde ...'; Synchronize(AtualizaProcesso); iTotal := extratos.Count; for extratoTMP in extratos do begin if agente.getObject(extratoTMP.Agente.ToString,'CODIGO') then begin iGrupo := agente.Grupo; dVerba := agente.Verba; end; // grupo de verba por agente ou verba fixa if iGrupo > 0 then begin if dVerba = 0 then begin dPercentualMax := verba.MaxPercentualGrupo(iGrupo.ToString); dPercentualMin := verba.MinPercentualGrupo(iGrupo.ToString); if bSLA then begin dPercentual := Trunc(extratoTMP.SLA); if dPercentual < dpercentualMin then dPercentual := dPercentualMin; if dPercentual > dpercentualMax then dPercentual := dPercentualMax; end else begin dPercentual := dPercentualMax; end; if dVerba = 0 then begin verba.Percentual := dPercentual; if verba.getObject(iGrupo.ToString,'PERCENTUAL') then begin dVerba := verba.Verba; end; end; end; end; // grupo de verba por entregador ou verba fixa SetLength(aParam,1); aParam[0] := extratoTMP.Entregador; entrEgadores := entregadorDAO.FindEntregador('ENTREGADOR', aParam); Finalize(aParam); if entregadores.Count > 0 then begin if entregadores[0].Verba > 0 then dVerba := entregadores[0].Verba; iGrupo := entregadores[0].Grupo; end; if iGrupo > 0 then begin dPercentualMax := verba.MaxPercentualGrupo(iGrupo.ToString); dPercentualMin := verba.MinPercentualGrupo(iGrupo.ToString); if bSLA then begin dPercentual := Trunc(extratoTMP.SLA); if dPercentual < dpercentualMin then dPercentual := dPercentualMin; if dPercentual > dpercentualMax then dPercentual := dPercentualMax; end else begin dPercentual := dPercentualMax; end; if dVerba = 0 then begin verba.Percentual := dPercentual; if verba.getObject(iGrupo.ToString,'PERCENTUAL') then begin dVerba := verba.Verba; end; end; end; extratoTMP.Verba := dVerba; if not extratoDAO.Update(extratoTMP) then begin Application.MessageBox(PChar('Erro ao gravar a verba no extrato do entregador ' + extrato.Id.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally agente.Free; entregadorDAO.Free; extratoTMP.Free; extratoDAO.Free; end; end; procedure Thread_ProcessaFechamento.TerminaProcesso; begin sMensagem := ''; FdPos := 0; view_FechamentoExpressas.sbFechamento.Panels[0].Text := ''; view_FechamentoExpressas.pbFechamento.Position := 0; view_FechamentoExpressas.pbFechamento.Refresh; view_FechamentoExpressas.pbFechamento.Visible := False; view_FechamentoExpressas.sbFechamento.Refresh; view_FechamentoExpressas.dsFechamento.Enabled := True; view_FechamentoExpressas.actProcessar.Enabled := True; if bFlag then begin Application.MessageBox('Fechamento já encerrado!', 'Atenção', MB_OK + MB_ICONINFORMATION); end else begin view_FechamentoExpressas.actCancelar.Enabled := True; view_FechamentoExpressas.actEncerrar.Enabled := True ; end; view_FechamentoExpressas.dxActivityIndicator1.Active := False; end; procedure Thread_ProcessaFechamento.TotalizaExtrato; var extratoTMP: TExtratosExpressas; aParam: array of Variant; iPos: Integer; iTotal: Integer; begin try extratoDAO := TExtratosExpressasDAO.Create; extratos := TObjectList<TExtratosExpressas>.Create; SetLength(aParam,3); aParam[0] := dtInicio; aParam[1] := dtFinal; aParam[2] := 0; extratos := extratoDAO.FindExtrato('PERIODO', aParam); Finalize(aParam); FdPos := 0; iPos := 0; sMensagem := 'PROCESSANDO A TOTALIZAÇÃO DO EXTRATO. Aguarde ...'; Synchronize(AtualizaProcesso); iTotal := extratos.Count; for extratoTMP in extratos do begin extratoTMP.ValorEntregas := (extratoTMP.Entregas - extratoTMP.PFP) * extratoTMP.Verba; extratoTMP.ValorVolumesExtra := extratoTMP.PFP * 15; extratoTMP.ValorProducao := extratoTMP.ValorEntregas + extratoTMP.ValorVolumesExtra; extratoTMP.ValorTotalCreditos := extratoTMP.ValorProducao + extratoTMP.ValorCreditos; extratoTMP.ValorTotalDebitos := extratoTMP.ValorRestricao + extratoTMP.ValorExtravio + extratoTMP.ValorDebitos; extratoTMP.ValorTotalGeral := extratoTMP.ValorTotalCreditos + extratoTMP.ValorTotalDebitos; if not extratoDAO.Update(extratoTMP) then begin Application.MessageBox(PChar('Erro ao totalizar o extrato do entregador ' + extratoTMP.Id.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR); end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally extratoDAO.Free; end; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 568 of 570 From : John Reid 1:150/170.0 24 Apr 93 14:16 To : Mark Gryn Subj : Diskette Serial Numbers ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ MG> If anyone happens to know how to find the serial number of a MG> diskette, please let me know, code is nice :) This should probably have code added to check for early DOS versions that do not support media id. } unit ugetmid; {Get media ID} INTERFACE uses dos; type TMID = record InfoLevel : word; SN : array[0..1] of word; Labl : array[1..11] of byte; Typ : array[1..8] of byte; end; procedure GetMediaID(Drive : byte; {0=default, 1=A:, 2=B:, 3=C:, etc.} var MID : TMID); IMPLEMENTATION procedure GetMediaID(Drive : byte; var MID : TMID) ; var Regs : registers; begin Regs.bx := Drive; Regs.ch := $08; Regs.cl := $66; Regs.ds := Seg(MID); Regs.dx := Ofs(MID); Regs.ax := $440D; MsDos(Regs) end; END.
unit Aurelius.Drivers.RemoteDB; {$I Aurelius.inc} interface uses Classes, DB, Variants, Generics.Collections, XData.XDataset, XData.XDataset.RemoteDB, Aurelius.Drivers.Base, Aurelius.Drivers.Interfaces; type TXDatasetResultSetAdapter = class(TDriverResultSetAdapter<TXDataset>) public function GetFieldValue(FieldIndex: Integer): Variant; overload; override; end; TXDatasetStatementAdapter = class(TInterfacedObject, IDBStatement) private FQuery: TXDataset; public constructor Create(AQuery: TXDataset); destructor Destroy; override; procedure SetSQLCommand(SQLCommand: string); procedure SetParams(Params: TEnumerable<TDBParam>); procedure Execute; function ExecuteQuery: IDBResultSet; end; TRemoteDBConnectionAdapter = class(TDriverConnectionAdapter<TRemoteDBDatabase>, IDBConnection) protected function RetrieveSqlDialect: string; override; public procedure Connect; procedure Disconnect; function IsConnected: Boolean; function CreateStatement: IDBStatement; function BeginTransaction: IDBTransaction; end; TXDatasetTransactionAdapter = class(TInterfacedObject, IDBTransaction) private FDatabase: TXDatabase; public constructor Create(ADatabase: TXDatabase); procedure Commit; procedure Rollback; end; implementation { TXDatasetStatementAdapter } uses SysUtils, Aurelius.Drivers.Exceptions, Aurelius.Global.Utils; constructor TXDatasetStatementAdapter.Create(AQuery: TXDataset); begin FQuery := AQuery; end; destructor TXDatasetStatementAdapter.Destroy; begin FQuery.Free; inherited; end; procedure TXDatasetStatementAdapter.Execute; begin TXDatabase(FQuery.Database).ExecSQL(FQuery.SQL.Text, FQuery.Params); end; function TXDatasetStatementAdapter.ExecuteQuery: IDBResultSet; var ResultSet: TXDataset; I: Integer; begin ResultSet := TXDataset.Create(nil); try ResultSet.Database := FQuery.Database; ResultSet.SQL := FQuery.SQL; for I := 0 to FQuery.Params.Count - 1 do begin ResultSet.Params[I].DataType := FQuery.Params[I].DataType; ResultSet.Params[I].Value := FQuery.Params[I].Value; end; ResultSet.Open; except ResultSet.Free; raise; end; Result := TXDatasetResultSetAdapter.Create(ResultSet); end; procedure TXDatasetStatementAdapter.SetParams(Params: TEnumerable<TDBParam>); var P: TDBParam; Parameter: TParam; Bytes: TBytes; begin for P in Params do begin Parameter := FQuery.Params.ParamByName(P.ParamName); if P.ParamType in [ftBlob, ftOraBlob, ftOraClob] then begin // Specific SQL-Direct workaround for blob fields. If param type is ftBlob, then we must set the // blob content as string, because it's the only way it works fine for all databases Parameter.DataType := P.ParamType; Bytes := TUtils.VariantToBytes(P.ParamValue); if VarIsNull(P.ParamValue) or (Length(Bytes) = 0) then Parameter.Clear else Parameter.AsBlob := Bytes; end else begin Parameter.DataType := P.ParamType; Parameter.Value := P.ParamValue; end; end; end; procedure TXDatasetStatementAdapter.SetSQLCommand(SQLCommand: string); begin FQuery.SQL.Text := SQLCommand; end; { TXDatasetConnectionAdapter } procedure TRemoteDBConnectionAdapter.Disconnect; begin if Connection <> nil then Connection.Connected := False; end; function TRemoteDBConnectionAdapter.RetrieveSqlDialect: string; begin if Connection = nil then Exit(''); Result := Connection.SqlDialect; end; function TRemoteDBConnectionAdapter.IsConnected: Boolean; begin if Connection <> nil then Result := Connection.Connected else Result := false; end; function TRemoteDBConnectionAdapter.CreateStatement: IDBStatement; var Statement: TXDataset; begin if Connection = nil then Exit(nil); Statement := TXDataset.Create(nil); try Statement.Database := Connection; except Statement.Free; raise; end; Result := TXDatasetStatementAdapter.Create(Statement); end; procedure TRemoteDBConnectionAdapter.Connect; begin if Connection <> nil then Connection.Connected := True; end; function TRemoteDBConnectionAdapter.BeginTransaction: IDBTransaction; begin if Connection = nil then Exit(nil); Connection.Connected := true; if not Connection.InTransaction then begin Connection.BeginTransaction; Result := TXDatasetTransactionAdapter.Create(Connection); end else Result := TXDatasetTransactionAdapter.Create(nil); end; { TXDatasetTransactionAdapter } procedure TXDatasetTransactionAdapter.Commit; begin if (FDatabase = nil) then Exit; FDatabase.Commit; end; constructor TXDatasetTransactionAdapter.Create(ADatabase: TXDatabase); begin FDatabase := ADatabase; end; procedure TXDatasetTransactionAdapter.Rollback; begin if (FDatabase = nil) then Exit; FDatabase.Rollback; end; { TXDatasetResultSetAdapter } function TXDatasetResultSetAdapter.GetFieldValue(FieldIndex: Integer): Variant; var S: string; begin Result := inherited GetFieldValue(FieldIndex); case VarType(Result) of varUString, varOleStr: begin S := VarToStr(Result); Result := VarAsType(S, varString); end; end; end; end.
unit Tests.Adapter; interface uses DUnitX.TestFramework; type [TestFixture] TTestAdapter = class(TObject) public [Setup] procedure Setup; [TearDown] procedure TearDown; // Sample Methods // Simple single Test [Test] procedure Test1; // Test with TestCase Attribute to supply parameters. [Test] [TestCase('TestA','1,2')] [TestCase('TestB','3,4')] procedure Test2(const AValue1 : Integer;const AValue2 : Integer); end; implementation procedure TTestAdapter.Setup; begin end; procedure TTestAdapter.TearDown; begin end; procedure TTestAdapter.Test1; begin end; procedure TTestAdapter.Test2(const AValue1 : Integer;const AValue2 : Integer); begin end; initialization TDUnitX.RegisterTestFixture(TTestAdapter); end.
unit PLAT_PlatFunctionLink; interface uses Menus, Classes, PLAT_QuickLink; type TPlatFunctionLink = class(TQuickLink) private FPopupMenu: TPopupMenu; FMenuItem: TMenuItem; procedure SetMenuItem(const Value: TMenuItem); function FindMenuItem(szData: string): TMenuItem; procedure RefreshPopupMenu; public constructor Create; destructor Destroy; override; procedure Execute; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; property MenuItem: TMenuItem read FMenuItem write SetMenuItem; end; implementation { TPlatFunctionLink } uses PLAT_Utils, Windows, Forms; procedure TPlatFunctionLink.Execute; var pt: TPoint; begin inherited; if MenuItem.Count = 0 then MenuItem.Click else begin GetCursorPos(pt); RefreshPopupMenu; FPopupMenu.Popup(pt.x, pt.y); end; end; procedure TPLatFunctionLink.RefreshPopupMenu; begin FPopupMenu.Items.Clear; FPopupMenu.Items.Add(MenuItem); end; function TPlatFunctionLink.FindMenuItem(szData: string): TMenuItem; begin Result := Application.MainForm.FindComponent(szData) as TMenuItem; end; procedure TPlatFunctionLink.LoadFromStream(Stream: TStream); var szData: string; begin inherited; TUtils.LoadStringFromStream(Stream, szData); Tutils.LoadStringFromStream(Stream, FCaption); TUtils.LoadStringFromStream(Stream, FDescription); Stream.Read(FLeft, SizeOf(FLeft)); Stream.Read(FTop, SizeOf(FTop)); TUtils.LoadStringFromStream(Stream, szData); FMenuItem := FindMenuItem(szData); end; procedure TPlatFunctionLink.SaveToStream(Stream: TStream); var i: Integer; szData: string; begin szData := self.ClassName; TUtils.SaveStringToStream(Stream, szData); //pub start Tutils.SaveStringToStream(Stream, FCaption); TUtils.SaveStringToStream(Stream, FDescription); Stream.Write(FLeft, SizeOf(FLeft)); Stream.Write(FTop, SizeOf(FTop)); //pub start TUtils.SaveStringToStream(Stream, MenuItem.Name); end; procedure TPlatFunctionLink.SetMenuItem(const Value: TMenuItem); begin FMenuItem := Value; end; constructor TPlatFunctionLink.Create; begin FPopupMenu := TPopupMenu.Create(Forms.Application); end; destructor TPlatFunctionLink.Destroy; begin FpopupMenu.Free; inherited; end; end.
unit testkata; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, example; type TTestKata= class(TTestCase) protected procedure SetUp; override; procedure TearDown; override; published procedure TestHookUp; end; implementation procedure TTestKata.SetUp; begin end; procedure TTestKata.TearDown; begin end; procedure TTestKata.TestHookUp; var Greeter: TGreeter; begin Greeter := TGreeter.Create; AssertEquals('Hello, World!', Greeter.Hello('World')); FreeAndNil(Greeter); end; initialization RegisterTest(TTestKata); end.
const eps = 1e-3; var n: integer; k, l, sign, newsum, oldsum: real; begin n := 1; // индекс, кол-во слагаемых sign := 1.0; // чередование знаков newsum := 0; k := 1; repeat l := 1; repeat oldsum := newsum; newsum := newsum + sign * k * l / sqr (k + l); l := l + 1; n := n + 1; until abs (newsum - oldsum) < eps; k := k + 1; sign := -sign; until abs (newsum - oldsum) < eps; writeln ('Serie sum = ', newsum:8:5); writeln ('Number of serie components = ', n); end.
{********************************************************} { } { Zeos Database Objects } { Common resource constants } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZCommonConst; interface {$INCLUDE ../Zeos.inc} resourcestring {$IFNDEF RUSSIAN} {$IFNDEF GERMAN} {$IFNDEF PORTUGUESE} {$IFNDEF FRENCH} {$IFNDEF POLISH} {$IFNDEF CZECH} {$IFNDEF ITALIAN} {$IFNDEF DUTCH} {$IFNDEF SPANISH} {$IFNDEF CROATIAN} {$IFNDEF HUNGARY} SPrevMonth = 'Prior month|'; SPrevYear = 'Prior year|'; SNextMonth = 'Next month|'; SNextYear = 'Next year|'; SDateDlgTitle = 'Choose date'; SDefaultFilter = 'All files (*.*)|*.*'; SBrowse = 'List'; SSyntaxError = 'Syntax error'; SIncorVarIdx = 'Incorrect variable index'; SIncorFuncIdx = 'Incorrect function index'; STypesMismatch = 'Types mismatch'; SFuncNotFound = 'Function = "%s" not found'; SVarNotFound = 'Variable = "%s" not found'; SIncorOperate = 'Incorrect operation'; SEvalError = 'Evalution error'; SStackFull = 'Stack is full'; SStackEmpty = 'Stack is empty'; SIncorFuncParam = 'Incorrect params in function = "%s"'; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF RUSSIAN} SPrevMonth = '¤­ňńűńˇ¨ŔÚ ýň˝ ÷|'; SPrevYear = '¤­ňńűńˇ¨ŔÚ Ńţń|'; SNextMonth = 'ĐŰňńˇ■¨ŔÚ ýň˝ ÷|'; SNextYear = 'ĐŰňńˇ■¨ŔÚ Ńţń|'; SDateDlgTitle = '┬űßň­Ŕ˛ň ńÓ˛ˇ'; SDefaultFilter = '┬˝ň ˘ÓÚŰű (*.*)|*.*'; SBrowse = 'Đ´Ŕ˝ţŕ'; SSyntaxError = 'ĐŔݲÓŕ˝Ŕ¸ň˝ŕÓ  ţ°ŔßŕÓ'; SIncorVarIdx = '═ň´­ÓÔŔŰŘÝűÚ ŔÝńňŕ˝ ´ň­ňýňÝÝţÚ'; SIncorFuncIdx = '═ň´­ÓÔŔŰŘÝűÚ ŔÝńňŕ˝ ˘ˇÝŕ÷ŔŔ'; STypesMismatch = '╬°ŔßŕÓ ˛Ŕ´ţÔ'; SFuncNotFound = 'ďˇÝŕ÷Ŕ  = "%s" Ýň ÝÓÚńňÝÓ'; SVarNotFound = '¤ň­ňýňÝÝÓ  = "%s" Ýň ÝÓÚńňÝÓ'; SIncorOperate = '═ň´­ÓÔŔŰŘÝÓ  ţ´ň­Ó÷Ŕ '; SEvalError = '╬°ŔßŕÓ Ôű¸Ŕ˝ŰňÝŔÚ'; SStackFull = 'вňŕ ´ţŰţÝ'; SStackEmpty = 'вňŕ ´ˇ˝˛'; SIncorFuncParam = '═ň´­ÓÔŔŰŘÝűň ´Ó­Óýň˛­ű Ô ˘ˇÝŕ÷ŔŔ = "%s"'; {$ENDIF} {$IFDEF GERMAN} SPrevMonth = 'Voriger Monat|'; SPrevYear = 'Voriges Jahr|'; SNextMonth = 'Nńchster Monat|'; SNextYear = 'Nńchstes Jahr|'; SDateDlgTitle = 'Datum wńhlen'; SDefaultFilter = 'Alle Dateien (*.*)|*.*'; SBrowse = 'Liste'; SSyntaxError = 'Syntax-Fehler'; SIncorVarIdx = 'Falscher Variablen-Index'; SIncorFuncIdx = 'Falscher Funktions-Index'; STypesMismatch = 'Typ-Fehler'; SFuncNotFound = 'Funktion = "%s" nicht gefunden'; SVarNotFound = 'Variable = "%s" nicht gefunden'; SIncorOperate = 'Falsche Operation'; SEvalError = 'Auswertungsfehler'; SStackFull = 'Stack ist voll'; SStackEmpty = 'Stack ist leer'; SIncorFuncParam = 'Falsche Parameter in Funktion = "%s"'; {$ENDIF} {$IFDEF PORTUGUESE} SPrevMonth = 'M˙s anterior|'; SPrevYear = 'Ano anterior|'; SNextMonth = 'Pr║ximo m˙s|'; SNextYear = 'Pr║ximo ano|'; SDateDlgTitle = 'Escolha a data'; SDefaultFilter = 'Todos os arquivos (*.*)|*.*'; SBrowse = 'Lista'; SSyntaxError = 'Erro de sintaxe'; SIncorVarIdx = '-ndice variavel incorreto'; SIncorFuncIdx = 'Incorrect function index'; STypesMismatch = 'Erro de tipos'; SFuncNotFound = 'Fun¸ˇo = "%s" nˇo encontrada'; SVarNotFound = 'Vari˝vel = "%s" nˇo encontrada'; SIncorOperate = 'Opera¸ˇo incorreta'; SEvalError = 'Erro de avalia¸ˇo'; SStackFull = 'A pilha est˝ cheia'; SStackEmpty = 'A Pilha est˝ vazia'; SIncorFuncParam = 'Par˛metros incorretos na fun¸ˇo = "%s"'; {$ENDIF} {$IFDEF FRENCH} SPrevMonth = 'Mois prÚcÚdent|'; SPrevYear = 'AnnÚe prÚcÚdente|'; SNextMonth = 'Mois suivant|'; SNextYear = 'AnnÚe suivante|'; SDateDlgTitle = 'Choisir la date'; SDefaultFilter = 'Tous les fichiers (*.*)|*.*'; SBrowse = 'Liste'; SSyntaxError = 'Erreur de syntaxe'; SIncorVarIdx = 'Indice de variable incorrect'; SIncorFuncIdx = 'Indice de fonction incorrect'; STypesMismatch = 'Type incorrect'; SFuncNotFound = 'Fonction = "%s" non trouvÚe'; SVarNotFound = 'Variable = "%s" non trouvÚe'; SIncorOperate = 'OpÚration incorrecte'; SEvalError = 'Erreur d''Úvaluation'; SStackFull = 'Pile pleine'; SStackEmpty = 'Pile vide'; SIncorFuncParam = 'ParamŔtre incorrect de la fonction = "%s"'; {$ENDIF} {$IFDEF POLISH} SPrevMonth = 'Poprzedni miesiŽc|'; SPrevYear = 'Poprzedni rok|'; SNextMonth = 'Nast˙pny miesiŽc|'; SNextYear = 'Nast˙pny rok|'; SDateDlgTitle = 'Wybierz dat˙'; SDefaultFilter = 'Wszystkie pliki (*.*)|*.*'; SBrowse = 'Lista'; SSyntaxError = 'BŽŽd skŽadni'; SIncorVarIdx = 'BŽ˙dny indeks zmiennej'; SIncorFuncIdx = 'BŽ˙dny indeks funkcji'; STypesMismatch = 'Przestawienie typ║w'; SFuncNotFound = 'Nie znaleziono funkcji "%s"'; SVarNotFound = 'Nie znaleziono zmiennej "%s"'; SIncorOperate = 'BŽ˙dna operacja'; SEvalError = 'BŽ˙dne oszacowanie'; SStackFull = 'PrzepeŽniony stos'; SStackEmpty = 'Pusty stos'; SIncorFuncParam = 'BŽ˙dne argumenty funkcji "%s"'; {$ENDIF} {$IFDEF CZECH} SPrevMonth = 'Prior month|'; SPrevYear = 'Prior year|'; SNextMonth = 'Next month|'; SNextYear = 'Next year|'; SDateDlgTitle = 'Choose date'; SDefaultFilter = 'All files (*.*)|*.*'; SBrowse = 'List'; SSyntaxError = 'Syntax error'; SIncorVarIdx = 'Incorrect variable index'; SIncorFuncIdx = 'Incorrect function index'; STypesMismatch = 'Types mismatch'; SFuncNotFound = 'Function = "%s" not found'; SVarNotFound = 'Variable = "%s" not found'; SIncorOperate = 'Incorrect operation'; SEvalError = 'Evalution error'; SStackFull = 'Stack is full'; SStackEmpty = 'Stack is empty'; SIncorFuncParam = 'Incorrect params in function = "%s"'; {$ENDIF} {$IFDEF ITALIAN} SPrevMonth = 'mese precedente|'; SPrevYear = 'anno precedente|'; SNextMonth = 'mese successivo|'; SNextYear = 'anno successivo|'; SDateDlgTitle = 'Scegli una data'; SDefaultFilter = 'Tutti i file (*.*)|*.*'; SBrowse = 'Lista'; SSyntaxError = 'Errore di sintassi'; SIncorVarIdx = 'Errato variable index'; SIncorFuncIdx = 'Errato function index'; STypesMismatch = 'Tipo errato'; SFuncNotFound = 'Funzione = "%s" non trovata'; SVarNotFound = 'Variabile = "%s" non trovata'; SIncorOperate = 'Operazione non corretta'; SEvalError = 'Errore di valutazione'; SStackFull = 'Stack pieno'; SStackEmpty = 'Stack vuoto'; SIncorFuncParam = 'Parametri incorretti nella funzione = "%s"'; {$ENDIF} {$IFDEF DUTCH} SPrevMonth = 'Vorige maand|'; SPrevYear = 'Vorig jaar|'; SNextMonth = 'Volgende maand|'; SNextYear = 'Volgend jaar|'; SDateDlgTitle = 'Kies datum'; SDefaultFilter = 'Alle bestanden (*.*)|*.*'; SBrowse = 'Lijst'; SSyntaxError = 'Syntax fout'; SIncorVarIdx = 'Incorrecte variable index'; SIncorFuncIdx = 'Incorrecte functie index'; STypesMismatch = 'Types passen niet'; SFuncNotFound = 'Functie = "%s" niet gevonden'; SVarNotFound = 'Variable = "%s" niet gevonden'; SIncorOperate = 'Incorrecte operatie'; SEvalError = 'Evalutiefout'; SStackFull = 'Stack is vol'; SStackEmpty = 'Stack is leeg'; SIncorFuncParam = 'Incorrecte parameters in functie = "%s"'; {$ENDIF} {$IFDEF SPANISH} SPrevMonth = 'Mes Anterior|'; SPrevYear = 'A˝o Anterior|'; SNextMonth = 'Mes Siguiente|'; SNextYear = 'A˝o Siguiente|'; SDateDlgTitle = 'Elegir Fechas'; SDefaultFilter = 'Todos los archivos (*.*)|*.*'; SBrowse = 'Listar'; SSyntaxError = 'Error de Syntaxis'; SIncorVarIdx = 'Indice de variable arroneo'; SIncorFuncIdx = 'Indice de Funcion Erroneo'; STypesMismatch = 'Tipos iguales'; SFuncNotFound = 'Funcion = "%s" no existe'; SVarNotFound = 'Variable = "%s" no existe'; SIncorOperate = 'Operacion Incorrecta'; SEvalError = 'Error de Evaluacion'; SStackFull = 'Pila Llena'; SStackEmpty = 'Pila Vacia'; SIncorFuncParam = 'Parametros incorrectos en la funcion = "%s"'; {$ENDIF} {$IFDEF CROATIAN} SPrevMonth = 'Predhodni mjesec|'; SPrevYear = 'Predhodna godina|'; SNextMonth = 'Slijede÷i mjesec|'; SNextYear = 'Slijede÷a godina|'; SDateDlgTitle = 'Izaberi nadnevak'; SDefaultFilter = 'Sve datoteke (*.*)|*.*'; SBrowse = 'Listaj'; SSyntaxError = 'Sintaksna gre┌ka'; SIncorVarIdx = 'Krivi indeks varijable'; SIncorFuncIdx = 'Krivi indeks funkcije'; STypesMismatch = 'Nekompatibilni tipovi'; SFuncNotFound = 'Funkcija = "%s" nije pronaĘena'; SVarNotFound = 'Varijabla = "%s" nije pronaĘena'; SIncorOperate = 'Kriva operacija'; SEvalError = 'Gre┌ka u izra°unu'; SStackFull = 'Stog je pun'; SStackEmpty = 'Stog je prazan'; SIncorFuncParam = 'Krivi parametri u funkciji = "%s"'; {$ENDIF} {$IFDEF HUNGARY} SPrevMonth = 'El§z§ hˇnap|'; SPrevYear = 'El§z§ Úv|'; SNextMonth = 'K÷v. hˇnap|'; SNextYear = 'K÷v. Úv|'; SDateDlgTitle = 'Dßtumvßlasztßs'; SDefaultFilter = 'Minden file (*.*)|*.*'; SBrowse = 'Lista'; SSyntaxError = 'Nyelvtani hiba'; SIncorVarIdx = 'Hibßs vßltozˇ index'; SIncorFuncIdx = 'Hibßs fŘggvÚny index'; STypesMismatch = 'TÝpuskeveredÚs'; SFuncNotFound = ' = "%s" fŘggvÚny nem talßlhatˇ'; SVarNotFound = ' = "%s" vßltozˇ nem talßlhatˇ'; SIncorOperate = 'Hibßs művelet'; SEvalError = 'KiÚrtÚkelÚs hiba'; SStackFull = 'Stack tele'; SStackEmpty = 'Stack Řres'; SIncorFuncParam = 'Hibßs paramÚter a = "%s" fŘggvÚnyben'; {$ENDIF} implementation end.
{******************************************************************************* 作者: dmzn@163.com 2013-10-31 描述: 管理任务单配比 *******************************************************************************} unit UFormRwd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Grids, ValEdit, ComCtrls, StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxLabel, ImgList; type TfFormRwd = class(TForm) PanelClient: TPanel; Splitter1: TSplitter; PanelTop: TPanel; ListRwd: TListView; cxLabel1: TcxLabel; Splitter2: TSplitter; ListSJ: TListView; ImageList1: TImageList; Panel1: TPanel; EditName: TLabeledEdit; EditGB: TLabeledEdit; cxLabel2: TcxLabel; BtnSave: TButton; ListSC: TListView; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure ListRwdClick(Sender: TObject); procedure ListSJChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure EditGBChange(Sender: TObject); procedure BtnSaveClick(Sender: TObject); private { Private declarations } FLastRwd: string; FLastList: TListView; procedure LoadRwdList; function GetSelectedRwd: string; procedure LoadRwdData(const nID: string); procedure MakeSQLList(const nList: TStrings); public { Public declarations } end; procedure ShowRwdPBForm; //入口函数 implementation {$R *.dfm} uses DB, ULibFun, UMgrDBConn, UFormCtrl, IniFiles, USysConst; var gForm: TfFormRwd = nil; //全局使用 procedure ShowRwdPBForm; begin if not Assigned(gForm) then gForm := TfFormRwd.Create(Application); //xxxxx with gForm do begin BackupData(sSCCtrl, sTable_RwdPB); LoadRwdList; Show; end; end; procedure TfFormRwd.FormCreate(Sender: TObject); var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sConfigFile); try FLastRwd := ''; FLastList := nil; LoadFormConfig(Self, nIni); PanelTop.Height := nIni.ReadInteger(Name, 'PanelH', 300); ListSC.Width := nIni.ReadInteger(Name, 'ListW', 300); finally nIni.Free; end; end; procedure TfFormRwd.FormClose(Sender: TObject; var Action: TCloseAction); var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sConfigFile); try SaveFormConfig(Self, nIni); nIni.WriteInteger(Name, 'PanelH', PanelTop.Height); nIni.WriteInteger(Name, 'ListW', ListSC.Width); finally nIni.Free; end; Action := caFree; gForm := nil; end; //------------------------------------------------------------------------------ function TfFormRwd.GetSelectedRwd: string; begin if Assigned(ListRwd.Selected) then Result := ListRwd.Selected.Caption else Result := ''; end; procedure TfFormRwd.LoadRwdList; var nStr: string; nIdx: Integer; nWorker: PDBWorker; begin nWorker := nil; try ListRwd.Clear; nStr := Format('Select * From %s', [sTable_Rwd]); with gDBConnManager.SQLQuery(nStr, nWorker, sSCCtrl) do if RecordCount > 0 then begin if ListRwd.Columns.Count < 1 then begin for nIdx:=0 to FieldCount - 2 do with ListRwd.Columns.Add do begin Caption := Fields[nIdx].FieldName; Width := 75; end; end; First; while not Eof do begin with ListRwd.Items.Add do begin Caption := Fields[0].AsString; for nIdx:=1 to FieldCount - 2 do SubItems.Add(Fields[nIdx].AsString); //xxxxx end; Next; end; end; finally gDBConnManager.ReleaseConnection(nWorker); end; end; procedure TfFormRwd.ListRwdClick(Sender: TObject); var nStr: string; begin nStr := GetSelectedRwd; if (nStr <> '') and (nStr <> FLastRwd) then begin LoadRwdData(nStr); FLastRwd := nStr; end; end; function FindListItem(const nLV: TListView; const nField: string): TListItem; var nIdx: Integer; begin Result := nil; for nIdx:=nLV.Items.Count - 1 downto 0 do if CompareText(nField, nLV.Items[nIdx].SubItems[3]) = 0 then begin Result := nLV.Items[nIdx]; Break; end; end; //Date: 2013-10-31 //Parm: 任务单号 //Desc: 载入nID的数据 procedure TfFormRwd.LoadRwdData(const nID: string); var nStr: string; nIdx: Integer; nItem: TListItem; nWorker: PDBWorker; begin nWorker := nil; try ListSC.Clear; ListSJ.Clear; nStr := 'Select * From %s Order By FID'; nStr := Format(nStr, [sTable_RwdPBName]); with gDBConnManager.SQLQuery(nStr, nWorker, sSCCtrl) do if RecordCount > 0 then begin First; while not Eof do begin with ListSC.Items.Add do begin Caption := FieldByName('FDisName').AsString; SubItems.Add(FieldByName('FClgg').AsString); SubItems.Add(''); SubItems.Add(''); SubItems.Add(FieldByName('FpbName1').AsString); end; with ListSJ.Items.Add do begin Caption := FieldByName('FDisName').AsString; SubItems.Add(FieldByName('FClgg').AsString); SubItems.Add(''); SubItems.Add(''); SubItems.Add(FieldByName('FpbName1').AsString); end; Next; end; end; //-------------------------------------------------------------------------- nStr := 'Select * From %s_b Where pb_bh=''%s'''; nStr := Format(nStr, [sTable_RwdPB, nID]); with gDBConnManager.WorkerQuery( nWorker, nStr) do if RecordCount > 0 then begin First; while not Eof do begin nStr := FieldByName('pb_flag').AsString; if nStr = '0' then begin for nIdx:=FieldCount - 1 downto 0 do begin nItem := FindListItem(ListSC, Fields[nIdx].FieldName); if Assigned(nItem) then nItem.SubItems[1] := Fields[nIdx].AsString; //xxxxx end; end else if nStr = '1' then begin for nIdx:=FieldCount - 1 downto 0 do begin nItem := FindListItem(ListSJ, Fields[nIdx].FieldName); if Assigned(nItem) then nItem.SubItems[1] := Fields[nIdx].AsString; //xxxxx end; end; Next; end; end; finally gDBConnManager.ReleaseConnection(nWorker); end; end; procedure TfFormRwd.ListSJChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if Assigned(Item) and (Sender as TWinControl).Focused then begin EditName.Text := Item.Caption; EditGB.Text := Item.SubItems[1]; FLastList := Sender as TListView; end else EditName.Text := ''; end; procedure TfFormRwd.EditGBChange(Sender: TObject); begin if (Sender as TWinControl).Focused and IsNumber(EditGB.Text, True) then begin if Assigned(FLastList) and Assigned(FLastList.Selected) then FLastList.Selected.SubItems[2] := EditGB.Text; //xxxxx end; end; procedure TfFormRwd.MakeSQLList(const nList: TStrings); var nStr: string; nIdx: Integer; nMI: TDynamicMacroArray; begin SetLength(nMI, ListSC.Items.Count); for nIdx:=0 to ListSC.Items.Count - 1 do with ListSC.Items[nIdx] do begin nMI[nIdx].FMacro := SubItems[3]; if IsNumber(SubItems[2], True) then nMI[nIdx].FValue := SubItems[2] else nMI[nIdx].FValue := SubItems[1]; if not IsNumber(nMI[nIdx].FValue, True) then nMI[nIdx].FValue := '0'; //xxxxx end; nStr := 'pb_bh=''%s'' And pb_flag=''%s'''; nStr := Format(nStr, [GetSelectedRwd, '0']); nStr := MakeSQLByMI(nMI, sTable_RwdPB + '_b', nStr, False); nList.Add(nStr); //生产配比 for nIdx:=0 to ListSJ.Items.Count - 1 do with ListSJ.Items[nIdx] do begin nMI[nIdx].FMacro := SubItems[3]; if IsNumber(SubItems[2], True) then nMI[nIdx].FValue := SubItems[2] else nMI[nIdx].FValue := SubItems[1]; if not IsNumber(nMI[nIdx].FValue, True) then nMI[nIdx].FValue := '0'; //xxxxx end; nStr := 'pb_bh=''%s'' And pb_flag=''%s'''; nStr := Format(nStr, [GetSelectedRwd, '1']); nStr := MakeSQLByMI(nMI, sTable_RwdPB + '_b', nStr, False); nList.Add(nStr); //砂浆配比 end; procedure TfFormRwd.BtnSaveClick(Sender: TObject); var nList: TStrings; begin if GetSelectedRwd() = '' then begin ShowMsg('请在上面的列表中选择配比', sHint); Exit; end; BtnSave.Enabled := False; nList := nil; try nList := TStringList.Create; MakeSQLList(nList); gDBConnManager.ExecSQLs(nList, True, sSCCtrl); finally nList.Free; BtnSave.Enabled := True; ShowMsg('保存成功', sHint); end; end; end.
unit Mail4Delphi; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface uses {$IF DEFINED(FPC)} Classes, SysUtils, Variants, {$ELSE} System.Classes, System.SysUtils, System.Variants, {$ENDIF} IdSMTP, IdSSLOpenSSL, IdMessage, IdMessageParts, IdText, IdAttachmentFile, IdExplicitTLSClientServerBase, Mail4Delphi.Intf; type IMail = Mail4Delphi.Intf.IMail; TMail = class(TInterfacedObject, IMail) private const CONNECT_TIMEOUT = 60000; READ_TIMEOUT = 60000; private FIdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL; FIdSMTP: TIdSMTP; FIdMessage: TIdMessage; FIdText: TIdText; FSSL: Boolean; FAuth: Boolean; FReceiptRecipient: Boolean; function AddTo(const AMail: string; const AName: string = ''): IMail; function From(const AMail: string; const AName: string = ''): IMail; function ReceiptRecipient(const AValue: Boolean): IMail; function Subject(const ASubject: string): IMail; function AddReplyTo(const AMail: string; const AName: string = ''): IMail; function AddCC(const AMail: string; const AName: string = ''): IMail; function AddBCC(const AMail: string; const AName: string = ''): IMail; function AddBody(const ABody: string): IMail; function ClearBody: IMail; function ClearAttachments: IMail; function Host(const AHost: string): IMail; function UserName(const AUserName: string): IMail; function Password(const APassword: string): IMail; function Port(const APort: Integer): IMail; function AddAttachment(const AFile: string; ATemporaryFile: Boolean = False): IMail; overload; function AddAttachment(const AStream: TStream; const AFileName: string; const AContentType: string = ''): IMail; overload; function Auth(const AValue: Boolean): IMail; function SSL(const AValue: Boolean): IMail; function ContentType(const AValue: string): IMail; function ConnectTimeout(const ATimeout: Integer): IMail; function ReadTimeout(const ATimeout: Integer): IMail; function Clear: IMail; function SendMail: Boolean; function SetUpEmail: Boolean; function Connect: Boolean; function Disconnect: Boolean; function MessageDefault: IMail; protected property IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL read FIdSSLIOHandlerSocket write FIdSSLIOHandlerSocket; property IdSMTP: TIdSMTP read FIdSMTP write FIdSMTP; property IdMessage: TIdMessage read FIdMessage write FIdMessage; property IdText: TIdText read FIdText write FIdText; property SetSSL: Boolean read FSSL write FSSL; property SetAuth: Boolean read FAuth write FAuth; property SetReceiptRecipient: Boolean read FReceiptRecipient write FReceiptRecipient; public class function New: IMail; constructor Create; destructor Destroy; override; end; implementation function TMail.From(const AMail: string; const AName: string = ''): IMail; begin if AMail.Trim.IsEmpty then raise Exception.Create('Sender email not informed!'); FIdMessage.From.Address := AMail.Trim; FIdMessage.From.Name := AName.Trim; Result := Self; end; function TMail.AddBCC(const AMail: string; const AName: string = ''): IMail; begin Result := Self; if AMail.Trim.IsEmpty then Exit; with FIdMessage.BccList.Add do begin Address := AMail.Trim; Name := AName.Trim; end; end; function TMail.AddAttachment(const AFile: string; ATemporaryFile: Boolean): IMail; var LFile: TIdAttachmentFile; begin LFile := TIdAttachmentFile.Create(FIdMessage.MessageParts, AFile); LFile.ContentDescription := ExtractFileName(AFile); LFile.FileIsTempFile := ATemporaryFile; Result := Self; end; function TMail.AddAttachment(const AStream: TStream; const AFileName: string; const AContentType: string): IMail; var LFile: TIdAttachmentFile; begin AStream.Position := 0; LFile := TIdAttachmentFile.Create(FIdMessage.MessageParts, AFileName); LFile.StoredPathName := EmptyStr; LFile.ContentDescription := AFileName; if not AContentType.Trim.IsEmpty then LFile.ContentType := AContentType; LFile.LoadFromStream(AStream); Result := Self; end; function TMail.Auth(const AValue: Boolean): IMail; begin FAuth := AValue; Result := Self; end; function TMail.AddBody(const ABody: string): IMail; begin FIdText.Body.Add(ABody); Result := Self; end; function TMail.Host(const AHost: string): IMail; begin if AHost.Trim.IsEmpty then raise Exception.Create('Server not informed!'); FIdSMTP.Host := AHost; Result := Self; end; function TMail.MessageDefault: IMail; begin FIdMessage.Encoding := meMIME; FIdMessage.ConvertPreamble := True; FIdMessage.Priority := mpNormal; FIdMessage.ContentType := 'multipart/mixed'; FIdMessage.CharSet := 'utf-8'; FIdMessage.Date := Now; Result := Self; end; function TMail.Password(const APassword: string): IMail; begin if APassword.Trim.IsEmpty then raise Exception.Create('Password not informed!'); FIdSMTP.Password := APassword; Result := Self; end; function TMail.Port(const APort: Integer): IMail; begin if VarIsNull(APort) then raise Exception.Create('Port not informed!'); FIdSMTP.Port := APort; Result := Self; end; function TMail.ReadTimeout(const ATimeout: Integer): IMail; begin if (ATimeout > 0) then FIdSMTP.ReadTimeout := ATimeout; Result := Self; end; function TMail.ReceiptRecipient(const AValue: Boolean): IMail; begin FReceiptRecipient := AValue; Result := Self; end; function TMail.SSL(const AValue: Boolean): IMail; begin FSSL := AValue; Result := Self; end; function TMail.AddCC(const AMail: string; const AName: string = ''): IMail; begin Result := Self; if AMail.Trim.IsEmpty then Exit; with FIdMessage.CCList.Add do begin Address := AMail.Trim; Name := AName.Trim; end; end; function TMail.AddReplyTo(const AMail: string; const AName: string = ''): IMail; begin Result := Self; if AMail.Trim.IsEmpty then Exit; with FIdMessage.ReplyTo.Add do begin Address := AMail.Trim; Name := AName.Trim; end; end; function TMail.Subject(const ASubject: string): IMail; begin if ASubject.Trim.IsEmpty then raise Exception.Create('Subject not informed!'); FIdMessage.Subject := ASubject; Result := Self; end; function TMail.AddTo(const AMail: string; const AName: string = ''): IMail; begin if AMail.Trim.IsEmpty then raise Exception.Create('Recipient email not informed!'); with FIdMessage.Recipients.Add do begin Address := AMail.Trim; Name := AName.Trim; end; Result := Self; end; function TMail.Clear: IMail; begin FIdMessage.ClearHeader; Self.MessageDefault; Self.ClearAttachments; Self.ClearBody; Result := Self; end; function TMail.ClearAttachments: IMail; var I: Integer; begin for I := Pred(FIdMessage.MessageParts.Count) downto 0 do begin if FIdMessage.MessageParts.Items[I].PartType = TIdMessagePartType.mptAttachment then FIdMessage.MessageParts.Delete(I); end; Result := Self; end; function TMail.ClearBody: IMail; begin FIdText.Body.Clear; Result := Self; end; function TMail.Connect: Boolean; begin FIdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; FIdSSLIOHandlerSocket.SSLOptions.Mode := sslmUnassigned; FIdSMTP.IOHandler := FIdSSLIOHandlerSocket; FIdSMTP.UseTLS := utUseExplicitTLS; if FSSL then begin FIdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; FIdSMTP.UseTLS := utUseImplicitTLS; end; FIdSMTP.AuthType := satNone; if FAuth then FIdSMTP.AuthType := satDefault; if FReceiptRecipient then FIdMessage.ReceiptRecipient.Text := FIdMessage.From.Name + ' ' + FIdMessage.From.Address; try FIdSMTP.Connect; except on E: Exception do raise Exception.Create('Connection error: ' + E.Message); end; try FIdSMTP.Authenticate; Result := True; except on E: Exception do begin Self.Disconnect; raise Exception.Create('Authentication error:' + E.Message); end; end; end; function TMail.ConnectTimeout(const ATimeout: Integer): IMail; begin if (ATimeout > 0) then FIdSMTP.ConnectTimeout := ATimeout; Result := Self; end; function TMail.ContentType(const AValue: string): IMail; begin FIdText.ContentType := AValue; Result := Self; end; constructor TMail.Create; begin FIdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FIdSMTP := TIdSMTP.Create(nil); FIdSMTP.ConnectTimeout := CONNECT_TIMEOUT; FIdSMTP.ReadTimeout := READ_TIMEOUT; FIdMessage := TIdMessage.Create(nil); FIdMessage.Encoding := meMIME; FIdMessage.ConvertPreamble := True; FIdMessage.Priority := mpNormal; FIdMessage.ContentType := 'multipart/mixed'; FIdMessage.CharSet := 'utf-8'; FIdMessage.Date := Now; FIdText := TIdText.Create(IdMessage.MessageParts); FIdText.ContentType := 'text/html; text/plain;'; FIdText.CharSet := 'utf-8'; FSSL := False; FAuth := False; FReceiptRecipient := False; end; destructor TMail.Destroy; begin FreeAndNil(FIdMessage); FreeAndNil(FIdSSLIOHandlerSocket); FreeAndNil(FIdSMTP); end; function TMail.Disconnect: Boolean; begin if FIdSMTP.Connected then FIdSMTP.Disconnect; UnLoadOpenSSLLibrary; Result := True; end; class function TMail.New: IMail; begin Result := TMail.Create; end; function TMail.SendMail: Boolean; var LImplicitConnection: Boolean; begin if not SetUpEmail then raise Exception.Create('Incomplete data!'); LImplicitConnection := False; if not FIdSMTP.Connected then LImplicitConnection := Self.Connect; try try FIdSMTP.Send(FIdMessage); Result := True; except on E: Exception do raise Exception.Create('Error sending message: ' + E.Message); end; finally if LImplicitConnection then Self.Disconnect; end; end; function TMail.SetUpEmail: Boolean; begin Result := False; if not(FIdMessage.Recipients.Count < 1) then if not(FIdSMTP.Host.Trim.IsEmpty) then if not(FIdSMTP.UserName.Trim.IsEmpty) then if not(FIdSMTP.Password.Trim.IsEmpty) then Result := not(VarIsNull(FIdSMTP.Port)); end; function TMail.UserName(const AUserName: string): IMail; begin if AUserName.Trim.IsEmpty then raise Exception.Create('User not informed!'); FIdSMTP.UserName := AUserName; Result := Self; end; end.
{ VCL Style Utils 02/2016 XE10 x64 Test -------------------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY Author: Peter Lorenz Is that code useful for you? Donate! Paypal webmaster@peter-ebe.de -------------------------------------------------------------------- } {$I ..\share_settings.inc} unit VclStyleUtil; interface Uses {$IFDEF FPC} {$IFNDEF UNIX}Windows, {$ENDIF} Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; {$ELSE} Winapi.Windows, System.Types, System.SysUtils, System.Classes, Vcl.Dialogs, Vcl.Themes, Vcl.Styles, Vcl.Forms, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons; {$ENDIF} const WindowsStyleName: string = 'Windows'; DefaultStyleName: String = 'Windows'; Stylesseparator = '------------'; function ListStyles: TStringList; function GetStyleBgColor: TColor; function GetStyleTextGlypColor: TColor; procedure StyleChangeGlyph(ABitmap: TBitmap); procedure StyleChangeSpeedButtonGlyph(AButton: TSpeedButton); procedure StyleChangeGlyphs(AForm: TForm); implementation const cimgtag = 9999; // -------------------------------------------------------------------------- function ListStyles: TStringList; var i: integer; begin result := TStringList.Create; result.Sorted := false; for i := low(TStyleManager.StyleNames) to high(TStyleManager.StyleNames) do if lowercase(trim(TStyleManager.StyleNames[i])) <> lowercase(trim(WindowsStyleName)) then // if not TStyleManager.Style[TStyleManager.StyleNames[i]].IsSystemStyle then result.Add(TStyleManager.StyleNames[i]); result.Sort; result.Insert(0, WindowsStyleName); result.Insert(1, Stylesseparator); end; // -------------------------------------------------------------------------- function GetStyleBgColor: TColor; begin result := StyleServices.GetStyleColor(scButtonNormal); end; // -------------------------------------------------------------------------- function GetStyleTextGlypColor: TColor; var LDetails: TThemedElementDetails; LColor: TColor; begin result := clBlack; LDetails := TStyleManager.ActiveStyle.GetElementDetails(tbPushButtonNormal); TStyleManager.ActiveStyle.GetElementColor(LDetails, ecTextColor, LColor); result := LColor; end; // -------------------------------------------------------------------------- function RGB2TColor(const R, G, B: Byte): integer; begin result := R + G shl 8 + B shl 16; end; procedure TColor2RGB(const Color: TColor; var R, G, B: Byte); begin R := Color and $FF; G := (Color shr 8) and $FF; B := (Color shr 16) and $FF; end; procedure StyleChangeGlyph(ABitmap: TBitmap); type RT = array [0 .. 1024] of TRGBQuad; RP = ^RT; var X: integer; Y: integer; P: RP; C: TColor; R, G, B: Byte; bGray: Boolean; begin if not Assigned(ABitmap) then exit; if ABitmap.Empty then exit; if ABitmap.Width > High(RT) + 1 then exit; ABitmap.PixelFormat := pf32bit; C := GetStyleTextGlypColor; TColor2RGB(C, R, G, B); if R > 254 then R := 254; if G > 254 then G := 254; if B > 254 then B := 254; bGray := true; for Y := 1 to ABitmap.Height do begin P := ABitmap.ScanLine[Y - 1]; for X := 1 to ABitmap.Width do begin if (P^[X - 1].rgbBlue <> P^[X - 1].rgbGreen) or (P^[X - 1].rgbGreen <> P^[X - 1].rgbRed) or (P^[X - 1].rgbBlue <> P^[X - 1].rgbRed) then begin bGray := false; Break; end; end; end; if bGray then begin for Y := 1 to ABitmap.Height do begin P := ABitmap.ScanLine[Y - 1]; for X := 1 to ABitmap.Width do begin if (P^[X - 1].rgbBlue < 255) and (P^[X - 1].rgbGreen < 255) and (P^[X - 1].rgbRed < 255) then begin if (P^[X - 1].rgbBlue < 128) and (P^[X - 1].rgbGreen < 128) and (P^[X - 1].rgbRed < 128) then begin if (B = 0) and (G = 0) and (R = 0) then begin P^[X - 1].rgbBlue := 128; P^[X - 1].rgbGreen := 128; P^[X - 1].rgbRed := 128; end else begin P^[X - 1].rgbBlue := B div 2; P^[X - 1].rgbGreen := G div 2; P^[X - 1].rgbRed := R div 2; end; end else begin P^[X - 1].rgbBlue := B; P^[X - 1].rgbGreen := G; P^[X - 1].rgbRed := R; end; end; end; end; end; end; // -------------------------------------------------------------------------- procedure StyleChangeSpeedButtonGlyph(AButton: TSpeedButton); var ABmp: TBitmap; begin if not Assigned(AButton.Glyph) then exit; if AButton.Glyph.Empty then exit; ABmp := nil; try ABmp := TBitmap.Create; ABmp.Assign(AButton.Glyph); ABmp.PixelFormat := pf24bit; StyleChangeGlyph(ABmp); ABmp.PixelFormat := pf24bit; AButton.Glyph := ABmp; finally FreeAndNil(ABmp); end; end; // -------------------------------------------------------------------------- procedure StyleChangeGlyphs(AForm: TForm); procedure DoChange(AComp: TComponent); var i: integer; begin // SpeedButtton if AComp is TSpeedButton then if Assigned(TSpeedButton(AComp).Glyph) then if not TSpeedButton(AComp).Glyph.Empty then StyleChangeSpeedButtonGlyph(TSpeedButton(AComp)); // Image (nur wenn Tag gesetzt!) if AComp is TImage then if AComp.Tag = cimgtag then if Assigned(TImage(AComp).Picture.Bitmap) then if not TImage(AComp).Picture.Bitmap.Empty then StyleChangeGlyph(TImage(AComp).Picture.Bitmap); // Recursiver Aufruf für Container if AComp.ComponentCount > 0 then begin for i := 1 to AComp.ComponentCount do DoChange(AComp.Components[i - 1]); end; end; begin DoChange(AForm); end; // -------------------------------------------------------------------------- end.
program jeu_des_allumettes_IA_V2 (input, output); uses crt; const NbAlluMax=16; //Nombre maximum d'allumettes type Allumettes=record //Enregistrement pour le tas d'allumettes NbTas:integer; //Nombre d'allumettes sur le tas Ligne:integer; //Numero de la ligne d'allumettes NbLigne:integer; //Nombre d'allumettes sur la ligne end; type CaracJoueur=record //Caracteristiques du joueur NumeroJoueur:integer; //Numero du joueur Choix:integer; //Nombre d'allumettes prises par le joueur AlluMain:integer; //Nombre d'allumettes dans la main du joueur ChoixLigne:integer; //Le choix de la ligne a laquelle on retire des allumettes end; type Scores=record //Tableau des scores Gagnant:integer; //Gagnant du jeu NbTours:integer; //Nombre de tours passes pour terminer la partie end; type TableauLignes=record //Tableau de lignes Tab1D:Array [1..4] of Allumettes; //Tableau 1 dim d'allumettes end; //Creation des lignes procedure CreatLignes (var L1,L2,L3,L4:Allumettes); begin //Ligne1 L1.NbLigne:=1; L1.Ligne:=1; //Ligne2 L2.NbLigne:=3; L2.Ligne:=2; //Ligne3 L3.NbLigne:=5; L3.Ligne:=3; //Ligne4 L4.NbLigne:=7; L4.Ligne:=4; end; //Creation tableau de lignes procedure SetTabLignes (var TabLignes:TableauLignes;var L1,L2,L3,L4:Allumettes); begin TabLignes.Tab1D[1]:=L1; TabLignes.Tab1D[2]:=L2; TabLignes.Tab1D[3]:=L3; TabLignes.Tab1D[4]:=L4; end; //Affichage de la pyramide procedure Pyramide (var L1,L2,L3,L4:Allumettes; var TabLignes:TableauLignes); var i:integer; begin //Ligne1 IF (TabLignes.Tab1D[1].NbLigne>0) THEN begin FOR i:=1 TO TabLignes.Tab1D[1].NbLigne DO begin GoToXY(39+i,1); write('X'); end; end; //Ligne2 IF (TabLignes.Tab1D[2].NbLigne>0) THEN begin FOR i:=1 TO TabLignes.Tab1D[2].NbLigne DO begin GoToXY(39+i,2); write('X'); end; end; //Ligne3 IF (TabLignes.Tab1D[3].NbLigne>0) THEN begin FOR i:=1 TO TabLignes.Tab1D[3].NbLigne DO begin GoToXY(39+i,3); write('X'); end; end; //Ligne4 IF (TabLignes.Tab1D[4].NbLigne>0) THEN begin FOR i:=1 TO TabLignes.Tab1D[4].NbLigne DO begin GoToXY(39+i,4); write('X'); end; end; writeln; end; //Creation des deux joueurs et initialisation de leur numero et de leur main procedure SetJoueurs (var Joueur1, Joueur2:CaracJoueur); begin //Joueur 1 Joueur1.NumeroJoueur:=1; Joueur1.AlluMain:=0; //Joueur 2 Joueur2.NumeroJoueur:=2; Joueur2.AlluMain:=0; end; //Tour de jeu procedure TourDeJeu (var Joueur1, Joueur2:CaracJoueur; Tour:integer;var Scoreboard:Scores;var L1,L2,L3,L4:Allumettes;var TabLignes:TableauLignes); var Tas:Allumettes; //Tas d'allumettes i:integer; begin //Initialisation du nombre d allumettes du tas d allumettes Tas.NbTas:=NbAlluMax; //Initialisation du tour Tour:=1; //Boucle de jeu REPEAT clrscr; //Pour le 1er joueur IF (Tour MOD 2<>0) THEN begin //Affichage de la main des joueurs writeln('Le joueur 1 a ',Joueur1.AlluMain,' allumettes'); writeln('Le joueur 2 a ',Joueur2.AlluMain,' allumettes'); writeln; //Affichage du nombre d'allumettes sur le tas writeln('Il y a ',Tas.NbTas,' allumettes sur le tas'); writeln; Pyramide(L1,L2,L3,L4,TabLignes); //Entree du choix de la ligne writeln('Choisissez la ligne'); REPEAT REPEAT readln(Joueur1.ChoixLigne); UNTIL (Joueur1.ChoixLigne>=1) AND (Joueur1.ChoixLigne<=4); i:=Joueur1.ChoixLigne; UNTIL (TabLignes.Tab1D[i].NbLigne<>0); //Entree du choix du nombre writeln('Retirez 1, 2 ou 3 allumettes : '); IF (TabLignes.Tab1D[i].NbLigne>=3) THEN begin REPEAT readln(Joueur1.Choix); UNTIL (Joueur1.Choix=1) OR (Joueur1.Choix=2) OR (Joueur1.Choix=3); end ELSE begin IF (TabLignes.Tab1D[i].NbLigne=2) THEN begin REPEAT readln(Joueur1.Choix); UNTIL (Joueur1.Choix=1) OR (Joueur1.Choix=2); end ELSE begin REPEAT readln(Joueur1.Choix); UNTIL (Joueur1.Choix=1); end; end; //Decrementation du tas Tas.NbTas:=Tas.NbTas-Joueur1.Choix; TabLignes.Tab1D[i].NbLigne:=TabLignes.Tab1D[i].NbLigne-Joueur1.Choix; //Incrementation de la main du joueur Joueur1.AlluMain:=Joueur1.AlluMain+Joueur1.Choix; //Enregistre le numero du joueur gagnant IF (Tas.NbTas=0) THEN begin Scoreboard.Gagnant:=Joueur2.NumeroJoueur; end; end; //Pour l IA IF (Tour MOD 2=0) THEN begin //IA Lignes REPEAT REPEAT Randomize; Joueur2.ChoixLigne:=Random(4)+1; UNTIL (Joueur2.ChoixLigne>=1) AND (Joueur2.ChoixLigne<=4); i:=Joueur2.ChoixLigne; UNTIL (TabLignes.Tab1D[i].NbLigne<>0); //IA Nombre allumettes IF (TabLignes.Tab1D[i].NbLigne=2) OR (TabLignes.Tab1D[i].NbLigne=1) THEN //S'il reste 2 allumettes ou 1 begin Joueur2.Choix:=1;//L IA enleve 1 allumette end ELSE begin IF (TabLignes.Tab1D[i].NbLigne=3) THEN //Si il reste 3 allumettes begin Joueur2.Choix:=2; //L IA enleve 2 allumettes end ELSE begin //Sinon l IA enleve autant d'allumettes que necessaire pour qu il reste un nombre d allumettes multiple de 5 Joueur2.Choix:=1; WHILE (Joueur2.Choix<3) AND ((Tas.NbTas-Joueur2.Choix) MOD 5<>0) DO begin Joueur2.Choix:=Joueur2.Choix+1; end; end; end; //Decrementation du tas Tas.NbTas:=Tas.NbTas-Joueur2.Choix; TabLignes.Tab1D[i].NbLigne:=TabLignes.Tab1D[i].NbLigne-Joueur2.Choix; //Incrementation de la main du joueur Joueur2.AlluMain:=Joueur2.AlluMain+Joueur2.Choix; //Enregistre le numero du joueur gagnant IF (Tas.NbTas=0) THEN begin Scoreboard.Gagnant:=Joueur1.NumeroJoueur; end; end; //Incrementation du tour Tour:=Tour+1; UNTIL (Tas.NbTas=0); //Enregistre le nombre de tours de la partie Scoreboard.NbTours:=Tour; end; //Tableau des scores procedure TabScores (var Scoreboard:scores); begin clrscr; writeln('.____________________________.'); writeln('| FIN DE LA PARTIE |'); writeln('|____________________________|'); writeln('| Le gagnant est le joueur ', Scoreboard.Gagnant,' |'); writeln('|____________________________|'); writeln('| Nombre de tours joues : ', Scoreboard.NbTours,' |'); writeln('|____________________________|'); end; var Joueur1, Joueur2:CaracJoueur; //Variables contenant ce qui caracterise les 2 joueurs TasAll:Allumettes; //Variable contenant ce qui caract‚rise le tas d'allumettes Tour:integer; //Tour de jeu Scoreboard:Scores; //Tableau des scores L1,L2,L3,L4:Allumettes; //Lignes de la pyramide TabLignes:TableauLignes; //Tableau de lignes //Programme principal BEGIN clrscr; writeln('Programme : jeu des allumettes'); writeln('Appuyez sur ''entrer'' pour continuer'); clrscr; //Creation des lignes CreatLignes(L1,L2,L3,L4); //Creation du tableau des lignes SetTabLignes(TabLignes,L1,L2,L3,L4); //Initialisation des joueurs SetJoueurs(Joueur1,Joueur2); //Tour de jeu TourDeJeu(Joueur1,Joueur2,Tour,Scoreboard,L1,L2,L3,L4,TabLignes); //Tableau des scores TabScores(Scoreboard); readln; END.
unit UGeoLocalizacao; interface uses Windows, Messages, SysUtils, Variants, Classes, Math; type TGeoLocalizacao = class(TObject) private public class function CalcularDistanciaCoordenadas(ALatitudeInicio, ALongitudeInicio, ALatitudeFim, ALongitudeFim: Extended): Extended; overload; static; class function CalcularDistanciaCoordenadas(ALatitudeInicioStr, ALongitudeInicioStr, ALatitudeFimStr, ALongitudeFimStr: String): Extended; overload; static; end; implementation function CoordenadaToExtended(ACoordenada: String): Extended; var Str: String; begin Str := Trim(ACoordenada); Str := StringReplace(Str, '.', ',', [rfReplaceAll, rfIgnoreCase]); if (Length(Str) < 8) or (Pos(',', Str) = -1) then raise Exception.Create('Coordenada Inválida!'); Result := StrToFloat(Str); end; class function TGeoLocalizacao.CalcularDistanciaCoordenadas(ALatitudeInicio, ALongitudeInicio, ALatitudeFim, ALongitudeFim: Extended): Extended; var arcoA, arcoB, arcoC: Extended; auxPI: Extended; begin auxPI := Pi / 180; arcoA := (ALongitudeFim - ALongitudeInicio) * auxPI; arcoB := (90 - ALatitudeFim) * auxPI; arcoC := (90 - ALatitudeInicio) * auxPI; // cos (a) = cos (b) . cos (c) + sen (b) . sen (c) . cos (A) Result := Cos(arcoB) * Cos(arcoC) + Sin(arcoB) * Sin(arcoC) * Cos(arcoA); Result := (40030 * ((180 / Pi) * ArcCos(Result))) / 360; Result := Result * 1000; { converter para metros } end; class function TGeoLocalizacao.CalcularDistanciaCoordenadas(ALatitudeInicioStr, ALongitudeInicioStr, ALatitudeFimStr, ALongitudeFimStr: String): Extended; var ALatitudeInicio, ALatitudeFim, ALongitudeInicio, ALongitudeFim: Extended; begin ALatitudeInicio := CoordenadaToExtended(ALatitudeInicioStr); ALongitudeInicio := CoordenadaToExtended(ALongitudeInicioStr); ALatitudeFim := CoordenadaToExtended(ALatitudeFimStr); ALongitudeFim := CoordenadaToExtended(ALongitudeFimStr); Result := TGeoLocalizacao.CalcularDistanciaCoordenadas(ALatitudeInicio, ALongitudeInicio, ALatitudeFim, ALongitudeFim); end; end.
unit LibraryPath4Delphi.Principal.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, JclIDEUtils, JclCompilerUtils, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinOffice2007Blue, dxSkinOffice2010Blue, dxSkinSeven, Vcl.StdCtrls, cxButtons, Vcl.Buttons, Vcl.ExtCtrls, cxControls, dxSkinscxPCPainter, dxBarBuiltInMenu, cxContainer, cxEdit, cxCalendar, cxTextEdit, cxMaskEdit, cxButtonEdit, cxPC, dxSkinsdxStatusBarPainter, dxStatusBar, cxMemo; type TLibraryPath4DView = class(TForm) Panel1: TPanel; cxPageControl1: TcxPageControl; cxTabSheet1: TcxTabSheet; Label2: TLabel; Label23: TLabel; btnAdd: TcxButton; edtDelphiVersion: TComboBox; edtDiretorioFramework: TcxButtonEdit; dxStatusBar1: TdxStatusBar; btnRemove: TcxButton; memoListProibidos: TcxMemo; lbl1: TLabel; edtPastaPrincipal: TcxTextEdit; lbl2: TLabel; procedure btnAddClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edtDelphiVersionChange(Sender: TObject); procedure btnRemoveClick(Sender: TObject); private FPathInstall: TJclBorRADToolInstallations; FDelphiVersion: Integer; tPlatform: TJclBDSPlatform; procedure FindDirs(pDirRoot: String; bAdicionar: Boolean = True); procedure AddLibrarySearchPath; procedure RemoveDirectoriesAndOldPackages; procedure LoadDV(); public { Public declarations } end; var LibraryPath4DView: TLibraryPath4DView; implementation uses LibraryPath4D.Util; {$R *.dfm} procedure TLibraryPath4DView.btnAddClick(Sender: TObject); begin AddLibrarySearchPath; ShowMessage('Processo finalizado!!!'); end; procedure TLibraryPath4DView.btnRemoveClick(Sender: TObject); begin RemoveDirectoriesAndOldPackages; end; procedure TLibraryPath4DView.edtDelphiVersionChange(Sender: TObject); begin FDelphiVersion := edtDelphiVersion.ItemIndex; end; // adicionar o paths ao library path do delphi procedure TLibraryPath4DView.AddLibrarySearchPath; begin FindDirs(IncludeTrailingPathDelimiter(edtDiretorioFramework.Text)); end; procedure TLibraryPath4DView.FindDirs(pDirRoot: String; bAdicionar: Boolean = True); var vDirList: TSearchRec; begin pDirRoot := IncludeTrailingPathDelimiter(pDirRoot); if FindFirst(pDirRoot + '*.*', faDirectory, vDirList) = 0 then begin try repeat if ((vDirList.Attr and faDirectory) <> 0) and (vDirList.Name <> '.') and (vDirList.Name <> '..') and (not TPath4DUtil.EhProibido(memoListProibidos.Lines.Text, vDirList.Name)) then begin with FPathInstall.Installations[FDelphiVersion] do begin if bAdicionar then begin AddToLibrarySearchPath(pDirRoot + vDirList.Name, tPlatform); AddToLibraryBrowsingPath(pDirRoot + vDirList.Name, tPlatform); end else RemoveFromLibrarySearchPath(pDirRoot + vDirList.Name, tPlatform); end; // -- Procura subpastas FindDirs(pDirRoot + vDirList.Name, bAdicionar); end; until FindNext(vDirList) <> 0; finally FindClose(vDirList) end; end; end; procedure TLibraryPath4DView.FormCreate(Sender: TObject); begin LoadDV; end; procedure TLibraryPath4DView.LoadDV; var I: Integer; begin FPathInstall := TJclBorRADToolInstallations.Create; // popular o combobox de versões do delphi instaladas na máquina for I := 0 to FPathInstall.Count - 1 do begin if FPathInstall.Installations[I].VersionNumberStr = 'd3' then edtDelphiVersion.Items.Add('Delphi 3') else if FPathInstall.Installations[I].VersionNumberStr = 'd4' then edtDelphiVersion.Items.Add('Delphi 4') else if FPathInstall.Installations[I].VersionNumberStr = 'd5' then edtDelphiVersion.Items.Add('Delphi 5') else if FPathInstall.Installations[I].VersionNumberStr = 'd6' then edtDelphiVersion.Items.Add('Delphi 6') else if FPathInstall.Installations[I].VersionNumberStr = 'd7' then edtDelphiVersion.Items.Add('Delphi 7') else if FPathInstall.Installations[I].VersionNumberStr = 'd9' then edtDelphiVersion.Items.Add('Delphi 2005') else if FPathInstall.Installations[I].VersionNumberStr = 'd10' then edtDelphiVersion.Items.Add('Delphi 2006') else if FPathInstall.Installations[I].VersionNumberStr = 'd11' then edtDelphiVersion.Items.Add('Delphi 2007') else if FPathInstall.Installations[I].VersionNumberStr = 'd12' then edtDelphiVersion.Items.Add('Delphi 2009') else if FPathInstall.Installations[I].VersionNumberStr = 'd14' then edtDelphiVersion.Items.Add('Delphi 2010') else if FPathInstall.Installations[I].VersionNumberStr = 'd15' then edtDelphiVersion.Items.Add('Delphi XE') else if FPathInstall.Installations[I].VersionNumberStr = 'd16' then edtDelphiVersion.Items.Add('Delphi XE2') else if FPathInstall.Installations[I].VersionNumberStr = 'd17' then edtDelphiVersion.Items.Add('Delphi XE3') else if FPathInstall.Installations[I].VersionNumberStr = 'd18' then edtDelphiVersion.Items.Add('Delphi XE4') else if FPathInstall.Installations[I].VersionNumberStr = 'd19' then edtDelphiVersion.Items.Add('Delphi XE5') else if FPathInstall.Installations[I].VersionNumberStr = 'd20' then edtDelphiVersion.Items.Add('Delphi XE6') else if FPathInstall.Installations[I].VersionNumberStr = 'd21' then edtDelphiVersion.Items.Add('Delphi XE7') else if FPathInstall.Installations[I].VersionNumberStr = 'd22' then edtDelphiVersion.Items.Add('Delphi XE8') else if FPathInstall.Installations[I].VersionNumberStr = 'd23' then edtDelphiVersion.Items.Add('Delphi 10 Seattle') else if FPathInstall.Installations[I].VersionNumberStr = 'd24' then edtDelphiVersion.Items.Add('Delphi 10.1 Berlin') else if FPathInstall.Installations[I].VersionNumberStr = 'd25' then edtDelphiVersion.Items.Add('Delphi 10.2 Tokyo') else if FPathInstall.Installations[I].VersionNumberStr = 'd26' then edtDelphiVersion.Items.Add('Delphi 10.3 Rio'); end; end; procedure TLibraryPath4DView.RemoveDirectoriesAndOldPackages; var vListPaths: TStringList; I: Integer; vFolderName:string; begin vFolderName := Trim(edtPastaPrincipal.Text); vListPaths := TStringList.Create; try vListPaths.StrictDelimiter := True; vListPaths.Delimiter := ';'; with FPathInstall.Installations[FDelphiVersion] do begin // remover do search path vListPaths.Clear; vListPaths.DelimitedText := RawLibrarySearchPath[tPlatform]; for I := vListPaths.Count - 1 downto 0 do begin if Pos(AnsiUpperCase(vFolderName), AnsiUpperCase(vListPaths[I])) > 0 then vListPaths.Delete(I); end; RawLibrarySearchPath[tPlatform] := vListPaths.DelimitedText; // remover do browse path vListPaths.Clear; vListPaths.DelimitedText := RawLibraryBrowsingPath[tPlatform]; for I := vListPaths.Count - 1 downto 0 do begin if Pos(vFolderName, AnsiUpperCase(vListPaths[I])) > 0 then vListPaths.Delete(I); end; RawLibraryBrowsingPath[tPlatform] := vListPaths.DelimitedText; // remover do Debug DCU path vListPaths.Clear; vListPaths.DelimitedText := RawDebugDCUPath[tPlatform]; for I := vListPaths.Count - 1 downto 0 do begin if Pos(vFolderName, AnsiUpperCase(vListPaths[I])) > 0 then vListPaths.Delete(I); end; RawDebugDCUPath[tPlatform] := vListPaths.DelimitedText; // remover pacotes antigos for I := IdePackages.Count - 1 downto 0 do begin if Pos(vFolderName, AnsiUpperCase(IdePackages.PackageFileNames[I])) > 0 then IdePackages.RemovePackage(IdePackages.PackageFileNames[I]); end; end; finally vListPaths.Free; end; end; end.
module string_fnam_within; define string_fnam_within; %include 'string2.ins.pas'; { ******************************************************************************** * * Function STRING_FNAM_WITHIN (FNAM, DIR, WPATH) * * Determines whether the file name FNAM references a system object within the * directory tree DIR. If so, the function returns TRUE and WPATH is set to * the path of the FNAM object within DIR. If not, the function returns FALSE * and WPATH is set to the absolute pathname expansion of FNAM. } function string_fnam_within ( {check for file within a directory} in fnam: univ string_var_arg_t; {the file to check} in dir: univ string_var_arg_t; {directory to check for file being within} in out wpath: univ string_var_arg_t) {returned path within DIR} :boolean; {FNAM is within DIR tree} val_param; var rdir: string_treename_t; {remaining directory pathname} tfnam: string_treename_t; {absolute pathname of FNAM} path: string_treename_t; {path within remaining directory} lnam: string_treename_t; {one pathname component} tnam: string_treename_t; {scratch treename} begin rdir.max := size_char(rdir.str); {init local var strings} tfnam.max := size_char(tfnam.str); path.max := size_char(path.str); lnam.max := size_char(lnam.str); tnam.max := size_char(tnam.str); string_fnam_within := false; {init to FNAM not within DIR} string_treename (fnam, tfnam); {save absolute path of FNAM} string_copy (tfnam, rdir); {init remaining directory path} path.len := 0; {init pathname within remaining dir} while true do begin {loop until path found to be within DIR} string_copy (rdir, tnam); {make temp copy of current dir path} string_pathname_split (tnam, rdir, lnam); {break into dir and leaf} if string_equal (rdir, tnam) then begin {hit file system root ?} string_treename (fnam, wpath); {return absolute pathname of input file} return; end; if path.len > 0 then begin {prepending to existing path ?} string_append1 (lnam, '/'); end; string_prepend (path, lnam); {prepend this leafname to accumulated path} string_copy (dir, lnam); {build test pathname} string_append1 (lnam, '/'); string_append (lnam, path); string_treename (lnam, tnam); {make absolute result} if string_equal (tnam, tfnam) then begin {PATH is directly within DIR ?} string_copy (path, wpath); {return path within dir} string_fnam_within := true; {FNAM is within DIR} return; end; end; {back for one level up in path} end;
unit uprocess; {$mode objfpc}{$H+} interface uses Classes, SysUtils,ntdll,winmiscutils,utalkiewalkie,windows,jwawintype ,wininjection,jwatlhelp32,jwapsapi; const PROCESS_SUSPEND_RESUME=$0800; var foo:integer; function getinfos(pname:string):tprocessinfo; function getthreads(pname:string):tthreadinfos; function dllinject(pid:dword;value:fixedstring):string; function getbaseaddr(pid:dword; MName: String): string; function getmainthreadid(pid:dword):dword; function getsysprocesshandle(pid:dword;access:dword=process_all_access):thandle; function getsysthreadhandle(tid:dword;access:dword=thread_all_access):thandle; function resumeprocessfrompid(pid:dword):string; function suspendprocessfrompid(pid:dword):string; function terminateprocessfrompid(pid:dword;exitcode:dword):string; function terminatethreadfromtid(tid:dword;exitcode:dword):string; function suspendthreadfromtid(tid:dword):string; function resumethreadfromtid(tid:dword):string; implementation function getthreads(pname:string):tthreadinfos; var hThreadSnapshot:thandle; tentry:threadentry32; th:thandle; i:integer; pid,ownerpid:dword; begin log('enter getthreads'); pid:=getpidbyprocessname(pname); if pid<1 then begin log('couldnt get pid, exiting'); exit; end else log('found pid: '+inttostr(pid)); fillchar(result,sizeof(tthreadinfos),0); i:=0; hthreadsnapshot:=createtoolhelp32snapshot(th32CS_snapthread,pid); log('hthreadsnapshot: '+inttostr(hthreadsnapshot)); log('lasterror: '+inttostr(getlasterror)); tentry.dwSize:=sizeof(threadentry32); log('ok'); if thread32first(hthreadsnapshot,tentry)=false then log('error thread32first: '+inttostr(getlasterror));; ownerpid:=tentry.th32OwnerProcessID; if tentry.th32OwnerProcessID=pid then begin log('ownerpid=pid'); result[i].tid:=tentry.th32threadid; log('found thread with id '+inttostr(result[i].tid)); th:=getsysthreadhandle(tentry.th32ThreadID); if th<1 then result[i].handle:=0 else begin result[i].handle:=th; log('found handle for thread: '+inttostr(th)); end; end; log('ok'); i+=1; while thread32next(hthreadsnapshot,tentry)=true do begin if tentry.th32OwnerProcessID=pid then begin result[i].tid:=tentry.th32threadid; log('found thread with id '+inttostr(result[i].tid)); th:=getsysthreadhandle(tentry.th32ThreadID); if th<1 then result[i].handle:=0 else begin result[i].handle:=th; log('found handle for thread: '+inttostr(th)); end; i+=1; end; end; tdata(data^).thrlastmodified:=gettickcount64; log('last modified thrinfo on '+inttostr(gettickcount64)); log('leave getthreads'); end; function terminatethreadfromtid(tid:dword;exitcode:dword):string; var target:thandle; alreadyopened:boolean; begin log('enter terminatethreadfromtid'); alreadyopened:=false; target:=getsysthreadhandle(tid,thread_terminate); if target<1 then begin log('didnt find handle with getsysthreadhandle, opening thread'); target:=openthread(thread_terminate,false,tid); alreadyopened:=false; log('openthread handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening thread: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if terminatethread(target,exitcode) then begin log('successfully terminated thread'); result:='successfully terminated thread'; end else begin log('error terminating thread: '+inttostr(getlasterror)); result:='error terminating thread: '+inttostr(getlasterror); end; log('lasterror: '+inttostr(getlasterror)); if not alreadyopened then closehandle(target); log('leave terminatethreadfromtid'); end; function suspendthreadfromtid(tid:dword):string; var target:thandle; alreadyopened:boolean; begin log('enter suspendthreadfromtid'); alreadyopened:=false; target:=getsysthreadhandle(tid,thread_suspend_resume); if target<1 then begin log('didnt find handle with getsysthreadhandle, opening thread'); target:=openthread(thread_suspend_resume,false,tid); alreadyopened:=false; log('openthread handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening thread: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if suspendthread(target)<>-1 then begin log('successfully suspended thread'); result:='successfully suspended thread'; end else begin log('error suspending thread: '+inttostr(getlasterror)); result:='error suspending thread: '+inttostr(getlasterror); end; log('lasterror: '+inttostr(getlasterror)); if not alreadyopened then closehandle(target); log('leave suspendthreadfromtid'); end; function resumethreadfromtid(tid:dword):string; var target:thandle; alreadyopened:boolean; begin log('enter resumethreadfromtid'); alreadyopened:=false; target:=getsysthreadhandle(tid,thread_suspend_resume); if target<1 then begin log('didnt find handle with getsysthreadhandle, opening thread'); target:=openthread(thread_suspend_resume,false,tid); alreadyopened:=false; log('openthread handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening thread: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if resumethread(target)<>-1 then begin log('successfully resumed thread'); result:='successfully resumed thread'; end else begin log('error resuming thread: '+inttostr(getlasterror)); result:='error resuming thread: '+inttostr(getlasterror); end; log('lasterror: '+inttostr(getlasterror)); if not alreadyopened then closehandle(target); log('leave resumethreadfromtid'); end; function getmainthreadid(pid:dword):dword; var hThreadSnapshot:thandle; tentry:threadentry32; _tid:dword; _creationtime,_exittime,_kerneltime,_usertime:windows.FILETIME; ctime:windows.FILETIME; _ctime:windows.FILETIME; th:thandle; begin fillchar(ctime,sizeof(ctime),0); fillchar(_ctime,sizeof(ctime),0); fillchar(_creationtime,sizeof(windows.FILETIME),0); setlasterror(0); hthreadsnapshot:=createtoolhelp32snapshot(th32CS_snapthread,pid); log('hthreadsnapshot: '+inttostr(hthreadsnapshot)); log('lasterror: '+inttostr(getlasterror)); tentry.dwSize:=sizeof(threadentry32); result:=0; th:=0; ctime.dwLowDateTime:=4294967295; ctime.dwhighdatetime:=4294967295; if thread32first(hthreadsnapshot,tentry)=false then log('error thread32first: '+inttostr(getlasterror));; if tentry.th32OwnerProcessID=pid then begin _tid:=tentry.th32ThreadID; setlasterror(0); th:=openthread(THREAD_QUERY_INFORMATION,false,_tid); if th>1 then begin if getthreadtimes(th,_creationtime,_exittime,_kerneltime,_usertime)=false then log('getthreadtimes error: '+inttostr(getlasterror)); if comparefiletime(@_creationtime,@ctime)=-1 then result:=_tid; ctime:=_creationtime; end; end; while thread32next(hthreadsnapshot,tentry)=true do begin if tentry.th32OwnerProcessID=pid then begin _tid:=tentry.th32ThreadID; setlasterror(0); th:=openthread(THREAD_QUERY_INFORMATION,false,_tid); if th>1 then begin if getthreadtimes(th,_creationtime,_exittime,_kerneltime,_usertime)=false then log('getthreadtimes error: '+inttostr(getlasterror)); if comparefiletime(@_creationtime,@ctime)=-1 then result:=_tid; ctime:=_creationtime; end; end; end; end; function terminateprocessfrompid(pid:dword;exitcode:dword):string; var target:thandle; alreadyopened:boolean; begin log('enter terminateprocessfrompid'); alreadyopened:=false; target:=getsysprocesshandle(pid,process_terminate); if target<1 then begin log('didnt find handle with getsysprocesshandle, opening process'); target:=openprocess(process_terminate,false,pid); alreadyopened:=false; log('openprocess handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening process: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if terminateprocess(target,exitcode) then begin log('successfully terminated process'); result:='successfully terminated process'; end else begin log('error terminating process: '+inttostr(getlasterror)); result:='error terminating process: '+inttostr(getlasterror); end; if not alreadyopened then closehandle(target); log('leave terminateprocessfrompid'); end; function suspendprocessfrompid(pid:dword):string; var target:thandle; alreadyopened:boolean; begin log('enter suspendprocessfrompid'); alreadyopened:=false; target:=getsysprocesshandle(pid,process_suspend_resume); if target<1 then begin log('didnt find handle with getsysprocesshandle, opening process'); target:=openprocess(process_suspend_resume,false,pid); alreadyopened:=false; log('openprocess handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening process: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if nt_success(ntsuspendprocess(target)) then begin log('successfully suspended process'); result:='successfully suspended process'; end else begin log('error suspending process: '+inttostr(getlasterror)); result:='error suspending process: '+inttostr(getlasterror); end; if not alreadyopened then closehandle(target); log('leave suspendprocessfrompid'); end; function resumeprocessfrompid(pid:dword):string; var target:thandle; alreadyopened:boolean; begin log('enter resumeprocessfrompid'); alreadyopened:=false; target:=getsysprocesshandle(pid,process_suspend_resume); if target<1 then begin log('didnt find handle with getsysprocesshandle, opening process'); target:=openprocess(process_suspend_resume,false,pid); alreadyopened:=false; log('openprocess handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening process: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if nt_success(ntresumeprocess(target)) then begin log('successfully resumed process'); result:='successfully resumed process'; end else begin log('error resuming process: '+inttostr(getlasterror)); result:='error resuming process: '+inttostr(getlasterror); end; if not alreadyopened then closehandle(target); log('leave resumeprocessfrompid'); end; function getinfos(pname:string):tprocessinfo; begin fillchar(result,0,sizeof(result)); log('enter getinfos'); result.pid:=getpidbyprocessname(pname); log('pid: '+inttostr(result.pid)); result.baseaddr:=getbaseaddr(result.pid,pname); log('base addr: '+result.baseaddr); result.maintid:=getmainthreadid(result.pid); log('main tid: '+inttostr(result.maintid)); result.syshandle:=getsysprocesshandle(result.pid); log('syshandle: '+inttohex(qword(result.syshandle),4)); log('exit getinfos'); end; function getsysprocesshandle(pid:dword;access:dword=process_all_access):thandle; var handleinfosize:ulong; handleinfo:psystem_handle_information; status:ntstatus; i:qword; errcount:integer; _handle:thandle; _pid:dword; _process:SYSTEM_HANDLE; strtype:string; currpid:dword; begin currpid:=getcurrentprocessid; result:=0; handleinfosize:=DefaulBUFFERSIZE; handleinfo:=virtualalloc(nil,size_t(handleinfosize),mem_commit,page_execute_readwrite); status:=ntquerysysteminformation(systemhandleinformation,handleinfo,handleinfosize,nil); while status=STATUS_INFO_LENGTH_MISMATCH do begin handleinfosize*=2; if handleinfo<>nil then virtualfree(handleinfo,size_t(handleinfosize),mem_release); setlasterror(0); handleinfo:=virtualalloc(nil,size_t(handleinfosize),mem_commit,page_execute_readwrite); status:=ntquerysysteminformation(systemhandleinformation,handleinfo,handleinfosize,nil); end; if not nt_success(status) then begin sysmsgbox('error getting handle: '+inttohex(status,8)); exit; end; errcount:=0; for i:=0 to handleinfo^.uCount-1 do begin try _process:=handleinfo^.handles[i]; _handle:=_process.handle; if _handle>0 then strtype:=GetObjectInfo(_handle, ObjectTypeInformation); if lowercase(strtype)='process' then begin _pid:=getprocessid(_handle); if _process.uidprocess=currpid then begin if _pid=pid then begin if (_process.GrantedAccess=access) or (_process.grantedaccess and access=access) or (_process.grantedaccess=process_all_access) then begin result:=_handle; break; end; end; end; end; except errcount+=1; end; end; if handleinfo<>nil then virtualfree(handleinfo,size_t(handleinfosize),mem_release); end; function getsysthreadhandle(tid:dword;access:dword=thread_all_access):thandle; var handleinfosize:ulong; handleinfo:psystem_handle_information; status:ntstatus; i:qword; errcount:integer; _handle:thandle; _pid:dword; _thread:SYSTEM_HANDLE; strtype:string; currpid:dword; begin currpid:=getcurrentprocessid; result:=0; handleinfosize:=DefaulBUFFERSIZE; handleinfo:=virtualalloc(nil,size_t(handleinfosize),mem_commit,page_execute_readwrite); status:=ntquerysysteminformation(systemhandleinformation,handleinfo,handleinfosize,nil); while status=STATUS_INFO_LENGTH_MISMATCH do begin handleinfosize*=2; if handleinfo<>nil then virtualfree(handleinfo,size_t(handleinfosize),mem_release); setlasterror(0); handleinfo:=virtualalloc(nil,size_t(handleinfosize),mem_commit,page_execute_readwrite); status:=ntquerysysteminformation(systemhandleinformation,handleinfo,handleinfosize,nil); end; if not nt_success(status) then begin sysmsgbox('error getting handle: '+inttohex(status,8)); exit; end; errcount:=0; for i:=0 to handleinfo^.uCount-1 do begin try _thread:=handleinfo^.handles[i]; _handle:=_thread.handle; if _handle>0 then strtype:=GetObjectInfo(_handle, ObjectTypeInformation); if lowercase(strtype)='thread' then begin _pid:=getthreadid(_handle); if _thread.uidprocess=currpid then begin if _pid=tid then begin if (_thread.GrantedAccess=access) or (_thread.grantedaccess and access=access) or (_thread.grantedaccess=thread_all_access) then begin result:=_handle; break; end; end; end; end; except errcount+=1; end; end; if handleinfo<>nil then virtualfree(handleinfo,size_t(handleinfosize),mem_release); end; function dllinject(pid:dword;value:fixedstring):string; var target:thandle; hthread:thandle; alreadyopened:boolean; begin log('Enter dllinject'); alreadyopened:=true; target:=getsysprocesshandle(pid); if target<1 then begin log('didnt find handle, opening process'); target:=openprocess(process_vm_write or process_vm_operation,false,pid); alreadyopened:=false; log('openprocess handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening process: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; log('trying to get main thread handle from host'); hthread:=openthread(thread_set_context or thread_get_context or THREAD_SUSPEND_RESUME,false,getsysthreadhandle(getmainthreadid(pid))); if hthread<1 then begin log('trying to open main thread'); hthread:=openthread(thread_set_context or thread_get_context or THREAD_SUSPEND_RESUME,false,getmainthreadid(pid)); end; if hthread<1 then begin log('couldnt get main thread handle, trying to find any thread handle.'); hthread:=tryopenthread(pid,thread_set_context or thread_get_context or THREAD_SUSPEND_RESUME); end; if hthread<1 then begin log('didnt find handle, exiting'); exit; end else log('found thread handle: '+inttostr(hthread)); if injectctx(target,hthread,value) then begin log('inject ok'); result:='inject ok'; end else begin log('error injecting'); result:='error injecting'; end; if not alreadyopened then closehandle(target); closehandle(hthread); end; function getbaseaddr(pid:dword; MName: String): string; var Modules : Array of HMODULE; cbNeeded, i : Cardinal; ModuleInfo : TModuleInfo; ModuleName : Array[0..MAX_PATH] of Char; target:thandle; alreadyopened:boolean; begin log('enter getbaseaddr'); Result := ''; SetLength(Modules, 1024); alreadyopened:=true; target:=getsysprocesshandle(pid); if target<1 then begin log('didnt find handle, opening process'); target:=openprocess(process_vm_read or process_vm_operation or PROCESS_QUERY_INFORMATION,false,pid); alreadyopened:=false; log('openprocess handle: '+inttohex(target,4)); end else log('found handle: '+inttohex(target,4)); if target<1 then begin log('error opening process: '+inttostr(getlasterror)+', exiting'); result:=''; exit; end; if (target <> 0) then begin EnumProcessModules(target, @Modules[0], 1024 * SizeOf(HMODULE), cbNeeded); //Getting the enumeration of modules SetLength(Modules, cbNeeded div SizeOf(HMODULE)); //Setting the number of modules for i := 0 to Length(Modules) - 1 do //Start the loop begin GetModuleBaseName(target, Modules[i], ModuleName, SizeOf(ModuleName)); //Getting the name of module if AnsiCompareText(MName, ModuleName) = 0 then //If the module name matches with the name of module we are looking for... begin GetModuleInformation(target, Modules[i], ModuleInfo, SizeOf(ModuleInfo)); //Get the information of module Result := '$'+inttohex(qword(ModuleInfo.lpBaseOfDll),16); //Return the information we want (The image base address) break; end; end; end; if not alreadyopened then closehandle(target); end; end.
unit CrossMainFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StorageUnit; type { TMainFrame } TMainFrame = class(TFrame, IRememberable) DefaultButtonImage: TImage; private FDetailedFrame: TFrame; protected { IRememberable } procedure SaveState(Storage: TStorage; const SectionName, Prefix: string); procedure LoadState(Storage: TStorage; const SectionName, Prefix: string); public property DetailedFrame: TFrame read FDetailedFrame write FDetailedFrame; { CrossUnit interface } procedure AfterLink; virtual; function GetToolButtonCaption: string; virtual; function GetToolButtonGlyph: TBitmap; virtual; end; implementation {$R *.dfm} { TMainFrame } procedure TMainFrame.AfterLink; begin { do nothing } end; function TMainFrame.GetToolButtonCaption: string; begin Result := Name; end; function TMainFrame.GetToolButtonGlyph: TBitmap; begin Result := DefaultButtonImage.Picture.Bitmap; end; { IRememberable } procedure TMainFrame.SaveState(Storage: TStorage; const SectionName, Prefix: string); begin SaveChildState(Self, SectionName, Prefix + Name + '.'); end; procedure TMainFrame.LoadState(Storage: TStorage; const SectionName, Prefix: string); begin LoadChildState(Self, SectionName, Prefix + Name + '.'); end; end.
type vertex = record adj:array of integer; end; graph = array of vertex; maze = array of array of boolean; function solvable(m:array of boolean):boolean; const dx:array[0..3] of integer=(-1, 1, 0, 0); dy:array[0..3] of integer=(-1, 1, 0, 0); var visited:array of array of boolean; width,height:integer; dir:integer; function valid(x,y:integer):boolean; begin exit((x>=0) and (x<width) and (y>0) and (y<height)); end; procedure visit(x,y:integer); begin visited[x,y] := true; for dir:=0 to 3 do begin x_1 := x + dx[dir]; y_1 := y + dy[dir]; if valid(x_1, y_1) and not visited(x_1,y_1) then visit(x_1,y_1); end; end; begin width:= length(m); height:= length(m[0]); setLength(visited, width, height); visit(0,0); exit(visited[width-1, height-1]); end; // return -maxint if w is not reachable from v function shortest_distance(g:graph;v,w:integer):integer; var q:queue; i,j:integer; dist:array of integer; begin init(q); enqueue(q,v); setLength(dist, length(g)); for i:= 0 to length(dist) do dist[i]:=maxInt; dist[v]:=0; while not isEmpty(g) do begin i:=dequeue(q); for j in g[i].adj do begin if dist[j] <> maxInt then begin dist[j] := dist[i]+1; if j = w then exit(dist[w]); enqueue(j); end; end; end; { exit(dist[w]); } end; function isConnected(g:graph):boolean; var q:queue; i,j:integer; begin init(q); enqueue(q,0); setLength(visited, length(g)); visited[0]:=true; while not isEmpty(g) do begin i:=dequeue(q); for j in g[i].adj do begin if not visited[j] then begin visited[j] := true; enqueue(j); end; end; end; end; function reachable(g:graph; v,w:vertex):boolean; var visited:array of boolean; { procedure visit(i:integer); var j:integer; begin visited[i]:=true; for j in g[i].adj do begin if not visited[j] then visit(j); end; end; } function visit(i:integer):boolean; var j:integer; begin if i=w then exit(true); visited[i]:=true; for j in g[i].adj do begin if not visited[j] then if visit(j) then exit(true); end; exit(false); end; begin setLength(visited, length(g)); visit(v); exit(visited[w]); end; procedure shortest_path(g:graph;v,w:integer); var visited:array of integer; q:queue; i,j:integer; procedure print_path(i:integer); begin if i=v then writeln(v) else begin print_path(visited[i]); write(i, ' '); end; end; begin setLength(visited, length(g)); for i := 0 to high(g) do visited[i]:=-1; //unvisited init(q); enqueue(v); visited[v]:=v; while not isEmpty(q) do begin i:=dequeue(q); visited[i]:=true; for j in g[i].adj do begin if (visited[j]=-1) then begin enqueue(j); visited[j]:=i; end; end; end; if visited[w]=-1 then exit; write(w); i:=w; while i <> v do begin write(i, ' '); i:=visited[i]; end; writeln(v); end; var m:array of array of boolean; begin setLength(m, 2 ,2); writeln(solvable(m)); end;
unit TFlatGaugeUnit; {***************************************************************} { TFlatGauge } { Copyright ©1999 Lloyd Kinsella. } { } { FlatStyle is Copyright ©1998-99 Maik Porkert. } {***************************************************************} interface {$I Version.inc} uses WinProcs, WinTypes, SysUtils, Messages, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, Consts, FlatUtilitys; type TFlatGauge = class(TGraphicControl) private FUseAdvColors: Boolean; FAdvColorBorder: TAdvColors; FBarColor, FBorderColor: TColor; FMinValue, FMaxValue, FProgress: LongInt; FShowText: Boolean; procedure SetShowText(Value: Boolean); procedure SetMinValue(Value: Longint); procedure SetMaxValue(Value: Longint); procedure SetProgress(Value: Longint); procedure SetColors (Index: Integer; Value: TColor); procedure SetAdvColors (Index: Integer; Value: TAdvColors); procedure SetUseAdvColors (Value: Boolean); procedure CMSysColorChange (var Message: TMessage); message CM_SYSCOLORCHANGE; procedure CMParentColorChanged (var Message: TWMNoParams); message CM_PARENTCOLORCHANGED; protected procedure CalcAdvColors; procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property AdvColorBorder: TAdvColors index 0 read FAdvColorBorder write SetAdvColors default 50; property UseAdvColors: Boolean read FUseAdvColors write SetUseAdvColors default False; property Color default $00E0E9EF; property BorderColor: TColor index 0 read FBorderColor write SetColors default $00555E66; property BarColor: TColor index 1 read FBarColor write SetColors default $00996633; property MinValue: Longint read FMinValue write SetMinValue default 0; property MaxValue: Longint read FMaxValue write SetMaxValue default 100; property Progress: Longint read FProgress write SetProgress; property ShowText: Boolean read FShowText write SetShowText default True; property Align; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property ShowHint; property Visible; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; {$IFDEF D4CB4} property Anchors; property BiDiMode; property Constraints; property DragKind; property ParentBiDiMode; property OnEndDock; property OnStartDock; {$ENDIF} end; implementation constructor TFlatGauge.Create(AOwner: TComponent); begin inherited Create (AOwner); ControlStyle := ControlStyle + [csOpaque]; Width := 145; Height := 25; MinValue := 0; MaxValue := 100; Progress := 25; ShowText := True; BarColor := $00996633; BorderColor := $00555E66; Color := $00E0E9EF; end; procedure TFlatGauge.Paint; var R, R2, RC: TRect; LeftBitmap, RightBitmap: TBitmap; PercentText: String; TextPosX: Integer; XProgress: Integer; begin with Canvas do begin R := ClientRect; Brush.Color := Color; FillRect(R); Frame3D(Canvas, R, FBorderColor, FBorderColor, 1); InflateRect (R, -2, -2); LeftBitmap := TBitmap.Create; try LeftBitmap.Height := ClientHeight - 4; LeftBitmap.Width := ClientWidth - 4; RightBitmap := TBitmap.Create; try RightBitmap.Height := ClientHeight - 4; RightBitmap.Width := ClientWidth - 4; try PercentText := IntToStr(Trunc(((FProgress-FMinValue)/(FMaxValue-FMinValue)) * 100)) + ' %'; except PercentText := 'error'; end; TextPosX := (ClientWidth div 2) - (TextWidth(PercentText) div 2); with LeftBitmap.Canvas do begin Pen.Color := FBarColor; Brush.Color := FBarColor; Brush.Style := bsSolid; Rectangle (0, 0, LeftBitmap.Width, LeftBitmap.Height); if FShowText then begin Font.Assign (Self.Font); Font.Color := Color; TextOut (TextPosX, (LeftBitmap.Height div 2) - (TextHeight(PercentText) div 2), PercentText); end; end; with RightBitmap.Canvas do begin Pen.Color := Color; Brush.Color := Color; Brush.Style := bsSolid; Rectangle (0, 0, RightBitmap.Width, RightBitmap.Height); if FShowText then begin Font.Assign (Self.Font); Font.Color := FBarColor; TextOut (TextPosX, (LeftBitmap.Height div 2) - (TextHeight(PercentText) div 2), PercentText); end; end; R2 := ClientRect; Dec (R2.Right, 4); Dec (R2.Bottom, 4); try XProgress := Trunc(((FProgress-FMinValue)/(FMaxValue-FMinValue)) * LeftBitmap.Width); except XProgress := 0; end; Dec (R2.Right, LeftBitmap.Width-XProgress); RC := R; Dec (RC.Right, LeftBitmap.Width-XProgress); CopyRect (RC, LeftBitmap.Canvas, R2); R2 := ClientRect; Dec (R2.Right, 4); Dec (R2.Bottom, 4); Inc (R2.Left, XProgress); RC := R; Inc (RC.Left, XProgress); CopyRect (RC, RightBitmap.Canvas, R2); finally RightBitmap.Free; end; finally LeftBitmap.Free; end; end; end; procedure TFlatGauge.SetShowText(Value: Boolean); begin if FShowText <> Value then begin FShowText := Value; Repaint; end; end; procedure TFlatGauge.SetMinValue(Value: Longint); begin if Value <> FMinValue then begin if Value > FMaxValue then FMinValue := FMaxValue else FMinValue := Value; if FProgress < Value then FProgress := Value; Repaint; end; end; procedure TFlatGauge.SetMaxValue(Value: Longint); begin if Value <> FMaxValue then begin if Value < FMinValue then FMaxValue := FMinValue else FMaxValue := Value; if FProgress > Value then FProgress := Value; Repaint; end; end; procedure TFlatGauge.SetProgress(Value: Longint); begin if Value < FMinValue then Value := FMinValue else if Value > FMaxValue then Value := FMaxValue; if FProgress <> Value then begin FProgress := Value; Repaint; end; end; procedure TFlatGauge.SetColors (Index: Integer; Value: TColor); begin case Index of 0: FBorderColor := Value; 1: FBarColor := Value; end; Invalidate; end; procedure TFlatGauge.CalcAdvColors; begin if FUseAdvColors then begin FBorderColor := CalcAdvancedColor(Color, FBorderColor, FAdvColorBorder, darken); end; end; procedure TFlatGauge.SetAdvColors (Index: Integer; Value: TAdvColors); begin case Index of 0: FAdvColorBorder := Value; end; CalcAdvColors; Invalidate; end; procedure TFlatGauge.SetUseAdvColors (Value: Boolean); begin if Value <> FUseAdvColors then begin FUseAdvColors := Value; ParentColor := Value; CalcAdvColors; Invalidate; end; end; procedure TFlatGauge.CMSysColorChange (var Message: TMessage); begin if FUseAdvColors then begin ParentColor := True; CalcAdvColors; end; Invalidate; end; procedure TFlatGauge.CMParentColorChanged (var Message: TWMNoParams); begin inherited; if FUseAdvColors then begin ParentColor := True; CalcAdvColors; end; Invalidate; end; end.
unit AudioFormat; interface uses SysUtils, FileUtils; type TAudioFile = class(TFile) end; type TAudioData = class(TObject) public nChannels: Word; nSamplesPerSec: LongWord; nBitsPerSample: Word; nBlockAlign: Word; Data: TFile; constructor Create; destructor Destroy; procedure Calculate_nBlockAlign; procedure ReadSample(Number, Channel: LongInt; var Value: Integer); procedure WriteSample(Number, Channel: LongInt; Value: Integer); function Extremum(Number, Channel: LongInt): Boolean; private Name: String; end; procedure CopyAudio(var AudioSource, AudioGeter: TAudioData; Start, Finish: Cardinal); procedure DeleteAudio(var AudioData: TAudioData; Start, Finish: Cardinal); procedure InsertAudio(var AudioSource, AudioGeter: TAudioData; Start: Cardinal); procedure OverwriteAudio(var AudioSource, AudioGeter: TAudioData; Start: Cardinal); procedure MixAudio(var AudioSource, AudioGeter: TAudioData; Start: Cardinal); procedure ReverseAudio(var AudioData: TAudioData; Start, Count: Cardinal); procedure AddBrainWave(var AudioData: TAudioData; Start, Count, Freq1, Freq2: Integer); procedure SetSpeedOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Speed: Real); function ChangeSpeedOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Speed: Real): Cardinal; procedure SetnSamplesPerSec(var AudioData: TAudioData; Value: Cardinal); procedure SetnBitsPerSample(var AudioData: TAudioData; Value: Cardinal); procedure SetnChannels(var AudioData: TAudioData; Value: Cardinal); procedure SetVolumeOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Volume: Real); procedure Echo(var AudioData: TAudioData; Start, Count, Number, Delay: Cardinal; Volume: Real); procedure Reverberation(var AudioData: TAudioData; Start, Count, Number, Delay: Cardinal; Volume: Real); procedure ChangeVolumeOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Volume: Real); procedure ReChangeVolumeOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Volume: Real); procedure Normalize(var AudioData: TAudioData; Start, Count: Cardinal); implementation constructor TAudioData.Create; var TempDir, FileName: String; i: Word; begin inherited Create; TempDir := GetEnvironmentVariable('TEMP')+'\'; i := 0; FileName := TempDir + '\' + '0.TAD'; while FileExists(FileName) do begin Inc(i); Str(i, FileName); FileName := TempDir + '\' + FileName + '.TAD'; end; Name := FileName; Data := TFile.Create(FileName); end; procedure TAudioData.Calculate_nBlockAlign; begin nBlockAlign := nBitsPerSample div 8; if nBitsPerSample mod 8 <> 0 then Inc(nBlockAlign); nBlockAlign := nBlockAlign*nChannels; end; procedure TAudioData.ReadSample(Number, Channel: LongInt; var Value: Integer); var i: Byte; Mult, AbsValue: LongWord; begin Calculate_nBlockAlign; Data.Position := Number*nBlockAlign + Channel*(nBlockAlign div nChannels); AbsValue := 0; Data.Read(AbsValue, nBlockAlign div nChannels); Mult := 1; for i := 1 to nBlockAlign div nChannels do Mult := Mult*256; if nBitsPerSample>8 then if AbsValue >= Trunc(Mult/2) then Value := AbsValue - Mult else Value := AbsValue else Value := AbsValue-128; end; procedure TAudioData.WriteSample(Number, Channel: LongInt; Value: Integer); var K: Byte; N: Cardinal; begin Calculate_nBlockAlign; Data.Position := Number*nBlockAlign + Channel*(nBlockAlign div nChannels); if Data.Position>Data.Size then begin K := 0; N := Data.Position + nBlockAlign div nChannels; Data.Position := Data.Size; while Data.Position<=N do Data.Write(K, 1); Data.Position := Number*nBlockAlign + Channel*(nBlockAlign div nChannels); end; if nBitsPerSample<=8 then Value := Value+128; Data.Write(Value, nBlockAlign div nChannels); end; function TAudioData.Extremum(Number, Channel: LongInt): Boolean; var Smp1, Smp, Smp2: Integer; begin if (Number = 0) or (Number + 1 = Data.Size div nBlockAlign) then begin Extremum := True; Exit; end; ReadSample(Number-1, Channel, Smp1); ReadSample(Number, Channel, Smp); ReadSample(Number+1, Channel, Smp2); if (Smp1<Smp)and(Smp>Smp2) or (Smp1>Smp)and(Smp<Smp2) then Extremum := True else Extremum := False; end; destructor TAudioData.Destroy; begin Data.Destroy; DeleteFile(Name); inherited Destroy; end; procedure CopyAudio(var AudioSource, AudioGeter: TAudioData; Start, Finish: Cardinal); var i: Cardinal; Buf: array[0..63] of Byte; begin AudioGeter.Data.Clear; AudioGeter.nChannels := AudioSource.nChannels; AudioGeter.nSamplesPerSec := AudioSource.nSamplesPerSec; AudioGeter.nBitsPerSample := AudioSource.nBitsPerSample; AudioGeter.Calculate_nBlockAlign; AudioSource.Data.Position := Start*AudioSource.nBlockAlign; for i := 1 to Abs(Finish-Start) do begin AudioSource.Data.Read(Buf, AudioSource.nBlockAlign); AudioGeter.Data.Write(Buf, AudioSource.nBlockAlign); end; AudioGeter.nChannels := AudioSource.nChannels; AudioGeter.nSamplesPerSec := AudioSource.nSamplesPerSec; AudioGeter.nBitsPerSample := AudioSource.nBitsPerSample; end; procedure InsertAudio(var AudioSource, AudioGeter: TAudioData; Start: Cardinal); var i: Cardinal; Buf: Byte; begin if AudioSource.Data.Size = 0 then Exit; AudioGeter.Data.Insert(Start*AudioGeter.nBlockAlign, AudioSource.Data.Size); AudioSource.Data.Position := 0; AudioGeter.Data.Position := Start*AudioGeter.nBlockAlign; for i := 1 to AudioSource.Data.Size do begin AudioSource.Data.Read(Buf, 1); AudioGeter.Data.Write(Buf, 1); end; end; procedure DeleteAudio(var AudioData: TAudioData; Start, Finish: Cardinal); begin AudioData.Data.Delete(Start*AudioData.nBlockAlign, Abs(Finish-Start)*AudioData.nBlockAlign); end; procedure OverwriteAudio(var AudioSource, AudioGeter: TAudioData; Start: Cardinal); var i: Cardinal; Buf: Byte; begin if AudioSource.Data.Size = 0 then Exit; AudioSource.Data.Position := 0; AudioGeter.Data.Position := Start*AudioGeter.nBlockAlign; for i := 1 to AudioSource.Data.Size do begin AudioSource.Data.Read(Buf, 1); AudioGeter.Data.Write(Buf, 1); end; end; procedure MixAudio(var AudioSource, AudioGeter: TAudioData; Start: Cardinal); var i, Channel, AudioSize: Cardinal; Value, MaxValue: Int64; Samp1, Samp2: Integer; begin if AudioSource.Data.Size = 0 then Exit; AudioSize := AudioGeter.Data.Size div AudioGeter.nBlockAlign; MaxValue := 1; for i := 1 to AudioGeter.nBitsPerSample-1 do MaxValue := MaxValue*2; for i := 0 to AudioSource.Data.Size div AudioGeter.nBlockAlign - 1 do for Channel := 0 to AudioGeter.nChannels-1 do begin AudioSource.ReadSample(i, Channel, Samp1); if Start+i<AudioSize then AudioGeter.ReadSample(Start+i, Channel, Samp2) else Samp2 := 0; Value := Samp1 + Samp2; if (Value < -MaxValue)or(Value >= MaxValue) then Value := Trunc((Value)/2); AudioGeter.WriteSample(Start+i, Channel, Value); end; end; procedure ReverseAudio(var AudioData: TAudioData; Start, Count: Cardinal); var i, AbsStart, AbsFinish, AbsCount: Cardinal; BufferStart: Cardinal; Buf: Int64; TempAudio: TAudioData; begin TempAudio := TAudioData.Create; AbsStart := Start*AudioData.nBlockAlign; AbsCount := Count*AudioData.nBlockAlign; AbsFinish := AbsStart+AbsCount; i := AbsFinish; repeat if i-AbsStart>=MaxSizeOfBuffer then BufferStart := i - MaxSizeOfBuffer else BufferStart := AbsStart; AudioData.Data.Position := BufferStart; AudioData.Data.Read(Buf, 1); while i>BufferStart do begin i := i - AudioData.nBlockAlign; AudioData.Data.Position := i; AudioData.Data.Read(Buf, AudioData.nBlockAlign); TempAudio.Data.Write(Buf, AudioData.nBlockAlign); end; until i=AbsStart; AudioData.Data.Position := AbsStart; TempAudio.Data.Position := 0; for i := 1 to Count do begin TempAudio.Data.Read(Buf, AudioData.nBlockAlign); AudioData.Data.Write(Buf, AudioData.nBlockAlign); end; TempAudio.Destroy; end; procedure AddBrainWave(var AudioData: TAudioData; Start, Count, Freq1, Freq2: Integer); var i, MaxAmplitude: Cardinal; T, TL, TR: Real; Freq: Integer; SampL, SampR: Integer; begin if AudioData.nChannels = 1 then Exit; MaxAmplitude := 1; for i := 1 to AudioData.nBitsPerSample-1 do MaxAmplitude := MaxAmplitude*2; for i := Start to Start+Count-1 do begin Freq := Freq1 + Round((i-Start)*(Freq2-Freq1)/Count); T := 2*Pi/(AudioData.nSamplesPerSec/(Freq/100)); TL := 2*Pi/(AudioData.nSamplesPerSec/(50+50*Freq/100)); TR := 2*Pi/(AudioData.nSamplesPerSec/(50+50*Freq/100+Freq/100)); AudioData.ReadSample(i, 0, SampL); AudioData.ReadSample(i, 1, SampR); SampL := Trunc(0.6*SampL+0.4*MaxAmplitude*Sin(i*TL)); SampR := Trunc(0.6*SampR+0.4*MaxAmplitude*Sin(i*TR)); AudioData.WriteSample(i, 0, SampL); AudioData.WriteSample(i, 1, SampR); end; end; procedure Normalize(var AudioData: TAudioData; Start, Count: Cardinal); var i, MaxAmplitude, MaxVolume: Cardinal; Volume: Integer; K: Real; Channel: Word; begin MaxAmplitude := 1; for i := 1 to AudioData.nBitsPerSample-1 do MaxAmplitude := MaxAmplitude*2; for Channel := 0 to AudioData.nChannels-1 do begin MaxVolume := 0; for i := Start to Start+Count-1 do begin AudioData.ReadSample(i, Channel, Volume); if Abs(Volume) > MaxVolume then MaxVolume := Abs(Volume); end; K := MaxAmplitude/MaxVolume; for i := Start to Start+Count-1 do begin AudioData.ReadSample(i, Channel, Volume); Volume := Round(Volume*K); AudioData.WriteSample(i, Channel, Volume); end; end; end; procedure SetSpeedOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Speed: Real); var i, j, k, n, NewCount: Cardinal; Channel: Byte; Smp1, Smp2: Integer; Interval: Real; TempAudio: TAudioData; Buf: Int64; begin if (Speed = 1) or (Speed = 0) then Exit; TempAudio := TAudioData.Create; TempAudio.nChannels := AudioData.nChannels; TempAudio.nSamplesPerSec := AudioData.nSamplesPerSec; TempAudio.nBitsPerSample := AudioData.nBitsPerSample; TempAudio.nBlockAlign := AudioData.nBlockAlign; NewCount := Round(Count/Speed); if Speed > 1 then begin i := NewCount; Interval := Speed; AudioData.Data.Position := Start*AudioData.nBlockAlign; while i<>0 do begin AudioData.Data.Read(Buf, AudioData.nBlockAlign); TempAudio.Data.Write(Buf, AudioData.nBlockAlign); AudioData.Data.Position := AudioData.Data.Position - AudioData.nBlockAlign + Trunc(Interval)*AudioData.nBlockAlign; Interval := Interval-Trunc(Interval)+Speed; Dec(i); end; end else begin Speed := 1/Speed; for Channel := 0 to AudioData.nChannels-1 do begin i := 0; j := 0; Interval := Speed; while i<>Count do begin AudioData.ReadSample(Start+i, Channel, Smp1); if i+1<>Count then AudioData.ReadSample(Start+i+1, Channel, Smp2) else Smp2 := Smp1; k := Trunc(Interval); for n := 0 to k-1 do TempAudio.WriteSample(j+n, Channel, Round(Smp1+(Smp2-Smp1)/k*n)); Interval := Interval-Trunc(Interval)+Speed; Inc(i); Inc(j, k); end; end; end; DeleteAudio(AudioData, Start, Start+Count-1); InsertAudio(TempAudio, AudioData, Start); TempAudio.Destroy; end; function ChangeSpeedOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Speed: Real): Cardinal; var i, j, k, n: Cardinal; Channel: Byte; Smp1, Smp2: Integer; Interval, FinalSpeed: Real; TempAudio: TAudioData; Buf: Int64; begin if (Speed = 1) or (Speed = 0) then Exit; TempAudio := TAudioData.Create; TempAudio.nChannels := AudioData.nChannels; TempAudio.nSamplesPerSec := AudioData.nSamplesPerSec; TempAudio.nBitsPerSample := AudioData.nBitsPerSample; TempAudio.nBlockAlign := AudioData.nBlockAlign; FinalSpeed := Speed; if Speed > 1 then begin Speed := 1; Interval := Speed; AudioData.Data.Position := Start*AudioData.nBlockAlign; while AudioData.Data.Position div AudioData.nBlockAlign < Start+Count do begin AudioData.Data.Read(Buf, AudioData.nBlockAlign); TempAudio.Data.Write(Buf, AudioData.nBlockAlign); AudioData.Data.Position := AudioData.Data.Position - AudioData.nBlockAlign + Trunc(Interval)*AudioData.nBlockAlign; Interval := Interval-Trunc(Interval)+Speed; Speed := Speed+Trunc(Interval)*(FinalSpeed-1)/Count; end; end else begin FinalSpeed := 1/FinalSpeed; for Channel := 0 to AudioData.nChannels-1 do begin i := 0; j := 0; Speed := 1; Interval := Speed; while i<>Count do begin AudioData.ReadSample(Start+i, Channel, Smp1); if i+1<>Count then AudioData.ReadSample(Start+i+1, Channel, Smp2) else Smp2 := Smp1; k := Trunc(Interval); for n := 0 to k-1 do TempAudio.WriteSample(j+n, Channel, Round(Smp1+(Smp2-Smp1)/k*n)); Interval := Interval-Trunc(Interval)+Speed; Inc(i); Inc(j, k); Speed := Speed+(FinalSpeed-1)/Count; end; end; end; DeleteAudio(AudioData, Start, Start+Count-1); InsertAudio(TempAudio, AudioData, Start); ChangeSpeedOfAudio := TempAudio.Data.Size div TempAudio.nBlockAlign; TempAudio.Destroy; end; procedure SetnSamplesPerSec(var AudioData: TAudioData; Value: Cardinal); var AudioSize: Cardinal; begin if AudioData.nSamplesPerSec = Value then Exit; with AudioData do AudioSize := Data.Size div nBlockAlign; if AudioSize <> 0 then SetSpeedOfAudio(AudioData, 0, AudioSize, AudioData.nSamplesPerSec/Value); AudioData.nSamplesPerSec := Value; end; procedure SetnBitsPerSample(var AudioData: TAudioData; Value: Cardinal); var AudioSize, Max1, Max2, i: Cardinal; Channel: Word; Smp: Integer; Mult: Real; TempAudio: TAudioData; begin if AudioData.nBitsPerSample = Value then Exit; with AudioData do AudioSize := Data.Size div nBlockAlign; TempAudio := TAudioData.Create; TempAudio.nChannels := AudioData.nChannels; TempAudio.nSamplesPerSec := AudioData.nSamplesPerSec; TempAudio.nBitsPerSample := Value; TempAudio.Calculate_nBlockAlign; Max1 := 1; for i := 1 to AudioData.nBlockAlign div AudioData.nChannels do Max1 := Max1*256; Max2 := 1; for i := 1 to TempAudio.nBlockAlign div TempAudio.nChannels do Max2 := Max2*256; Mult := Max2/Max1; if AudioSize<>0 then begin for Channel := 0 to AudioData.nChannels-1 do for i := 0 to AudioSize-1 do begin AudioData.ReadSample(i, Channel, Smp); Smp := Trunc(Smp*Mult); TempAudio.WriteSample(i, Channel, Smp); end; AudioData.Data.Clear; OverwriteAudio(TempAudio, AudioData, 0); end; TempAudio.Destroy; AudioData.nBitsPerSample := Value; AudioData.Calculate_nBlockAlign; end; procedure SetnChannels(var AudioData: TAudioData; Value: Cardinal); var AudioSize: Cardinal; TempAudio: TAudioData; i: Integer; Channel: Cardinal; Smp: Integer; begin if AudioData.nChannels = Value then Exit; with AudioData do AudioSize := Data.Size div nBlockAlign; TempAudio := TAudioData.Create; TempAudio.nChannels := Value; TempAudio.nSamplesPerSec := AudioData.nSamplesPerSec; TempAudio.nBitsPerSample := AudioData.nBitsPerSample; TempAudio.Calculate_nBlockAlign; for i := 0 to AudioSize-1 do for Channel := 0 to Value-1 do begin if Channel < AudioData.nChannels then AudioData.ReadSample(i, Channel, Smp) else AudioData.ReadSample(i, AudioData.nChannels-1, Smp); TempAudio.WriteSample(i, Channel, Smp); end; AudioData.Data.Clear; AudioData.nChannels := Value; AudioData.Calculate_nBlockAlign; OverWriteAudio(TempAudio, AudioData, 0); TempAudio.Destroy; end; procedure SetVolumeOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Volume: Real); var MaxValue: Cardinal; Value: Integer; i: Cardinal; Channel: Word; begin MaxValue := 1; for i := 1 to AudioData.nBlockAlign div AudioData.nChannels do MaxValue := MaxValue*256; MaxValue := MaxValue div 2 - 1; for Channel := 0 to AudioData.nChannels-1 do for i := Start to Start+Count-1 do begin AudioData.ReadSample(i, Channel, Value); //Value := Trunc(Value*Exp(Volume/20)); Value := Trunc(Value*Volume); if Abs(Value)>MaxValue then if Value<0 then Value := -MaxValue else Value := MaxValue; AudioData.WriteSample(i, Channel, Value); end; end; procedure Echo(var AudioData: TAudioData; Start, Count, Number, Delay: Cardinal; Volume: Real); var TempAudio: TAudioData; i, j, DelaySmp: Cardinal; SummSmp: Int64; Mult: Real; Smp: Integer; Channel: Word; MaxValue: Cardinal; begin for i := 1 to AudioData.nBlockAlign div AudioData.nChannels do MaxValue := MaxValue*256; MaxValue := MaxValue div 2 - 1; TempAudio := TAudioData.Create; TempAudio.nChannels := AudioData.nChannels; TempAudio.nSamplesPerSec := AudioData.nSamplesPerSec; TempAudio.nBitsPerSample := AudioData.nBitsPerSample; TempAudio.Calculate_nBlockAlign; DelaySmp := Round(Delay*AudioData.nSamplesPerSec/1000); for Channel := 0 to AudioData.nChannels-1 do for i := Start to Start+Count-1 do begin AudioData.ReadSample(i, Channel, Smp); SummSmp := Smp; Mult := Volume; for j := 1 to Number do begin if i-Start < DelaySmp*j then Smp := 0 else AudioData.ReadSample(i-DelaySmp*j, Channel, Smp); SummSmp := SummSmp + Round(Mult*Smp); Mult := Mult*Volume; end; Smp := Round(SummSmp/(Number+1)); if Abs(Smp)>MaxValue then if Smp<0 then Smp := -MaxValue else Smp := MaxValue; TempAudio.WriteSample(i-Start, Channel, Smp); end; OverwriteAudio(TempAudio, AudioData, Start); TempAudio.Destroy; Normalize(AudioData, Start, Count); end; procedure Reverberation(var AudioData: TAudioData; Start, Count, Number, Delay: Cardinal; Volume: Real); var TempAudio: TAudioData; i, j, k, DelaySmp: Cardinal; SummSmp: Int64; SmpBuf: array[0..64] of Int64; Mult: Real; Smp: Integer; Channel: Word; MaxValue: Cardinal; begin for i := 1 to AudioData.nBlockAlign div AudioData.nChannels do MaxValue := MaxValue*256; MaxValue := MaxValue div 2 - 1; TempAudio := TAudioData.Create; TempAudio.nChannels := AudioData.nChannels; TempAudio.nSamplesPerSec := AudioData.nSamplesPerSec; TempAudio.nBitsPerSample := AudioData.nBitsPerSample; TempAudio.Calculate_nBlockAlign; DelaySmp := Round(Delay*AudioData.nSamplesPerSec/1000); for Channel := 0 to AudioData.nChannels-1 do for i := Start to Start+Count-1 do begin for j := Number downto 0 do begin if i-Start < DelaySmp*j then Smp := 0 else AudioData.ReadSample(i-DelaySmp*j, Channel, Smp); SmpBuf[j] := Smp; end; Mult := Volume; for j := 1 to Number do begin for k := 1 to Number do SmpBuf[k-1] := SmpBuf[k-1] + Round(SmpBuf[k]*Mult); Mult := Mult*Volume; end; Smp := Round(SmpBuf[0]/(Number+1)); if Abs(Smp)>MaxValue then if Smp<0 then Smp := -MaxValue else Smp := MaxValue; TempAudio.WriteSample(i-Start, Channel, Smp); end; OverwriteAudio(TempAudio, AudioData, Start); TempAudio.Destroy; Normalize(AudioData, Start, Count); end; procedure ChangeVolumeOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Volume: Real); var MaxValue: Cardinal; Value: Integer; i: Cardinal; FinalVolume: Real; Channel: Word; begin MaxValue := 1; for i := 1 to AudioData.nBlockAlign div AudioData.nChannels do MaxValue := MaxValue*256; MaxValue := MaxValue div 2 - 1; FinalVolume := Volume; for Channel := 0 to AudioData.nChannels-1 do begin Volume := 1; for i := Start to Start+Count-1 do begin AudioData.ReadSample(i, Channel, Value); //Value := Trunc(Value*Exp(Volume/20)); Value := Trunc(Value*Volume); if Abs(Value)>MaxValue then if Value<0 then Value := -MaxValue else Value := MaxValue; AudioData.WriteSample(i, Channel, Value); Volume := Volume + (FinalVolume-1)/Count; end; end; end; procedure ReChangeVolumeOfAudio(var AudioData: TAudioData; Start, Count: Cardinal; Volume: Real); var MaxValue: Cardinal; Value: Integer; i: Cardinal; FinalVolume: Real; Channel: Word; begin MaxValue := 1; for i := 1 to AudioData.nBlockAlign div AudioData.nChannels do MaxValue := MaxValue*256; MaxValue := MaxValue div 2 - 1; FinalVolume := Volume; for Channel := 0 to AudioData.nChannels-1 do begin Volume := 0; for i := Start to Start+Count-1 do begin AudioData.ReadSample(i, Channel, Value); //Value := Trunc(Value*Exp(Volume/20)); Value := Trunc(Value*Volume); if Abs(Value)>MaxValue then if Value<0 then Value := -MaxValue else Value := MaxValue; AudioData.WriteSample(i, Channel, Value); Volume := Volume + FinalVolume/Count; end; end; end; end.
unit PACCSort; {$i PACC.inc} interface uses PACCTypes,PasMP; type TUntypedSortCompareFunction=function(const a,b:pointer):TPACCInt32; TIndirectSortCompareFunction=function(const a,b:pointer):TPACCInt32; // Sorts data direct inplace procedure UntypedDirectIntroSort(const pItems:pointer;const pLeft,pRight,pElementSize:TPACCInt32;const pCompareFunc:TUntypedSortCompareFunction); // Sorts data indirect outplace with an extra pointer array procedure IndirectIntroSort(const pItems:pointer;const pLeft,pRight:TPACCInt32;const pCompareFunc:TIndirectSortCompareFunction); implementation procedure MemorySwap(pA,pB:pointer;pSize:TPACCInt32); var Temp:TPACCInt32; begin while pSize>=SizeOf(TPACCInt32) do begin Temp:=TPACCUInt32(pA^); TPACCUInt32(pA^):=TPACCUInt32(pB^); TPACCUInt32(pB^):=Temp; inc(TPACCPtrUInt(pA),SizeOf(TPACCUInt32)); inc(TPACCPtrUInt(pB),SizeOf(TPACCUInt32)); dec(pSize,SizeOf(TPACCUInt32)); end; while pSize>=SizeOf(TPACCUInt8) do begin Temp:=TPACCUInt8(pA^); TPACCUInt8(pA^):=TPACCUInt8(pB^); TPACCUInt8(pB^):=Temp; inc(TPACCPtrUInt(pA),SizeOf(TPACCUInt8)); inc(TPACCPtrUInt(pB),SizeOf(TPACCUInt8)); dec(pSize,SizeOf(TPACCUInt8)); end; end; procedure UntypedDirectIntroSort(const pItems:pointer;const pLeft,pRight,pElementSize:TPACCInt32;const pCompareFunc:TUntypedSortCompareFunction); type PByteArray=^TByteArray; TByteArray=array[0..$3fffffff] of TPACCUInt8; PStackItem=^TStackItem; TStackItem=record Left,Right,Depth:TPACCInt32; end; var Left,Right,Depth,i,j,Middle,Size,Parent,Child,Pivot,iA,iB,iC:TPACCInt32; StackItem:PStackItem; Stack:array[0..31] of TStackItem; begin if pLeft<pRight then begin StackItem:=@Stack[0]; StackItem^.Left:=pLeft; StackItem^.Right:=pRight; StackItem^.Depth:=TPasMPMath.BitScanReverse((pRight-pLeft)+1) shl 1; inc(StackItem); while TPACCPtrUInt(pointer(StackItem))>TPACCPtrUInt(pointer(@Stack[0])) do begin dec(StackItem); Left:=StackItem^.Left; Right:=StackItem^.Right; Depth:=StackItem^.Depth; Size:=(Right-Left)+1; if Size<16 then begin // Insertion sort iA:=Left; iB:=iA+1; while iB<=Right do begin iC:=iB; while (iA>=Left) and (iC>=Left) and (pCompareFunc(pointer(@PByteArray(pItems)^[iA*pElementSize]),pointer(@PByteArray(pItems)^[iC*pElementSize]))>0) do begin MemorySwap(@PByteArray(pItems)^[iA*pElementSize],@PByteArray(pItems)^[iC*pElementSize],pElementSize); dec(iA); dec(iC); end; iA:=iB; inc(iB); end; end else begin if (Depth=0) or (TPACCPtrUInt(pointer(StackItem))>=TPACCPtrUInt(pointer(@Stack[high(Stack)-1]))) then begin // Heap sort i:=Size div 2; repeat if i>0 then begin dec(i); end else begin dec(Size); if Size>0 then begin MemorySwap(@PByteArray(pItems)^[(Left+Size)*pElementSize],@PByteArray(pItems)^[Left*pElementSize],pElementSize); end else begin break; end; end; Parent:=i; repeat Child:=(Parent*2)+1; if Child<Size then begin if (Child<(Size-1)) and (pCompareFunc(pointer(@PByteArray(pItems)^[(Left+Child)*pElementSize]),pointer(@PByteArray(pItems)^[(Left+Child+1)*pElementSize]))<0) then begin inc(Child); end; if pCompareFunc(pointer(@PByteArray(pItems)^[(Left+Parent)*pElementSize]),pointer(@PByteArray(pItems)^[(Left+Child)*pElementSize]))<0 then begin MemorySwap(@PByteArray(pItems)^[(Left+Parent)*pElementSize],@PByteArray(pItems)^[(Left+Child)*pElementSize],pElementSize); Parent:=Child; continue; end; end; break; until false; until false; end else begin // Quick sort width median-of-three optimization Middle:=Left+((Right-Left) shr 1); if (Right-Left)>3 then begin if pCompareFunc(pointer(@PByteArray(pItems)^[Left*pElementSize]),pointer(@PByteArray(pItems)^[Middle*pElementSize]))>0 then begin MemorySwap(@PByteArray(pItems)^[Left*pElementSize],@PByteArray(pItems)^[Middle*pElementSize],pElementSize); end; if pCompareFunc(pointer(@PByteArray(pItems)^[Left*pElementSize]),pointer(@PByteArray(pItems)^[Right*pElementSize]))>0 then begin MemorySwap(@PByteArray(pItems)^[Left*pElementSize],@PByteArray(pItems)^[Right*pElementSize],pElementSize); end; if pCompareFunc(pointer(@PByteArray(pItems)^[Middle*pElementSize]),pointer(@PByteArray(pItems)^[Right*pElementSize]))>0 then begin MemorySwap(@PByteArray(pItems)^[Middle*pElementSize],@PByteArray(pItems)^[Right*pElementSize],pElementSize); end; end; Pivot:=Middle; i:=Left; j:=Right; repeat while (i<Right) and (pCompareFunc(pointer(@PByteArray(pItems)^[i*pElementSize]),pointer(@PByteArray(pItems)^[Pivot*pElementSize]))<0) do begin inc(i); end; while (j>=i) and (pCompareFunc(pointer(@PByteArray(pItems)^[j*pElementSize]),pointer(@PByteArray(pItems)^[Pivot*pElementSize]))>0) do begin dec(j); end; if i>j then begin break; end else begin if i<>j then begin MemorySwap(@PByteArray(pItems)^[i*pElementSize],@PByteArray(pItems)^[j*pElementSize],pElementSize); if Pivot=i then begin Pivot:=j; end else if Pivot=j then begin Pivot:=i; end; end; inc(i); dec(j); end; until false; if i<Right then begin StackItem^.Left:=i; StackItem^.Right:=Right; StackItem^.Depth:=Depth-1; inc(StackItem); end; if Left<j then begin StackItem^.Left:=Left; StackItem^.Right:=j; StackItem^.Depth:=Depth-1; inc(StackItem); end; end; end; end; end; end; procedure IndirectIntroSort(const pItems:pointer;const pLeft,pRight:TPACCInt32;const pCompareFunc:TIndirectSortCompareFunction); type PPointers=^TPointers; TPointers=array[0..$ffff] of pointer; PStackItem=^TStackItem; TStackItem=record Left,Right,Depth:TPACCInt32; end; var Left,Right,Depth,i,j,Middle,Size,Parent,Child:TPACCInt32; Pivot,Temp:pointer; StackItem:PStackItem; Stack:array[0..31] of TStackItem; begin if pLeft<pRight then begin StackItem:=@Stack[0]; StackItem^.Left:=pLeft; StackItem^.Right:=pRight; StackItem^.Depth:=TPasMPMath.BitScanReverse((pRight-pLeft)+1) shl 1; inc(StackItem); while TPACCPtrUInt(pointer(StackItem))>TPACCPtrUInt(pointer(@Stack[0])) do begin dec(StackItem); Left:=StackItem^.Left; Right:=StackItem^.Right; Depth:=StackItem^.Depth; Size:=(Right-Left)+1; if Size<16 then begin // Insertion sort for i:=Left+1 to Right do begin Temp:=PPointers(pItems)^[i]; j:=i-1; if (j>=Left) and (pCompareFunc(PPointers(pItems)^[j],Temp)>0) then begin repeat PPointers(pItems)^[j+1]:=PPointers(pItems)^[j]; dec(j); until not ((j>=Left) and (pCompareFunc(PPointers(pItems)^[j],Temp)>0)); PPointers(pItems)^[j+1]:=Temp; end; end; end else begin if (Depth=0) or (TPACCPtrUInt(pointer(StackItem))>=TPACCPtrUInt(pointer(@Stack[high(Stack)-1]))) then begin // Heap sort i:=Size div 2; Temp:=nil; repeat if i>0 then begin dec(i); Temp:=PPointers(pItems)^[Left+i]; end else begin dec(Size); if Size>0 then begin Temp:=PPointers(pItems)^[Left+Size]; PPointers(pItems)^[Left+Size]:=PPointers(pItems)^[Left]; end else begin break; end; end; Parent:=i; Child:=(i*2)+1; while Child<Size do begin if ((Child+1)<Size) and (pCompareFunc(PPointers(pItems)^[Left+Child+1],PPointers(pItems)^[Left+Child])>0) then begin inc(Child); end; if pCompareFunc(PPointers(pItems)^[Left+Child],Temp)>0 then begin PPointers(pItems)^[Left+Parent]:=PPointers(pItems)^[Left+Child]; Parent:=Child; Child:=(Parent*2)+1; end else begin break; end; end; PPointers(pItems)^[Left+Parent]:=Temp; until false; end else begin // Quick sort width median-of-three optimization Middle:=Left+((Right-Left) shr 1); if (Right-Left)>3 then begin if pCompareFunc(PPointers(pItems)^[Left],PPointers(pItems)^[Middle])>0 then begin Temp:=PPointers(pItems)^[Left]; PPointers(pItems)^[Left]:=PPointers(pItems)^[Middle]; PPointers(pItems)^[Middle]:=Temp; end; if pCompareFunc(PPointers(pItems)^[Left],PPointers(pItems)^[Right])>0 then begin Temp:=PPointers(pItems)^[Left]; PPointers(pItems)^[Left]:=PPointers(pItems)^[Right]; PPointers(pItems)^[Right]:=Temp; end; if pCompareFunc(PPointers(pItems)^[Middle],PPointers(pItems)^[Right])>0 then begin Temp:=PPointers(pItems)^[Middle]; PPointers(pItems)^[Middle]:=PPointers(pItems)^[Right]; PPointers(pItems)^[Right]:=Temp; end; end; Pivot:=PPointers(pItems)^[Middle]; i:=Left; j:=Right; repeat while (i<Right) and (pCompareFunc(PPointers(pItems)^[i],Pivot)<0) do begin inc(i); end; while (j>=i) and (pCompareFunc(PPointers(pItems)^[j],Pivot)>0) do begin dec(j); end; if i>j then begin break; end else begin if i<>j then begin Temp:=PPointers(pItems)^[i]; PPointers(pItems)^[i]:=PPointers(pItems)^[j]; PPointers(pItems)^[j]:=Temp; end; inc(i); dec(j); end; until false; if i<Right then begin StackItem^.Left:=i; StackItem^.Right:=Right; StackItem^.Depth:=Depth-1; inc(StackItem); end; if Left<j then begin StackItem^.Left:=Left; StackItem^.Right:=j; StackItem^.Depth:=Depth-1; inc(StackItem); end; end; end; end; end; end; end.
unit UServerContainer; interface uses System.SysUtils, System.Classes, Datasnap.DSTCPServerTransport, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSAuth, IPPeerServer, DbxSocketChannelNative, DbxCompressionFilter; type TServerContainer = class(TDataModule) DataSnapServer: TDSServer; DSTCPServerTransport1: TDSTCPServerTransport; DSAuthenticationManager1: TDSAuthenticationManager; DSServerClass1: TDSServerClass; DSServerClassConfiguracao: TDSServerClass; DSServerClassRelatorio: TDSServerClass; DSServerClassLancamento: TDSServerClass; DSServerClassCadastro: TDSServerClass; procedure DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DSAuthenticationManager1UserAuthorize(Sender: TObject; EventObject: TDSAuthorizeEventObject; var valid: Boolean); procedure DSAuthenticationManager1UserAuthenticate(Sender: TObject; const Protocol, Context, User, Password: string; var valid: Boolean; UserRoles: TStrings); procedure DSServerClassCadastroGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DSServerClassLancamentoGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DSServerClassRelatorioGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DSServerClassConfiguracaoGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private public end; var ServerContainer: TServerContainer; implementation uses Winapi.Windows, uServerMethods, UDSServerModuleCadastro, UDSServerModuleConfiguracao, UDSServerModuleMovimento, UDSServerModuleRelatorio; {$R *.dfm} procedure TServerContainer.DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := uServerMethods.TServerMethods; end; procedure TServerContainer.DSServerClassLancamentoGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := TDSServerModuleMovimento; end; procedure TServerContainer.DSServerClassRelatorioGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := TDSServerModuleRelatorio; end; procedure TServerContainer.DSServerClassCadastroGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := TDSServerModuleCadastro; end; procedure TServerContainer.DSServerClassConfiguracaoGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := TDSServerModuleConfiguracao; end; procedure TServerContainer.DataModuleCreate(Sender: TObject); begin DataSnapServer.Start; end; procedure TServerContainer.DataModuleDestroy(Sender: TObject); begin DataSnapServer.Stop; end; procedure TServerContainer.DSAuthenticationManager1UserAuthenticate(Sender: TObject; const Protocol, Context, User, Password: string; var valid: Boolean; UserRoles: TStrings); begin { TODO : Validate the client user and password. If role-based authorization is needed, add role names to the UserRoles parameter } valid := True; end; procedure TServerContainer.DSAuthenticationManager1UserAuthorize(Sender: TObject; EventObject: TDSAuthorizeEventObject; var valid: Boolean); begin { TODO : Authorize a user to execute a method. Use values from EventObject such as UserName, UserRoles, AuthorizedRoles and DeniedRoles. Use DSAuthenticationManager1.Roles to define Authorized and Denied roles for particular server methods. } valid := True; end; end.
unit UPortMap; interface uses SysUtils, idhttp, classes, idudpclient, Forms; type // 端口映射 TPortMapping = class private IdUdpClient : TIdUDPClient; private location, server, usn: string; st : string; routerip: string; routerport: integer; private controlurl: string; public HasDivice, IsPortMapable : Boolean; // 是否可以进行端口映射 public constructor Create; destructor Destroy; override; public // UPNP 端口映射 procedure AddMapping( LocalIp, LocalPort, InternetPort : string ); procedure RemoveMapping( InternetPort : string ); function getInternetIp : string; private // UPNP 设备查找 function FindDivice: Boolean; function FindControl: Boolean; private // 信息提取 function FindDeviceInfo(ResponseStr : string):Boolean; function FindControlURL(ResponseStr: string): Boolean; end; MyLog = class public class procedure Log( s : string ); class procedure Logln( s : string ); end; implementation uses UDebugForm, UChangeInfo; { TPortMapping } procedure TPortMapping.AddMapping( LocalIp, LocalPort, InternetPort : string ); var Protocol : string; InternalPort, ExternalPort: Integer; InternalClient, RemoteHost: string; PortMappingDeion: string; LeaseDuration: integer; cmd, body, request : string; IdHttp : TIdHTTP; HttpParams : TStringList; a: TMemoryStream; ResponseStr: string; begin // 不能进行端口映射 if not IsPortMapable then Exit; Protocol := 'TCP'; InternalClient := LocalIp; RemoteHost := ''; InternalPort := StrToIntdef( LocalPort, -1 ); ExternalPort := StrToIntdef( InternetPort, -1 ); PortMappingDeion := 'BackupCow' + ' (' + LocalIp + ':' + LocalPort + ') ' + InternetPort + ' TCP'; LeaseDuration := 0; // Port 格式不正确 if ( InternalPort = -1 ) or ( ExternalPort = -1 ) then Exit; cmd := 'AddPortMapping'; body := '<?xml version="1.0"?>'#13#10 + '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"'#13#10 + 's:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'#13#10 + '<s:Body>'#13#10 + '<u:' + cmd + ' xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">'#13#10 + '<NewRemoteHost>' + RemoteHost + '</NewRemoteHost>'#13#10 + '<NewExternalPort>' + inttostr(ExternalPort) + '</NewExternalPort>'#13#10 + '<NewProtocol>' + Protocol + '</NewProtocol>'#13#10 + '<NewInternalPort>' + inttostr(InternalPort) + '</NewInternalPort>'#13#10 + '<NewInternalClient>' + InternalClient + '</NewInternalClient>'#13#10 + '<NewEnabled>1</NewEnabled>'#13#10 + '<NewPortMappingDescription>' + PortMappingDeion + '</NewPortMappingDescription>'#13#10 + '<NewLeaseDuration>' + inttostr(LeaseDuration) + '</NewLeaseDuration>'#13#10 + '</u:' + cmd + '>'#13#10 + '</s:Body>'#13#10 + '</s:Envelope>'#13#10; request := 'POST ' + controlurl + ' HTTP/1.1'#13#10 + 'Host: ' + routerip + ':' + inttostr(routerport) + #13#10 + 'SoapAction: "urn:schemas-upnp-org:service:WANIPConnection:1#' + cmd + '"'#13#10 + 'Content-Type: text/xml; charset="utf-8"'#13#10 + 'Content-Length: ' + inttostr(length(body)) + #13#10#13#10; IdHttp := TIdHTTP.Create(nil); IdHttp.AllowCookies := True; IdHttp.ConnectTimeout := 2000; IdHTTP.Request.CustomHeaders.Text := 'SoapAction: "urn:schemas-upnp-org:service:WANIPConnection:1#' + cmd + '"'; IdHTTP.Request.ContentType := 'text/xml; charset="utf-8"'; HttpParams := TStringList.Create; HttpParams.Text := body; MyLog.Log( 'Send Map Request : ' ); MyLog.Logln( body ); try a := TMemoryStream.Create; HttpParams.SaveToStream( a ); a.Position := 0; ResponseStr := IdHTTP.Post( controlurl , a); MyLog.Log( 'Rev Map Response : ' ); MyLog.Logln( ResponseStr ); except on e: Exception do begin end; end; a.Free; HttpParams.Free; IdHttp.Free; end; procedure TPortMapping.RemoveMapping( InternetPort : string ); var Protocol: string; ExternalPort: Integer; cmd, body, request : string; IdHttp : TIdHTTP; a: TMemoryStream; HttpParams : TStringList; res: string; begin // 不能进行端口映射 if not IsPortMapable then Exit; Protocol := 'TCP'; ExternalPort := StrToInt( InternetPort ); cmd := 'DeletePortMapping'; body := '<?xml version="1.0"?>'#13#10 + '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'#13#10 + '<s:Body>'#13#10 + '<u:' + cmd + ' xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">'#13#10 + '<NewRemoteHost></NewRemoteHost>'#13#10 + '<NewExternalPort>' + inttostr(ExternalPort) + '</NewExternalPort>'#13#10 + '<NewProtocol>TCP</NewProtocol>'#13#10 + '</u:' + cmd + '>'#13#10 + '</s:Body>'#13#10 + '</s:Envelope>'#13#10; request := 'POST ' + controlurl + ' HTTP/1.0'#13#10 + 'Host: ' + routerip + ':' + inttostr(routerport) + #13#10 + 'SoapAction: "urn:schemas-upnp-org:service:WANIPConnection:1#' + cmd + '"'#13#10 + 'Content-Type: text/xml; charset="utf-8"'#13#10 + 'Content-Length: ' + inttostr(length(body)) + #13#10#13#10 + body; IdHttp := TIdHTTP.Create(nil); IdHttp.AllowCookies := True; IdHttp.ConnectTimeout := 2000; IdHTTP.Request.CustomHeaders.Text := 'SoapAction: "urn:schemas-upnp-org:service:WANIPConnection:1#' + cmd + '"'; IdHTTP.Request.ContentType := 'text/xml; charset="utf-8"'; HttpParams := TStringList.Create; HttpParams.Text := body; try a := TMemoryStream.Create; HttpParams.SaveToStream( a ); a.Position := 0; res := IdHTTP.Post( controlurl, a); except on e: Exception do begin end; end; a.Free; HttpParams.Free; IdHttp.Free; end; constructor TPortMapping.Create; var i : Integer; begin IdUdpClient := TIdUDPClient.Create(nil); IdUdpClient.BroadcastEnabled := True; IdUdpClient.Host := '239.255.255.250'; IdUdpClient.port := 1900; IsPortMapable := False; HasDivice := False; // 尝试 10 次端口映射 for i := 1 to 10 do begin // 端口映射成功, 跳出 if FindDivice and FindControl then begin IsPortMapable := True; Break; end; // 映射不成功, 且不存在映射设备, 跳出 if not HasDivice then Break; Application.ProcessMessages; Sleep(50); end; end; function TPortMapping.FindControl: Boolean; var IdHttp : TIdHTTP; ResponseStr: string; begin IdHttp := TIdHTTP.Create(nil); IdHttp.AllowCookies := True; IdHttp.ConnectTimeout := 2000; IdHttp.ReadTimeout := 2000; try ResponseStr := IdHttp.Get(location); Result := FindControlURL(ResponseStr); except Result := False; end; IdHttp.Free; end; function TPortMapping.FindControlURL(ResponseStr: string): Boolean; var tmpstr, tmp: string; j: integer; FulllAdress : string; begin result := False; tmpstr := ResponseStr; // 查找设备urn:schemas-upnp-org:device:InternetGatewayDevice:1的描述段... j := pos(uppercase('<deviceType>urn:schemas-upnp-org:device:InternetGatewayDevice:1</deviceType>'), uppercase(tmpstr)); if j <= 0 then exit; delete(tmpstr, 1, j + length('<deviceType>urn:schemas-upnp-org:device:InternetGatewayDevice:1</deviceType>') - 1); // 再查找urn:schemas-upnp-org:device:WANDevice:1的描述段... j := pos(uppercase('<deviceType>urn:schemas-upnp-org:device:WANDevice:1</deviceType>'), uppercase(tmpstr)); if j <= 0 then exit; delete(tmpstr, 1, j + length('<deviceType>urn:schemas-upnp-org:device:WANDevice:1</deviceType>') - 1); // 再查找urn:schemas-upnp-org:device:WANConnectionDevice:1的描述段... j := pos(uppercase('<deviceType>urn:schemas-upnp-org:device:WANConnectionDevice:1</deviceType>'), uppercase(tmpstr)); if j <= 0 then exit; delete(tmpstr, 1, j + length('<deviceType>urn:schemas-upnp-org:device:WANConnectionDevice:1</deviceType>') - 1); // 最后找到服务urn:schemas-upnp-org:service:WANIPConnection:1的描述段... j := pos(uppercase('<serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>'), uppercase(tmpstr)); if j <= 0 then exit; delete(tmpstr, 1, j + length('<serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>') - 1); // 得到ControlURL... j := pos(uppercase('<controlURL>'), uppercase(tmpstr)); if j <= 0 then exit; delete(tmpstr, 1, j + length('<controlURL>') - 1); j := pos(uppercase('</controlURL>'), uppercase(tmpstr)); if j <= 0 then exit; controlurl := copy(tmpstr, 1, j - 1); FulllAdress := 'http://' + routerip + ':' + inttostr(routerport); if Pos( FulllAdress, controlurl ) <= 0 then controlurl := FulllAdress + controlurl; Result := True; end; function TPortMapping.FindDivice: Boolean; var RequestStr: string; ResponseStr:string; begin RequestStr := 'M-SEARCH * HTTP/1.1'#13#10 + 'HOST: 239.255.255.250:1900'#13#10 + 'MAN: "ssdp:discover"'#13#10 + 'MX: 3'#13#10 + 'ST: upnp:rootdevice'#13#10#13#10; try IdUdpClient.Send(RequestStr); ResponseStr := IdUdpClient.ReceiveString(2000); HasDivice := Trim(ResponseStr) <> ''; Result := FindDeviceInfo( ResponseStr ); except Result := False; end; end; function TPortMapping.getInternetIp: string; var cmd, body, request : string; IdHttp : TIdHTTP; HttpParams : TStringList; a: TMemoryStream; ResponeStr : string; PosIp : Integer; begin Result := ''; // 不能进行端口映射 if not IsPortMapable then Exit; cmd := 'GetExternalIPAddress'; body := '<?xml version="1.0"?>'#13#10 + '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'#13#10 + '<s:Body>'#13#10 + '<u:' + cmd + ' xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">'#13#10 + '</u:' + cmd + '>'#13#10 + '</s:Body>'#13#10 + '</s:Envelope>'#13#10; request := 'POST ' + controlurl + ' HTTP/1.0'#13#10 + 'Host: ' + routerip + ':' + inttostr(routerport) + #13#10 + 'SoapAction: "urn:schemas-upnp-org:service:WANIPConnection:1#' + cmd + '"'#13#10 + 'Content-Type: text/xml; charset="utf-8"'#13#10 + 'Content-Length: ' + inttostr(length(body)) + #13#10#13#10 + body; IdHttp := TIdHTTP.Create(nil); IdHttp.AllowCookies := True; IdHttp.ConnectTimeout := 2000; IdHTTP.Request.CustomHeaders.Text := 'SoapAction: "urn:schemas-upnp-org:service:WANIPConnection:1#' + cmd + '"'; IdHTTP.Request.ContentType := 'text/xml; charset="utf-8"'; HttpParams := TStringList.Create; HttpParams.Text := body; try a := TMemoryStream.Create; HttpParams.SaveToStream( a ); a.Position := 0; ResponeStr := IdHTTP.Post( controlurl , a); except on e: Exception do begin end; end; a.Free; HttpParams.Free; IdHttp.Free; // 从返回信息中提取 Ip PosIp := Pos( '<NEWEXTERNALIPADDRESS>', UpperCase( ResponeStr ) ); if PosIp > 0 then begin delete( ResponeStr, 1, PosIp + 21 ); PosIp := pos( '</', ResponeStr ); ResponeStr := trim( copy( ResponeStr, 1, PosIp - 1 ) ); end; Result := ResponeStr; end; function TPortMapping.FindDeviceInfo(ResponseStr: string):Boolean; var tmpstr: string; buffer: array[0..4096] of char; j: integer; begin Result := False; tmpstr := ResponseStr; // 收到的信息不是设备搜寻结果,忽略! if uppercase(copy(tmpstr, 1, 5)) <> 'HTTP/' then exit; // 找出 ST st := tmpstr; j := Pos( 'ST:', UpperCase( st ) ); if j < 0 then Exit else begin delete(ST, 1, j + 2); j := pos(#13#10, ST); ST := trim(copy(ST, 1, j - 1)); if LowerCase(ST) <> 'upnp:rootdevice' then Exit; end; // 找出 Location location := tmpstr; j := pos('LOCATION:', uppercase(location)); if j < 0 then Exit else begin delete(location, 1, j + 8); j := pos(#13#10, location); location := trim(copy(location, 1, j - 1)); end; // 找出 Server server := tmpstr; j := pos('SERVER:', uppercase(server)); if j < 0 then Exit else begin delete(server, 1, j + 6); j := pos(#13#10, server); server := trim(copy(server, 1, j - 1)); end; // 找出 USN usn := tmpstr; j := pos('USN:', uppercase(usn)); if j < 0 then Exit else begin delete(usn, 1, j + 3); j := pos(#13#10, usn); usn := trim(copy(usn, 1, j - 1)); end; // 找出 Ip tmpstr := location; if copy(uppercase(tmpstr), 1, 7) = 'HTTP://' then delete(tmpstr, 1, 7); j := pos(':', tmpstr); if j <= 0 then exit; routerip := copy(tmpstr, 1, j - 1); delete(tmpstr, 1, j); // 找出 Port j := pos('/', tmpstr); if j > 1 then begin routerport := StrToIntDef(copy(tmpstr, 1, j - 1), -1); delete(tmpstr, 1, j - 1); end else begin j := pos(#13#10, tmpstr); if j <= 1 then exit; routerport := strtointdef(copy(tmpstr, 1, j - 1), -1); end; // 出错的情况 if ( location = '' ) or ( server = '' ) or ( usn = '' ) or ( routerip = '' ) or ( routerport < 0 ) then Exit; Result := True; end; destructor TPortMapping.Destroy; begin IdUdpClient.Free; inherited; end; { MyLog } class procedure MyLog.Log(s: string); var WriteLog : TWriteLog; begin // WriteLog := TWriteLog.Create( s ); // MyFaceChange.AddChange( WriteLog ); end; class procedure MyLog.Logln(s: string); begin Log( s ); Log( '' ); end; end.
unit UsefulBmpConcepts; interface uses System.RTLConsts, SysUtils, FMX.MaterialSources, System.UIConsts, FMX.Objects3D, FMX.Types3D, Classes, System.Math, System.Types, System.UITypes, FMX.Graphics, FMX.Types, FMX.Ani, FMX.Utils, System.Math.Vectors; Procedure DefaultTexture(AControl: TCustomMesh); Procedure DefaultLandscapeMaterial(AControl: TCustomMesh); Procedure DefaultMatTexture(AControl: TCustomMesh); Procedure DefaultMaterial(AControl: TCustomMesh); Function ColorBitMap(Ax, Ay: Integer; Const ASat:Single=0.75;Const ALum:Single=0.5; AxCont:Boolean=False;AyCont:Boolean=False): TBitMap; Function ColorLumBitMap(Ax, Ay: Integer;Const ASat:Single=0.75):TBitMap; Function ColorSatBitMap(Ax, Ay: Integer;Const ALum:Single=0.5):TBitMap; Function ColorTransparentBitMap(Ax, Ay: Integer;Const ASat:Single=0.75;Const ALum:Single=0.5):TBitMap; Function LandscapeBitMap(Ax, Ay: Integer; AFormat:Integer; Const ASat:Single=0.75; Const ALum:Single=0.5;Const AOpacity:Single=0.25):TBitMap; implementation Procedure DefaultLandscapeMaterial(AControl: TCustomMesh); var mat: TLightMaterialSource; begin // DefaultTexture(AControl); mat := TLightMaterialSource.Create(AControl); mat.Parent := AControl; // mat.Ambient := claDarkgreen; mat.Ambient := claBlack; mat.Diffuse := claWhite; mat.Emissive := claNull;//claTomato; mat.Texture := LandscapeBitMap(10, 360,2,0.75,0.5,0.3); AControl.MaterialSource := mat;{} end; Procedure DefaultMatTexture(AControl: TCustomMesh); var mat: TLightMaterialSource; begin mat := TLightMaterialSource.Create(AControl); mat.Parent := AControl; mat.Ambient := claBlack; mat.Diffuse := claViolet; mat.Emissive := claTomato; mat.Texture := ColorBitMap(10, 360); AControl.MaterialSource := mat; end; Procedure DefaultMaterial(AControl: TCustomMesh); var mat: TLightMaterialSource; begin mat := TLightMaterialSource.Create(AControl); mat.Parent := AControl; mat.Ambient := claBlack; mat.Diffuse := claViolet; mat.Emissive := claTomato; AControl.MaterialSource := mat; end; Function ColorBitMap(Ax, Ay: Integer; Const ASat,ALum:Single; AxCont,AyCont:Boolean): TBitMap; Var Bmp: TBitMap; BmpData: TBitmapData; k, j: Integer; begin Bmp := TBitMap.Create(Ax, Ay); if Bmp.Map(TMapAccess.ReadWrite, BmpData) then for k := 0 to Ay - 1 do for j := 0 to Ax - 1 do if ((j mod 60 = 0) And AxCont) or ((k Mod 60 = 0)And AyCont) then BmpData.SetPixel(j, k, claBlack) else BmpData.SetPixel(j, k, CorrectColor(HSLtoRGB( { (Ak-k) } k / Ay, ASat, ALum))); Bmp.Unmap(BmpData); Result := Bmp; end; Function ColorLumBitMap(Ax, Ay: Integer;Const ASat:Single):TBitMap; Var Bmp: TBitMap; BmpData: TBitmapData; k, j: Integer; begin Bmp := TBitMap.Create(Ax, Ay); if Bmp.Map(TMapAccess.ReadWrite, BmpData) then for k := 0 to Ay - 1 do for j := 0 to Ax - 1 do BmpData.SetPixel(j, k, CorrectColor(HSLtoRGB( { (Ak-k) } k / Ay, ASat, j/ax))); Bmp.Unmap(BmpData); Result := Bmp; end; Function ColorSatBitMap(Ax, Ay: Integer;Const ALum:Single):TBitMap; Var Bmp: TBitMap; BmpData: TBitmapData; k, j: Integer; begin Bmp := TBitMap.Create(Ax, Ay); if Bmp.Map(TMapAccess.ReadWrite, BmpData) then for k := 0 to Ay - 1 do for j := 0 to Ax - 1 do BmpData.SetPixel(j, k, CorrectColor(HSLtoRGB( { (Ak-k) } k / Ay, j/ax, ALum))); Bmp.Unmap(BmpData); Result := Bmp; end; Function ColorTransparentBitMap(Ax, Ay: Integer;Const ASat:Single=0.75;Const ALum:Single=0.5):TBitMap; Var Bmp: TBitMap; PixCol: TAlphaColor; BmpData: TBitmapData; k, j: Integer; begin Bmp := TBitMap.Create(Ax, Ay); if Bmp.Map(TMapAccess.ReadWrite, BmpData) then for k := 0 to Ay - 1 do for j := 0 to Ax - 1 do Begin //0 to 1 PixCol:= CorrectColor(HSLtoRGB( { (Ak-k) } k / Ay, ASat, ALum)); BmpData.SetPixel(j, k, MakeColor(PixCol,1-j/ax) ); End; Bmp.Unmap(BmpData); Result := Bmp; end; Function LandscapeBitMap(Ax, Ay: Integer; AFormat:Integer;Const ASat:Single; Const ALum:Single;Const AOpacity:Single):TBitMap; {sub} function FormatColor(aVert,aHorz:Single; AColNo:Integer; AColRng:Single):TAlphaColor; Var PercentInCols:Single; begin Result:=claBrown; case AFormat of 0: Result:= CorrectColor(HSLtoRGB( aHorz, ASat, ALum)); 1: Result:=MakeColor(Round(255*0.5{aj/ax}),125,Round(255*aHorz)); 2: case AColNo of 0..3: Result:=MakeColor(145,Round(250*(1-aHorz)),0); 4..5: Begin PercentInCols:=(aVert-4*AColRng)/AColRng/2; if PercentInCols<0.0 then PercentInCols:=0.0; Result:=MakeColor(Round(145+(255-145)*PercentInCols), Round(250*(1-aHorz*(1-PercentInCols))),0); //>> Yellow End; 6..7: Result:=MakeColor( MakeColor(Round(100*aHorz),0,Round(100+100*aHorz)),0.70); //Blue else Result:=claYellow; end; 3: Result:=MakeColor(145,Round(220*aVert),Round(180*aHorz)); // 3: Result:=MakeColor(Round(255*aj/ax),Round(255*ak/ay),125); 4: Result:=MakeColor(Round(255*aVert),255,Round(255*aHorz)); 5: Result:=MakeColor(Round(255*aVert),Round(255*aHorz),255); 6: Result:=MakeColor(255,Round(255*aVert),Round(255*aHorz)); 7: Result:=MakeColor(255,Round(255*aVert),Round(255*aHorz)); 8: Result:=MakeColor(Round(255*aVert),Round(255*aHorz),255); 9: Result:=MakeColor(Round(255*aVert),Round(255*aHorz),255-Round(255*aHorz)); 10: Result:=MakeColor(Result,aVert); end; Result:=MakeColor(result,AOpacity); end; Var Bmp: TBitMap; PixCol: TAlphaColor; BmpData: TBitmapData; k, j, ColNo, ColDiv: Integer; JFract,KFract:single; ColRng:Single; begin Bmp := TBitMap.Create(Ax, Ay); ColDiv := ax div 7; ColRng := ColDiv/ax; //as % of whole if Bmp.Map(TMapAccess.ReadWrite, BmpData) then for k := 0 to Ay - 1 do begin KFract:= k/ay; //0 to 1 for j := 0 to Ax - 1 do Begin JFract:= J/ax; //0 to 1 ColNo:= j div ColDiv; PixCol:= FormatColor(JFract,KFract,ColNo,ColRng); BmpData.SetPixel(j, k, PixCol); End; End; Bmp.Unmap(BmpData); Result := Bmp; end; Procedure DefaultTexture(AControl: TCustomMesh); var Txr: TTextureMaterialSource; begin Txr := TTextureMaterialSource.Create(AControl); Txr.Parent := AControl; Txr.Texture := ColorBitMap(1, 360); AControl.MaterialSource := Txr; end; { http://edn.embarcadero.com/article/42007 procedure TForm1.GenerateMesh; const MaxX = 30; MaxZ = 30; var u, v : Double; P : array [0..3] of TPoint3D; d : Double; NP, NI : Integer; BMP : TBitmap; k : Integer; begin Mesh1.Data.Clear; d := 0.5; NP := 0; NI := 0; Mesh1.Data.VertexBuffer.Length := Round(2*MaxX*2*MaxZ/d/d)*4; Mesh1.Data.IndexBuffer.Length := Round(2*MaxX*2*MaxZ/d/d)*6; BMP := TBitmap.Create(1,360); for k := 0 to 359 do BMP.Pixels[0,k] := CorrectColor(HSLtoRGB(k/360,0.75,0.5)); u := -MaxX; while u < MaxX do begin v := -MaxZ; while v < MaxZ do begin // Set up the points in the XZ plane P[0].x := u; P[0].z := v; P[1].x := u+d; P[1].z := v; P[2].x := u+d; P[2].z := v+d; P[3].x := u; P[3].z := v+d; // Calculate the corresponding function values for Y = f(X,Z) P[0].y := f(Func,P[0].x,P[0].z); P[1].y := f(Func,P[1].x,P[1].z); P[2].y := f(Func,P[2].x,P[2].z); P[3].y := f(Func,P[3].x,P[3].z); with Mesh1.Data do begin // Set the points with VertexBuffer do begin Vertices[NP+0] := P[0]; Vertices[NP+1] := P[1]; Vertices[NP+2] := P[2]; Vertices[NP+3] := P[3]; end; // Map the colors with VertexBuffer do begin TexCoord0[NP+0] := PointF(0,(P[0].y+35)/45); TexCoord0[NP+1] := PointF(0,(P[1].y+35)/45); TexCoord0[NP+2] := PointF(0,(P[2].y+35)/45); TexCoord0[NP+3] := PointF(0,(P[3].y+35)/45); end; // Map the triangles IndexBuffer[NI+0] := NP+1; IndexBuffer[NI+1] := NP+2; IndexBuffer[NI+2] := NP+3; IndexBuffer[NI+3] := NP+3; IndexBuffer[NI+4] := NP+0; IndexBuffer[NI+5] := NP+1; end; NP := NP+4; NI := NI+6; v := v+d; end; u := u+d; end; Mesh1.Material.Texture := BMP; end; } end.
unit uProfessorDAO; interface uses system.SysUtils, uDAO, uProfessor, uEndereco, system.Generics.Collections, FireDac.comp.Client, Data.db, uAula, system.uitypes; type TProfessorDAO = class(TconectDAO) private FListaProfessor: TObjectList<TProfessor>; FListaHorario: TObjectList<TProfessor>; procedure CriaLista(Ds: TFDQuery); procedure CriaListaHora(Ds: TFDQuery); public Constructor Create; Destructor Destroy; override; function CadastrarProfessor(pProfessor: TProfessor; pEndereco: TEndereco): boolean; function CadastrarProfessor_Curso(pProfessor: TProfessor): boolean; function PesquisaProfessor(pProfessor: TProfessor): TObjectList<TProfessor>; function CadastroHorario(pProfessor: TProfessor): boolean; function ListarHorario(pProfessor: TProfessor): TObjectList<TProfessor>; function EditProfessor(pProfessor: TProfessor): boolean; function UpdateProfessor_curso(pProfessor: TProfessor): boolean; function Deletar_horario(pProfessor: TProfessor): boolean; function HorarioLivre(hora: TDateTime; Dia: string; pProfessor: TProfessor): boolean; function HorarioLivreUpdate(pAula: TAula): boolean; function RetornaID(pProfessor: TProfessor): integer; function RetornaProfessor(pProfessor: TProfessor): TProfessor; function DeleteProfessor(pProfessor: TProfessor): boolean; function DeleteAluno_curso(pProfessor: TProfessor): boolean; end; implementation { TProfessorDAO } function TProfessorDAO.CadastrarProfessor(pProfessor: TProfessor; pEndereco: TEndereco): boolean; var SQL: string; begin SQL := 'select id_endereco from endereco ' + 'where id_endereco not in (select id_endereco from aluno) ' + 'and id_endereco not in (select id_endereco from professor)' + 'and id_endereco not in (select id_endereco from adm)'; FQuery := RetornarDataSet(SQL); pEndereco.id := FQuery.fieldByName('id_endereco').AsInteger; SQL := 'INSERT INTO professor VALUES(default, ' + QuotedSTR(pProfessor.Nome) + ', ' + QuotedSTR(InttoStr(pEndereco.id)) + ', ' + QuotedSTR(FormatDateTime('dd/mm/yyyy', pProfessor.DataNasc)) + ', ' + QuotedSTR(pProfessor.Cpf) + ', ' + QuotedSTR(pProfessor.rg) + ', ' + QuotedSTR(pProfessor.CNPJ) + ', ' + QuotedSTR(pProfessor.contato) + ', ' + QuotedSTR(pProfessor.email) + ')'; result := executarComando(SQL) > 0; end; function TProfessorDAO.CadastrarProfessor_Curso(pProfessor: TProfessor) : boolean; var I: integer; SQL: string; begin for I := 0 to pProfessor.Tamanho - 1 do if pProfessor.Cursos[I] <> '' then begin SQL := 'SELECT id_Professor FROM professor WHERE cpf = ' + QuotedSTR(pProfessor.Cpf); FQuery := RetornarDataSet(SQL); pProfessor.id := FQuery.fieldByName('id_professor').AsInteger; SQL := 'SELECT id_curso FROM curso WHERE nome = ' + QuotedSTR(pProfessor.Cursos[I]); FQuery := RetornarDataSet(SQL); pProfessor.Curso := FQuery.fieldByName('id_curso').AsString; SQL := 'INSERT INTO professor_curso VALUES (' + QuotedSTR(InttoStr(pProfessor.id)) + ', ' + QuotedSTR(pProfessor.Curso) + ')'; result := executarComando(SQL) > 0; end; end; function TProfessorDAO.CadastroHorario(pProfessor: TProfessor): boolean; var SQL: string; begin SQL := 'INSERT INTO horario_professor VALUES(default, ' + QuotedSTR(InttoStr(pProfessor.id)) + ', ' + QuotedSTR(FormatDateTime('HH:mm', pProfessor.HoraInicio)) + ', ' + QuotedSTR(FormatDateTime('HH:mm', pProfessor.HoraFim)) + ', ' + QuotedSTR(pProfessor.Dia) + ')'; result := executarComando(SQL) > 0; end; constructor TProfessorDAO.Create; begin inherited; FListaHorario := TObjectList<TProfessor>.Create; FListaProfessor := TObjectList<TProfessor>.Create; end; procedure TProfessorDAO.CriaLista(Ds: TFDQuery); var I, count: integer; SQL: string; begin I := 0; FListaProfessor.Clear; while not Ds.eof do begin FListaProfessor.Add(TProfessor.Create); FListaProfessor[I].id := Ds.fieldByName('id_professor').AsInteger; FListaProfessor[I].Nome := Ds.fieldByName('nome').AsString; FListaProfessor[I].IDEndereco := Ds.fieldByName('id_endereco').AsInteger; FListaProfessor[I].DataNasc := Ds.fieldByName('data_nasc').AsDateTime; FListaProfessor[I].Cpf := Ds.fieldByName('cpf').AsString; FListaProfessor[I].rg := Ds.fieldByName('rg').AsString; FListaProfessor[I].CNPJ := Ds.fieldByName('cnpj').AsString; FListaProfessor[I].contato := Ds.fieldByName('telefone').AsString; FListaProfessor[I].email := Ds.fieldByName('email').AsString; SQL := 'select nome from curso where id_curso in ' + '(select id_curso from professor_curso where id_professor =' + QuotedSTR(InttoStr(FListaProfessor[I].id)) + ' )'; FQuery2 := RetornarDataSet2(SQL); while not FQuery2.eof do begin FListaProfessor[I].Tamanho := FListaProfessor[I].Tamanho + 1; SetLength(FListaProfessor[I].Cursos, FListaProfessor[I].Tamanho); FListaProfessor[I].Cursos[FListaProfessor[I].Tamanho - 1] := FQuery2.fieldByName('nome').AsString; FQuery2.Next; end; Ds.Next; I := I + 1; end; end; procedure TProfessorDAO.CriaListaHora(Ds: TFDQuery); var I: integer; begin I := 0; FListaHorario.Clear; while not Ds.eof do begin FListaHorario.Add(TProfessor.Create); FListaHorario[I].IdHora := Ds.fieldByName('id_horario').AsInteger; FListaHorario[I].HoraInicio := Ds.fieldByName('hora_inicio').AsDateTime; FListaHorario[I].HoraFim := Ds.fieldByName('hora_fim').AsDateTime; FListaHorario[I].Dia := Ds.fieldByName('dia').AsString; Ds.Next; I := I + 1; end; end; function TProfessorDAO.Deletar_horario(pProfessor: TProfessor): boolean; var SQL: String; begin SQL := 'Delete from horario_professor where id_horario = ' + QuotedSTR(InttoStr(pProfessor.IdHora)); result := executarComando(SQL) > 0; end; function TProfessorDAO.DeleteAluno_curso(pProfessor: TProfessor): boolean; var SQL: string; Aula: TAula; begin try Aula := TAula.Create; SQL := 'select * from aula where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); FQuery2 := RetornarDataSet2(SQL); while not FQuery2.eof do begin Aula.id_aluno := FQuery2.fieldByName('id_aluno').AsInteger; Aula.id_curso := FQuery2.fieldByName('id_curso').AsInteger; SQL := 'delete from aluno_curso where ctid in(select ctid from aluno_curso where id_aluno = ' + QuotedSTR(InttoStr(Aula.id_aluno)) + ' and id_curso =' + QuotedSTR(InttoStr(Aula.id_curso)) + ' limit 1)'; executarComando(SQL); FQuery2.Next; end; finally Aula.Free; end; end; function TProfessorDAO.DeleteProfessor(pProfessor: TProfessor): boolean; VAR SQL: string; begin DeleteAluno_curso(pProfessor); SQL := 'delete from horario_professor where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); result := executarComando(SQL) > 0; SQL := 'delete from professor_curso where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); result := executarComando(SQL) > 0; SQL := 'delete from aula where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); result := executarComando(SQL) > 0; SQL := 'delete from professor where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); result := executarComando(SQL) > 0; SQL := 'delete from endereco where id_endereco = ' + QuotedSTR(InttoStr(pProfessor.IDEndereco)); result := executarComando(SQL) > 0; end; destructor TProfessorDAO.Destroy; begin inherited; if Assigned(FListaProfessor) then FreeAndNil(FListaProfessor); if Assigned(FListaHorario) then FreeAndNil(FListaHorario); end; function TProfessorDAO.EditProfessor(pProfessor: TProfessor): boolean; var SQL: string; begin SQL := 'update professor Set nome = ' + QuotedSTR(pProfessor.Nome) + ', data_nasc = ' + QuotedSTR(DateToStr(pProfessor.DataNasc)) + ', cpf = ' + QuotedSTR(pProfessor.Cpf) + ', rg = ' + QuotedSTR(pProfessor.rg) + ', cnpj = ' + QuotedSTR(pProfessor.CNPJ) + ', telefone = ' + QuotedSTR(pProfessor.contato) + ', email = ' + QuotedSTR(pProfessor.email) + ' where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); result := executarComando(SQL) > 0; end; function TProfessorDAO.HorarioLivre(hora: TDateTime; Dia: string; pProfessor: TProfessor): boolean; var SQL: string; Professor: TProfessor; hora_Fim_aula, HoraAux: TTime; begin result := true; Professor := TProfessor.Create; HoraAux := StrToTime('01:00:00'); hora_Fim_aula := hora + HoraAux; SQL := 'select id_professor from professor where nome = ' + QuotedSTR(pProfessor.Nome); FQuery := RetornarDataSet(SQL); pProfessor.id := FQuery.fieldByName('id_professor').AsInteger; SQL := 'select hora_inicio, hora_fim, dia from horario_professor ' + 'where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); FQuery := RetornarDataSet(SQL); while not FQuery.eof do begin Professor.HoraInicio := FQuery.fieldByName('hora_inicio').AsDateTime; Professor.HoraFim := FQuery.fieldByName('hora_fim').AsDateTime; Professor.Dia := FQuery.fieldByName('dia').AsString; if Dia = Professor.Dia then begin if (Professor.HoraInicio < hora) and (hora < Professor.HoraFim) then result := false; if (Professor.HoraInicio < hora + HoraAux) and (hora + HoraAux < Professor.HoraFim) then result := false; if (Professor.HoraInicio = hora) and (hora_Fim_aula = Professor.HoraFim) then result := false; end; FQuery.Next; end; SQL := 'select hora_inicio, dia from aula' + ' where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); FQuery := RetornarDataSet(SQL); while not FQuery.eof do begin Professor.HoraInicio := FQuery.fieldByName('hora_inicio').AsDateTime; Professor.HoraFim := Professor.HoraInicio + HoraAux; Professor.Dia := FQuery.fieldByName('dia').AsString; if Dia = Professor.Dia then begin if (Professor.HoraInicio < hora) and (hora < Professor.HoraFim) then result := false; if (Professor.HoraInicio < hora + HoraAux) and (hora + HoraAux < Professor.HoraFim) then result := false; if (Professor.HoraInicio = hora) and (hora + HoraAux = Professor.HoraFim) then result := false; end; FQuery.Next; end; end; function TProfessorDAO.HorarioLivreUpdate(pAula: TAula): boolean; var SQL: string; HoraAux: TTime; Professor: TProfessor; begin result := true; Professor := TProfessor.Create; HoraAux := StrToTime('01:00:00'); SQL := 'select hora_inicio, hora_fim, dia from horario_professor ' + 'where id_professor = ' + QuotedSTR(InttoStr(pAula.id_professor)); FQuery := RetornarDataSet(SQL); while not FQuery.eof do begin Professor.HoraInicio := FQuery.fieldByName('hora_inicio').AsDateTime; Professor.HoraFim := FQuery.fieldByName('hora_fim').AsDateTime; Professor.Dia := FQuery.fieldByName('dia').AsString; if pAula.Dia = Professor.Dia then begin if (Professor.HoraInicio < pAula.hora_inicio) and (pAula.hora_inicio < Professor.HoraFim) then result := false; if (Professor.HoraInicio < pAula.hora_inicio + HoraAux) and (pAula.hora_inicio + HoraAux < Professor.HoraFim) then result := false; if (Professor.HoraInicio = pAula.hora_inicio) and (pAula.hora_inicio + HoraAux = Professor.HoraFim) then result := false; end; FQuery.Next; end; SQL := 'select hora_inicio, dia from aula' + ' where id_professor = ' + QuotedSTR(InttoStr(pAula.id_professor)) + ' and id_aula <> ' + QuotedSTR(InttoStr(pAula.id)); FQuery := RetornarDataSet(SQL); while not FQuery.eof do begin Professor.HoraInicio := FQuery.fieldByName('hora_inicio').AsDateTime; Professor.HoraFim := Professor.HoraInicio + HoraAux; Professor.Dia := FQuery.fieldByName('dia').AsString; if pAula.Dia = Professor.Dia then begin if (Professor.HoraInicio < pAula.hora_inicio) and (pAula.hora_inicio < Professor.HoraFim) then result := false; if (Professor.HoraInicio < pAula.hora_inicio + HoraAux) and (pAula.hora_inicio + HoraAux < Professor.HoraFim) then result := false; end; FQuery.Next; end; end; function TProfessorDAO.ListarHorario(pProfessor: TProfessor) : TObjectList<TProfessor>; var SQL: string; begin result := nil; SQL := 'SELECT * FROM horario_professor WHERE id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); FQuery := RetornarDataSet(SQL); if not(FQuery.IsEmpty) then begin CriaListaHora(FQuery); result := FListaHorario; end; end; function TProfessorDAO.PesquisaProfessor(pProfessor: TProfessor) : TObjectList<TProfessor>; var SQL: string; begin result := nil; SQL := 'SELECT * FROM professor WHERE nome LIKE ' + QuotedSTR('%' + pProfessor.Nome + '%') + 'and cnpj LIKE ' + QuotedSTR('%' + pProfessor.CNPJ + '%') + ' and telefone LIKE ' + QuotedSTR('%' + pProfessor.contato + '%') + 'and id_professor in (select id_professor from professor_curso where id_curso in (select id_curso from curso where nome like ' + QuotedSTR('%' + pProfessor.Curso + '%') + ')) order by nome'; FQuery := RetornarDataSet(SQL); if not(FQuery.IsEmpty) then begin CriaLista(FQuery); result := FListaProfessor; end; end; function TProfessorDAO.RetornaID(pProfessor: TProfessor): integer; var SQL: string; begin SQL := 'select id_Professor from professor where nome = ' + QuotedSTR(pProfessor.Nome); FQuery := RetornarDataSet(SQL); result := FQuery.fieldByName('id_Professor').AsInteger; end; function TProfessorDAO.RetornaProfessor(pProfessor: TProfessor): TProfessor; var SQL: string; Professor: TProfessor; begin SQL := 'select * from professor where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); FQuery := RetornarDataSet(SQL); Professor := TProfessor.Create; Professor.id := FQuery.fieldByName('id_professor').AsInteger; Professor.Nome := FQuery.fieldByName('nome').AsString; Professor.IDEndereco := FQuery.fieldByName('id_endereco').AsInteger; Professor.DataNasc := FQuery.fieldByName('data_nasc').AsDateTime; Professor.Cpf := FQuery.fieldByName('cpf').AsString; Professor.rg := FQuery.fieldByName('rg').AsString; Professor.CNPJ := FQuery.fieldByName('cnpj').AsString; Professor.contato := FQuery.fieldByName('telefone').AsString; Professor.email := FQuery.fieldByName('email').AsString; SQL := 'select nome from curso where id_curso in ' + '(select id_curso from professor_curso where id_professor =' + QuotedSTR(InttoStr(pProfessor.id)) + ' )'; FQuery := RetornarDataSet(SQL); while not FQuery.eof do begin Professor.Tamanho := Professor.Tamanho + 1; SetLength(Professor.Cursos, Professor.Tamanho); Professor.Cursos[Professor.Tamanho - 1] := FQuery.fieldByName('nome').AsString; FQuery.Next; end; result := Professor; end; function TProfessorDAO.UpdateProfessor_curso(pProfessor: TProfessor): boolean; var SQL: string; I: integer; begin SQL := 'Delete from professor_curso where id_professor = ' + QuotedSTR(InttoStr(pProfessor.id)); executarComando(SQL); for I := 0 to pProfessor.Tamanho - 1 do if pProfessor.Cursos[I] <> '' then begin SQL := 'SELECT id_Professor FROM professor WHERE cpf = ' + QuotedSTR(pProfessor.Cpf); FQuery := RetornarDataSet(SQL); pProfessor.id := FQuery.fieldByName('id_professor').AsInteger; SQL := 'SELECT id_curso FROM curso WHERE nome = ' + QuotedSTR(pProfessor.Cursos[I]); FQuery := RetornarDataSet(SQL); pProfessor.Curso := FQuery.fieldByName('id_curso').AsString; SQL := 'INSERT INTO professor_curso VALUES (' + QuotedSTR(InttoStr(pProfessor.id)) + ', ' + QuotedSTR(pProfessor.Curso) + ')'; result := executarComando(SQL) > 0; end; end; end.
//Aziz Vicentini - Brasil //E-mail: azizvc@yahoo.com.br //Arquivo de definição do Carro unit CarDef; interface uses Windows, SysUtils, IniFiles; type TCarDefRodas = packed record Peso: Single; SUSPENSION_ERP: Single; SUSPENSION_CFM: Single; Position: array[0..2] of Single; //X,Y,Z end; TCarDefHeader = packed record Marca: string[50]; Nome: string[50]; Ano: Word; VelMax: Word; Torque: Single; Rpm: Word; Frenagem: Single; Peso: Single; Marchas: Byte; AtritoPneus: Single; Relacao: array[0..5] of Word; CentroMassa: array[0..2] of Single; //X,Y,Z //centro da massa do corpo do carro Rodas: array[0..3] of TCarDefRodas; end; TCarDef = class public Header: TCarDefHeader; constructor Create; destructor Destroy; override; procedure LoadFromFile (const FileName: string); end; implementation constructor TCarDef.Create; begin //--- end; destructor TCarDef.Destroy; begin inherited Destroy; end; procedure TCarDef.LoadFromFile(const FileName: string); var Ini: TIniFile; I: Byte; begin Ini := TIniFile.Create(FileName); try Header.Marca:= Ini.ReadString('Carro','Marca',' '); Header.Nome:= Ini.ReadString('Carro','Nome','sem nome'); Header.Ano:= Ini.ReadInteger('Carro','Ano', 0 ); Header.VelMax:= Ini.ReadInteger('Espec','VelMax',1); Header.Torque:= Ini.ReadFloat('Espec','Torque',1); Header.Rpm:= Ini.ReadInteger('Espec','RPM',1); Header.Frenagem:= Ini.ReadFloat('Espec','Frenagem',10); Header.Peso:= Ini.ReadFloat('Espec','Peso',1); Header.Marchas:= Ini.ReadInteger('Espec','Marchas',0); Header.AtritoPneus:= Ini.ReadFloat('Espec','AtritoPneus',0); Header.Relacao[0]:= Ini.ReadInteger('Marchas','1a',0); Header.Relacao[1]:= Ini.ReadInteger('Marchas','2a',0); Header.Relacao[2]:= Ini.ReadInteger('Marchas','3a',0); Header.Relacao[3]:= Ini.ReadInteger('Marchas','4a',0); Header.Relacao[4]:= Ini.ReadInteger('Marchas','5a',0); Header.Relacao[5]:= Ini.ReadInteger('Marchas','6a',0); Header.CentroMassa[0]:= Ini.ReadFloat('CentroMassa','X',0); Header.CentroMassa[1]:= Ini.ReadFloat('CentroMassa','Y',0); Header.CentroMassa[2]:= Ini.ReadFloat('CentroMassa','Z',0); for I:= 0 to 3 do begin Header.Rodas[I].Peso:= Ini.ReadFloat('Roda'+IntToStr(I),'Peso',1); Header.Rodas[I].SUSPENSION_ERP:= Ini.ReadFloat('Roda'+IntToStr(I),'CargaSuspensao', 0.4); Header.Rodas[I].SUSPENSION_CFM:= Ini.ReadFloat('Roda'+IntToStr(I),'RigidezSuspensao', 0.1); Header.Rodas[I].Position[0]:= Ini.ReadFloat('Roda'+IntToStr(I),'PosX',0); Header.Rodas[I].Position[1]:= Ini.ReadFloat('Roda'+IntToStr(I),'PosY',0); Header.Rodas[I].Position[2]:= Ini.ReadFloat('Roda'+IntToStr(I),'PosZ',0); end; finally Ini.Free; end; end; end.
unit Test.AsyncIO.Net.IP; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, NetTestCase, IdWinsock2, AsyncIO, AsyncIO.Net.IP, EchoTestServer; type // Test methods for class IPv4Address TestIPv4Address = class(TNetTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure TestExplicitCast; procedure TestImplicitCast; procedure TestTryFromString; end; // Test methods for class IPv6Address TestIPv6Address = class(TNetTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure TestExplicitCast; procedure TestImplicitCast; procedure TestTryFromString; end; // Test methods for class IPAddress TestIPAddress = class(TNetTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure TestExplicitCast; procedure TestSetAsIPv4; procedure TestSetAsIPv6; procedure TestGetAsIPv4; procedure TestGetAsIPv6; end; // Test methods for class IPEndpoint TestIPEndpoint = class(TNetTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure TestImplicitCast; procedure TestFromDataIPv4; procedure TestFromDataIPv6; procedure TestSetAddressIPv4; procedure TestSetAddressIPv6; procedure TestGetAddressIPv4; procedure TestGetAddressIPv6; end; // Test methods for class IPSocket TestIPResolver = class(TNetTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure TestResolveBasic; procedure TestResolveIPv4; procedure TestResolveIPv6; end; // Test methods for AsyncConnect function TestAsyncConnect = class(TNetTestCase) strict private FTestServer: IEchoTestServer; FService: IOService; FResolverResults: IPResolver.Results; FSocket: IPSocket; public procedure SetUp; override; procedure TearDown; override; published procedure TestAsyncConnectSingle; procedure TestAsyncConnectMultiple; procedure TestAsyncConnectConditional; procedure TestAsyncConnectNonExisting; end; implementation uses System.SysUtils, AsyncIO.OpResults; procedure TestIPv4Address.SetUp; begin end; procedure TestIPv4Address.TearDown; begin end; procedure TestIPv4Address.TestExplicitCast; var Addr: UInt32; IPv4Addr: IPv4Address; begin Addr := $0A010203; IPv4Addr := IPv4Address(Addr); CheckEqualsHex(Addr, IPv4Addr.Data, 'Explicit cast stored wrong address'); end; procedure TestIPv4Address.TestImplicitCast; var Addr: UInt32; IPv4Addr: IPv4Address; ReturnValue: string; begin Addr := IPv4Address.Loopback.Data; IPv4Addr := IPv4Address(Addr); ReturnValue := IPv4Addr; CheckEquals('127.0.0.1', ReturnValue, 'Implicit cast returned wrong address'); end; procedure TestIPv4Address.TestTryFromString; var IPv4Addr: IPv4Address; ReturnValue: boolean; begin IPv4Addr := IPv4Address.Any; ReturnValue := IPv4Address.TryFromString('1.2.3.4', IPv4Addr); CheckTrue(ReturnValue, 'TryFromString failed to convert address 1'); CheckEqualsHex($01020304, IPv4Addr.Data, 'TryFromString returned wrong address 1'); ReturnValue := IPv4Address.TryFromString('127.0.0.1', IPv4Addr); CheckTrue(ReturnValue, 'TryFromString failed to convert address 2'); CheckEqualsHex($7F000001, IPv4Addr.Data, 'TryFromString returned wrong address 2'); ReturnValue := IPv4Address.TryFromString('100.200.300.400', IPv4Addr); CheckFalse(ReturnValue, 'TryFromString failed reject bad address'); end; procedure TestIPv6Address.SetUp; begin end; procedure TestIPv6Address.TearDown; begin end; procedure TestIPv6Address.TestExplicitCast; const Addr: IPv6Address.IPv6AddressBytes = ($01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F, $10); var IPv6Addr: IPv6Address; begin IPv6Addr := IPv6Address(Addr); CheckEquals(IPv6Address(Addr), IPv6Addr, 'Explicit cast stored wrong address'); end; procedure TestIPv6Address.TestImplicitCast; const Addr: IPv6Address.IPv6AddressBytes = ($01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F, $10); var IPv6Addr: IPv6Address; ReturnValue: string; begin IPv6Addr := IPv6Address(Addr); ReturnValue := LowerCase(IPv6Addr); CheckEqualsString(ReturnValue, '102:304:506:708:90a:b0c:d0e:f10', 'Implicit cast returned wrong address'); end; procedure TestIPv6Address.TestTryFromString; const Addr1: IPv6Address.IPv6AddressBytes = (0, $01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $42); var IPv6Addr: IPv6Address; ReturnValue: boolean; begin IPv6Addr := IPv6Address.Any; ReturnValue := IPv6Address.TryFromString('1::42', IPv6Addr); CheckTrue(ReturnValue, 'TryFromString failed to convert address'); CheckEquals(IPv6Address(Addr1), IPv6Addr, 'TryFromString returned wrong address 1'); ReturnValue := IPv6Address.TryFromString('10.0.0.1', IPv6Addr); CheckFalse(ReturnValue, 'TryFromString failed reject bad address'); end; procedure TestIPAddress.SetUp; begin end; procedure TestIPAddress.TearDown; begin end; procedure TestIPAddress.TestExplicitCast; var ReturnValue: IPAddress; begin ReturnValue := IPAddress('127.0.0.1'); CheckTrue(ReturnValue.IsIPv4, 'IPAddress failed to convert to IPv4 address 1'); CheckFalse(ReturnValue.IsIPv6, 'IPAddress failed to convert to IPv4 address 2'); CheckTrue(ReturnValue.IsLoopback, 'IPAddress failed to convert to IPv4 loopback address'); ReturnValue := IPAddress('::1'); CheckFalse(ReturnValue.IsIPv4, 'IPAddress failed to convert to IPv6 address 1'); CheckTrue(ReturnValue.IsIPv6, 'IPAddress failed to convert to IPv6 address 2'); CheckTrue(ReturnValue.IsLoopback, 'IPAddress failed to convert to IPv6 loopback address'); end; procedure TestIPAddress.TestGetAsIPv4; var Addr: IPAddress; ReturnValue: IPv4Address; begin Addr := IPv4Address.Broadcast; ReturnValue := Addr.AsIPv4; CheckEquals(IPv4Address.Broadcast.Data, ReturnValue.Data, 'IPAddress failed to get IPv4 address'); end; procedure TestIPAddress.TestGetAsIPv6; var Addr: IPAddress; ReturnValue: IPv6Address; begin Addr := IPv6Address.Loopback; ReturnValue := Addr.AsIPv6; CheckEquals(IPv6Address.Loopback, ReturnValue, 'IPAddress failed to get IPv6 address'); end; procedure TestIPAddress.TestSetAsIPv4; var Addr: IPAddress; begin Addr.AsIPv4 := IPv4Address.Loopback; CheckTrue(Addr.IsIPv4, 'IPAddress failed to set IPv4 address 1'); CheckFalse(Addr.IsIPv6, 'IPAddress failed to set IPv4 address 2'); CheckTrue(Addr.IsLoopback, 'IPAddress failed to set IPv4 address 3'); CheckFalse(Addr.IsMulticast, 'IPAddress failed to set IPv4 address 4'); end; procedure TestIPAddress.TestSetAsIPv6; var Addr: IPAddress; begin Addr.AsIPv6 := IPv6Address.Loopback; CheckFalse(Addr.IsIPv4, 'IPAddress failed to set IPv6 address 1'); CheckTrue(Addr.IsIPv6, 'IPAddress failed to set IPv6 address 2'); CheckTrue(Addr.IsLoopback, 'IPAddress failed to set IPv6 address 3'); CheckFalse(Addr.IsMulticast, 'IPAddress failed to set IPv6 address 4'); end; procedure TestIPEndpoint.SetUp; begin end; procedure TestIPEndpoint.TearDown; begin end; procedure TestIPEndpoint.TestFromDataIPv4; var Data: sockaddr_in; ReturnValue: IPEndpoint; begin FillChar(Data, SizeOf(Data), 0); Data.sin_family := AF_INET; Data.sin_port := htons(42); Data.sin_addr.S_addr := INADDR_LOOPBACK; ReturnValue := IPEndpoint.FromData(Data, SizeOf(Data)); CheckTrue(ReturnValue.IsIPv4, 'Failed to set IPv4 address 1'); CheckFalse(ReturnValue.IsIPv6, 'Failed to set IPv4 address 2'); CheckEquals(ReturnValue.Address.AsIPv4, IPv4Address(ntohl(Data.sin_addr.S_addr)), 'Failed to set IPv4 address 3'); CheckEquals(42, ReturnValue.Port, 'Failed to set port'); end; procedure TestIPEndpoint.TestFromDataIPv6; const Addr: IPv6Address.IPv6AddressBytes = ($01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F, $10); var Data: SOCKADDR_IN6; ReturnValue: IPEndpoint; begin FillChar(Data, SizeOf(Data), 0); Data.sin6_family := AF_INET6; Data.sin6_port := htons(42); Move(Addr, Data.sin6_addr.s6_bytes, 16); ReturnValue := IPEndpoint.FromData(Data, SizeOf(Data)); CheckFalse(ReturnValue.IsIPv4, 'Failed to set IPv6 address 1'); CheckTrue(ReturnValue.IsIPv6, 'Failed to set IPv6 address 2'); CheckEquals(ReturnValue.Address.AsIPv6, IPv6Address(Addr), 'Failed to set IPv6 address 3'); CheckEquals(42, ReturnValue.Port, 'Failed to set port'); end; procedure TestIPEndpoint.TestGetAddressIPv4; var Addr: IPAddress; Endp: IPEndpoint; ReturnValue: IPAddress; begin Addr := IPv4Address.Loopback; Endp := Endpoint(Addr, 1042); ReturnValue := Endp.Address; CheckEquals(Addr, ReturnValue, 'Failed to get IPv4 address'); end; procedure TestIPEndpoint.TestGetAddressIPv6; var Addr: IPAddress; Endp: IPEndpoint; ReturnValue: IPAddress; begin Addr := IPv6Address.Loopback; Endp := Endpoint(Addr, 1042); ReturnValue := Endp.Address; CheckEquals(Addr, ReturnValue, 'Failed to get IPv6 address'); end; procedure TestIPEndpoint.TestImplicitCast; var Endp: IPEndpoint; ReturnValue: string; begin Endp := Endpoint(IPv4Address.Loopback, 1042); ReturnValue := Endp; CheckEquals('127.0.0.1:1042', ReturnValue, 'Failed to cast IPv4 endpoint'); Endp := Endpoint(IPv6Address.Loopback, 1042); ReturnValue := Endp; CheckEquals('[::1]:1042', ReturnValue, 'Failed to cast IPv6 endpoint'); end; procedure TestIPEndpoint.TestSetAddressIPv4; var Addr: IPAddress; Endp: IPEndpoint; begin Endp := Endpoint(IPAddressFamily.v6, 1234); Addr := IPv4Address.Loopback; Endp.Address := Addr; CheckTrue(Endp.IsIPv4, 'Failed to set IPv4 address 1'); CheckFalse(Endp.IsIPv6, 'Failed to set IPv4 address 2'); CheckEquals(Addr, Endp.Address, 'Failed to set IPv4 address 3'); end; procedure TestIPEndpoint.TestSetAddressIPv6; var Addr: IPAddress; Endp: IPEndpoint; begin Endp := Endpoint(IPAddressFamily.v4, 1234); Addr := IPv6Address.Loopback; Endp.Address := Addr; CheckFalse(Endp.IsIPv4, 'Failed to set IPv6 address 1'); CheckTrue(Endp.IsIPv6, 'Failed to set IPv6 address 2'); CheckEquals(Addr, Endp.Address, 'Failed to set IPv6 address 3'); end; procedure TestIPResolver.SetUp; begin end; procedure TestIPResolver.TearDown; begin end; procedure TestIPResolver.TestResolveBasic; var ReturnValue: IPResolver.Results; begin ReturnValue := IPResolver.Resolve(Query('localhost', '')); CheckTrue(Length(ReturnValue.ToArray()) > 0, 'Failed to resolve localhost'); end; procedure TestIPResolver.TestResolveIPv4; var ReturnValue: IPResolver.Results; Entries: TArray<IPResolver.Entry>; begin ReturnValue := IPResolver.Resolve(Query(IPProtocol.TCP.v4, 'localhost', '')); Entries := ReturnValue.ToArray(); CheckTrue(Length(Entries) > 0, 'Failed to resolve IPv4 localhost 1'); CheckEquals(IPv4Address.Loopback, Entries[0].Endpoint.Address.AsIPv4, 'Failed to resolve IPv4 loopback 2'); CheckEquals('localhost', Entries[0].HostName, 'Failed to resolve IPv4 loopback 3'); CheckEquals('', Entries[0].ServiceName, 'Failed to resolve IPv4 loopback 4'); end; procedure TestIPResolver.TestResolveIPv6; var ReturnValue: IPResolver.Results; Entries: TArray<IPResolver.Entry>; begin ReturnValue := IPResolver.Resolve(Query(IPProtocol.TCP.v6, 'localhost', '')); Entries := ReturnValue.ToArray(); CheckTrue(Length(Entries) > 0, 'Failed to resolve IPv6 localhost 1'); CheckEquals(IPv6Address.Loopback, Entries[0].Endpoint.Address.AsIPv6, 'Failed to resolve IPv6 loopback 2'); CheckEquals('localhost', Entries[0].HostName, 'Failed to resolve IPv6 loopback 3'); CheckEquals('', Entries[0].ServiceName, 'Failed to resolve IPv6 loopback 4'); end; { TestAsyncConnect } procedure TestAsyncConnect.SetUp; begin FTestServer := NewEchoTestServer(7); FService := NewIOService(); FResolverResults := IPResolver.Resolve(Query('localhost', '7')); FSocket := NewTCPSocket(FService); end; procedure TestAsyncConnect.TearDown; begin FTestServer := nil; FService := nil; FSocket := nil; end; procedure TestAsyncConnect.TestAsyncConnectConditional; var Endpoints: TArray<IPEndpoint>; EndpointIndex: integer; Condition: ConnectCondition; ConditionExecuted: boolean; Handler: ConnectHandler; HandlerExecuted: boolean; begin FTestServer.Start; Endpoints := FResolverResults.GetEndpoints(); ConditionExecuted := False; HandlerExecuted := False; EndpointIndex := 0; Condition := function(const Res: OpResult; const Endpoint: IPEndpoint): boolean begin ConditionExecuted := True; CheckTrue(Res.Success, 'Connect result: ' + Res.Message); CheckTrue(EndpointIndex < Length(Endpoints), 'Connect condition index 1'); CheckEquals(Endpoints[EndpointIndex], Endpoint, 'Connect condition'); EndpointIndex := EndpointIndex + 1; // connect to the last one result := EndpointIndex = Length(Endpoints); end; Handler := procedure(const Res: OpResult; const Endpoint: IPEndpoint) begin HandlerExecuted := True; CheckTrue(Res.Success, 'Connect result: ' + Res.Message); CheckEquals(Length(Endpoints), EndpointIndex, 'Connect condition index 2'); CheckEquals(Endpoints[EndpointIndex-1], Endpoint, 'Connected endpoint'); end; AsyncConnect(FSocket, FResolverResults, Condition, Handler); FService.RunOne; CheckTrue(ConditionExecuted, 'Connect condition not executed'); CheckTrue(HandlerExecuted, 'Connect handler not executed'); end; procedure TestAsyncConnect.TestAsyncConnectMultiple; var Endpoints: TArray<IPEndpoint>; Handler: ConnectHandler; HandlerExecuted: boolean; begin FTestServer.Start; Endpoints := FResolverResults.GetEndpoints(); HandlerExecuted := False; Handler := procedure(const Res: OpResult; const Endpoint: IPEndpoint) begin HandlerExecuted := True; CheckTrue(Res.Success, 'Connect result: ' + Res.Message); CheckEquals(Endpoints[0], Endpoint, 'Connected endpoint'); end; AsyncConnect(FSocket, FResolverResults, Handler); FService.RunOne; CheckTrue(HandlerExecuted, 'Connect handler not executed'); end; procedure TestAsyncConnect.TestAsyncConnectNonExisting; var Endpoints: TArray<IPEndpoint>; Handler: ConnectHandler; HandlerExecuted: boolean; begin SetLength(Endpoints, 2); Endpoints[0] := Endpoint(IPAddress('10.20.31.42'), 1); Endpoints[1] := Endpoint(IPAddress('10.42.31.20'), 1); HandlerExecuted := False; Handler := procedure(const Res: OpResult; const Endpoint: IPEndpoint) begin HandlerExecuted := True; CheckFalse(Res.Success, 'Connection attempts should fail but didn''t'); end; AsyncConnect(FSocket, Endpoints, Handler); // two connection attempts FService.RunOne; FService.RunOne; CheckTrue(HandlerExecuted, 'Connect handler not executed'); end; procedure TestAsyncConnect.TestAsyncConnectSingle; var Endpoints: TArray<IPEndpoint>; Handler: ConnectHandler; HandlerExecuted: boolean; begin FTestServer.Start; Endpoints := FResolverResults.GetEndpoints(); SetLength(Endpoints, 1); HandlerExecuted := False; Handler := procedure(const Res: OpResult; const Endpoint: IPEndpoint) begin HandlerExecuted := True; CheckTrue(Res.Success, 'Connect result: ' + Res.Message); CheckEquals(Endpoints[0], Endpoint, 'Connected endpoint'); end; AsyncConnect(FSocket, Endpoints, Handler); FService.RunOne; CheckTrue(HandlerExecuted, 'Connect handler not executed'); end; initialization // Register any test cases with the test runner RegisterTest(TestIPv4Address.Suite); RegisterTest(TestIPv6Address.Suite); RegisterTest(TestIPAddress.Suite); RegisterTest(TestIPEndpoint.Suite); RegisterTest(TestIPResolver.Suite); RegisterTest(TestAsyncConnect.Suite); end.
unit Pattern.ConcreteVisitorSalario; interface uses Pattern.Visitor, Pattern.ConcreteElementProgramador, Pattern.ConcreteElementGerente; type TSalario = class(TInterfacedObject, IVisitor) // Método que será invocado quando o objeto do parâmetro for da classe TProgramador procedure Visit(Programador: TProgramador); overload; // Método que será invocado quando o objeto do parâmetro for da classe TGerente procedure Visit(Gerente: TGerente); overload; end; implementation uses System.SysUtils, DateUtils; { TSalario } // Cálculo do aumento do salário para programadores procedure TSalario.Visit(Programador: TProgramador); var PorcentagemPorDiaTrabalhado: real; begin // Aplica um aumento de 6% no salário Programador.Salario := Programador.Salario * 1.06; // Aplica um aumento adicional de 0,002% por cada dia trabalhado PorcentagemPorDiaTrabalhado := DaysBetween(Date, Programador.Admissao) * 0.002; Programador.Salario := Programador.Salario * (1 + PorcentagemPorDiaTrabalhado / 100); end; // Cálculo do aumento do salário para gerentes procedure TSalario.Visit(Gerente: TGerente); var QtdeAnosNaEmpresa: byte; begin // Aplica um aumento de 8% no salário Gerente.Salario := Gerente.Salario * 1.08; // Calcula a quantidade de anos que o gerente está na empresa QtdeAnosNaEmpresa := YearsBetween(Date, Gerente.Admissao); // Conforme a quantidade de anos, um aumento adicional é aplicado case QtdeAnosNaEmpresa of 2..3: Gerente.Salario := Gerente.Salario * 1.03; // até 3 anos: 3% 4..5: Gerente.Salario := Gerente.Salario * 1.04; // até 5 anos: 4% 6..10: Gerente.Salario := Gerente.Salario * 1.05; // até 10 anos: 5% end; end; end.
unit uEdtUser; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseForm, StdCtrls, Buttons, SysSvc, DBIntf, _Sys; type TfrmEdtUser = class(TBaseForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; btn_OK: TBitBtn; btn_Cancel: TBitBtn; edt_UserName: TEdit; edt_Psw: TEdit; cb_Role: TComboBox; procedure btn_OKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FListFiller: IListFiller; function GetPsw: String; function GetRoleID: Integer; function GetUserName: String; procedure SetPsw(const Value: String); procedure SetRoleID(const Value: Integer); procedure SetUserName(const Value: String); function GetRoleName: string; { Private declarations } public property UserName: String read GetUserName write SetUserName; property Psw: String read GetPsw write SetPsw; property RoleID: Integer read GetRoleID write SetRoleID; property RoleName: string read GetRoleName; end; var frmEdtUser: TfrmEdtUser; implementation {$R *.dfm} procedure TfrmEdtUser.btn_OKClick(Sender: TObject); begin inherited; if edt_UserName.Text = '' then begin sys.Dialogs.Warning('用户名不能为空!'); edt_UserName.SetFocus; exit; end; if cb_Role.ItemIndex = -1 then begin sys.Dialogs.Warning('请选择角色!'); cb_Role.SetFocus; exit; end; self.ModalResult := mrOK; end; procedure TfrmEdtUser.FormCreate(Sender: TObject); begin inherited; FListFiller := SysService as IListFiller; FListFiller.FillList('[Role]', 'RoleName', self.cb_Role.Items); end; procedure TfrmEdtUser.FormDestroy(Sender: TObject); begin inherited; FListFiller.ClearList(self.cb_Role.Items); end; function TfrmEdtUser.GetPsw: String; begin Result := self.edt_Psw.Text; end; function TfrmEdtUser.GetRoleID: Integer; var idx: Integer; DataRecord: IDataRecord; begin Result := 0; idx := self.cb_Role.ItemIndex; if idx <> -1 then begin DataRecord := FListFiller.GetDataRecord(idx, self.cb_Role.Items); Result := DataRecord.FieldValueAsInteger('ID'); end; end; function TfrmEdtUser.GetRoleName: string; begin Result := self.cb_Role.Text; end; function TfrmEdtUser.GetUserName: String; begin Result := self.edt_UserName.Text; end; procedure TfrmEdtUser.SetPsw(const Value: String); begin self.edt_Psw.Text := Value; end; procedure TfrmEdtUser.SetRoleID(const Value: Integer); var i: Integer; DataRecord: IDataRecord; begin for i := 0 to self.cb_Role.Items.Count - 1 do begin DataRecord := FListFiller.GetDataRecord(i, self.cb_Role.Items); if DataRecord.FieldValueAsInteger('ID') = Value then begin self.cb_Role.ItemIndex := i; exit; end; end; end; procedure TfrmEdtUser.SetUserName(const Value: String); begin self.edt_UserName.Text := Value; end; end.
{* * * Blinker swap function demo * * MS PASCAL 4.0 * * Copyright (c) A.S.M. Inc, 1992 - 1997 * * Compile: PAS1 swapdemo; * PAS2 * *} program swapdemo(input,output); {$include : 'blinker.inc'} const ON = 1 ; OFF = 0 ; var i : integer ; keystr : string (100); retptr : ADS of string(100); begin if (SWPGETPID(ADS('swapdemo.pas')) = 0) THEN { if we're not running already } begin writeln (output,'Pascal Swap example') ; writeln (output,'===================') ; writeln (output,' ') ; writeln (output,'Swap defaults ') ; writeln (output,' ') ; writeln (output,'Use EMS memory : ',SWPUSEEMS(OFF)) ; writeln (output,'Use XMS memory : ',SWPUSEXMS(OFF)) ; writeln (output,'Use UMBs : ',SWPUSEUMB(OFF)) ; writeln (output,'Save/restore video mode : ',SWPVIDMDE(OFF)) ; writeln (output,'Save/restore directory : ',SWPCURDIR(OFF)) ; writeln (output,'Display message : ',SWPDISMSG(OFF)) ; writeln (output,'Wait for keypress : ',SWPGETKEY(OFF)) ; writeln (output,'Suppress <Ctrl><Alt><Del> : ',SWPNOBOOT(OFF)) ; writeln (output,' ') ; { need to pass a far pointer to an ASCIIZ string to bligetpid, and blisetpid } writeln (output,'Program already running? : ',SWPGETPID(ads('swapdemo.pas'*chr(0)))) ; writeln (output,'Set program ID to swapdemo.pas : ',SWPSETPID(ads('swapdemo.pas'*chr(0)))) ; writeln (output,' ') ; { enable ems / xms / umbs } i := SWPUSEEMS(ON) ; i := SWPUSEXMS(ON) ; i := SWPUSEUMB(ON) ; { save / restore current directory and video mode } { video buffer contents are not saved } i := SWPCURDIR(ON) ; i := SWPVIDMDE(ON) ; writeln (output,'Shelling to DOS...'); writeln (output,'Run swapdemo again to see SWPGETPID.'); writeln (output,'-------------------------------------------------------------------------'); { Set a new prompt } i := SWPSETENV(ads ('PROMPT=Pascal SwapDemo - $p$g'*chr(0))) ; i := SWPKEYBRD(ads('hello'*chr(0))) ; i := SWPKEYBRD(ads (chr(34)*'dir /w'*chr(34)*chr(123)*'enter'*chr(125)*chr(34)*'swapdemo'*chr(34)*chr(0))) ; i := SWPRUNCMD(ads(chr(0)), 0, ads(chr(0)),ads(chr(0)) ) ; writeln (output,'-------------------------------------------------------------------------'); writeln (output,'Back from shell, status is : ',i); writeln (output,'Major error code is : ',SWPERRMAJ) ; writeln (output,'Minor error code is : ',SWPERRMIN) ; writeln (output,'Child process return code was : ',SWPERRLEV) ; retptr := SWPGETSTR ; writeln (output,'Child process return string was : ',retptr^) ; writeln; end else { we're already running, terminate the program } begin writeln(output,'This is the second invocation of SWAPDEMO'); writeln(output,'Please enter a message to return to the parent'); readln (input,keystr); i := SWPSETSTR (ads('swapdemo.pas'*chr(0)),ads('Value'*chr(0))) ; i := SWPADDSTR (ads('swapdemo.pas'*chr(0)),ads(keystr)) ; writeln(output,'Type EXIT to return to previous swapdemo.pas') ; end end.
unit Unit2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Clipbrd, ComCtrls, ExtCtrls; type TForm2 = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Memo1: TMemo; Image1: TImage; procedure FormCreate(Sender: TObject); private procedure ClipBoardChanged(var Message: TMessage); Message WM_DRAWCLIPBOARD; public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} { Fontes http://www.devmedia.com.br/identificando-mudancas-no-clipboard-delphi/24036 http://delphi.about.com/od/vclusing/a/tclipboard.htm } procedure TForm2.ClipBoardChanged(var Message: TMessage); begin { uses Clipbrd } // CF_TEXT - Text with each line ending with a CR-LF combination. // CF_BITMAP - A Windows bitmap graphic. // CF_METAFILEPICT - A Windows metafile graphic. // CF_PICTURE - An object of type TPicture. // CF_OBJECT - Any persistent object. if Clipboard.HasFormat(CF_TEXT) then begin Memo1.Lines.Clear; Memo1.Lines.Add(Clipboard.AsText); Self.Caption := FormatDateTime('hh:nn:ss', Now); end; if Clipboard.HasFormat(CF_BITMAP) then begin Image1.Picture.Bitmap.Assign(Clipboard); end; end; procedure TForm2.FormCreate(Sender: TObject); begin Memo1.Lines.Clear; SetClipboardViewer(Handle); end; end.
unit prodPriceForm; interface uses Forms, QExport3CustomSource, DB, dxmdaset, dxtrprds, QExport3, QExport3XLS, Classes, ActnList, Menus, TB2Item, ComCtrls, TB2Dock, TB2Toolbar, Controls; type TPriceForm = class(TForm) TBDock1: TTBDock; TBToolbar1: TTBToolbar; TBPopupMenu1: TTBPopupMenu; ActionList1: TActionList; StatusBar1: TStatusBar; XLS: TQExport3XLS; Action1: TAction; TBItem2: TTBItem; Data: TdxDBTreePrintData; CustomSource: TqeCustomSource; procedure Action1Execute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CustomSourceGetNextRecord(Sender: TObject; RecNo: Integer; var Eof: Boolean); procedure CustomSourceGetColumnValue(Sender: TObject; RecNo: Integer; Column: TqeCustomColumn; var Value: Variant); procedure XLSGetDataParams(Sender: TObject; Sheet, Col, Row: Integer; Format: TxlsFormat; var FormatText: String); private function PropertyValueByName(const PropertyName: String): Variant; end; function GetPriceForm: Integer; procedure GetPriceFormTmp; implementation uses prodMainForm, prodPriceDataSource, cxExportGrid4Link, progDataModule, Variants; {$R *.dfm} function GetPriceForm: Integer; var Form: TPriceForm; begin Form := TPriceForm.Create(Application); try Result := Form.ShowModal; finally Form.Free; end; end; procedure GetPriceFormTmp; var Form: TPriceForm; begin Form := TPriceForm.Create(Application); try Form.Action1Execute(nil); finally Form.Free; end; end; procedure TPriceForm.Action1Execute(Sender: TObject); begin XLS.Execute; end; procedure TPriceForm.FormCreate(Sender: TObject); begin DM.Products.Filter := 'is_printable = 1'; DM.Products.Filtered := True; Data.Open; DM.Products.Filtered := False; end; procedure TPriceForm.CustomSourceGetNextRecord(Sender: TObject; RecNo: Integer; var Eof: Boolean); begin Data.Next; Eof := Data.Eof; end; procedure TPriceForm.CustomSourceGetColumnValue(Sender: TObject; RecNo: Integer; Column: TqeCustomColumn; var Value: Variant); begin case Column.Index of 0: Value := Data['product_article']; 1: Value := Data['full_title']; 2: Value := PropertyValueByName('_price'); end; end; procedure TPriceForm.XLSGetDataParams(Sender: TObject; Sheet, Col, Row: Integer; Format: TxlsFormat; var FormatText: String); begin if Data['is_folder'] = 1 then begin Format.Font.Color := TxlsColor(Data['dx$level']*3); Format.Font.Size := 12; Format.Font.Style := [xfsBold]; end; end; function TPriceForm.PropertyValueByName( const PropertyName: String): Variant; begin Result := Null; if Data['is_folder'] = 1 then Exit; if DM.Properties.Locate('name', PropertyName, []) then begin if DM.Values.Locate('product_id;property_id', VarArrayOf([Data['product_id'], DM.Properties['property_id']]), [loPartialKey]) then Result := DM.Values['value']; end; end; end.
unit USistemaException; interface uses SysUtils; type ESistemaException = class(Exception) end; EPersistentException = class(ESistemaException) end; EContaException = class(EPersistentException) end; ELimiteEnquadramentoException = class(ESistemaException) end; ESaldoContaException = class(ESistemaException) end; EInicializacaoPeriodoContabilException = class(ESistemaException) end; EFiltroException = class(ESistemaException) end; EExportException = class(ESistemaException) end; EImportException = class(ESistemaException) end; EAtualizaException = class(ESistemaException) end; ELoadNfeException = class(EImportException) end; ELicenceException = class(ESistemaException) end; EInvalidImportSelection = class(EImportException) end; implementation end.